mirror of
https://github.com/warmbly/warmbly.git
synced 2026-11-28 08:05:45 +00:00
Merge remote-tracking branch 'origin/main' into fix/ai-editors-use-click-outside
This commit is contained in:
+15
-2
@@ -438,8 +438,6 @@ BILLING_PROVIDER=none
|
||||
# BOX_GOOGLE_CLIENT_SECRET=
|
||||
# Optional backend kill switch; unset enables connects when both keys are set.
|
||||
# BOX_GOOGLE_OAUTH_CONNECT=false
|
||||
# Dashboard visibility, independent of backend availability. Off by default.
|
||||
WARMBLY_GMAIL_OAUTH_CONNECT=false
|
||||
# Redirect URI: <API_PUBLIC_URL>/addresses/outlook/callback
|
||||
# BOX_OUTLOOK_CLIENT_ID=
|
||||
# BOX_OUTLOOK_CLIENT_SECRET=
|
||||
@@ -623,6 +621,21 @@ PUBSUB_ENABLED=false
|
||||
# SEARCH_API_URL=
|
||||
# SEARCH_API_KEY=
|
||||
|
||||
# === Lead finder (optional) ===================================================
|
||||
#
|
||||
# Works with nothing set: OpenStreetMap through public Overpass servers, the
|
||||
# Photon geocoder and OpenFreeMap tiles. Your own Overpass (comma-separated, tried
|
||||
# in order) is far more dependable than the shared public ones. Instance keys let
|
||||
# every workspace without its own key search that source, at a credit a page.
|
||||
# A map style hosted elsewhere also needs its origins in WARMBLY_CSP_CONNECT_ORIGINS.
|
||||
# LEAD_FINDER_OVERPASS_URL=
|
||||
# LEAD_FINDER_GEOCODER_URL=
|
||||
# LEAD_FINDER_MAP_STYLE_URL=
|
||||
# LEAD_FINDER_MAP_STYLE_DARK_URL=
|
||||
# LEAD_FINDER_GOOGLE_PLACES_API_KEY=
|
||||
# LEAD_FINDER_FOURSQUARE_API_KEY=
|
||||
# LEAD_FINDER_OUTSCRAPER_API_KEY=
|
||||
|
||||
|
||||
# === Integrations (optional) ==================================================
|
||||
# Shared redirect URI for the CRM and messaging OAuth flows. Unset, it becomes
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
const {
|
||||
ECSClient, DescribeServicesCommand, DescribeTasksCommand, UpdateServiceCommand,
|
||||
} = require("@aws-sdk/client-ecs");
|
||||
const { CloudWatchClient, DescribeAlarmsCommand } = require("@aws-sdk/client-cloudwatch");
|
||||
const {
|
||||
configuration: deploymentConfiguration, describe, compareTags, register, same, waitForService,
|
||||
ATTACHMENT_PROXY, ATTACHMENT_PROXY_TAG,
|
||||
} = require("./aws-deploy.cjs");
|
||||
|
||||
const tagValue = (tags, key) => tags.find((t) => t.key === key)?.value;
|
||||
const canonicalTags = (tags) => JSON.stringify(tags.filter((t) => !t.key.startsWith("aws:")).sort((a, b) => a.key.localeCompare(b.key)));
|
||||
|
||||
function configuration(env) {
|
||||
const config = deploymentConfiguration({ ...env, DEPLOY_MODE: "redeploy", DEPLOY_SERVICES: "backend", DEPLOY_FLEET: "false", DEPLOY_BAKE_SECONDS: "300" });
|
||||
if (!config.tag || !config.images || config.images.tag !== config.tag || compareTags(config.tag, "v0.6.75") < 0) {
|
||||
throw new Error("A published v0.6.75 or newer release and its images.json are required");
|
||||
}
|
||||
const account = config.cluster.split(":")[4];
|
||||
const expected = env.CONFIG_EXPECTED_TASK_DEFINITION || "";
|
||||
const expectedPrefix = `arn:aws:ecs:us-east-1:${account}:task-definition/${config.prefix}-backend:`;
|
||||
if (!expected.startsWith(expectedPrefix) || !/^[1-9]\d*$/.test(expected.slice(expectedPrefix.length))) {
|
||||
throw new Error("CONFIG_EXPECTED_TASK_DEFINITION must identify this cluster's backend revision");
|
||||
}
|
||||
if (!["true", "false"].includes(env.CONFIG_ATTACHMENT_DOWNLOAD_PROXY)) throw new Error("CONFIG_ATTACHMENT_DOWNLOAD_PROXY must be true or false");
|
||||
const tasks = JSON.parse(env.CONFIG_EXPECTED_TASKS || "null");
|
||||
const taskPrefix = `arn:aws:ecs:us-east-1:${account}:task/${config.cluster.split("/").pop()}/`;
|
||||
if (!Array.isArray(tasks) || !tasks.length || tasks.some((task) => typeof task !== "string" || !task.startsWith(taskPrefix) || !/^[a-f0-9]{32}$/.test(task.slice(taskPrefix.length))) ||
|
||||
new Set(tasks).size !== tasks.length) throw new Error("CONFIG_EXPECTED_TASKS must list unique current task ARNs from this cluster's read-only preflight");
|
||||
return { ...config, expected, tasks, value: env.CONFIG_ATTACHMENT_DOWNLOAD_PROXY };
|
||||
}
|
||||
|
||||
async function service(ecs, config) {
|
||||
const out = await ecs.send(new DescribeServicesCommand({ cluster: config.cluster, services: [`${config.prefix}-backend`] }));
|
||||
const live = out.services?.[0];
|
||||
if (out.failures?.length || out.services?.length !== 1 || live.status !== "ACTIVE") throw new Error("Backend service is unavailable");
|
||||
return live;
|
||||
}
|
||||
|
||||
function stable(live, expected, count) {
|
||||
if (live.taskDefinition !== expected || !Number.isInteger(live.desiredCount) || live.desiredCount < 1 || live.runningCount !== live.desiredCount || live.pendingCount !== 0 ||
|
||||
live.deployments?.length !== 1 || live.deployments[0].rolloutState !== "COMPLETED" ||
|
||||
live.deployments[0].taskDefinition !== expected || live.deployments[0].runningCount !== live.desiredCount ||
|
||||
live.deployments[0].desiredCount !== live.desiredCount || live.deployments[0].pendingCount !== 0 ||
|
||||
(count !== undefined && live.desiredCount !== count)) throw new Error("Backend must be stable on the expected revision and task count");
|
||||
}
|
||||
|
||||
async function verifyTasks(ecs, config, live, definition) {
|
||||
stable(live, definition.taskDefinitionArn);
|
||||
const arns = config.tasks;
|
||||
if (new Set(arns).size !== live.desiredCount || arns.length !== live.desiredCount) throw new Error("Every running backend task must be accounted for");
|
||||
for (let offset = 0; offset < arns.length; offset += 100) {
|
||||
const batch = arns.slice(offset, offset + 100);
|
||||
const out = await ecs.send(new DescribeTasksCommand({ cluster: config.cluster, tasks: batch }));
|
||||
if (out.failures?.length || out.tasks?.length !== batch.length || new Set(out.tasks.map((t) => t.taskArn)).size !== batch.length) {
|
||||
throw new Error("Every running backend task must be described");
|
||||
}
|
||||
for (const task of out.tasks) {
|
||||
if (!batch.includes(task.taskArn) || task.taskDefinitionArn !== live.taskDefinition || task.group !== `service:${live.serviceName}` ||
|
||||
task.lastStatus !== "RUNNING" || task.desiredStatus !== "RUNNING" || task.containers?.length !== 1 || task.containers[0].name !== "backend" ||
|
||||
task.containers[0].image !== definition.containerDefinitions[0].image ||
|
||||
(definition.containerDefinitions[0].healthCheck && task.healthStatus !== "HEALTHY") ||
|
||||
task.overrides?.containerOverrides?.some((c) => Object.keys(c).some((k) => k !== "name"))) {
|
||||
throw new Error("Every backend task must use the verified image and unmodified service configuration");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function alarms(clients, config) {
|
||||
const out = await clients.cloudwatch.send(new DescribeAlarmsCommand({ AlarmNamePrefix: `${config.prefix}-backend-`, StateValue: "ALARM" }));
|
||||
if (out.MetricAlarms?.length || out.CompositeAlarms?.length) throw new Error("Backend alarm fired during configuration rollout");
|
||||
}
|
||||
|
||||
async function observe(clients, config, definition, count, sleep, report) {
|
||||
for (let waited = 0; waited <= 300; waited += 15) {
|
||||
stable(await service(clients.ecs, config), definition.taskDefinitionArn, count);
|
||||
await alarms(clients, config);
|
||||
if (waited < 300) await sleep(15000);
|
||||
}
|
||||
const current = await describe(clients.ecs, definition.taskDefinitionArn);
|
||||
if (!same(current.definition, definition)) throw new Error("Backend configuration readback does not match the expected definition");
|
||||
report("Backend configuration and service counts verified after a 300s bake; independently inspect the resulting tasks and download responses");
|
||||
}
|
||||
|
||||
async function configure(clients, config, sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), report = console.log) {
|
||||
const live = await service(clients.ecs, config);
|
||||
stable(live, live.taskDefinition);
|
||||
const source = await describe(clients.ecs, live.taskDefinition);
|
||||
const definition = source.definition;
|
||||
const container = definition.containerDefinitions?.[0];
|
||||
const variant = tagValue(source.tags, "warmbly-image-variant");
|
||||
if (tagValue(source.tags, "warmbly-release") !== config.tag || !["default", "kafka"].includes(variant) ||
|
||||
definition.family !== `${config.prefix}-backend` || definition.containerDefinitions?.length !== 1 || container.name !== "backend") {
|
||||
throw new Error("Live backend must identify the selected release, family and image variant");
|
||||
}
|
||||
const digest = config.images.images?.[`backend${variant === "kafka" ? "-kafka" : ""}`];
|
||||
if (config.images.registry !== "ghcr.io/warmbly/warmbly" || !/^sha256:[a-f0-9]{64}$/.test(digest || "") ||
|
||||
container.image !== `${config.images.registry}/backend@${digest}`) throw new Error("Live backend image must match the attested release digest");
|
||||
if (container.secrets?.some((s) => s.name === ATTACHMENT_PROXY)) throw new Error("Attachment proxy flag must not be secret-backed");
|
||||
const values = (container.environment || []).filter((e) => e.name === ATTACHMENT_PROXY);
|
||||
const managed = tagValue(source.tags, ATTACHMENT_PROXY_TAG);
|
||||
if (values.length > 1 || (values.length && !["true", "false"].includes(values[0].value)) ||
|
||||
(managed !== undefined && (values.length !== 1 || managed !== values[0].value))) throw new Error("Attachment proxy configuration is ambiguous");
|
||||
await verifyTasks(clients.ecs, config, live, definition);
|
||||
await alarms(clients, config);
|
||||
if ((values[0]?.value || "false") === config.value) {
|
||||
if (config.value === "true" && managed === undefined) {
|
||||
const latest = await describe(clients.ecs, definition.family);
|
||||
const explicit = latest.definition.containerDefinitions?.[0]?.environment?.some((e) => e.name === ATTACHMENT_PROXY);
|
||||
if (tagValue(latest.tags, ATTACHMENT_PROXY_TAG) === undefined && !explicit) {
|
||||
throw new Error("Enabled attachment configuration requires a management tag or an explicit Terraform value before a no-change request");
|
||||
}
|
||||
}
|
||||
report("Backend already has the requested attachment configuration; no change");
|
||||
await observe(clients, config, definition, live.desiredCount, sleep, report);
|
||||
return { taskDefinition: live.taskDefinition, previous: live.taskDefinition, changed: false };
|
||||
}
|
||||
if (live.taskDefinition !== config.expected) throw new Error("Expected backend revision changed; inspect it before requesting a configuration change");
|
||||
const rendered = structuredClone(definition);
|
||||
rendered.containerDefinitions[0].environment = (container.environment || []).filter((e) => e.name !== ATTACHMENT_PROXY);
|
||||
rendered.containerDefinitions[0].environment.push({ name: ATTACHMENT_PROXY, value: config.value });
|
||||
const tags = source.tags.filter((t) => t.key !== ATTACHMENT_PROXY_TAG);
|
||||
tags.push({ key: ATTACHMENT_PROXY_TAG, value: config.value });
|
||||
const latest = await describe(clients.ecs, definition.family);
|
||||
const prepared = same(latest.definition, rendered) && canonicalTags(latest.tags) === canonicalTags(tags);
|
||||
const next = prepared ? latest.definition.taskDefinitionArn : await register(clients.ecs, source, rendered, tags, config.tag, report);
|
||||
stable(await service(clients.ecs, config), live.taskDefinition, live.desiredCount);
|
||||
try {
|
||||
// Every backend writer must use the shared deployment queue.
|
||||
await clients.ecs.send(new UpdateServiceCommand({ cluster: config.cluster, service: live.serviceName, taskDefinition: next }));
|
||||
await waitForService(clients.ecs, config, "backend", next, sleep);
|
||||
await observe(clients, config, { ...rendered, taskDefinitionArn: next }, live.desiredCount, sleep, report);
|
||||
return { taskDefinition: next, previous: live.taskDefinition, changed: true };
|
||||
} catch (error) {
|
||||
try {
|
||||
const current = await service(clients.ecs, config);
|
||||
if (![live.taskDefinition, next].includes(current.taskDefinition) || current.desiredCount !== live.desiredCount) {
|
||||
throw new Error("Backend changed concurrently; automatic rollback refused");
|
||||
}
|
||||
if (current.taskDefinition === next) await clients.ecs.send(new UpdateServiceCommand({ cluster: config.cluster, service: live.serviceName, taskDefinition: live.taskDefinition }));
|
||||
await waitForService(clients.ecs, config, "backend", live.taskDefinition, sleep);
|
||||
stable(await service(clients.ecs, config), live.taskDefinition, live.desiredCount);
|
||||
if (!same((await describe(clients.ecs, live.taskDefinition)).definition, definition)) throw new Error("Previous backend definition readback changed");
|
||||
report("Restored and verified the exact previous backend revision and service counts; independently inspect its current tasks");
|
||||
} catch {
|
||||
throw new Error("Configuration rollout failed and rollback could not be verified; inspect the backend before any further change", { cause: error });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
const region = { region: "us-east-1", maxAttempts: 3 };
|
||||
const clients = { ecs: new ECSClient(region), cloudwatch: new CloudWatchClient(region) };
|
||||
const lines = [];
|
||||
const report = (line) => { console.log(line); lines.push(line); };
|
||||
Promise.resolve().then(() => configure(clients, configuration(process.env), undefined, report)).catch((error) => {
|
||||
const message = error?.$metadata ? `AWS request failed: ${error.name}` : error.message;
|
||||
report(`Failed: ${message}`);
|
||||
process.exitCode = 1;
|
||||
}).finally(() => {
|
||||
if (process.env.GITHUB_STEP_SUMMARY) require("node:fs").appendFileSync(process.env.GITHUB_STEP_SUMMARY, `### Backend configuration\n\n\`\`\`\n${lines.join("\n")}\n\`\`\`\n`);
|
||||
for (const client of Object.values(clients)) client.destroy();
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { configuration, configure };
|
||||
@@ -0,0 +1,277 @@
|
||||
const { test } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const { mkdtempSync, writeFileSync, rmSync } = require("node:fs");
|
||||
const { tmpdir } = require("node:os");
|
||||
const { join } = require("node:path");
|
||||
const { configuration, configure } = require("./aws-backend-config.cjs");
|
||||
const { REGISTER_FIELDS, ATTACHMENT_PROXY, ATTACHMENT_PROXY_TAG } = require("./aws-deploy.cjs");
|
||||
|
||||
const root = "arn:aws:ecs:us-east-1:000000000000:";
|
||||
const arn = (revision) => `${root}task-definition/fixture-backend:${revision}`;
|
||||
const task = (number) => `${root}task/fixture/${number.toString(16).padStart(32, "0")}`;
|
||||
const runningTasks = (revision, count = 2) => Array.from({ length: count }, (_, i) => task(revision * 1000 + i + 1));
|
||||
const image = `ghcr.io/warmbly/warmbly/backend@sha256:${"a".repeat(64)}`;
|
||||
|
||||
function fixture(t, options = {}) {
|
||||
const count = options.taskCount || 2;
|
||||
const dir = mkdtempSync(join(tmpdir(), "backend-config-"));
|
||||
t.after(() => rmSync(dir, { recursive: true, force: true }));
|
||||
const manifest = { tag: "v0.6.75", registry: "ghcr.io/warmbly/warmbly", images: { "backend-kafka": `sha256:${"a".repeat(64)}` } };
|
||||
writeFileSync(join(dir, "images.json"), JSON.stringify(manifest));
|
||||
const env = { AWS_ECS_CLUSTER: root + "cluster/fixture", DEPLOY_TAG: manifest.tag, DEPLOY_IMAGES_JSON: join(dir, "images.json"),
|
||||
CONFIG_EXPECTED_TASK_DEFINITION: arn(1), CONFIG_EXPECTED_TASKS: JSON.stringify(runningTasks(1, count)), CONFIG_ATTACHMENT_DOWNLOAD_PROXY: "true" };
|
||||
const cfg = configuration(env);
|
||||
const live = { serviceName: "fixture-backend", status: "ACTIVE", taskDefinition: arn(1), desiredCount: count, runningCount: count, pendingCount: 0,
|
||||
deployments: [{ rolloutState: "COMPLETED", taskDefinition: arn(1), desiredCount: count, runningCount: count, pendingCount: 0 }] };
|
||||
const base = { family: "fixture-backend", status: "ACTIVE", revision: 1, taskDefinitionArn: arn(1),
|
||||
taskRoleArn: root + "role/task", executionRoleArn: root + "role/execution", networkMode: "awsvpc", cpu: "256", memory: "512",
|
||||
requiresCompatibilities: ["FARGATE"], runtimePlatform: { cpuArchitecture: "ARM64", operatingSystemFamily: "LINUX" },
|
||||
ephemeralStorage: { sizeInGiB: 30 }, volumes: [{ name: "fixture" }],
|
||||
containerDefinitions: [{ name: "backend", image, stopTimeout: 120, readonlyRootFilesystem: true,
|
||||
environment: [{ name: "TLS_ONLY", value: "true" }],
|
||||
secrets: [{ name: "PRIMARY_DB", valueFrom: "fixture:immutable-version" }],
|
||||
healthCheck: { command: ["CMD", "/app/healthcheck"], interval: 30, retries: 3 },
|
||||
logConfiguration: { logDriver: "awslogs", options: { "awslogs-group": "/fixture" } } }] };
|
||||
const tags = [{ key: "warmbly-release", value: manifest.tag }, { key: "warmbly-image-variant", value: "kafka" }, { key: "Owner", value: "fixture" }];
|
||||
const defs = new Map([[arn(1), { definition: base, tags }]]);
|
||||
const calls = [];
|
||||
const sleeps = [];
|
||||
let latest = arn(1);
|
||||
const ecs = {};
|
||||
ecs.send = async (command) => {
|
||||
const name = command.constructor.name;
|
||||
calls.push({ name, input: structuredClone(command.input) });
|
||||
if (options.hook) await options.hook(name, { live, defs, calls });
|
||||
switch (name) {
|
||||
case "DescribeServicesCommand": return { services: [structuredClone(live)] };
|
||||
case "DescribeTaskDefinitionCommand": {
|
||||
const entry = defs.get(command.input.taskDefinition === "fixture-backend" ? latest : command.input.taskDefinition);
|
||||
return { taskDefinition: structuredClone(entry.definition), tags: structuredClone(entry.tags) };
|
||||
}
|
||||
case "DescribeTasksCommand": return { tasks: (options.missingTask ? command.input.tasks.slice(1) : command.input.tasks).map((taskArn) => ({
|
||||
taskArn, taskDefinitionArn: options.wrongTask ? arn(99) : live.taskDefinition,
|
||||
group: options.foreignGroup ? "service:fixture-foreign" : "service:fixture-backend", lastStatus: "RUNNING",
|
||||
desiredStatus: options.drainingTask || !runningTasks(Number(live.taskDefinition.split(":").pop()), count).includes(taskArn) ? "STOPPED" : "RUNNING",
|
||||
healthStatus: options.unhealthyTask ? "UNHEALTHY" : "HEALTHY",
|
||||
containers: [{ name: "backend", image }], overrides: { containerOverrides: options.override ? [{ name: "backend", command: ["other"] }] : [{ name: "backend" }] },
|
||||
})) };
|
||||
case "RegisterTaskDefinitionCommand": {
|
||||
latest = arn(defs.size + 1);
|
||||
const { tags: nextTags, ...input } = structuredClone(command.input);
|
||||
if (options.reorderEnvironment) input.containerDefinitions[0].environment.reverse();
|
||||
defs.set(latest, { definition: { ...input, status: "ACTIVE", taskDefinitionArn: latest }, tags: nextTags });
|
||||
return { taskDefinition: { taskDefinitionArn: latest } };
|
||||
}
|
||||
case "UpdateServiceCommand": {
|
||||
live.taskDefinition = command.input.taskDefinition;
|
||||
live.deployments = [{ rolloutState: options.failedRoll && live.taskDefinition !== arn(1) ? "FAILED" : "COMPLETED",
|
||||
taskDefinition: live.taskDefinition, desiredCount: count, runningCount: count, pendingCount: 0 }];
|
||||
return {};
|
||||
}
|
||||
default: throw new Error(`Unexpected ${name}`);
|
||||
}
|
||||
};
|
||||
const cloudwatch = { async send(command) {
|
||||
calls.push({ name: command.constructor.name, input: structuredClone(command.input) });
|
||||
return { MetricAlarms: options.alarm && live.taskDefinition !== arn(1) ? [{ AlarmName: "fixture-backend-5xx" }] : [] };
|
||||
} };
|
||||
const run = () => configure({ ecs, cloudwatch }, cfg, async (ms) => sleeps.push(ms), () => {});
|
||||
const prepare = (definition, nextTags) => {
|
||||
latest = arn(defs.size + 1);
|
||||
defs.set(latest, { definition: { ...structuredClone(definition), taskDefinitionArn: latest }, tags: structuredClone(nextTags) });
|
||||
};
|
||||
return { env, cfg, live, base, tags, defs, calls, sleeps, run, prepare };
|
||||
}
|
||||
|
||||
const mutations = (f) => f.calls.filter((c) => ["RegisterTaskDefinitionCommand", "UpdateServiceCommand"].includes(c.name));
|
||||
|
||||
test("only the allowlisted flag and ownership tag change; every live task is checked and a full bake completes", async (t) => {
|
||||
const f = fixture(t);
|
||||
const previous = structuredClone(f.base);
|
||||
const result = await f.run();
|
||||
assert.equal(result.changed, true);
|
||||
const registration = f.calls.find((c) => c.name === "RegisterTaskDefinitionCommand").input;
|
||||
for (const field of REGISTER_FIELDS.filter((field) => field !== "containerDefinitions")) assert.deepEqual(registration[field], previous[field]);
|
||||
const container = structuredClone(registration.containerDefinitions[0]);
|
||||
assert.deepEqual(container.environment.pop(), { name: ATTACHMENT_PROXY, value: "true" });
|
||||
assert.deepEqual(container, previous.containerDefinitions[0]);
|
||||
assert.deepEqual(Object.fromEntries(registration.tags.map((tag) => [tag.key, tag.value])),
|
||||
Object.fromEntries([...f.tags, { key: ATTACHMENT_PROXY_TAG, value: "true" }].map((tag) => [tag.key, tag.value])));
|
||||
assert.deepEqual(f.calls.filter((c) => c.name === "UpdateServiceCommand").map((c) => c.input), [{ cluster: f.cfg.cluster, service: "fixture-backend", taskDefinition: arn(2) }]);
|
||||
assert.equal(f.sleeps.reduce((a, b) => a + b, 0), 300000);
|
||||
assert.equal(f.calls.filter((c) => c.name === "DescribeAlarmsCommand").length, 22);
|
||||
assert.ok(!f.calls.some((c) => c.name === "ListTasksCommand"), "the operation uses existing deployment permissions");
|
||||
const count = mutations(f).length;
|
||||
await assert.rejects(f.run(), /unmodified service configuration/, "an old task snapshot must be refreshed before retrying");
|
||||
f.cfg.tasks = runningTasks(2);
|
||||
assert.equal((await f.run()).changed, false);
|
||||
assert.equal(mutations(f).length, count, "repeated request is a no-op even with its original expected revision");
|
||||
assert.equal(f.sleeps.reduce((a, b) => a + b, 0), 600000, "an interrupted bake is always observed afresh without rolling again");
|
||||
});
|
||||
|
||||
test("provider environment ordering preserves a successful full bake without rollback", async (t) => {
|
||||
const f = fixture(t, { reorderEnvironment: true });
|
||||
assert.equal((await f.run()).changed, true);
|
||||
assert.equal(f.live.taskDefinition, arn(2));
|
||||
assert.deepEqual(f.calls.filter((c) => c.name === "UpdateServiceCommand").map((c) => c.input.taskDefinition), [arn(2)]);
|
||||
assert.equal(f.sleeps.reduce((a, b) => a + b, 0), 300000);
|
||||
});
|
||||
|
||||
test("a prepared definition with reordered environment bindings is reused", async (t) => {
|
||||
const f = fixture(t);
|
||||
const prepared = structuredClone(f.base);
|
||||
prepared.containerDefinitions[0].environment.unshift({ name: ATTACHMENT_PROXY, value: "true" });
|
||||
f.prepare(prepared, [...f.tags, { key: ATTACHMENT_PROXY_TAG, value: "true" }]);
|
||||
assert.equal((await f.run()).taskDefinition, arn(2));
|
||||
assert.ok(!f.calls.some((c) => c.name === "RegisterTaskDefinitionCommand"));
|
||||
});
|
||||
|
||||
test("disabling is explicit and preserves the remainder of the running definition", async (t) => {
|
||||
const f = fixture(t);
|
||||
await f.run();
|
||||
f.cfg.expected = arn(2);
|
||||
f.cfg.tasks = runningTasks(2);
|
||||
f.cfg.value = "false";
|
||||
await f.run();
|
||||
const current = f.defs.get(arn(3));
|
||||
assert.equal(current.definition.containerDefinitions[0].environment.find((e) => e.name === ATTACHMENT_PROXY).value, "false");
|
||||
assert.equal(current.tags.find((tag) => tag.key === ATTACHMENT_PROXY_TAG).value, "false");
|
||||
});
|
||||
|
||||
test("an enabled no-change request requires a deployment source that owns the setting", async (t) => {
|
||||
const f = fixture(t);
|
||||
f.prepare(f.base, f.tags);
|
||||
f.base.containerDefinitions[0].environment.push({ name: ATTACHMENT_PROXY, value: "true" });
|
||||
await assert.rejects(f.run(), /requires a management tag or an explicit Terraform value/);
|
||||
assert.deepEqual(mutations(f), []);
|
||||
assert.deepEqual(f.sleeps, []);
|
||||
});
|
||||
|
||||
for (const value of ["true", "false"]) test(`an explicit Terraform ${value} value owns an enabled no-change request`, async (t) => {
|
||||
const f = fixture(t);
|
||||
const template = structuredClone(f.base);
|
||||
template.containerDefinitions[0].environment.push({ name: ATTACHMENT_PROXY, value });
|
||||
f.prepare(template, f.tags);
|
||||
f.base.containerDefinitions[0].environment.push({ name: ATTACHMENT_PROXY, value: "true" });
|
||||
assert.equal((await f.run()).changed, false);
|
||||
assert.deepEqual(mutations(f), []);
|
||||
assert.equal(f.sleeps.reduce((a, b) => a + b, 0), 300000);
|
||||
});
|
||||
|
||||
test("a live managed enabled setting remains owned when the latest template omits it", async (t) => {
|
||||
const f = fixture(t);
|
||||
f.prepare(f.base, f.tags);
|
||||
f.base.containerDefinitions[0].environment.push({ name: ATTACHMENT_PROXY, value: "true" });
|
||||
f.tags.push({ key: ATTACHMENT_PROXY_TAG, value: "true" });
|
||||
assert.equal((await f.run()).changed, false);
|
||||
assert.deepEqual(mutations(f), []);
|
||||
assert.equal(f.sleeps.reduce((a, b) => a + b, 0), 300000);
|
||||
});
|
||||
|
||||
test("an absent false setting needs no ownership change", async (t) => {
|
||||
const f = fixture(t);
|
||||
f.cfg.value = "false";
|
||||
assert.equal((await f.run()).changed, false);
|
||||
assert.deepEqual(mutations(f), []);
|
||||
assert.equal(f.sleeps.reduce((a, b) => a + b, 0), 300000);
|
||||
});
|
||||
|
||||
test("every preflight task is described within the API batch limit", async (t) => {
|
||||
const f = fixture(t, { taskCount: 101 });
|
||||
await f.run();
|
||||
const descriptions = f.calls.filter((c) => c.name === "DescribeTasksCommand");
|
||||
assert.deepEqual(descriptions.map((c) => c.input.tasks.length), [100, 1]);
|
||||
assert.deepEqual(descriptions.flatMap((c) => c.input.tasks), f.cfg.tasks);
|
||||
});
|
||||
|
||||
for (const [name, options, mutate] of [
|
||||
["mixed task definitions", { wrongTask: true }], ["unhealthy task", { unhealthyTask: true }], ["task override", { override: true }],
|
||||
["draining task", { drainingTask: true }],
|
||||
["missing described task", { missingTask: true }], ["foreign task group", { foreignGroup: true }],
|
||||
["incomplete preflight", {}, (f) => { f.cfg.tasks.pop(); }],
|
||||
["duplicate preflight task", {}, (f) => { f.cfg.tasks[1] = f.cfg.tasks[0]; }],
|
||||
["stale expected revision", {}, (f) => { f.cfg.expected = arn(99); }],
|
||||
["wrong image", {}, (f) => { f.base.containerDefinitions[0].image += "bad"; }],
|
||||
["wrong release", {}, (f) => { f.tags[0].value = "v0.6.74"; }],
|
||||
["missing variant", {}, (f) => { f.tags.splice(1, 1); }],
|
||||
["zero tasks", {}, (f) => { f.live.desiredCount = f.live.runningCount = 0; }],
|
||||
["unknown desired count", {}, (f) => { f.live.desiredCount = f.live.runningCount = undefined; }],
|
||||
["deployment count mismatch", {}, (f) => { f.live.deployments[0].runningCount = 1; }],
|
||||
["deployment revision mismatch", {}, (f) => { f.live.deployments[0].taskDefinition = arn(99); }],
|
||||
["active rollout", {}, (f) => { f.live.deployments[0].rolloutState = "IN_PROGRESS"; }],
|
||||
["duplicate flag", {}, (f) => { f.base.containerDefinitions[0].environment.push(...["true", "false"].map((value) => ({ name: ATTACHMENT_PROXY, value }))); }],
|
||||
["secret-backed flag", {}, (f) => { f.base.containerDefinitions[0].secrets.push({ name: ATTACHMENT_PROXY, valueFrom: "secret" }); }],
|
||||
["mismatched ownership tag", {}, (f) => { f.tags.push({ key: ATTACHMENT_PROXY_TAG, value: "true" }); }],
|
||||
]) test(`${name} is refused before mutations`, async (t) => {
|
||||
const f = fixture(t, options);
|
||||
mutate?.(f);
|
||||
await assert.rejects(f.run());
|
||||
assert.deepEqual(mutations(f), []);
|
||||
});
|
||||
|
||||
for (const options of [{ alarm: true }, { failedRoll: true }]) test(`${JSON.stringify(options)} restores and verifies the exact prior revision`, async (t) => {
|
||||
const f = fixture(t, options);
|
||||
await assert.rejects(f.run());
|
||||
assert.equal(f.live.taskDefinition, arn(1));
|
||||
assert.deepEqual(f.calls.filter((c) => c.name === "UpdateServiceCommand").map((c) => c.input.taskDefinition), [arn(2), arn(1)]);
|
||||
assert.equal(f.calls.at(-1).name, "DescribeTaskDefinitionCommand");
|
||||
});
|
||||
|
||||
test("a desired-count change during rollback prevents a successful restore report", async (t) => {
|
||||
const f = fixture(t, { alarm: true, hook: (name, { live, calls }) => {
|
||||
if (name === "DescribeServicesCommand" && calls.filter((c) => c.name === "UpdateServiceCommand").length === 2) {
|
||||
live.desiredCount = live.runningCount = 3;
|
||||
live.deployments[0].desiredCount = live.deployments[0].runningCount = 3;
|
||||
}
|
||||
} });
|
||||
await assert.rejects(f.run(), /rollback could not be verified/);
|
||||
assert.equal(f.live.taskDefinition, arn(1));
|
||||
assert.equal(f.live.desiredCount, 3, "another writer's count is preserved for operator inspection");
|
||||
assert.ok(f.calls.filter((c) => c.name === "UpdateServiceCommand").every((c) => !Object.hasOwn(c.input, "desiredCount")));
|
||||
});
|
||||
|
||||
test("a concurrent change before update is preserved", async (t) => {
|
||||
const f = fixture(t, { hook: (name, { live, calls }) => {
|
||||
if (name === "DescribeServicesCommand" && calls.some((c) => c.name === "RegisterTaskDefinitionCommand")) live.taskDefinition = arn(99);
|
||||
} });
|
||||
await assert.rejects(f.run(), /expected revision/);
|
||||
assert.equal(f.calls.filter((c) => c.name === "UpdateServiceCommand").length, 0);
|
||||
assert.equal(f.live.taskDefinition, arn(99));
|
||||
});
|
||||
|
||||
test("a concurrent change during the bake is never overwritten by rollback", async (t) => {
|
||||
const f = fixture(t, { hook: (name, { live, calls }) => {
|
||||
if (name === "DescribeServicesCommand" && calls.some((c) => c.name === "UpdateServiceCommand")) live.taskDefinition = arn(99);
|
||||
} });
|
||||
await assert.rejects(f.run(), /rollback could not be verified/);
|
||||
assert.equal(f.calls.filter((c) => c.name === "UpdateServiceCommand").length, 1);
|
||||
assert.equal(f.live.taskDefinition, arn(99));
|
||||
});
|
||||
|
||||
test("a prepared identical revision is reused after interruption before the service update", async (t) => {
|
||||
let interrupt = true;
|
||||
const f = fixture(t, { hook: (name, { calls }) => {
|
||||
if (interrupt && name === "DescribeServicesCommand" && calls.some((c) => c.name === "RegisterTaskDefinitionCommand")) {
|
||||
interrupt = false;
|
||||
throw new Error("interrupted before update");
|
||||
}
|
||||
} });
|
||||
await assert.rejects(f.run(), /interrupted/);
|
||||
await f.run();
|
||||
assert.equal(f.calls.filter((c) => c.name === "RegisterTaskDefinitionCommand").length, 1);
|
||||
});
|
||||
|
||||
test("configuration requires a supported release, exact backend ARN and explicit boolean", (t) => {
|
||||
const f = fixture(t);
|
||||
for (const overrides of [
|
||||
{ DEPLOY_TAG: "v0.6.74" }, { DEPLOY_TAG: "" }, { CONFIG_ATTACHMENT_DOWNLOAD_PROXY: "yes" },
|
||||
{ CONFIG_EXPECTED_TASK_DEFINITION: arn(1).replace("fixture-backend", "fixture-consumer") },
|
||||
{ CONFIG_EXPECTED_TASK_DEFINITION: arn(1).replace("000000000000", "111111111111") },
|
||||
{ CONFIG_EXPECTED_TASKS: "[]" }, { CONFIG_EXPECTED_TASKS: "null" },
|
||||
{ CONFIG_EXPECTED_TASKS: JSON.stringify([task(1), task(1)]) },
|
||||
{ CONFIG_EXPECTED_TASKS: JSON.stringify([task(1).replace("000000000000", "111111111111")]) },
|
||||
{ CONFIG_EXPECTED_TASKS: JSON.stringify([task(1).replace("/fixture/", "/foreign/")]) },
|
||||
]) assert.throws(() => configuration({ ...f.env, ...overrides }));
|
||||
assert.equal(configuration({ ...f.env, DEPLOY_BAKE_SECONDS: "0", DEPLOY_FLEET: "true" }).bake, 300);
|
||||
assert.equal(configuration(f.env).fleet, false);
|
||||
});
|
||||
@@ -21,6 +21,8 @@ const VARIANT_TAG = "warmbly-image-variant";
|
||||
const TAG_RE = /^v(\d+)\.(\d+)\.(\d+)$/;
|
||||
const DIGEST_RE = /^sha256:[a-f0-9]{64}$/;
|
||||
const VERSION_RE = /^[A-Za-z0-9-]{32,64}$/;
|
||||
const ATTACHMENT_PROXY = "CAMPAIGN_ATTACHMENT_DOWNLOAD_PROXY";
|
||||
const ATTACHMENT_PROXY_TAG = "warmbly-config-attachment-download-proxy";
|
||||
|
||||
function configuration(env) {
|
||||
const cluster = env.AWS_ECS_CLUSTER;
|
||||
@@ -46,8 +48,10 @@ function configuration(env) {
|
||||
}
|
||||
const bake = Number(String(env.DEPLOY_BAKE_SECONDS ?? "").trim() || 300);
|
||||
if (!Number.isInteger(bake) || bake < 0 || bake > 3600) throw new Error("DEPLOY_BAKE_SECONDS must be 0 through 3600");
|
||||
const fleetBake = Number(String(env.DEPLOY_FLEET_BAKE_SECONDS ?? "").trim() || 300);
|
||||
if (!Number.isInteger(fleetBake) || fleetBake < 300 || fleetBake > 3600) throw new Error("DEPLOY_FLEET_BAKE_SECONDS must be 300 through 3600");
|
||||
return {
|
||||
cluster, prefix, mode, tag, services, allServices: raw === "all", secretVersions, bake,
|
||||
cluster, prefix, mode, tag, services, allServices: raw === "all", secretVersions, bake, fleetBake,
|
||||
fleet: env.DEPLOY_FLEET !== "false",
|
||||
allowDroppedSecrets: env.DEPLOY_ALLOW_DROPPED_SECRETS === "true",
|
||||
images: env.DEPLOY_IMAGES_JSON ? JSON.parse(readFileSync(env.DEPLOY_IMAGES_JSON, "utf8")) : null,
|
||||
@@ -130,14 +134,35 @@ function repin(container, pins) {
|
||||
}
|
||||
}
|
||||
|
||||
function same(a, b) {
|
||||
return JSON.stringify(REGISTER_FIELDS.map((f) => a[f] ?? null)) === JSON.stringify(REGISTER_FIELDS.map((f) => b[f] ?? null));
|
||||
function canonical(value) {
|
||||
if (Array.isArray(value)) return value.map(canonical);
|
||||
if (value && typeof value === "object") return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonical(value[key])]));
|
||||
return value;
|
||||
}
|
||||
|
||||
function comparableDefinition(definition) {
|
||||
return REGISTER_FIELDS.map((field) => {
|
||||
let value = definition[field] ?? null;
|
||||
if (field === "containerDefinitions" && value) value = value.map((container) => {
|
||||
const copy = { ...container };
|
||||
// ECS may reorder named bindings; command and other array order stays significant.
|
||||
for (const key of ["environment", "secrets"]) if (copy[key]) copy[key] = [...copy[key]].sort((a, b) => a.name.localeCompare(b.name));
|
||||
return copy;
|
||||
});
|
||||
return canonical(value);
|
||||
});
|
||||
}
|
||||
|
||||
function same(a, b) {
|
||||
return JSON.stringify(comparableDefinition(a)) === JSON.stringify(comparableDefinition(b));
|
||||
}
|
||||
|
||||
const canonicalTags = (tags) => JSON.stringify(tags.filter((t) => !t.key.startsWith("aws:")).sort((a, b) => a.key.localeCompare(b.key)));
|
||||
|
||||
async function register(client, source, rendered, tags, release, report) {
|
||||
const carried = tags.filter((t) => t.key !== RELEASE_TAG && !t.key.startsWith("aws:"));
|
||||
if (release) carried.push({ key: RELEASE_TAG, value: release });
|
||||
if (same(source.definition, rendered) && tagValue(source.tags, RELEASE_TAG) === release) return source.definition.taskDefinitionArn;
|
||||
if (same(source.definition, rendered) && canonicalTags(source.tags) === canonicalTags(carried)) return source.definition.taskDefinitionArn;
|
||||
const input = {};
|
||||
for (const f of REGISTER_FIELDS) if (rendered[f] !== undefined && rendered[f] !== null) input[f] = rendered[f];
|
||||
input.tags = carried;
|
||||
@@ -169,8 +194,9 @@ async function logTail(clients, definition, task, report, quiet) {
|
||||
|
||||
// runTask runs a one-off task to completion; capture may be a predicate the log tail must meet.
|
||||
async function runTask(clients, config, network, arn, definition, label, sleep, report, options = {}) {
|
||||
const { command, environment, capture } = Array.isArray(options) ? { command: options } : options;
|
||||
const token = createHash("sha256").update(`${config.run}/${arn}/${label}/${JSON.stringify(command || [])}/${JSON.stringify(environment || [])}`).digest("hex");
|
||||
const { command, environment, capture, imagePullRetries = 0, pullAttempt = 0 } = Array.isArray(options) ? { command: options } : options;
|
||||
const identity = `${config.run}/${arn}/${label}/${JSON.stringify(command || [])}/${JSON.stringify(environment || [])}`;
|
||||
const token = createHash("sha256").update(identity + (pullAttempt ? `/pull-retry-${pullAttempt}` : "")).digest("hex");
|
||||
const name = definition.containerDefinitions[0].name;
|
||||
const override = { name, ...(command ? { command } : {}), ...(environment ? { environment } : {}) };
|
||||
const started = assertResponse(await clients.ecs.send(new RunTaskCommand({
|
||||
@@ -189,7 +215,16 @@ async function runTask(clients, config, network, arn, definition, label, sleep,
|
||||
const container = status.containers?.find((c) => c.name === name);
|
||||
const ok = status.stopCode === "EssentialContainerExited" && container?.exitCode === 0;
|
||||
let lines = !ok || command || capture ? await logTail(clients, definition, task, report, ok && capture) : [];
|
||||
if (!ok) throw new Error(`${label} failed; its log tail is above`);
|
||||
if (!ok) {
|
||||
const neverStarted = !status.startedAt && status.containers?.length > 0 && status.containers.every((c) => c.exitCode === undefined);
|
||||
const pullFailure = status.stopCode === "TaskFailedToStart" && /^CannotPullContainerError:/.test(status.stoppedReason || "");
|
||||
if (neverStarted && pullFailure && pullAttempt < imagePullRetries) {
|
||||
report(`${label} image pull failed before execution; retry ${pullAttempt + 1}/${imagePullRetries} with the same definition and overrides`);
|
||||
await sleep(30000 * (pullAttempt + 1));
|
||||
return runTask(clients, config, network, arn, definition, label, sleep, report, { ...options, pullAttempt: pullAttempt + 1 });
|
||||
}
|
||||
throw new Error(`${label} failed (${status.stopCode || "unknown stop code"}); inspect stopped task ${task}; its log tail is above`);
|
||||
}
|
||||
// Log delivery can trail the task stopping by a few seconds.
|
||||
for (let retry = 0; typeof capture === "function" && !capture(lines) && retry < 6; retry++) {
|
||||
await sleep(5000);
|
||||
@@ -236,6 +271,38 @@ function imageFor(config, key, fallback) {
|
||||
return `${config.images.registry}/${key.replace(/-kafka$/, "")}@${digest}`;
|
||||
}
|
||||
|
||||
function preserveBackendConfiguration(source, live, rendered, release) {
|
||||
const managed = tagValue(live.tags, ATTACHMENT_PROXY_TAG);
|
||||
const explicitValues = source.definition.containerDefinitions[0].environment?.filter((e) => e.name === ATTACHMENT_PROXY) || [];
|
||||
const explicit = explicitValues[0];
|
||||
const sourceManaged = tagValue(source.tags, ATTACHMENT_PROXY_TAG);
|
||||
const current = live.definition.containerDefinitions[0].environment?.filter((e) => e.name === ATTACHMENT_PROXY) || [];
|
||||
if (explicitValues.length > 1 || source.definition.containerDefinitions[0].secrets?.some((s) => s.name === ATTACHMENT_PROXY) ||
|
||||
(sourceManaged !== undefined && (explicitValues.length !== 1 || sourceManaged !== explicit.value))) {
|
||||
throw new Error("Backend attachment source configuration is ambiguous");
|
||||
}
|
||||
if (managed !== undefined) {
|
||||
if (!["true", "false"].includes(managed) || current.length !== 1 || current[0].value !== managed) {
|
||||
throw new Error("Backend attachment configuration tag and environment must agree");
|
||||
}
|
||||
}
|
||||
// An explicit Terraform value takes ownership; otherwise the live managed value survives rendering.
|
||||
const value = explicit && sourceManaged === undefined ? explicit.value
|
||||
: managed ?? (sourceManaged !== undefined ? current[0]?.value || "false" : undefined);
|
||||
if (value !== undefined && !["true", "false"].includes(value)) throw new Error("Backend attachment configuration must be true or false");
|
||||
if (value === "true" && compareTags(release, "v0.6.75") < 0) {
|
||||
throw new Error("Disable the attachment proxy explicitly before deploying a release older than v0.6.75");
|
||||
}
|
||||
const tags = source.tags.filter((t) => t.key !== ATTACHMENT_PROXY_TAG);
|
||||
if (value !== undefined) {
|
||||
const container = rendered.containerDefinitions[0];
|
||||
container.environment = (container.environment || []).filter((e) => e.name !== ATTACHMENT_PROXY);
|
||||
container.environment.push({ name: ATTACHMENT_PROXY, value });
|
||||
if (!(explicit && sourceManaged === undefined) && managed !== undefined) tags.push({ key: ATTACHMENT_PROXY_TAG, value });
|
||||
}
|
||||
return tags;
|
||||
}
|
||||
|
||||
async function deploy(clients, config, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), report = console.log) {
|
||||
const ecs = clients.ecs;
|
||||
const names = SERVICES.map((s) => `${config.prefix}-${s}`);
|
||||
@@ -301,6 +368,7 @@ async function deploy(clients, config, sleep = (ms) => new Promise((r) => setTim
|
||||
};
|
||||
const backendKey = deployBackend || families.includes("ops") ? `backend${variant(deployBackend ? "backend" : "ops") === "kafka" ? "-kafka" : ""}` : null;
|
||||
const rendered = {};
|
||||
const renderedTags = {};
|
||||
for (const name of families) {
|
||||
const def = structuredClone(sources[name].definition);
|
||||
const container = def.containerDefinitions?.[0];
|
||||
@@ -316,6 +384,9 @@ async function deploy(clients, config, sleep = (ms) => new Promise((r) => setTim
|
||||
} else if (name !== "validation") {
|
||||
container.image = imageFor(config, backendKey, liveDefs.backend.definition.containerDefinitions[0].image);
|
||||
}
|
||||
renderedTags[name] = name === "backend"
|
||||
? preserveBackendConfiguration(sources[name], liveDefs.backend, def, tag)
|
||||
: sources[name].tags;
|
||||
rendered[name] = def;
|
||||
}
|
||||
|
||||
@@ -337,7 +408,7 @@ async function deploy(clients, config, sleep = (ms) => new Promise((r) => setTim
|
||||
}
|
||||
|
||||
const arns = {};
|
||||
for (const name of families) arns[name] = await register(ecs, sources[name], rendered[name], sources[name].tags, tag, report);
|
||||
for (const name of families) arns[name] = await register(ecs, sources[name], rendered[name], renderedTags[name], tag, report);
|
||||
|
||||
const network = backend.networkConfiguration;
|
||||
if (arns.validation) await runTask(clients, config, network, arns.validation, rendered.validation, "Dependency check", sleep, report);
|
||||
@@ -383,10 +454,10 @@ async function deploy(clients, config, sleep = (ms) => new Promise((r) => setTim
|
||||
const digests = ["worker", "worker-kafka", "consumer", "consumer-kafka"]
|
||||
.filter((k) => DIGEST_RE.test(config.images.images?.[k] || ""))
|
||||
.map((k) => `${k}=${config.images.images[k]}`);
|
||||
const command = ["fleet", "rollout", "start", tag, "--canary", "1", "--waves", "100", "--bake", "30m"];
|
||||
const command = ["fleet", "rollout", "start", tag, "--canary", "1", "--waves", "100", "--bake", `${config.fleetBake}s`];
|
||||
if (digests.length) command.push("--digests", digests.join(","));
|
||||
await runTask(clients, config, network, arns.ops, rendered.ops, "Fleet rollout", sleep, report, { command });
|
||||
report(`Workers move to ${tag} in canary waves; follow with \`warmblyctl fleet rollout status\``);
|
||||
await runTask(clients, config, network, arns.ops, rendered.ops, "Fleet rollout", sleep, report, { command, imagePullRetries: 2 });
|
||||
report(`Workers move to ${tag}: one canary, then all remaining hosts, with ${config.fleetBake}s of healthy uptime per stage plus update time; follow with \`warmblyctl fleet rollout status\``);
|
||||
}
|
||||
return { tag, arns, pins: Object.fromEntries(Object.entries(pins).map(([arn, v]) => [secretService(arn, config.prefix) || arn, v])) };
|
||||
}
|
||||
@@ -411,4 +482,5 @@ if (require.main === module) {
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { configuration, deploy, runTask, describe, compareTags, parseRef, secretService, SERVICES };
|
||||
module.exports = { configuration, deploy, runTask, describe, compareTags, parseRef, secretService, SERVICES,
|
||||
REGISTER_FIELDS, same, register, waitForService, ATTACHMENT_PROXY, ATTACHMENT_PROXY_TAG };
|
||||
|
||||
@@ -3,7 +3,32 @@ const assert = require("node:assert/strict");
|
||||
const { mkdtempSync, writeFileSync } = require("node:fs");
|
||||
const { join } = require("node:path");
|
||||
const { tmpdir } = require("node:os");
|
||||
const { configuration, deploy, compareTags, parseRef } = require("./aws-deploy.cjs");
|
||||
const { configuration, deploy, runTask, compareTags, parseRef, same, ATTACHMENT_PROXY, ATTACHMENT_PROXY_TAG } = require("./aws-deploy.cjs");
|
||||
|
||||
test("definition equality compares named bindings while preserving every value and command order", () => {
|
||||
const base = { family: "fixture", containerDefinitions: [{ name: "backend", image: "fixture@sha256:fixed",
|
||||
command: ["serve", "--tls"], environment: [{ name: "TLS_ONLY", value: "true" }, { name: "REGION", value: "fixture" }],
|
||||
secrets: [{ name: "PRIMARY_DB", valueFrom: "database:version-one" }, { name: "AUTH_SECRET", valueFrom: "auth:version-one" }] }] };
|
||||
const reordered = structuredClone(base);
|
||||
reordered.containerDefinitions[0].environment.reverse();
|
||||
reordered.containerDefinitions[0].secrets.reverse();
|
||||
reordered.containerDefinitions[0].environment = reordered.containerDefinitions[0].environment.map(({ name, value }) => ({ value, name }));
|
||||
assert.ok(same(base, reordered));
|
||||
for (const mutate of [
|
||||
(c) => { c.environment[0].value = "false"; },
|
||||
(c) => { c.environment[0].name = "OTHER"; },
|
||||
(c) => { c.environment.pop(); },
|
||||
(c) => { c.environment.push({ ...c.environment[0] }); },
|
||||
(c) => { c.secrets[0].valueFrom = "database:version-two"; },
|
||||
(c) => { c.secrets.pop(); },
|
||||
(c) => { c.command.reverse(); },
|
||||
(c) => { c.image = "other@sha256:fixed"; },
|
||||
]) {
|
||||
const changed = structuredClone(base);
|
||||
mutate(changed.containerDefinitions[0]);
|
||||
assert.equal(same(base, changed), false);
|
||||
}
|
||||
});
|
||||
|
||||
const root = "arn:aws:ecs:us-east-1:000000000000:";
|
||||
const registry = "ghcr.io/warmbly/warmbly";
|
||||
@@ -149,6 +174,11 @@ const valueFrom = (def, key) => def.containerDefinitions[0].secrets.find((s) =>
|
||||
test("configuration refuses prereleases, bad modes and secret pins outside refresh-secrets", () => {
|
||||
assert.throws(() => config({ DEPLOY_TAG: "v1.3.0-rc.1" }), /prereleases never deploy/);
|
||||
assert.throws(() => config({ DEPLOY_MODE: "yolo" }), /DEPLOY_MODE/);
|
||||
for (const value of ["0", "299", "3601", "NaN", "300.5"]) {
|
||||
assert.throws(() => config({ DEPLOY_FLEET_BAKE_SECONDS: value }), /DEPLOY_FLEET_BAKE_SECONDS/);
|
||||
}
|
||||
assert.equal(config().fleetBake, 300);
|
||||
assert.equal(config({ DEPLOY_FLEET_BAKE_SECONDS: "1800" }).fleetBake, 1800);
|
||||
assert.throws(() => config({ DEPLOY_SERVICES: "backend,worker" }), /DEPLOY_SERVICES/);
|
||||
assert.throws(() => config({ DEPLOY_SECRET_VERSIONS: JSON.stringify({ backend: "a".repeat(36) }) }), /refresh-secrets/);
|
||||
assert.throws(() => config({ DEPLOY_MODE: "refresh-secrets", DEPLOY_SECRET_VERSIONS: JSON.stringify({ backend: "x" }) }), /secret version id/);
|
||||
@@ -173,6 +203,56 @@ test("a release renders from the latest revision, swaps variant digests and carr
|
||||
}
|
||||
});
|
||||
|
||||
function manageAttachments(f, revision, value) {
|
||||
const arn = `${root}task-definition/fixture-backend:${revision}`;
|
||||
f.defs[arn].containerDefinitions[0].environment.push({ name: ATTACHMENT_PROXY, value });
|
||||
f.tagsOf[arn].push({ key: ATTACHMENT_PROXY_TAG, value });
|
||||
}
|
||||
|
||||
for (const mode of ["deploy", "refresh-secrets"]) test(`${mode} preserves the live managed attachment setting`, async () => {
|
||||
const f = fixture();
|
||||
manageAttachments(f, 1, "true");
|
||||
await run(f, config({ DEPLOY_MODE: mode }));
|
||||
const backend = registered(f).find((r) => r.family === "fixture-backend");
|
||||
assert.deepEqual(backend.containerDefinitions[0].environment.filter((e) => e.name === ATTACHMENT_PROXY), [{ name: ATTACHMENT_PROXY, value: "true" }]);
|
||||
assert.equal(backend.tags.find((t) => t.key === ATTACHMENT_PROXY_TAG).value, "true");
|
||||
assert.ok(registered(f).filter((r) => r.family !== "fixture-backend").every((r) => !r.tags.some((t) => t.key === ATTACHMENT_PROXY_TAG)));
|
||||
});
|
||||
|
||||
test("an explicit Terraform attachment value takes ownership", async () => {
|
||||
const f = fixture();
|
||||
manageAttachments(f, 1, "true");
|
||||
f.defs[`${root}task-definition/fixture-backend:2`].containerDefinitions[0].environment.push({ name: ATTACHMENT_PROXY, value: "false" });
|
||||
await run(f, config());
|
||||
const backend = registered(f).find((r) => r.family === "fixture-backend");
|
||||
assert.equal(backend.containerDefinitions[0].environment.find((e) => e.name === ATTACHMENT_PROXY).value, "false");
|
||||
assert.ok(!backend.tags.some((t) => t.key === ATTACHMENT_PROXY_TAG));
|
||||
});
|
||||
|
||||
test("an attachment configuration prepared but never activated is not adopted by a release", async () => {
|
||||
const f = fixture();
|
||||
manageAttachments(f, 2, "true");
|
||||
await run(f, config());
|
||||
const backend = registered(f).find((r) => r.family === "fixture-backend");
|
||||
assert.equal(backend.containerDefinitions[0].environment.find((e) => e.name === ATTACHMENT_PROXY).value, "false");
|
||||
assert.ok(!backend.tags.some((t) => t.key === ATTACHMENT_PROXY_TAG));
|
||||
});
|
||||
|
||||
test("managed attachment configuration must agree with its environment", async () => {
|
||||
const f = fixture();
|
||||
manageAttachments(f, 1, "true");
|
||||
f.defs[`${root}task-definition/fixture-backend:1`].containerDefinitions[0].environment.find((e) => e.name === ATTACHMENT_PROXY).value = "false";
|
||||
await assert.rejects(run(f, config()), /tag and environment must agree/);
|
||||
assert.equal(registered(f).length, 0);
|
||||
});
|
||||
|
||||
test("a rollback below route support requires explicitly disabling the attachment proxy", async () => {
|
||||
const f = fixture({ liveTag: "v0.6.75" });
|
||||
manageAttachments(f, 1, "true");
|
||||
await assert.rejects(run(f, config({ DEPLOY_TAG: "v0.6.74", DEPLOY_MODE: "rollback" })), /Disable the attachment proxy explicitly/);
|
||||
assert.equal(registered(f).length, 0);
|
||||
});
|
||||
|
||||
test("the newest pinned secret version wins so a stale Terraform pin cannot undo a rotation", async () => {
|
||||
const f = fixture();
|
||||
await run(f, config());
|
||||
@@ -286,10 +366,66 @@ test("the fleet rollout gets the worker and consumer digests per variant", async
|
||||
const ops = runs(f).find((r) => r.overrides);
|
||||
const command = ops.overrides.containerOverrides[0].command;
|
||||
assert.deepEqual(command.slice(0, 4), ["fleet", "rollout", "start", "v1.3.0"]);
|
||||
assert.equal(command[command.indexOf("--bake") + 1], "300s");
|
||||
assert.equal(command[command.indexOf("--digests") + 1], `worker=${d("b")},worker-kafka=${d("c")},consumer=${d("b")},consumer-kafka=${d("c")}`);
|
||||
assert.equal(ops.overrides.containerOverrides[0].name, "ops");
|
||||
});
|
||||
|
||||
test("hosted fleet rollout carries a configured longer bake", async () => {
|
||||
const f = fixture();
|
||||
await run(f, config({ DEPLOY_FLEET_BAKE_SECONDS: "1800" }));
|
||||
const command = runs(f).find((r) => r.overrides).overrides.containerOverrides[0].command;
|
||||
assert.equal(command[command.indexOf("--bake") + 1], "1800s");
|
||||
});
|
||||
|
||||
test("fleet startup retries only confirmed image-pull failures before execution, with stable retry tokens", async () => {
|
||||
const pullFailure = { lastStatus: "STOPPED", stopCode: "TaskFailedToStart", stoppedReason: "CannotPullContainerError: manifest not found", containers: [{ name: "ops", runtimeId: "allocated-before-pull" }] };
|
||||
const success = { lastStatus: "STOPPED", stopCode: "EssentialContainerExited", containers: [{ name: "ops", exitCode: 0 }] };
|
||||
async function attempt(statuses, options = {}) {
|
||||
const requests = [], sleeps = [];
|
||||
const clients = {
|
||||
ecs: { async send(command) {
|
||||
if (command.constructor.name === "RunTaskCommand") {
|
||||
requests.push(command.input);
|
||||
return { tasks: [{ taskArn: `${root}task/fixture/${requests.length}` }] };
|
||||
}
|
||||
return { tasks: [statuses[Math.min(requests.length - 1, statuses.length - 1)]] };
|
||||
} },
|
||||
logs: { async send() { return { events: [] }; } },
|
||||
};
|
||||
const execute = () => runTask(clients, config(), {}, "fixture-ops:3", definition("ops", 3, {}), "Fleet rollout", async (ms) => sleeps.push(ms), () => {}, { command: ["fleet", "rollout", "start", "v1.3.0"], imagePullRetries: 2, ...options });
|
||||
return { execute, requests, sleeps };
|
||||
}
|
||||
const recovered = await attempt([pullFailure, success]);
|
||||
await recovered.execute();
|
||||
assert.equal(recovered.requests.length, 2);
|
||||
assert.deepEqual(recovered.sleeps, [30000]);
|
||||
assert.deepEqual(recovered.requests[0].overrides, recovered.requests[1].overrides);
|
||||
assert.equal(recovered.requests[0].taskDefinition, recovered.requests[1].taskDefinition);
|
||||
assert.notEqual(recovered.requests[0].clientToken, recovered.requests[1].clientToken);
|
||||
const replay = await attempt([pullFailure, success]);
|
||||
await replay.execute();
|
||||
assert.deepEqual(replay.requests.map((r) => r.clientToken), recovered.requests.map((r) => r.clientToken));
|
||||
const exhausted = await attempt([pullFailure]);
|
||||
await assert.rejects(exhausted.execute(), /Fleet rollout failed/);
|
||||
assert.equal(exhausted.requests.length, 3);
|
||||
assert.deepEqual(exhausted.sleeps, [30000, 60000]);
|
||||
for (const failure of [
|
||||
{ ...success, containers: [{ name: "ops", exitCode: 1 }] },
|
||||
{ ...pullFailure, startedAt: new Date() },
|
||||
{ ...pullFailure, containers: [{ name: "ops", exitCode: 1 }] },
|
||||
{ ...pullFailure, containers: [] },
|
||||
{ ...pullFailure, stoppedReason: "ResourceInitializationError: unavailable" },
|
||||
]) {
|
||||
const failed = await attempt([failure]);
|
||||
await assert.rejects(failed.execute(), /Fleet rollout failed/);
|
||||
assert.equal(failed.requests.length, 1);
|
||||
}
|
||||
const migration = await attempt([pullFailure], { imagePullRetries: 0 });
|
||||
await assert.rejects(migration.execute(), /failed/);
|
||||
assert.equal(migration.requests.length, 1);
|
||||
});
|
||||
|
||||
test("an unchanged definition reuses its revision and redeploy forces a fresh deployment", async () => {
|
||||
const f = fixture();
|
||||
await run(f, config({ DEPLOY_SERVICES: "forms", DEPLOY_FLEET: "false" }));
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/../.."
|
||||
ruby -ryaml <<'RUBY'
|
||||
workflow = YAML.load_file('.github/workflows/configure-origin-alb-aws.yml')
|
||||
trigger = workflow['on'] || workflow[true]
|
||||
raise 'only manual execution and offline PR checks are supported' unless trigger.keys.sort == ['pull_request', 'workflow_dispatch']
|
||||
inputs = trigger.fetch('workflow_dispatch').fetch('inputs')
|
||||
raise 'plan must be the default' unless inputs.dig('mode', 'default') == 'plan' && inputs.dig('mode', 'options') == ['plan', 'apply', 'rollback']
|
||||
raise 'exact plan selectors are required' unless inputs.keys.sort == ['mode', 'plan_run_id', 'plan_sha256', 'plan_version']
|
||||
jobs = workflow.fetch('jobs')
|
||||
raise 'no deployment or recovery jobs belong here' unless jobs.keys.sort == ['check', 'configure']
|
||||
job = jobs.fetch('configure')
|
||||
raise 'manual main workflow must follow offline checks' unless job['needs'] == 'check' && job['if'] == "github.event_name == 'workflow_dispatch'"
|
||||
raise 'ordinary environment must be retained' unless job['environment'] == 'aws-infrastructure'
|
||||
raise 'production serialization must be retained' unless job.dig('concurrency', 'group') == 'aws-production' && job.dig('concurrency', 'cancel-in-progress') == false
|
||||
raise 'only contents and OIDC permissions are needed' unless job['permissions'] == {'contents'=>'read', 'id-token'=>'write'}
|
||||
steps = job.fetch('steps')
|
||||
credentials = steps.select { |s| s['uses'] == 'aws-actions/configure-aws-credentials@v4' }
|
||||
raise 'one existing role with session restriction is required' unless credentials.length == 1 && credentials[0]['with'] == {
|
||||
'role-to-assume'=>'${{ vars.AWS_TERRAFORM_APPLY_ROLE_ARN }}', 'aws-region'=>'us-east-1',
|
||||
'inline-session-policy'=>'${{ steps.scope.outputs.policy }}'
|
||||
}
|
||||
scope = steps.index { |s| s['run'] == 'node .github/scripts/aws-origin-alb.cjs session-policy' }
|
||||
raise 'scope validation must precede credentials' unless scope && scope < steps.index(credentials[0])
|
||||
raise 'no secret inheritance or protection changes are supported' if workflow.to_s.match?(/secrets|aws-infrastructure-approval|AWS_TLS_RECOVERY|AWS_TERRAFORM_ENABLED|terraform apply|deploy-aws/)
|
||||
jobs.each_value do |j|
|
||||
raise 'job failures must stop execution' if j['continue-on-error']
|
||||
j.fetch('steps').each do |s|
|
||||
raise 'step failures must stop execution' if s['continue-on-error']
|
||||
raise 'checkout credentials must not persist' if s['uses'] == 'actions/checkout@v4' && s.dig('with', 'persist-credentials') != false
|
||||
end
|
||||
end
|
||||
puts 'Origin ALB workflow default, ordinary environment, session scope and production queue checks passed'
|
||||
RUBY
|
||||
@@ -0,0 +1,274 @@
|
||||
const { createHash } = require("node:crypto");
|
||||
const { spawnSync } = require("node:child_process");
|
||||
const { appendFileSync, mkdirSync, readFileSync, writeFileSync } = require("node:fs");
|
||||
const { join } = require("node:path");
|
||||
const { isDeepStrictEqual } = require("node:util");
|
||||
|
||||
const ACCOUNT = "925323749693";
|
||||
const REGION = "us-east-1";
|
||||
const BUCKET = `warmbly-terraform-use1-${ACCOUNT}`;
|
||||
const ROLE = `arn:aws:iam::${ACCOUNT}:role/warmbly-production-terraform-apply`;
|
||||
const LB = `arn:aws:elasticloadbalancing:${REGION}:${ACCOUNT}:loadbalancer/app/warmbly-production-ingress/19d5c82c1651c871`;
|
||||
const LISTENER = `arn:aws:elasticloadbalancing:${REGION}:${ACCOUNT}:listener/app/warmbly-production-ingress/19d5c82c1651c871/d0898c3f7d2223ea`;
|
||||
const BASELINE = "ELBSecurityPolicy-TLS13-1-2-2021-06";
|
||||
const DESIRED = "ELBSecurityPolicy-TLS13-1-2-Res-2021-06";
|
||||
const PREFIX = "warmbly/production/diagnostics/origin-alb-policy";
|
||||
const WORKFLOW = "warmbly/warmbly/.github/workflows/configure-origin-alb-aws.yml@refs/heads/main";
|
||||
const hash = (bytes) => createHash("sha256").update(bytes).digest("hex");
|
||||
const canonical = (value) => JSON.stringify(value, (_, v) => v && typeof v === "object" && !Array.isArray(v)
|
||||
? Object.fromEntries(Object.keys(v).sort().map((key) => [key, v[key]])) : v);
|
||||
const same = (a, b) => isDeepStrictEqual(a, b);
|
||||
const requireThat = (condition, message) => { if (!condition) throw new Error(message); };
|
||||
const planKey = (run) => `${PREFIX}/${run}/1/plan.json`;
|
||||
function privateJSON(bytes) {
|
||||
try { return JSON.parse(bytes); } catch { throw new Error("Private input is not valid JSON"); }
|
||||
}
|
||||
|
||||
function configuration(env) {
|
||||
requireThat(env.GITHUB_ACTIONS === "true" && env.GITHUB_REPOSITORY === "warmbly/warmbly" &&
|
||||
env.GITHUB_REF === "refs/heads/main" && env.GITHUB_EVENT_NAME === "workflow_dispatch" &&
|
||||
env.GITHUB_WORKFLOW_REF === WORKFLOW && env.GITHUB_RUN_ATTEMPT === "1" &&
|
||||
/^[1-9]\d*$/.test(env.GITHUB_RUN_ID || "") && /^[a-f0-9]{40}$/.test(env.GITHUB_SHA || ""),
|
||||
"A new main workflow dispatch is required; reruns are refused");
|
||||
requireThat(env.STATE_BUCKET === BUCKET && env.APPLY_ROLE === ROLE,
|
||||
"Configure AWS_TERRAFORM_STATE_BUCKET and AWS_TERRAFORM_APPLY_ROLE_ARN through the normal aws-infrastructure configuration gate; no role fallback is permitted");
|
||||
const mode = env.ORIGIN_ALB_MODE || "plan";
|
||||
requireThat(["plan", "apply", "rollback"].includes(mode), "Unknown origin ALB mode");
|
||||
const run = env.ORIGIN_ALB_PLAN_RUN_ID || "";
|
||||
const version = env.ORIGIN_ALB_PLAN_VERSION || "";
|
||||
const digest = env.ORIGIN_ALB_PLAN_SHA256 || "";
|
||||
if (mode === "plan") requireThat(!run && !version && !digest, "Plan mode does not accept prior plan inputs");
|
||||
else requireThat(/^[1-9]\d*$/.test(run) && run !== env.GITHUB_RUN_ID &&
|
||||
/^[A-Za-z0-9_./+=-]{1,1024}$/.test(version) && version !== "null" && /^[a-f0-9]{64}$/.test(digest),
|
||||
"Apply and rollback require the exact prior plan run, version and SHA-256");
|
||||
requireThat(env.WORK && env.GITHUB_OUTPUT && env.GITHUB_STEP_SUMMARY, "Private work directory and workflow output paths are required");
|
||||
return { mode, run, version, digest, source: env.GITHUB_SHA, currentRun: env.GITHUB_RUN_ID, work: env.WORK };
|
||||
}
|
||||
|
||||
function sessionPolicy(config) {
|
||||
const statements = [
|
||||
{ Effect: "Allow", Action: ["elasticloadbalancing:Describe*", "ec2:DescribeSecurityGroups"], Resource: "*" },
|
||||
{ Effect: "Allow", Action: "s3:PutObject", Resource: `arn:aws:s3:::${BUCKET}/${PREFIX}/${config.currentRun}/1/*`,
|
||||
Condition: { StringEquals: { "s3:x-amz-server-side-encryption": "AES256", "s3:ResourceAccount": ACCOUNT },
|
||||
Bool: { "aws:SecureTransport": "true" }, Null: { "s3:if-none-match": "false" } } },
|
||||
];
|
||||
if (config.mode !== "plan") statements.push(
|
||||
{ Effect: "Allow", Action: "s3:GetObjectVersion", Resource: `arn:aws:s3:::${BUCKET}/${planKey(config.run)}` },
|
||||
{ Effect: "Allow", Action: "elasticloadbalancing:ModifyListener", Resource: LISTENER },
|
||||
);
|
||||
return { Version: "2012-10-17", Statement: statements };
|
||||
}
|
||||
|
||||
function awsCLI(service, action, args = []) {
|
||||
const result = spawnSync("aws", [service, action, ...args, "--region", REGION, "--output", "json", "--no-cli-pager"],
|
||||
{ encoding: "utf8", maxBuffer: 16 * 1024 * 1024, timeout: 60000,
|
||||
env: { ...process.env, AWS_PAGER: "", AWS_CLI_AUTO_PROMPT: "off", AWS_MAX_ATTEMPTS: "1" } });
|
||||
// Provider output stays private, including failures that may contain request data.
|
||||
if (result.error || result.status !== 0) throw new Error(`AWS ${service} ${action} failed; use the normal IAM/configuration gate if access is insufficient`);
|
||||
return privateJSON(result.stdout);
|
||||
}
|
||||
|
||||
function sorted(rows, key) {
|
||||
requireThat(Array.isArray(rows) && rows.every((row) => typeof row[key] === "string") &&
|
||||
new Set(rows.map((row) => row[key])).size === rows.length, "Incomplete or duplicate ALB response");
|
||||
return rows.sort((a, b) => a[key].localeCompare(b[key]));
|
||||
}
|
||||
|
||||
function sortedCertificates(rows) {
|
||||
requireThat(Array.isArray(rows) && rows.every((row) => typeof row.CertificateArn === "string" && typeof row.IsDefault === "boolean") &&
|
||||
new Set(rows.map((row) => canonical([row.CertificateArn, row.IsDefault]))).size === rows.length,
|
||||
"Incomplete or duplicate ALB certificate response");
|
||||
return rows.sort((a, b) => a.CertificateArn.localeCompare(b.CertificateArn) || Number(a.IsDefault) - Number(b.IsDefault));
|
||||
}
|
||||
|
||||
async function collect(aws) {
|
||||
const lb = await aws("elbv2", "describe-load-balancers", ["--load-balancer-arns", LB]);
|
||||
requireThat(lb.LoadBalancers?.length === 1 && lb.LoadBalancers[0].LoadBalancerArn === LB &&
|
||||
lb.LoadBalancers[0].Type === "application" && lb.LoadBalancers[0].State?.Code === "active", "The exact origin ALB must be active");
|
||||
const listeners = sorted((await aws("elbv2", "describe-listeners", ["--load-balancer-arn", LB])).Listeners, "ListenerArn");
|
||||
requireThat(listeners.some((l) => l.ListenerArn === LISTENER), "The bound HTTPS listener is required");
|
||||
const listenerDetails = [];
|
||||
for (const listener of listeners) {
|
||||
const details = { arn: listener.ListenerArn,
|
||||
attributes: sorted((await aws("elbv2", "describe-listener-attributes", ["--listener-arn", listener.ListenerArn])).Attributes, "Key"),
|
||||
rules: sorted((await aws("elbv2", "describe-rules", ["--listener-arn", listener.ListenerArn])).Rules, "RuleArn") };
|
||||
if (listener.Protocol === "HTTPS") details.certificates = sortedCertificates((await aws("elbv2", "describe-listener-certificates", ["--listener-arn", listener.ListenerArn])).Certificates);
|
||||
listenerDetails.push(details);
|
||||
}
|
||||
const targetGroups = sorted((await aws("elbv2", "describe-target-groups", ["--load-balancer-arn", LB])).TargetGroups, "TargetGroupArn");
|
||||
const targetAttributes = [];
|
||||
for (const tg of targetGroups) targetAttributes.push({ arn: tg.TargetGroupArn,
|
||||
attributes: sorted((await aws("elbv2", "describe-target-group-attributes", ["--target-group-arn", tg.TargetGroupArn])).Attributes, "Key") });
|
||||
const groups = lb.LoadBalancers[0].SecurityGroups;
|
||||
requireThat(Array.isArray(groups) && groups.length > 0, "ALB security groups are required");
|
||||
return { loadBalancers: lb.LoadBalancers, listeners, listenerDetails, targetGroups, targetAttributes,
|
||||
loadBalancerAttributes: sorted((await aws("elbv2", "describe-load-balancer-attributes", ["--load-balancer-arn", LB])).Attributes, "Key"),
|
||||
securityGroups: sorted((await aws("ec2", "describe-security-groups", ["--group-ids", ...groups.slice().sort()])).SecurityGroups, "GroupId") };
|
||||
}
|
||||
|
||||
function assertSnapshot(snapshot, policy) {
|
||||
requireThat(Array.isArray(snapshot?.listeners), "The complete listener inventory is required");
|
||||
const listener = snapshot?.listeners?.filter((l) => l.ListenerArn === LISTENER);
|
||||
requireThat(listener?.length === 1 && listener[0].LoadBalancerArn === LB && listener[0].Port === 443 &&
|
||||
listener[0].Protocol === "HTTPS" && listener[0].SslPolicy === policy && listener[0].Certificates?.length > 0,
|
||||
"Exact listener identity, HTTPS port, certificates and policy baseline are required");
|
||||
requireThat(snapshot.loadBalancers?.length === 1 && snapshot.loadBalancers[0].LoadBalancerArn === LB &&
|
||||
Array.isArray(snapshot.listenerDetails) && Array.isArray(snapshot.targetGroups) &&
|
||||
Array.isArray(snapshot.targetAttributes) && Array.isArray(snapshot.loadBalancerAttributes) && Array.isArray(snapshot.securityGroups),
|
||||
"A complete preserved origin snapshot is required");
|
||||
const ids = (rows, key) => rows.map((row) => row[key]).sort();
|
||||
requireThat(same(ids(snapshot.listeners, "ListenerArn"), ids(snapshot.listenerDetails, "arn")) &&
|
||||
snapshot.listenerDetails.every((d) => Array.isArray(d.attributes) && Array.isArray(d.rules)) &&
|
||||
snapshot.listenerDetails.find((d) => d.arn === LISTENER).certificates?.some((c) => c.IsDefault === true) &&
|
||||
same(ids(snapshot.targetGroups, "TargetGroupArn"), ids(snapshot.targetAttributes, "arn")) &&
|
||||
snapshot.targetAttributes.every((d) => Array.isArray(d.attributes)) &&
|
||||
snapshot.securityGroups.length > 0 && same(snapshot.loadBalancers[0].SecurityGroups.slice().sort(), ids(snapshot.securityGroups, "GroupId")),
|
||||
"Every listener, certificate inventory, target group attribute set and security group must be preserved");
|
||||
}
|
||||
|
||||
function makePlan(snapshot, config, now = new Date()) {
|
||||
assertSnapshot(snapshot, BASELINE);
|
||||
const after = structuredClone(snapshot);
|
||||
after.listeners.find((l) => l.ListenerArn === LISTENER).SslPolicy = DESIRED;
|
||||
return { schemaVersion: 1, repository: "warmbly/warmbly", workflow: WORKFLOW, source: config.source,
|
||||
run: config.currentRun, createdAt: now.toISOString(), account: ACCOUNT, region: REGION,
|
||||
changes: [{ address: "aws_lb_listener.https", action: "update", listener: LISTENER, field: "SslPolicy", before: BASELINE, after: DESIRED }],
|
||||
before: snapshot, after };
|
||||
}
|
||||
|
||||
function checkPlan(plan, config, now = new Date()) {
|
||||
requireThat(plan?.schemaVersion === 1 && plan.repository === "warmbly/warmbly" && plan.workflow === WORKFLOW &&
|
||||
plan.account === ACCOUNT && plan.region === REGION && plan.source === config.source && plan.run === config.run,
|
||||
"Plan must bind this workflow source, account, region and prior plan run");
|
||||
const age = now.getTime() - Date.parse(plan.createdAt);
|
||||
requireThat(Number.isFinite(age) && age >= 0 && age <= 24 * 60 * 60 * 1000, "Plan must be at most 24 hours old; prepare a fresh plan");
|
||||
requireThat(same(plan, makePlan(plan.before, { source: config.source, currentRun: config.run }, new Date(plan.createdAt))),
|
||||
"The complete plan may change only the bound listener SslPolicy from the exact baseline to the restricted policy");
|
||||
assertSnapshot(plan.after, DESIRED);
|
||||
}
|
||||
|
||||
async function health(aws, snapshot) {
|
||||
const routes = snapshot.listenerDetails.find((d) => d.arn === LISTENER).rules;
|
||||
const arns = new Set();
|
||||
for (const rule of routes) for (const action of rule.Actions || []) {
|
||||
if (action.TargetGroupArn) arns.add(action.TargetGroupArn);
|
||||
for (const tg of action.ForwardConfig?.TargetGroups || []) if ((tg.Weight ?? 1) > 0) arns.add(tg.TargetGroupArn);
|
||||
}
|
||||
requireThat(arns.size > 0, "HTTPS forwarding targets are required");
|
||||
const observations = [];
|
||||
for (const arn of [...arns].sort()) {
|
||||
const tg = snapshot.targetGroups.find((g) => g.TargetGroupArn === arn);
|
||||
requireThat(tg?.Protocol === "HTTPS", "Every active HTTPS route must retain HTTPS targets");
|
||||
const result = await aws("elbv2", "describe-target-health", ["--target-group-arn", arn]);
|
||||
requireThat(result.TargetHealthDescriptions?.length > 0 && result.TargetHealthDescriptions.every((t) => t.TargetHealth?.State === "healthy"),
|
||||
"Every routed HTTPS target must be healthy");
|
||||
observations.push({ arn, ...result });
|
||||
}
|
||||
return observations;
|
||||
}
|
||||
|
||||
async function put(aws, config, name, value) {
|
||||
const bytes = canonical(value) + "\n";
|
||||
const path = join(config.work, name);
|
||||
writeFileSync(path, bytes, { mode: 0o600, flag: "wx" });
|
||||
const checksum = createHash("sha256").update(bytes).digest("base64");
|
||||
const metadata = await aws("s3api", "put-object", ["--bucket", BUCKET, "--key", `${PREFIX}/${config.currentRun}/1/${name}`,
|
||||
"--expected-bucket-owner", ACCOUNT, "--server-side-encryption", "AES256", "--if-none-match", "*",
|
||||
"--checksum-algorithm", "SHA256", "--checksum-sha256", checksum, "--body", path]);
|
||||
requireThat(metadata.ServerSideEncryption === "AES256" && metadata.ChecksumSHA256 === checksum &&
|
||||
typeof metadata.VersionId === "string" && metadata.VersionId.length > 0 && metadata.VersionId !== "null", "Encrypted versioned immutable evidence is required");
|
||||
return { sha256: hash(bytes), version: metadata.VersionId };
|
||||
}
|
||||
|
||||
async function loadPlan(aws, config) {
|
||||
const path = join(config.work, "reviewed-plan.json");
|
||||
const metadata = await aws("s3api", "get-object", ["--bucket", BUCKET, "--key", planKey(config.run),
|
||||
"--version-id", config.version, "--expected-bucket-owner", ACCOUNT, path]);
|
||||
requireThat(metadata.VersionId === config.version && metadata.DeleteMarker !== true && metadata.ServerSideEncryption === "AES256",
|
||||
"The exact encrypted private plan version is required");
|
||||
const bytes = readFileSync(path);
|
||||
requireThat(hash(bytes) === config.digest, "Private plan SHA-256 differs from the reviewed digest");
|
||||
const plan = privateJSON(bytes);
|
||||
checkPlan(plan, config);
|
||||
return plan;
|
||||
}
|
||||
|
||||
async function execute(aws, config, plan, evidence) {
|
||||
const rollback = config.mode === "rollback";
|
||||
const before = rollback ? plan.after : plan.before;
|
||||
const after = rollback ? plan.before : plan.after;
|
||||
const policy = rollback ? BASELINE : DESIRED;
|
||||
evidence.preflight = await collect(aws);
|
||||
requireThat(same(evidence.preflight, before), "Live origin baseline drifted; prepare a new reviewed plan");
|
||||
evidence.healthBefore = await health(aws, before);
|
||||
await put(aws, config, "intent.json", { mode: config.mode, source: config.source, planRun: config.run,
|
||||
planVersion: config.version, planSha256: config.digest, before, after, healthBefore: evidence.healthBefore });
|
||||
// Recheck after archiving, immediately before the sole configuration write.
|
||||
evidence.prewrite = await collect(aws);
|
||||
requireThat(same(evidence.prewrite, before), "Live origin changed before the write; a new plan is required");
|
||||
evidence.writeAttempted = true;
|
||||
evidence.response = await aws("elbv2", "modify-listener", ["--listener-arn", LISTENER, "--ssl-policy", policy]);
|
||||
requireThat(evidence.response.Listeners?.length === 1 &&
|
||||
same(evidence.response.Listeners[0], after.listeners.find((l) => l.ListenerArn === LISTENER)), "Listener write response must match the exact desired listener");
|
||||
evidence.readback = await collect(aws);
|
||||
requireThat(same(evidence.readback, after), "Origin readback differs from the exact desired snapshot; inspect private evidence before scoped rollback");
|
||||
evidence.healthAfter = await health(aws, after);
|
||||
}
|
||||
|
||||
async function run(aws, config, report) {
|
||||
mkdirSync(config.work, { mode: 0o700 });
|
||||
const evidence = { mode: config.mode, source: config.source, run: config.currentRun, success: false, writeAttempted: false,
|
||||
reviewedPlan: { run: config.run, version: config.version, sha256: config.digest } };
|
||||
let message;
|
||||
let failure;
|
||||
try {
|
||||
const identity = await aws("sts", "get-caller-identity");
|
||||
requireThat(identity.Account === ACCOUNT && /^arn:aws:sts::925323749693:assumed-role\/warmbly-production-terraform-apply\/[^/]+$/.test(identity.Arn || ""),
|
||||
"The existing ordinary Terraform apply role is required");
|
||||
evidence.identity = identity;
|
||||
if (config.mode === "plan") {
|
||||
evidence.readback = await collect(aws);
|
||||
const plan = makePlan(evidence.readback, config);
|
||||
evidence.health = await health(aws, evidence.readback);
|
||||
const record = await put(aws, config, "plan.json", plan);
|
||||
message = `Plan only: one in-place origin listener SslPolicy update.\n\nPlan run: ${config.currentRun}\n\nPlan version: ${record.version}\n\nComplete plan SHA-256: ${record.sha256}\n\nReview the full private plan before a separate apply dispatch. No configuration write occurred.`;
|
||||
} else {
|
||||
const plan = await loadPlan(aws, config);
|
||||
await execute(aws, config, plan, evidence);
|
||||
message = `Origin policy ${config.mode} completed. Exact listener, certificates, attributes, rules, target groups and security groups read back unchanged apart from SslPolicy; routed HTTPS targets are healthy. Retain separate authorized origin handshake evidence.`;
|
||||
}
|
||||
evidence.success = true;
|
||||
} catch (error) {
|
||||
evidence.error = error.message;
|
||||
failure = error;
|
||||
}
|
||||
try {
|
||||
await put(aws, config, "result.json", evidence);
|
||||
} catch {
|
||||
const archiveFailure = `Result evidence archive failed; writeAttempted=${evidence.writeAttempted}`;
|
||||
if (!failure) throw new Error(archiveFailure);
|
||||
console.error(archiveFailure);
|
||||
}
|
||||
if (failure) throw failure;
|
||||
report(message);
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
process.umask(0o077);
|
||||
Promise.resolve().then(async () => {
|
||||
const config = configuration(process.env);
|
||||
const source = spawnSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" });
|
||||
requireThat(source.status === 0 && source.stdout.trim() === config.source, "Checkout must match the main workflow source");
|
||||
if (process.argv[2] === "session-policy") appendFileSync(process.env.GITHUB_OUTPUT, `policy=${canonical(sessionPolicy(config))}\n`);
|
||||
else {
|
||||
requireThat(process.argv[2] === "configure", "Unknown origin ALB command");
|
||||
await run(awsCLI, config, (message) => {
|
||||
console.log(message);
|
||||
appendFileSync(process.env.GITHUB_STEP_SUMMARY, `${message}\n`);
|
||||
});
|
||||
}
|
||||
}).catch((error) => { console.error(`Origin ALB configuration stopped: ${error.message}`); process.exitCode = 1; });
|
||||
}
|
||||
|
||||
module.exports = { ACCOUNT, BUCKET, ROLE, LB, LISTENER, BASELINE, DESIRED, PREFIX, WORKFLOW,
|
||||
configuration, sessionPolicy, collect, makePlan, checkPlan, health, put, execute, run, canonical, hash };
|
||||
@@ -0,0 +1,387 @@
|
||||
const { test } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const { mkdtempSync, readFileSync, writeFileSync, rmSync } = require("node:fs");
|
||||
const { tmpdir } = require("node:os");
|
||||
const { join } = require("node:path");
|
||||
const { ACCOUNT, BUCKET, ROLE, LB, LISTENER, BASELINE, DESIRED, PREFIX, WORKFLOW,
|
||||
configuration, sessionPolicy, collect, makePlan, checkPlan, execute, run, canonical, hash } = require("./aws-origin-alb.cjs");
|
||||
|
||||
const SOURCE = "a".repeat(40);
|
||||
const TG = `arn:aws:elasticloadbalancing:us-east-1:${ACCOUNT}:targetgroup/fixture/1234`;
|
||||
const CERT = `arn:aws:acm:us-east-1:${ACCOUNT}:certificate/fixture`;
|
||||
|
||||
function fixture(t) {
|
||||
const dir = mkdtempSync(join(tmpdir(), "origin-alb-"));
|
||||
t.after(() => rmSync(dir, { force: true, recursive: true }));
|
||||
const config = { mode: "plan", source: SOURCE, currentRun: "100", work: join(dir, "plan") };
|
||||
const listener = { ListenerArn: LISTENER, LoadBalancerArn: LB, Protocol: "HTTPS", Port: 443,
|
||||
SslPolicy: BASELINE, Certificates: [{ CertificateArn: CERT }],
|
||||
DefaultActions: [{ Type: "forward", TargetGroupArn: TG }], MutualAuthentication: { Mode: "off" } };
|
||||
const live = {
|
||||
loadBalancers: [{ LoadBalancerArn: LB, Type: "application", State: { Code: "active" }, SecurityGroups: ["sg-fixture"], DNSName: "fixture.invalid" }],
|
||||
listeners: [listener, { ListenerArn: LISTENER + "-http", LoadBalancerArn: LB, Protocol: "HTTP", Port: 80, DefaultActions: [{ Type: "redirect" }] }],
|
||||
listenerDetails: [{ arn: LISTENER, attributes: [{ Key: "fixture", Value: "true" }],
|
||||
certificates: [{ CertificateArn: CERT, IsDefault: true }],
|
||||
rules: [{ RuleArn: LISTENER + "/rule/fixture", IsDefault: true, Actions: listener.DefaultActions }] },
|
||||
{ arn: LISTENER + "-http", attributes: [], rules: [] }],
|
||||
targetGroups: [{ TargetGroupArn: TG, Protocol: "HTTPS", Port: 8443 }],
|
||||
targetAttributes: [{ arn: TG, attributes: [{ Key: "deregistration_delay.timeout_seconds", Value: "30" }] }],
|
||||
loadBalancerAttributes: [{ Key: "deletion_protection.enabled", Value: "true" }],
|
||||
securityGroups: [{ GroupId: "sg-fixture", IpPermissions: [{ IpProtocol: "tcp", FromPort: 443, ToPort: 443 }] }],
|
||||
};
|
||||
const calls = [];
|
||||
const objects = new Map();
|
||||
let unhealthy = false;
|
||||
const aws = async (service, action, args = []) => {
|
||||
calls.push({ service, action, args: structuredClone(args) });
|
||||
const arg = (name) => args[args.indexOf(name) + 1];
|
||||
switch (`${service}:${action}`) {
|
||||
case "sts:get-caller-identity": return { Account: ACCOUNT, Arn: `arn:aws:sts::${ACCOUNT}:assumed-role/warmbly-production-terraform-apply/fixture` };
|
||||
case "elbv2:describe-load-balancers": return { LoadBalancers: structuredClone(live.loadBalancers) };
|
||||
case "elbv2:describe-listeners": return { Listeners: structuredClone(live.listeners) };
|
||||
case "elbv2:describe-listener-attributes": return { Attributes: structuredClone(live.listenerDetails.find((d) => d.arn === arg("--listener-arn")).attributes) };
|
||||
case "elbv2:describe-listener-certificates": return { Certificates: structuredClone(live.listenerDetails.find((d) => d.arn === arg("--listener-arn")).certificates) };
|
||||
case "elbv2:describe-rules": return { Rules: structuredClone(live.listenerDetails.find((d) => d.arn === arg("--listener-arn")).rules) };
|
||||
case "elbv2:describe-target-groups": return { TargetGroups: structuredClone(live.targetGroups) };
|
||||
case "elbv2:describe-target-group-attributes": return { Attributes: structuredClone(live.targetAttributes.find((d) => d.arn === arg("--target-group-arn")).attributes) };
|
||||
case "elbv2:describe-load-balancer-attributes": return { Attributes: structuredClone(live.loadBalancerAttributes) };
|
||||
case "ec2:describe-security-groups": return { SecurityGroups: structuredClone(live.securityGroups) };
|
||||
case "elbv2:describe-target-health": return { TargetHealthDescriptions: [{ Target: { Id: "192.0.2.1", Port: 8443 }, TargetHealth: { State: unhealthy ? "unhealthy" : "healthy" } }] };
|
||||
case "elbv2:modify-listener": {
|
||||
assert.deepEqual(args.slice(0, 3), ["--listener-arn", LISTENER, "--ssl-policy"]);
|
||||
assert.equal(args.length, 4);
|
||||
live.listeners[0].SslPolicy = arg("--ssl-policy");
|
||||
return { Listeners: [structuredClone(live.listeners[0])] };
|
||||
}
|
||||
case "s3api:put-object": {
|
||||
const key = arg("--key");
|
||||
assert.equal(arg("--bucket"), BUCKET);
|
||||
assert.equal(arg("--expected-bucket-owner"), ACCOUNT);
|
||||
assert.equal(arg("--if-none-match"), "*");
|
||||
assert.equal(arg("--server-side-encryption"), "AES256");
|
||||
assert.ok(!objects.has(key), "immutable evidence cannot be overwritten");
|
||||
const bytes = readFileSync(arg("--body"));
|
||||
const metadata = { VersionId: `version-${objects.size}`, ChecksumSHA256: Buffer.from(hash(bytes), "hex").toString("base64"), ServerSideEncryption: "AES256" };
|
||||
assert.equal(arg("--checksum-sha256"), metadata.ChecksumSHA256);
|
||||
objects.set(key, { bytes, metadata });
|
||||
return metadata;
|
||||
}
|
||||
case "s3api:get-object": {
|
||||
assert.equal(arg("--bucket"), BUCKET);
|
||||
assert.equal(arg("--expected-bucket-owner"), ACCOUNT);
|
||||
const object = objects.get(arg("--key"));
|
||||
assert.equal(arg("--version-id"), object.metadata.VersionId);
|
||||
writeFileSync(args.at(-1), object.bytes);
|
||||
return object.metadata;
|
||||
}
|
||||
default: throw new Error(`Unexpected API ${service}:${action}`);
|
||||
}
|
||||
};
|
||||
const writeCalls = () => calls.filter((c) => c.action === "modify-listener");
|
||||
const reports = [];
|
||||
const plan = async () => {
|
||||
await run(aws, config, (s) => {
|
||||
assert.ok(objects.has(`${PREFIX}/100/1/result.json`));
|
||||
reports.push(s);
|
||||
});
|
||||
const object = objects.get(`${PREFIX}/100/1/plan.json`);
|
||||
return { mode: "apply", source: SOURCE, currentRun: "200", run: "100", version: object.metadata.VersionId,
|
||||
digest: hash(object.bytes), work: join(dir, "apply") };
|
||||
};
|
||||
return { config, live, calls, objects, aws, writeCalls, reports, plan, dir, setUnhealthy: () => { unhealthy = true; } };
|
||||
}
|
||||
|
||||
function env() {
|
||||
return { GITHUB_ACTIONS: "true", GITHUB_REPOSITORY: "warmbly/warmbly", GITHUB_REF: "refs/heads/main", GITHUB_EVENT_NAME: "workflow_dispatch",
|
||||
GITHUB_WORKFLOW_REF: WORKFLOW, GITHUB_RUN_ATTEMPT: "1", GITHUB_RUN_ID: "100", GITHUB_SHA: SOURCE,
|
||||
STATE_BUCKET: BUCKET, APPLY_ROLE: ROLE, WORK: "/tmp/fixture", GITHUB_OUTPUT: "/tmp/output", GITHUB_STEP_SUMMARY: "/tmp/summary" };
|
||||
}
|
||||
|
||||
test("default plan is main-only, refuses reruns, invalid scope and missing ordinary environment configuration", () => {
|
||||
assert.equal(configuration(env()).mode, "plan");
|
||||
for (const changes of [{ GITHUB_REF: "refs/heads/feature" }, { GITHUB_RUN_ATTEMPT: "2" }, { GITHUB_EVENT_NAME: "push" },
|
||||
{ GITHUB_WORKFLOW_REF: "other" }, { APPLY_ROLE: "" }, { STATE_BUCKET: "" }, { STATE_BUCKET: "other" },
|
||||
{ ORIGIN_ALB_MODE: "apply" }, { ORIGIN_ALB_MODE: "recovery" }, { ORIGIN_ALB_PLAN_RUN_ID: "99" }]) {
|
||||
assert.throws(() => configuration({ ...env(), ...changes }));
|
||||
}
|
||||
const apply = { ...env(), ORIGIN_ALB_MODE: "apply", ORIGIN_ALB_PLAN_RUN_ID: "99", ORIGIN_ALB_PLAN_VERSION: "version-1", ORIGIN_ALB_PLAN_SHA256: "f".repeat(64) };
|
||||
assert.equal(configuration(apply).run, "99");
|
||||
for (const changes of [{ ORIGIN_ALB_PLAN_RUN_ID: "100" }, { ORIGIN_ALB_PLAN_RUN_ID: "../other" },
|
||||
{ ORIGIN_ALB_PLAN_VERSION: "null" }, { ORIGIN_ALB_PLAN_VERSION: "invalid\nvalue" }, { ORIGIN_ALB_PLAN_SHA256: "bad" }]) {
|
||||
assert.throws(() => configuration({ ...apply, ...changes }));
|
||||
}
|
||||
});
|
||||
|
||||
test("session permissions intersect the existing role: no listener writes in plan, exact listener in apply, conditional private writes only", () => {
|
||||
const config = configuration(env());
|
||||
const plan = sessionPolicy(config);
|
||||
assert.ok(!canonical(plan).includes("ModifyListener"));
|
||||
assert.ok(!canonical(plan).includes("GetObject"));
|
||||
const apply = sessionPolicy({ ...config, mode: "apply", run: "99" });
|
||||
assert.deepEqual(apply.Statement.find((s) => s.Action === "elasticloadbalancing:ModifyListener"),
|
||||
{ Effect: "Allow", Action: "elasticloadbalancing:ModifyListener", Resource: LISTENER });
|
||||
const write = apply.Statement.find((s) => s.Action === "s3:PutObject");
|
||||
assert.equal(write.Resource, `arn:aws:s3:::${BUCKET}/${PREFIX}/100/1/*`);
|
||||
assert.equal(write.Condition.Null["s3:if-none-match"], "false");
|
||||
assert.equal(write.Condition.StringEquals["s3:x-amz-server-side-encryption"], "AES256");
|
||||
assert.equal(apply.Statement.find((s) => s.Action === "s3:GetObjectVersion").Resource, `arn:aws:s3:::${BUCKET}/${PREFIX}/99/1/plan.json`);
|
||||
const actions = apply.Statement.flatMap((s) => s.Action);
|
||||
assert.ok(!/secretsmanager|iam:|ecs:|DeleteObject|ModifyRule|Create/.test(actions.join(" ")));
|
||||
});
|
||||
|
||||
test("dry plan archives the complete baseline and exact change without a configuration write", async (t) => {
|
||||
const f = fixture(t);
|
||||
const baseline = structuredClone(f.live);
|
||||
await f.plan();
|
||||
assert.deepEqual(f.live, baseline);
|
||||
assert.equal(f.writeCalls().length, 0);
|
||||
const plan = JSON.parse(f.objects.get(`${PREFIX}/100/1/plan.json`).bytes);
|
||||
checkPlan(plan, { source: SOURCE, run: "100" });
|
||||
assert.equal(plan.before.listeners[0].SslPolicy, BASELINE);
|
||||
assert.equal(plan.after.listeners[0].SslPolicy, DESIRED);
|
||||
assert.ok(f.reports[0].includes("Complete plan SHA-256"));
|
||||
assert.ok(f.objects.has(`${PREFIX}/100/1/result.json`));
|
||||
});
|
||||
|
||||
test("complete plan guard rejects unrelated changes, replacements, missing identity and baseline drift", async (t) => {
|
||||
const f = fixture(t);
|
||||
const plan = makePlan(await collect(f.aws), f.config);
|
||||
const config = { source: SOURCE, run: "100" };
|
||||
for (const mutate of [
|
||||
(p) => { p.changes.push({ address: "aws_ecs_service.backend", action: "update" }); },
|
||||
(p) => { p.changes[0].action = "replace"; },
|
||||
(p) => { p.after.listeners[0].Port = 8443; },
|
||||
(p) => { p.after.listeners[0].Certificates[0].CertificateArn = "other"; },
|
||||
(p) => { p.after.listeners[0].DefaultActions = []; },
|
||||
(p) => { p.after.listeners[0].MutualAuthentication.Mode = "verify"; },
|
||||
(p) => { p.after.listeners[1].Port = 81; },
|
||||
(p) => { p.after.listenerDetails[0].rules = []; },
|
||||
(p) => { p.after.targetGroups[0].Port = 80; },
|
||||
(p) => { p.after.securityGroups[0].IpPermissions = []; },
|
||||
(p) => { p.before.listeners[0].SslPolicy = DESIRED; },
|
||||
(p) => { p.before.listeners[0].ListenerArn += "other"; },
|
||||
(p) => { p.before.listeners[0].LoadBalancerArn += "other"; },
|
||||
(p) => { p.before.listenerDetails = []; },
|
||||
(p) => { p.before.listenerDetails[0].certificates = []; },
|
||||
(p) => { p.before.targetAttributes = []; },
|
||||
(p) => { p.before.securityGroups = []; },
|
||||
(p) => { p.after.extra = "unreviewed"; },
|
||||
(p) => { p.source = "b".repeat(40); },
|
||||
(p) => { p.createdAt = "2000-01-01T00:00:00Z"; },
|
||||
(p) => { p.createdAt = "2999-01-01T00:00:00Z"; },
|
||||
]) {
|
||||
const invalid = structuredClone(plan);
|
||||
mutate(invalid);
|
||||
assert.throws(() => checkPlan(invalid, config));
|
||||
}
|
||||
});
|
||||
|
||||
test("apply changes only ssl policy after immutable intent and verifies the entire origin configuration", async (t) => {
|
||||
const f = fixture(t);
|
||||
const config = await f.plan();
|
||||
const before = structuredClone(f.live);
|
||||
await run(f.aws, config, (s) => {
|
||||
assert.ok(f.objects.has(`${PREFIX}/200/1/result.json`));
|
||||
f.reports.push(s);
|
||||
});
|
||||
const expected = structuredClone(before);
|
||||
expected.listeners[0].SslPolicy = DESIRED;
|
||||
assert.deepEqual(f.live, expected);
|
||||
assert.deepEqual(f.writeCalls(), [{ service: "elbv2", action: "modify-listener", args: ["--listener-arn", LISTENER, "--ssl-policy", DESIRED] }]);
|
||||
const intentIndex = f.calls.findIndex((c) => c.action === "put-object" && c.args.includes(`${PREFIX}/200/1/intent.json`));
|
||||
const writeIndex = f.calls.findIndex((c) => c.action === "modify-listener");
|
||||
assert.ok(intentIndex >= 0 && intentIndex < writeIndex);
|
||||
assert.equal(JSON.parse(f.objects.get(`${PREFIX}/200/1/result.json`).bytes).success, true);
|
||||
});
|
||||
|
||||
for (const mode of ["plan", "apply", "rollback"]) test(`${mode} completion requires a successful result archive`, async (t) => {
|
||||
const f = fixture(t);
|
||||
let config = f.config;
|
||||
if (mode !== "plan") config = await f.plan();
|
||||
if (mode === "rollback") {
|
||||
await run(f.aws, config, () => {});
|
||||
config = { ...config, mode, currentRun: "300", work: join(f.dir, "rollback") };
|
||||
}
|
||||
const resultKey = `${PREFIX}/${config.currentRun}/1/result.json`;
|
||||
const reports = [];
|
||||
const logs = [];
|
||||
let archivedEvidence;
|
||||
let reportsAtArchive;
|
||||
t.mock.method(console, "error", (...args) => logs.push(args));
|
||||
const aws = async (service, action, args) => {
|
||||
if (action === "put-object" && args.includes(resultKey)) {
|
||||
reportsAtArchive = [...reports];
|
||||
archivedEvidence = JSON.parse(readFileSync(args[args.indexOf("--body") + 1]));
|
||||
throw new Error("Private archive provider response\ncredential=fixture-secret");
|
||||
}
|
||||
return f.aws(service, action, args);
|
||||
};
|
||||
await assert.rejects(run(aws, config, (s) => reports.push(s)), {
|
||||
message: `Result evidence archive failed; writeAttempted=${mode !== "plan"}`,
|
||||
});
|
||||
assert.equal(archivedEvidence.success, true);
|
||||
assert.equal(archivedEvidence.writeAttempted, mode !== "plan");
|
||||
assert.deepEqual(reportsAtArchive, []);
|
||||
assert.deepEqual(reports, []);
|
||||
assert.deepEqual(logs, []);
|
||||
assert.ok(!f.objects.has(resultKey));
|
||||
assert.equal(f.live.listeners[0].SslPolicy, mode === "apply" ? DESIRED : BASELINE);
|
||||
assert.equal(f.writeCalls().length, mode === "plan" ? 0 : mode === "apply" ? 1 : 2);
|
||||
});
|
||||
|
||||
for (const writeAttempted of [false, true]) test(`operation error survives result archive failure with writeAttempted=${writeAttempted}`, async (t) => {
|
||||
const f = fixture(t);
|
||||
const config = await f.plan();
|
||||
const resultKey = `${PREFIX}/200/1/result.json`;
|
||||
const operationError = new Error("Origin policy operation failed");
|
||||
const reports = [];
|
||||
const logs = [];
|
||||
let archivedEvidence;
|
||||
t.mock.method(console, "error", (...args) => logs.push(args));
|
||||
const aws = async (service, action, args) => {
|
||||
if (!writeAttempted && action === "get-caller-identity") throw operationError;
|
||||
if (action === "put-object" && args.includes(resultKey)) {
|
||||
archivedEvidence = JSON.parse(readFileSync(args[args.indexOf("--body") + 1]));
|
||||
throw new Error("Private archive provider response\ncredential=fixture-secret");
|
||||
}
|
||||
const response = await f.aws(service, action, args);
|
||||
if (action === "modify-listener") throw operationError;
|
||||
return response;
|
||||
};
|
||||
await assert.rejects(run(aws, config, (s) => reports.push(s)), (error) => error === operationError);
|
||||
assert.equal(archivedEvidence.success, false);
|
||||
assert.equal(archivedEvidence.error, operationError.message);
|
||||
assert.equal(archivedEvidence.writeAttempted, writeAttempted);
|
||||
assert.deepEqual(reports, []);
|
||||
assert.deepEqual(logs, [[`Result evidence archive failed; writeAttempted=${writeAttempted}`]]);
|
||||
assert.ok(!f.objects.has(resultKey));
|
||||
assert.equal(f.writeCalls().length, writeAttempted ? 1 : 0);
|
||||
});
|
||||
|
||||
test("scoped rollback uses the same exact reviewed plan and restores only the baseline policy", async (t) => {
|
||||
const f = fixture(t);
|
||||
const config = await f.plan();
|
||||
const baseline = structuredClone(f.live);
|
||||
await run(f.aws, config, () => {});
|
||||
await run(f.aws, { ...config, mode: "rollback", currentRun: "300", work: join(f.dir, "rollback") }, () => {});
|
||||
assert.deepEqual(f.live, baseline);
|
||||
assert.deepEqual(f.writeCalls().map((c) => c.args), [["--listener-arn", LISTENER, "--ssl-policy", DESIRED], ["--listener-arn", LISTENER, "--ssl-policy", BASELINE]]);
|
||||
});
|
||||
|
||||
for (const defaultFirst of [true, false]) test(`plan, apply and rollback preserve default and SNI certificate entries with default first: ${defaultFirst}`, async (t) => {
|
||||
const f = fixture(t);
|
||||
const certificates = [{ CertificateArn: CERT, IsDefault: false }, { CertificateArn: CERT, IsDefault: true }];
|
||||
const inventory = f.live.listenerDetails.find((d) => d.arn === LISTENER);
|
||||
inventory.certificates = structuredClone(certificates);
|
||||
if (defaultFirst) inventory.certificates.reverse();
|
||||
const baseline = structuredClone(f.live);
|
||||
const config = await f.plan();
|
||||
assert.deepEqual(f.live, baseline);
|
||||
assert.equal(f.writeCalls().length, 0);
|
||||
const plan = JSON.parse(f.objects.get(`${PREFIX}/100/1/plan.json`).bytes);
|
||||
checkPlan(plan, { source: SOURCE, run: "100" });
|
||||
for (const snapshot of [plan.before, plan.after]) {
|
||||
assert.deepEqual(snapshot.listenerDetails.find((d) => d.arn === LISTENER).certificates, certificates);
|
||||
}
|
||||
for (const [mode, currentRun, policy] of [["apply", "200", DESIRED], ["rollback", "300", BASELINE]]) {
|
||||
inventory.certificates.reverse();
|
||||
const expected = structuredClone(f.live);
|
||||
expected.listeners[0].SslPolicy = policy;
|
||||
await run(f.aws, { ...config, mode, currentRun, work: join(f.dir, mode) }, () => {});
|
||||
assert.deepEqual(f.live, expected);
|
||||
const result = JSON.parse(f.objects.get(`${PREFIX}/${currentRun}/1/result.json`).bytes);
|
||||
assert.equal(result.success, true);
|
||||
assert.deepEqual(result.readback.listenerDetails.find((d) => d.arn === LISTENER).certificates, certificates);
|
||||
}
|
||||
assert.deepEqual(f.live, baseline);
|
||||
assert.deepEqual(f.writeCalls().map((c) => c.args), [["--listener-arn", LISTENER, "--ssl-policy", DESIRED], ["--listener-arn", LISTENER, "--ssl-policy", BASELINE]]);
|
||||
});
|
||||
|
||||
test("certificate inventory requires distinct ARN and default-status pairs with boolean status", async (t) => {
|
||||
for (const status of [true, false, undefined, "true"]) {
|
||||
const f = fixture(t);
|
||||
f.live.listenerDetails[0].certificates = [
|
||||
{ CertificateArn: CERT, IsDefault: status }, { CertificateArn: CERT, IsDefault: status },
|
||||
];
|
||||
await assert.rejects(collect(f.aws), /Incomplete or duplicate ALB certificate response/);
|
||||
assert.equal(f.writeCalls().length, 0);
|
||||
}
|
||||
});
|
||||
|
||||
test("certificate inventory rejects a single certificate with non-boolean default status", async (t) => {
|
||||
for (const status of [undefined, "true"]) {
|
||||
const f = fixture(t);
|
||||
f.live.listenerDetails[0].certificates = [{ CertificateArn: CERT, IsDefault: status }];
|
||||
await assert.rejects(collect(f.aws), /Incomplete or duplicate ALB certificate response/);
|
||||
assert.equal(f.writeCalls().length, 0);
|
||||
}
|
||||
});
|
||||
|
||||
for (const [label, drift] of [
|
||||
["policy", (f) => { f.live.listeners[0].SslPolicy = DESIRED; }],
|
||||
["certificate", (f) => { f.live.listeners[0].Certificates = []; }],
|
||||
["HTTP listener", (f) => { f.live.listeners[1].Port = 81; }],
|
||||
["rule", (f) => { f.live.listenerDetails[0].rules[0].Actions = []; }],
|
||||
["target group", (f) => { f.live.targetGroups[0].Port = 80; }],
|
||||
["security group", (f) => { f.live.securityGroups[0].IpPermissions = []; }],
|
||||
["listener attribute", (f) => { f.live.listenerDetails[0].attributes[0].Value = "false"; }],
|
||||
]) test(`apply refuses ${label} baseline drift before mutation`, async (t) => {
|
||||
const f = fixture(t);
|
||||
const config = await f.plan();
|
||||
drift(f);
|
||||
await assert.rejects(run(f.aws, config, () => {}), /baseline drifted/);
|
||||
assert.equal(f.writeCalls().length, 0);
|
||||
assert.equal(JSON.parse(f.objects.get(`${PREFIX}/200/1/result.json`).bytes).success, false);
|
||||
});
|
||||
|
||||
test("drift immediately after intent archival and rollback drift both refuse mutation", async (t) => {
|
||||
const f = fixture(t);
|
||||
const config = await f.plan();
|
||||
const plan = JSON.parse(f.objects.get(`${PREFIX}/100/1/plan.json`).bytes);
|
||||
const evidence = {};
|
||||
const aws = async (service, action, args) => {
|
||||
const out = await f.aws(service, action, args);
|
||||
if (action === "put-object") f.live.listeners[0].Port = 8443;
|
||||
return out;
|
||||
};
|
||||
// execute writes its intent into an existing private runner directory.
|
||||
await assert.rejects(execute(aws, { ...config, work: f.dir }, plan, evidence), /changed before the write/);
|
||||
assert.equal(f.writeCalls().length, 0);
|
||||
f.live.listeners[0].SslPolicy = DESIRED;
|
||||
await assert.rejects(run(f.aws, { ...config, mode: "rollback", currentRun: "300", work: join(f.dir, "rollback") }, () => {}), /baseline drifted/);
|
||||
assert.equal(f.writeCalls().length, 0);
|
||||
});
|
||||
|
||||
test("altered plan bytes, stale source, unhealthy targets and failed immutable archive refuse writes", async (t) => {
|
||||
for (const variant of ["digest", "source", "health", "archive", "versioning", "identity"]) {
|
||||
const f = fixture(t);
|
||||
const config = await f.plan();
|
||||
if (variant === "digest") config.digest = "f".repeat(64);
|
||||
if (variant === "source") config.source = "b".repeat(40);
|
||||
if (variant === "health") f.setUnhealthy();
|
||||
const aws = async (service, action, args) => {
|
||||
if (variant === "archive" && action === "put-object") throw new Error("Evidence permission denied");
|
||||
const response = await f.aws(service, action, args);
|
||||
if (variant === "versioning" && action === "put-object") delete response.VersionId;
|
||||
if (variant === "identity" && action === "get-caller-identity") response.Account = "000000000000";
|
||||
return response;
|
||||
};
|
||||
await assert.rejects(run(aws, config, () => {}));
|
||||
assert.equal(f.writeCalls().length, 0);
|
||||
}
|
||||
});
|
||||
|
||||
test("failed postwrite verification records attempted write and does not automatically overwrite concurrent changes", async (t) => {
|
||||
const f = fixture(t);
|
||||
const config = await f.plan();
|
||||
const aws = async (service, action, args) => {
|
||||
const out = await f.aws(service, action, args);
|
||||
if (action === "modify-listener") f.live.listeners[0].Port = 8443;
|
||||
return out;
|
||||
};
|
||||
await assert.rejects(run(aws, config, () => {}), /readback differs/);
|
||||
assert.equal(f.writeCalls().length, 1);
|
||||
const result = JSON.parse(f.objects.get(`${PREFIX}/200/1/result.json`).bytes);
|
||||
assert.equal(result.writeAttempted, true);
|
||||
assert.equal(result.success, false);
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/../.."
|
||||
ruby -ryaml <<'RUBY'
|
||||
workflow = YAML.load_file('.github/workflows/probe-origin-tls-aws.yml')
|
||||
trigger = workflow['on'] || workflow[true]
|
||||
raise 'only manual execution and offline checks are supported' unless trigger.keys.sort == ['pull_request', 'workflow_dispatch']
|
||||
raise 'no arbitrary execution inputs are supported' unless trigger['workflow_dispatch'].nil?
|
||||
jobs = workflow.fetch('jobs')
|
||||
raise 'only checks and a diagnostic belong here' unless jobs.keys.sort == ['check', 'probe']
|
||||
job = jobs.fetch('probe')
|
||||
raise 'manual diagnostic must follow checks' unless job['needs'] == 'check' && job['if'] == "github.event_name == 'workflow_dispatch'"
|
||||
raise 'ordinary environment required' unless job['environment'] == 'aws-infrastructure'
|
||||
raise 'production serialization required' unless job.dig('concurrency', 'group') == 'aws-production' && job.dig('concurrency', 'cancel-in-progress') == false
|
||||
raise 'bounded job required' unless job['timeout-minutes'] == 25
|
||||
raise 'only contents and OIDC permissions needed' unless job['permissions'] == {'contents'=>'read', 'id-token'=>'write'}
|
||||
steps = job.fetch('steps')
|
||||
credentials = steps.select { |s| s['uses'] == 'aws-actions/configure-aws-credentials@v4' }
|
||||
raise 'separate probe and cleanup credentials required' unless credentials.map { |s| s['id'] } == ['credentials', 'cleanup_credentials']
|
||||
['probe', 'cleanup'].each_with_index do |phase, i|
|
||||
raise 'existing role with phase policy and no credential reuse required' unless credentials[i]['with'] == {
|
||||
'role-to-assume'=>'${{ vars.AWS_TERRAFORM_APPLY_ROLE_ARN }}', 'aws-region'=>'us-east-1',
|
||||
'unset-current-credentials'=>true,
|
||||
'inline-session-policy'=>"${{ steps.scope.outputs.#{phase}_policy }}"
|
||||
}
|
||||
end
|
||||
scope = steps.index { |s| s['run'] == 'node .github/scripts/aws-origin-tls.cjs session-policy' }
|
||||
raise 'source gate must precede credentials' unless scope && steps[scope]['id'] == 'scope' && scope < steps.index(credentials[0])
|
||||
raise 'probe credentials require the successful source gate' if credentials[0]['if']
|
||||
probe = steps.find { |s| s['run'] == 'node .github/scripts/aws-origin-tls.cjs probe' }
|
||||
raise 'probe requires its successful credentials and timeout' unless probe && probe['timeout-minutes'] == 10 &&
|
||||
probe['if'] == "success() && steps.credentials.outcome == 'success'"
|
||||
raise 'probe must run once immediately after its credentials' unless steps.count { |s| s['run'] == probe['run'] } == 1 &&
|
||||
steps.index(probe) == steps.index(credentials[0]) + 1
|
||||
raise 'cleanup credentials must follow probe failure or credential failure after a successful source gate' unless
|
||||
credentials[1]['if'] == "always() && steps.scope.outcome == 'success'" && credentials[1]['timeout-minutes'] == 2 &&
|
||||
steps.index(credentials[1]) == steps.index(probe) + 1
|
||||
cleanup = steps.last
|
||||
raise 'bounded finalizer must require successful cleanup credentials with no earlier-session fallback' unless
|
||||
cleanup['run'] == 'node .github/scripts/aws-origin-tls.cjs finish' &&
|
||||
cleanup['if'] == "always() && steps.cleanup_credentials.outcome == 'success'" && cleanup['timeout-minutes'] == 8 &&
|
||||
steps.index(cleanup) == steps.index(credentials[1]) + 1
|
||||
raise 'no secret inheritance, bypasses or public artifacts' if workflow.to_s.match?(/secrets|upload-artifact|AWS_TERRAFORM_ENABLED|AWS_TLS_RECOVERY|terraform apply|deploy-aws/)
|
||||
jobs.each_value do |j|
|
||||
raise 'failures must stop execution' if j['continue-on-error']
|
||||
j.fetch('steps').each do |s|
|
||||
raise 'step failures must stop execution' if s['continue-on-error']
|
||||
raise 'checkout credentials must not persist' if s['uses'] == 'actions/checkout@v4' && s.dig('with', 'persist-credentials') != false
|
||||
end
|
||||
end
|
||||
puts 'Origin TLS workflow source gate, phase credentials, failure gating, ordinary environment and bounded cleanup checks passed'
|
||||
RUBY
|
||||
@@ -0,0 +1,306 @@
|
||||
const { spawnSync } = require("node:child_process");
|
||||
const { appendFileSync, mkdirSync, readFileSync, writeFileSync, existsSync } = require("node:fs");
|
||||
const { join } = require("node:path");
|
||||
const { ACCOUNT, BUCKET, ROLE, LB, LISTENER, DESIRED, hash, canonical } = require("./aws-origin-alb.cjs");
|
||||
const { CBC, GCM, TLS13, classify, validTargets } = require("./origin-tls-client.cjs");
|
||||
|
||||
const REGION = "us-east-1";
|
||||
const ECS = `arn:aws:ecs:${REGION}:${ACCOUNT}`;
|
||||
const CLUSTER = `${ECS}:cluster/warmbly-production`;
|
||||
const SERVICE = `${ECS}:service/warmbly-production/warmbly-production-backend`;
|
||||
const EXECUTION = `arn:aws:iam::${ACCOUNT}:role/warmbly-production-validation-execution`;
|
||||
const VPC = "vpc-038e4f0058030800b";
|
||||
const SG = "sg-0ddd1eb3234dad9e7";
|
||||
const ALB_SG = "sg-03a4f6f8010daff8d";
|
||||
const LOG = "/ecs/warmbly-production/validation";
|
||||
const PREFIX = "warmbly/production/diagnostics/origin-tls";
|
||||
// Official Node 22 bookworm ARM64 manifest, including OpenSSL and Debian public CAs.
|
||||
const IMAGE = "docker.io/library/node@sha256:a288699fc0f9676950742fae6efcd015180aa7ef2bf8a6477e4b0a8cc0ab1b3f";
|
||||
const requireThat = (ok, message) => { if (!ok) throw new Error(message); };
|
||||
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
const originIdentity = (enis) => canonical(enis.map((e) =>
|
||||
[e.NetworkInterfaceId, e.PrivateIpAddress, e.AvailabilityZone, e.SubnetId]).sort());
|
||||
|
||||
function configuration(env) {
|
||||
requireThat(env.GITHUB_ACTIONS === "true" && env.GITHUB_REPOSITORY === "warmbly/warmbly" &&
|
||||
env.GITHUB_REF === "refs/heads/main" && env.GITHUB_EVENT_NAME === "workflow_dispatch" &&
|
||||
env.GITHUB_WORKFLOW_REF === "warmbly/warmbly/.github/workflows/probe-origin-tls-aws.yml@refs/heads/main" &&
|
||||
env.GITHUB_RUN_ATTEMPT === "1" && /^[1-9]\d*$/.test(env.GITHUB_RUN_ID || "") &&
|
||||
/^[a-f0-9]{40}$/.test(env.GITHUB_SHA || ""), "A new main workflow dispatch is required; reruns are refused");
|
||||
requireThat(env.STATE_BUCKET === BUCKET && env.APPLY_ROLE === ROLE && env.WORK &&
|
||||
env.GITHUB_OUTPUT && env.GITHUB_STEP_SUMMARY, "Normal aws-infrastructure role, bucket and private paths required");
|
||||
return { run: env.GITHUB_RUN_ID, source: env.GITHUB_SHA, work: env.WORK,
|
||||
family: `warmbly-production-origin-tls-${env.GITHUB_RUN_ID}`, startedBy: `origin-tls-${env.GITHUB_RUN_ID}` };
|
||||
}
|
||||
|
||||
function sessionPolicy(config, phase) {
|
||||
requireThat(phase === "probe" || phase === "cleanup", "Explicit diagnostic credential phase required");
|
||||
const statements = phase === "probe" ? [
|
||||
{ Effect: "Allow", Action: ["elasticloadbalancing:DescribeLoadBalancers", "elasticloadbalancing:DescribeListeners",
|
||||
"ec2:DescribeNetworkInterfaces", "ec2:DescribeSubnets", "ecs:RegisterTaskDefinition"], Resource: "*" },
|
||||
{ Effect: "Allow", Action: "ecs:DescribeServices", Resource: SERVICE },
|
||||
{ Effect: "Allow", Action: "ecs:RunTask", Resource: `${ECS}:task-definition/${config.family}:*`,
|
||||
Condition: { ArnEquals: { "ecs:cluster": CLUSTER } } },
|
||||
{ Effect: "Allow", Action: "ecs:DescribeTasks", Resource: `${ECS}:task/warmbly-production/*` },
|
||||
{ Effect: "Allow", Action: "iam:PassRole", Resource: EXECUTION,
|
||||
Condition: { StringEquals: { "iam:PassedToService": "ecs-tasks.amazonaws.com" } } },
|
||||
] : [
|
||||
{ Effect: "Allow", Action: ["ecs:ListTaskDefinitions", "ecs:ListTasks"], Resource: "*" },
|
||||
{ Effect: "Allow", Action: "ecs:DeregisterTaskDefinition", Resource: "*" },
|
||||
{ Effect: "Allow", Action: ["ecs:DescribeTasks", "ecs:StopTask"], Resource: `${ECS}:task/warmbly-production/*` },
|
||||
{ Effect: "Allow", Action: "logs:GetLogEvents", Resource: `arn:aws:logs:${REGION}:${ACCOUNT}:log-group:${LOG}:log-stream:origin-tls-${config.run}/*` },
|
||||
];
|
||||
return { Version: "2012-10-17", Statement: [...statements,
|
||||
{ Effect: "Allow", Action: "s3:PutObject", Resource: `arn:aws:s3:::${BUCKET}/${PREFIX}/${config.run}/1/*`,
|
||||
Condition: { StringEquals: { "s3:x-amz-server-side-encryption": "AES256", "s3:ResourceAccount": ACCOUNT },
|
||||
Bool: { "aws:SecureTransport": "true" }, Null: { "s3:if-none-match": "false" } } },
|
||||
] };
|
||||
}
|
||||
|
||||
function awsCLI(service, action, args = []) {
|
||||
const result = spawnSync("aws", [service, action, ...args, "--region", REGION, "--output", "json", "--no-cli-pager",
|
||||
"--cli-connect-timeout", "5", "--cli-read-timeout", "8"], { encoding: "utf8", timeout: 15000,
|
||||
maxBuffer: 4 * 1024 * 1024, env: { ...process.env, AWS_PAGER: "", AWS_CLI_AUTO_PROMPT: "off", AWS_MAX_ATTEMPTS: "1" } });
|
||||
requireThat(!result.error && result.status === 0, `AWS ${service} ${action} failed; inspect normal access/configuration prerequisites`);
|
||||
try { return JSON.parse(result.stdout); } catch { throw new Error("AWS diagnostic response was not valid JSON"); }
|
||||
}
|
||||
|
||||
async function discover(aws) {
|
||||
const lb = (await aws("elbv2", "describe-load-balancers", ["--load-balancer-arns", LB])).LoadBalancers;
|
||||
requireThat(lb?.length === 1 && lb[0].LoadBalancerArn === LB && lb[0].VpcId === VPC &&
|
||||
lb[0].State?.Code === "active" && lb[0].Type === "application" && lb[0].IpAddressType === "ipv4" &&
|
||||
canonical(lb[0].SecurityGroups) === canonical([ALB_SG]), "Exact active origin ALB required");
|
||||
const listener = (await aws("elbv2", "describe-listeners", ["--listener-arns", LISTENER])).Listeners;
|
||||
requireThat(listener?.length === 1 && listener[0].ListenerArn === LISTENER && listener[0].LoadBalancerArn === LB &&
|
||||
listener[0].Protocol === "HTTPS" && listener[0].Port === 443 && listener[0].SslPolicy === DESIRED,
|
||||
"Bound HTTPS listener must have the reviewed restricted policy");
|
||||
const enis = (await aws("ec2", "describe-network-interfaces", ["--filters",
|
||||
"Name=description,Values=ELB app/warmbly-production-ingress/19d5c82c1651c871", `Name=vpc-id,Values=${VPC}`])).NetworkInterfaces;
|
||||
requireThat(enis?.length >= 2 && lb[0].AvailabilityZones?.length === 2 &&
|
||||
new Set(enis.map((e) => e.AvailabilityZone)).size === 2 && new Set(enis.map((e) => e.SubnetId)).size === 2 &&
|
||||
new Set(enis.map((e) => e.NetworkInterfaceId)).size === enis.length && validTargets(enis.map((e) => e.PrivateIpAddress)) &&
|
||||
enis.every((e) => /^eni-[a-f0-9]+$/.test(e.NetworkInterfaceId || "") && e.VpcId === VPC && e.Status === "in-use" &&
|
||||
e.RequesterManaged === true && e.OwnerId === ACCOUNT && e.Description === "ELB app/warmbly-production-ingress/19d5c82c1651c871" &&
|
||||
e.Groups?.length === 1 && e.Groups[0].GroupId === ALB_SG &&
|
||||
lb[0].AvailabilityZones?.some((z) => z.ZoneName === e.AvailabilityZone && z.SubnetId === e.SubnetId)), "Complete exact-ALB private ENIs required");
|
||||
const service = (await aws("ecs", "describe-services", ["--cluster", CLUSTER, "--services", SERVICE])).services;
|
||||
const network = service?.[0]?.networkConfiguration?.awsvpcConfiguration;
|
||||
requireThat(service?.length === 1 && service[0].serviceArn === SERVICE && service[0].status === "ACTIVE" &&
|
||||
network?.assignPublicIp === "ENABLED" && canonical(network.securityGroups) === canonical([SG]) &&
|
||||
network.subnets?.length === 2 && new Set(network.subnets).size === 2 &&
|
||||
enis.every((e) => network.subnets.includes(e.SubnetId)), "Existing application task network required");
|
||||
const subnets = (await aws("ec2", "describe-subnets", ["--subnet-ids", ...network.subnets])).Subnets;
|
||||
requireThat(subnets?.length === 2 && new Set(subnets.map((s) => s.SubnetId)).size === 2 &&
|
||||
subnets.every((s) => s.VpcId === VPC && s.State === "available" &&
|
||||
enis.some((e) => e.SubnetId === s.SubnetId)), "Existing application/ALB subnets required");
|
||||
return { at: new Date().toISOString(), lb: lb[0], listener: listener[0], enis, network };
|
||||
}
|
||||
|
||||
function definition(config, targets) {
|
||||
return { family: config.family, networkMode: "awsvpc", requiresCompatibilities: ["FARGATE"], cpu: "256", memory: "512",
|
||||
executionRoleArn: EXECUTION, runtimePlatform: { cpuArchitecture: "ARM64", operatingSystemFamily: "LINUX" },
|
||||
containerDefinitions: [{ name: "probe", image: IMAGE, essential: true, user: "1000:1000", readonlyRootFilesystem: true,
|
||||
linuxParameters: { capabilities: { drop: ["ALL"] } }, stopTimeout: 10,
|
||||
entryPoint: ["timeout", "-s", "KILL", "210", "node"], command: ["-e", readFileSync(join(__dirname, "origin-tls-client.cjs"), "utf8")],
|
||||
environment: [{ name: "ORIGIN_TLS_TASK", value: "1" }, { name: "ORIGIN_TLS_TARGETS", value: JSON.stringify(targets) }],
|
||||
logConfiguration: { logDriver: "awslogs", options: { "awslogs-group": LOG, "awslogs-region": REGION,
|
||||
"awslogs-stream-prefix": `origin-tls-${config.run}`, mode: "blocking" } } }] };
|
||||
}
|
||||
|
||||
const save = (config, evidence) => writeFileSync(join(config.work, "evidence.json"), JSON.stringify(evidence), { mode: 0o600 });
|
||||
const load = (config) => JSON.parse(readFileSync(join(config.work, "evidence.json")));
|
||||
async function archive(aws, config, name, evidence) {
|
||||
const bytes = Buffer.from(JSON.stringify(evidence));
|
||||
const path = join(config.work, name);
|
||||
writeFileSync(path, bytes, { mode: 0o600 });
|
||||
const checksum = Buffer.from(hash(bytes), "hex").toString("base64");
|
||||
const result = await aws("s3api", "put-object", ["--bucket", BUCKET, "--key", `${PREFIX}/${config.run}/1/${name}`,
|
||||
"--expected-bucket-owner", ACCOUNT, "--server-side-encryption", "AES256", "--if-none-match", "*",
|
||||
"--checksum-algorithm", "SHA256", "--checksum-sha256", checksum, "--body", path]);
|
||||
requireThat(result.ServerSideEncryption === "AES256" && result.ChecksumSHA256 === checksum &&
|
||||
typeof result.VersionId === "string" && result.VersionId.length > 0 && result.VersionId !== "null", "Private encrypted versioned evidence required");
|
||||
return { version: result.VersionId, sha256: hash(bytes) };
|
||||
}
|
||||
|
||||
async function execute(aws, config, pause = sleep) {
|
||||
mkdirSync(config.work, { recursive: true, mode: 0o700 });
|
||||
const evidence = { run: config.run, source: config.source, success: false, image: IMAGE };
|
||||
save(config, evidence);
|
||||
try {
|
||||
const identity = await aws("sts", "get-caller-identity");
|
||||
requireThat(identity.Account === ACCOUNT && /^arn:aws:sts::925323749693:assumed-role\/warmbly-production-terraform-apply\/[^/]+$/.test(identity.Arn || ""), "Existing infrastructure apply identity required");
|
||||
evidence.before = await discover(aws);
|
||||
const targets = evidence.before.enis.map((e) => e.PrivateIpAddress).sort();
|
||||
evidence.definition = definition(config, targets);
|
||||
await archive(aws, config, "intent.json", evidence);
|
||||
evidence.registerAttempted = true;
|
||||
save(config, evidence);
|
||||
const registered = await aws("ecs", "register-task-definition", ["--cli-input-json", JSON.stringify(evidence.definition)]);
|
||||
evidence.definitionArn = registered.taskDefinition?.taskDefinitionArn;
|
||||
requireThat(evidence.definitionArn?.startsWith(`${ECS}:task-definition/${config.family}:`), "Dedicated diagnostic definition required");
|
||||
save(config, evidence);
|
||||
// Refresh immediately before launch; a changed address requires a new dispatch.
|
||||
evidence.prelaunch = await discover(aws);
|
||||
requireThat(originIdentity(evidence.prelaunch.enis) === originIdentity(evidence.before.enis) &&
|
||||
canonical(evidence.prelaunch.network) === canonical(evidence.before.network), "Origin/task network changed before launch");
|
||||
const request = { cluster: CLUSTER, taskDefinition: evidence.definitionArn, launchType: "FARGATE", platformVersion: "1.4.0",
|
||||
count: 1, startedBy: config.startedBy, clientToken: config.startedBy, enableExecuteCommand: false,
|
||||
networkConfiguration: { awsvpcConfiguration: evidence.before.network } };
|
||||
evidence.runAttempted = true;
|
||||
save(config, evidence);
|
||||
const launched = await aws("ecs", "run-task", ["--cli-input-json", JSON.stringify(request)]);
|
||||
evidence.taskArn = launched.tasks?.[0]?.taskArn;
|
||||
requireThat(!launched.failures?.length && launched.tasks?.length === 1 &&
|
||||
evidence.taskArn?.startsWith(`${ECS}:task/warmbly-production/`), "One disposable diagnostic task required");
|
||||
save(config, evidence);
|
||||
for (let i = 0; i < 48; i++) {
|
||||
const readback = await aws("ecs", "describe-tasks", ["--cluster", CLUSTER, "--tasks", evidence.taskArn]);
|
||||
requireThat(!readback.failures?.length && readback.tasks?.length === 1, "Diagnostic task readback required");
|
||||
evidence.task = readback.tasks[0];
|
||||
requireThat(evidence.task.taskArn === evidence.taskArn && evidence.task.clusterArn === CLUSTER &&
|
||||
evidence.task.taskDefinitionArn === evidence.definitionArn && evidence.task.startedBy === config.startedBy &&
|
||||
evidence.task.launchType === "FARGATE" && evidence.task.enableExecuteCommand === false, "Exact diagnostic task identity required");
|
||||
save(config, evidence);
|
||||
if (evidence.task.lastStatus === "STOPPED") break;
|
||||
await pause(5000);
|
||||
}
|
||||
requireThat(evidence.task?.lastStatus === "STOPPED" && evidence.task.containers?.length === 1 &&
|
||||
evidence.task.containers[0].name === "probe" && evidence.task.containers[0].imageDigest === IMAGE.split("@")[1] &&
|
||||
evidence.task.containers[0].exitCode === 0, "Probe incomplete or inconclusive; inspect private evidence");
|
||||
evidence.after = await discover(aws);
|
||||
requireThat(originIdentity(evidence.after.enis) === originIdentity(evidence.before.enis) &&
|
||||
canonical(evidence.after.network) === canonical(evidence.before.network), "Origin interfaces or task network changed during probe");
|
||||
evidence.success = true;
|
||||
} catch (error) {
|
||||
evidence.failure = error.message;
|
||||
throw error;
|
||||
} finally { save(config, evidence); }
|
||||
}
|
||||
|
||||
async function finish(aws, config, pause = sleep) {
|
||||
if (!existsSync(join(config.work, "evidence.json"))) return;
|
||||
const evidence = load(config);
|
||||
evidence.cleanup = { errors: [], stopped: false, deregistered: false };
|
||||
const attempt = async (action) => { try { return await action(); } catch (error) { evidence.cleanup.errors.push(error.message); return null; } };
|
||||
// Recover identities even when a registration or launch response was lost.
|
||||
const candidates = new Set([evidence.taskArn].filter(Boolean));
|
||||
if (evidence.runAttempted) {
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const running = await attempt(() => aws("ecs", "list-tasks", ["--cluster", CLUSTER, "--started-by", config.startedBy]));
|
||||
// startedBy cannot be combined with another ListTasks filter.
|
||||
const stopped = await attempt(() => aws("ecs", "list-tasks", ["--cluster", CLUSTER, "--family", config.family, "--desired-status", "STOPPED"]));
|
||||
for (const task of [...(running?.taskArns || []), ...(stopped?.taskArns || [])]) candidates.add(task);
|
||||
if (candidates.size) break;
|
||||
await pause(5000);
|
||||
}
|
||||
}
|
||||
const tasks = [...candidates];
|
||||
const verified = new Set();
|
||||
const stopAttempted = new Set();
|
||||
evidence.cleanup.candidateTaskArns = tasks;
|
||||
save(config, evidence);
|
||||
if (tasks.length) {
|
||||
for (let i = 0; i < 12; i++) {
|
||||
const state = await attempt(() => aws("ecs", "describe-tasks", ["--cluster", CLUSTER, "--tasks", ...tasks]));
|
||||
evidence.cleanup.tasks = state;
|
||||
const owned = (state?.tasks || []).filter((t) => candidates.has(t.taskArn) && t.clusterArn === CLUSTER &&
|
||||
t.startedBy === config.startedBy && typeof evidence.definitionArn === "string" && t.taskDefinitionArn === evidence.definitionArn);
|
||||
for (const task of owned) {
|
||||
verified.add(task.taskArn);
|
||||
if (task.lastStatus !== "STOPPED" && !stopAttempted.has(task.taskArn)) {
|
||||
stopAttempted.add(task.taskArn);
|
||||
await attempt(() => aws("ecs", "stop-task", ["--cluster", CLUSTER, "--task", task.taskArn, "--reason", "Bounded origin TLS diagnostic cleanup"]));
|
||||
}
|
||||
}
|
||||
if (state && !state.failures?.length && new Set(owned.map((t) => t.taskArn)).size === tasks.length && owned.every((t) => t.lastStatus === "STOPPED")) {
|
||||
evidence.cleanup.stopped = true;
|
||||
break;
|
||||
}
|
||||
await pause(5000);
|
||||
}
|
||||
} else if (!evidence.runAttempted) {
|
||||
evidence.cleanup.stopped = true;
|
||||
}
|
||||
evidence.cleanup.taskArns = [...verified];
|
||||
evidence.cleanup.recovery = !evidence.runAttempted ? "not-required" :
|
||||
verified.size > 0 && verified.size === tasks.length ? "resolved" : "unresolved";
|
||||
if (evidence.cleanup.recovery === "unresolved") evidence.cleanup.errors.push("Diagnostic task identity unresolved");
|
||||
const definitionPattern = new RegExp(`^${ECS}:task-definition/${config.family}:\\d+$`);
|
||||
const isRunDefinition = (arn) => typeof arn === "string" && definitionPattern.exec(arn)?.[0] === arn;
|
||||
const arns = new Set([evidence.definitionArn].filter(isRunDefinition));
|
||||
let definitions;
|
||||
if (evidence.registerAttempted) {
|
||||
for (let i = 0; i < 3; i++) {
|
||||
definitions = await attempt(async () => {
|
||||
const result = await aws("ecs", "list-task-definitions", ["--family-prefix", config.family, "--status", "ACTIVE"]);
|
||||
requireThat(Array.isArray(result?.taskDefinitionArns), "Diagnostic definition discovery unconfirmed");
|
||||
return result;
|
||||
});
|
||||
for (const arn of (definitions?.taskDefinitionArns || []).filter(isRunDefinition)) arns.add(arn);
|
||||
if (arns.size) break;
|
||||
if (i < 2) await pause(5000);
|
||||
}
|
||||
}
|
||||
evidence.cleanup.definitionArns = [...arns];
|
||||
evidence.cleanup.definitionRecovery = !evidence.registerAttempted ? "not-required" : arns.size ? "resolved" : "unresolved";
|
||||
if (evidence.cleanup.definitionRecovery === "unresolved") evidence.cleanup.errors.push("Diagnostic definition identity unresolved");
|
||||
save(config, evidence);
|
||||
for (const arn of arns) {
|
||||
const result = await attempt(() => aws("ecs", "deregister-task-definition", ["--task-definition", arn]));
|
||||
if (result?.taskDefinition?.taskDefinitionArn !== arn || result?.taskDefinition?.status !== "INACTIVE") evidence.cleanup.errors.push("Diagnostic definition deregistration unconfirmed");
|
||||
}
|
||||
evidence.cleanup.deregistered = (!evidence.registerAttempted || !!definitions && arns.size > 0) && evidence.cleanup.errors.length === 0;
|
||||
evidence.logs = [];
|
||||
for (const task of verified) {
|
||||
let token;
|
||||
for (let i = 0; i < 6; i++) {
|
||||
const page = await attempt(() => aws("logs", "get-log-events", ["--log-group-name", LOG,
|
||||
"--log-stream-name", `origin-tls-${config.run}/probe/${task.split("/").pop()}`, "--start-from-head",
|
||||
...(token ? ["--next-token", token] : [])]));
|
||||
if (!page) break;
|
||||
evidence.logs.push(...(page.events || []));
|
||||
if (page.nextForwardToken === token) {
|
||||
if (verifiedLogs(evidence.logs, evidence.before?.enis?.map((e) => e.PrivateIpAddress) || [])) break;
|
||||
if (i === 5) break;
|
||||
await pause(5000);
|
||||
evidence.logs = [];
|
||||
token = undefined;
|
||||
continue;
|
||||
}
|
||||
token = page.nextForwardToken;
|
||||
}
|
||||
}
|
||||
const complete = verifiedLogs(evidence.logs, evidence.before?.enis?.map((e) => e.PrivateIpAddress) || []);
|
||||
evidence.success = evidence.success && complete && evidence.cleanup.stopped && evidence.cleanup.deregistered && evidence.cleanup.errors.length === 0;
|
||||
save(config, evidence);
|
||||
const archived = await archive(aws, config, "result.json", evidence);
|
||||
appendFileSync(process.env.GITHUB_STEP_SUMMARY, `Private origin TLS result: version ${archived.version}, SHA-256 ${archived.sha256}. Outcome: ${evidence.success ? "verified" : "inconclusive"}.\n`);
|
||||
requireThat(evidence.success, "Diagnostic incomplete, inconclusive or cleanup failed; inspect the private result before any new dispatch");
|
||||
}
|
||||
|
||||
function verifiedLogs(events, targets) {
|
||||
const rows = events.map((e) => { try { return JSON.parse(e.message); } catch { return null; } }).filter(Boolean);
|
||||
if (!validTargets(targets) || !rows.some((r) => r.kind === "complete" && r.success === true) ||
|
||||
rows.some((r) => r.kind === "handshake" && !targets.includes(r.ip))) return false;
|
||||
return targets.every((ip) => {
|
||||
const handshakes = rows.filter((r) => r.kind === "handshake" && r.ip === ip);
|
||||
return canonical(handshakes.map((r) => r.cipher)) === canonical([GCM[0], GCM[1], TLS13, ...CBC, GCM[0], TLS13]) &&
|
||||
handshakes.every((r) => classify(r, r.cipher === TLS13 ? "TLSv1.3" : "TLSv1.2", r.cipher, CBC.includes(r.cipher)) ===
|
||||
(CBC.includes(r.cipher) ? "refused" : "trusted"));
|
||||
});
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
process.umask(0o077);
|
||||
Promise.resolve().then(async () => {
|
||||
const config = configuration(process.env);
|
||||
const source = spawnSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" });
|
||||
requireThat(source.status === 0 && source.stdout.trim() === config.source, "Checkout must match main workflow source");
|
||||
if (process.argv[2] === "session-policy") {
|
||||
for (const phase of ["probe", "cleanup"]) appendFileSync(process.env.GITHUB_OUTPUT, `${phase}_policy=${canonical(sessionPolicy(config, phase))}\n`);
|
||||
} else if (process.argv[2] === "probe") await execute(awsCLI, config);
|
||||
else if (process.argv[2] === "finish") await finish(awsCLI, config);
|
||||
else throw new Error("Unknown diagnostic command");
|
||||
}).catch((error) => { console.error(`Origin TLS diagnostic stopped: ${error.message}`); process.exitCode = 1; });
|
||||
}
|
||||
module.exports = { configuration, sessionPolicy, discover, definition, archive, execute, finish, verifiedLogs, IMAGE, CLUSTER, SERVICE, EXECUTION, SG, ALB_SG, VPC, ECS, LOG };
|
||||
@@ -0,0 +1,778 @@
|
||||
const { test } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const { spawnSync } = require("node:child_process");
|
||||
const { mkdtempSync, readFileSync, rmSync, writeFileSync } = require("node:fs");
|
||||
const { tmpdir } = require("node:os");
|
||||
const { join } = require("node:path");
|
||||
const { ACCOUNT, BUCKET, ROLE, LB, LISTENER, DESIRED } = require("./aws-origin-alb.cjs");
|
||||
const { configuration, sessionPolicy, discover, definition, execute, finish, verifiedLogs, IMAGE, CLUSTER, SERVICE, EXECUTION, SG, ALB_SG, VPC, ECS, LOG } = require("./aws-origin-tls.cjs");
|
||||
const { probe, classify, invoke, CBC, TLS13 } = require("./origin-tls-client.cjs");
|
||||
const { refused } = require("./origin-tls-client.fixture.cjs");
|
||||
|
||||
const scaledTargets = ["10.42.0.85", "10.42.1.12", "10.42.0.86", "10.42.1.13"];
|
||||
|
||||
function logFixture(targets = ["10.42.0.85", "10.42.1.12"]) {
|
||||
const events = [];
|
||||
probe(targets, (args) => {
|
||||
if (args[0] === "version") return { status: 0, stdout: "OpenSSL fixture" };
|
||||
if (args[0] === "ciphers") return { status: 0, stdout: CBC.join(":") };
|
||||
const cipher = args.at(-1);
|
||||
return { command: ["openssl", ...args], ...(CBC.includes(cipher) ?
|
||||
refused(cipher) :
|
||||
{ status: 0, stdout: `-----BEGIN CERTIFICATE-----\nfixture\nNew, ${cipher === TLS13 ? "TLSv1.3" : "TLSv1.2"}, Cipher is ${cipher}\nVerify return code: 0 (ok)`, stderr: "" }) };
|
||||
}, (row) => events.push({ message: JSON.stringify(row) }));
|
||||
return events;
|
||||
}
|
||||
|
||||
const env = () => ({ GITHUB_ACTIONS: "true", GITHUB_REPOSITORY: "warmbly/warmbly", GITHUB_REF: "refs/heads/main",
|
||||
GITHUB_EVENT_NAME: "workflow_dispatch", GITHUB_WORKFLOW_REF: "warmbly/warmbly/.github/workflows/probe-origin-tls-aws.yml@refs/heads/main",
|
||||
GITHUB_RUN_ATTEMPT: "1", GITHUB_RUN_ID: "123456", GITHUB_SHA: "a".repeat(40), STATE_BUCKET: BUCKET, APPLY_ROLE: ROLE,
|
||||
WORK: "/tmp/fixture", GITHUB_OUTPUT: "/tmp/output", GITHUB_STEP_SUMMARY: "/tmp/summary" });
|
||||
|
||||
function fixture(t, change = () => {}, targets = ["10.42.0.85", "10.42.1.12"]) {
|
||||
const work = mkdtempSync(join(tmpdir(), "origin-tls-test-"));
|
||||
t.after(() => rmSync(work, { recursive: true, force: true }));
|
||||
const config = configuration({ ...env(), WORK: work });
|
||||
const arn = `${ECS}:task-definition/${config.family}:1`;
|
||||
const task = `${ECS}:task/warmbly-production/${"1".repeat(32)}`;
|
||||
const calls = [];
|
||||
const zones = [{ ZoneName: "us-east-1a", SubnetId: "subnet-a" }, { ZoneName: "us-east-1b", SubnetId: "subnet-b" }];
|
||||
const network = { subnets: zones.map((z) => z.SubnetId), securityGroups: [SG], assignPublicIp: "ENABLED" };
|
||||
const state = { taskArn: task, clusterArn: CLUSTER, taskDefinitionArn: arn, startedBy: config.startedBy,
|
||||
launchType: "FARGATE", enableExecuteCommand: false, lastStatus: "STOPPED",
|
||||
containers: [{ name: "probe", exitCode: 0, imageDigest: IMAGE.split("@")[1] }] };
|
||||
const aws = async (service, action, args = []) => {
|
||||
calls.push({ service, action, args });
|
||||
let result;
|
||||
switch (action) {
|
||||
case "get-caller-identity": result = { Account: ACCOUNT, Arn: `arn:aws:sts::${ACCOUNT}:assumed-role/warmbly-production-terraform-apply/fixture` }; break;
|
||||
case "describe-load-balancers": result = { LoadBalancers: [{ LoadBalancerArn: LB, VpcId: VPC,
|
||||
Type: "application", IpAddressType: "ipv4", State: { Code: "active" }, SecurityGroups: [ALB_SG], AvailabilityZones: zones }] }; break;
|
||||
case "describe-listeners": result = { Listeners: [{ ListenerArn: LISTENER, LoadBalancerArn: LB, Protocol: "HTTPS", Port: 443, SslPolicy: DESIRED }] }; break;
|
||||
case "describe-network-interfaces": result = { NetworkInterfaces: targets.map((ip, i) => {
|
||||
const z = zones[i % 2];
|
||||
return { Description: "ELB app/warmbly-production-ingress/19d5c82c1651c871", NetworkInterfaceId: `eni-${i + 1}`,
|
||||
AvailabilityZone: z.ZoneName, SubnetId: z.SubnetId, VpcId: VPC, Status: "in-use", RequesterManaged: true, OwnerId: ACCOUNT,
|
||||
PrivateIpAddress: ip, Groups: [{ GroupId: ALB_SG }] };
|
||||
}) }; break;
|
||||
case "describe-services": result = { services: [{ serviceArn: SERVICE, status: "ACTIVE", networkConfiguration: { awsvpcConfiguration: network } }] }; break;
|
||||
case "describe-subnets": result = { Subnets: zones.map((z) => ({ SubnetId: z.SubnetId, VpcId: VPC, State: "available" })) }; break;
|
||||
case "put-object": result = { ServerSideEncryption: "AES256", ChecksumSHA256: args[args.indexOf("--checksum-sha256") + 1], VersionId: "private-version" }; break;
|
||||
case "register-task-definition": result = { taskDefinition: { taskDefinitionArn: arn } }; break;
|
||||
case "run-task": result = { tasks: [state] }; break;
|
||||
case "describe-tasks": result = { tasks: [state] }; break;
|
||||
case "list-tasks": {
|
||||
assert.equal(args[1], CLUSTER);
|
||||
if (args.includes("--started-by")) {
|
||||
assert.deepEqual(args, ["--cluster", CLUSTER, "--started-by", config.startedBy]);
|
||||
result = { taskArns: state.lastStatus === "STOPPED" ? [] : [task] };
|
||||
} else {
|
||||
assert.deepEqual(args, ["--cluster", CLUSTER, "--family", config.family, "--desired-status", "STOPPED"]);
|
||||
result = { taskArns: state.lastStatus === "STOPPED" ? [task] : [] };
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "stop-task": state.lastStatus = "STOPPED"; result = { task: state }; break;
|
||||
case "list-task-definitions": result = { taskDefinitionArns: [arn] }; break;
|
||||
case "deregister-task-definition": result = { taskDefinition: { taskDefinitionArn: arn, status: "INACTIVE" } }; break;
|
||||
case "get-log-events": result = { events: args.includes("--next-token") ? [] : logFixture(targets), nextForwardToken: "end" }; break;
|
||||
default: throw new Error(`Unexpected ${service} ${action}`);
|
||||
}
|
||||
result = structuredClone(result);
|
||||
await change(action, result, calls);
|
||||
return result;
|
||||
};
|
||||
return { config, aws, calls, arn, task, state, evidence: () => JSON.parse(readFileSync(join(work, "evidence.json"))) };
|
||||
}
|
||||
|
||||
test("only fresh main dispatches under normal infrastructure configuration are admitted", () => {
|
||||
assert.equal(configuration(env()).run, "123456");
|
||||
for (const [key, value] of Object.entries({ GITHUB_ACTIONS: "false", GITHUB_REPOSITORY: "fork/warmbly", GITHUB_REF: "refs/heads/branch",
|
||||
GITHUB_EVENT_NAME: "pull_request", GITHUB_WORKFLOW_REF: "other", GITHUB_RUN_ATTEMPT: "2", GITHUB_RUN_ID: "../1",
|
||||
GITHUB_SHA: "bad", STATE_BUCKET: "other", APPLY_ROLE: "other", WORK: "", GITHUB_OUTPUT: "", GITHUB_STEP_SUMMARY: "" })) {
|
||||
assert.throws(() => configuration({ ...env(), [key]: value }), key);
|
||||
}
|
||||
});
|
||||
|
||||
test("each credential phase grants exactly its required operations and resource scopes", () => {
|
||||
const config = configuration(env());
|
||||
const allow = (Action, Resource, Condition) => ({ Effect: "Allow", Action, Resource, ...(Condition ? { Condition } : {}) });
|
||||
const archive = allow("s3:PutObject", `arn:aws:s3:::${BUCKET}/warmbly/production/diagnostics/origin-tls/${config.run}/1/*`, {
|
||||
StringEquals: { "s3:x-amz-server-side-encryption": "AES256", "s3:ResourceAccount": ACCOUNT },
|
||||
Bool: { "aws:SecureTransport": "true" }, Null: { "s3:if-none-match": "false" },
|
||||
});
|
||||
const expected = {
|
||||
probe: [
|
||||
allow(["elasticloadbalancing:DescribeLoadBalancers", "elasticloadbalancing:DescribeListeners",
|
||||
"ec2:DescribeNetworkInterfaces", "ec2:DescribeSubnets", "ecs:RegisterTaskDefinition"], "*"),
|
||||
allow("ecs:DescribeServices", SERVICE),
|
||||
allow("ecs:RunTask", `${ECS}:task-definition/${config.family}:*`, { ArnEquals: { "ecs:cluster": CLUSTER } }),
|
||||
allow("ecs:DescribeTasks", `${ECS}:task/warmbly-production/*`),
|
||||
allow("iam:PassRole", EXECUTION, { StringEquals: { "iam:PassedToService": "ecs-tasks.amazonaws.com" } }),
|
||||
archive,
|
||||
],
|
||||
cleanup: [
|
||||
allow(["ecs:ListTaskDefinitions", "ecs:ListTasks"], "*"),
|
||||
allow("ecs:DeregisterTaskDefinition", "*"),
|
||||
allow(["ecs:DescribeTasks", "ecs:StopTask"], `${ECS}:task/warmbly-production/*`),
|
||||
allow("logs:GetLogEvents", `arn:aws:logs:us-east-1:${ACCOUNT}:log-group:${LOG}:log-stream:origin-tls-${config.run}/*`),
|
||||
archive,
|
||||
],
|
||||
};
|
||||
for (const phase of ["probe", "cleanup"]) {
|
||||
const policy = sessionPolicy(config, phase);
|
||||
assert.deepEqual(policy, { Version: "2012-10-17", Statement: expected[phase] });
|
||||
assert.ok(JSON.stringify(policy).length < 2048);
|
||||
}
|
||||
for (const phase of [undefined, "", "finish", "all"]) assert.throws(() => sessionPolicy(config, phase), /credential phase/);
|
||||
});
|
||||
|
||||
test("the source gate emits distinct phase policies and refuses an unverified checkout", (t) => {
|
||||
const f = fixture(t);
|
||||
const revision = spawnSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" });
|
||||
assert.equal(revision.status, 0);
|
||||
const output = join(f.config.work, "output");
|
||||
const childEnv = { ...process.env, ...env(), WORK: f.config.work, GITHUB_OUTPUT: output, GITHUB_SHA: revision.stdout.trim() };
|
||||
const run = () => spawnSync(process.execPath, [join(__dirname, "aws-origin-tls.cjs"), "session-policy"], { env: childEnv, encoding: "utf8" });
|
||||
assert.equal(run().status, 0);
|
||||
const policies = Object.fromEntries(readFileSync(output, "utf8").trim().split("\n").map((line) => {
|
||||
const equals = line.indexOf("=");
|
||||
return [line.slice(0, equals), JSON.parse(line.slice(equals + 1))];
|
||||
}));
|
||||
assert.deepEqual(policies, { probe_policy: sessionPolicy(f.config, "probe"), cleanup_policy: sessionPolicy(f.config, "cleanup") });
|
||||
writeFileSync(output, "");
|
||||
childEnv.GITHUB_SHA = "0".repeat(40);
|
||||
assert.equal(run().status, 1);
|
||||
assert.equal(readFileSync(output, "utf8"), "");
|
||||
});
|
||||
|
||||
function phaseAWS(f, phase) {
|
||||
const actions = sessionPolicy(f.config, phase).Statement.flatMap((s) => s.Action);
|
||||
return (service, action, args) => {
|
||||
const prefix = { elbv2: "elasticloadbalancing", s3api: "s3" }[service] || service;
|
||||
const name = action.split("-").map((word) => word[0].toUpperCase() + word.slice(1)).join("");
|
||||
if (service !== "sts" || action !== "get-caller-identity") assert.ok(actions.includes(`${prefix}:${name}`), `${phase} must permit ${service} ${action}`);
|
||||
return f.aws(service, action, args);
|
||||
};
|
||||
}
|
||||
|
||||
for (const failure of [null, "register-task-definition", "run-task", "describe-tasks"]) {
|
||||
test(`phase sessions support ${failure || "successful probe"} cleanup with one registration and launch at most`, async (t) => {
|
||||
let lost = false;
|
||||
const f = fixture(t, (action) => {
|
||||
if (action === failure && !lost) { lost = true; throw new Error("Fixture lost response"); }
|
||||
});
|
||||
const oldSummary = process.env.GITHUB_STEP_SUMMARY;
|
||||
process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary");
|
||||
t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; });
|
||||
const probeRun = execute(phaseAWS(f, "probe"), f.config, async () => {});
|
||||
if (failure) await assert.rejects(probeRun, /lost response/);
|
||||
else await probeRun;
|
||||
const boundary = f.calls.length;
|
||||
if (failure && failure !== "register-task-definition") f.state.lastStatus = "RUNNING";
|
||||
const cleanup = finish(phaseAWS(f, "cleanup"), f.config, async () => {});
|
||||
if (failure) await assert.rejects(cleanup, /incomplete/);
|
||||
else await cleanup;
|
||||
assert.ok(!f.calls.slice(0, boundary).some((c) => c.action === "deregister-task-definition"));
|
||||
assert.ok(!f.calls.slice(boundary).some((c) => ["register-task-definition", "run-task"].includes(c.action)));
|
||||
assert.equal(f.calls.filter((c) => c.action === "register-task-definition").length, 1);
|
||||
assert.equal(f.calls.filter((c) => c.action === "run-task").length, failure === "register-task-definition" ? 0 : 1);
|
||||
assert.equal(f.evidence().cleanup.deregistered, true);
|
||||
assert.equal(f.evidence().success, !failure);
|
||||
assert.equal(f.calls.at(-1).action, "put-object");
|
||||
assert.deepEqual(JSON.parse(readFileSync(join(f.config.work, "result.json"))), f.evidence());
|
||||
});
|
||||
}
|
||||
|
||||
test("fresh definition contains only the official digest, hard-bounded TLS client and existing execution/log facilities", () => {
|
||||
const task = definition(configuration(env()), ["10.42.0.85", "10.42.1.12"]);
|
||||
assert.deepEqual(Object.keys(task).sort(), ["family", "networkMode", "requiresCompatibilities", "cpu", "memory", "executionRoleArn", "runtimePlatform", "containerDefinitions"].sort());
|
||||
assert.equal(task.executionRoleArn, EXECUTION);
|
||||
assert.equal(task.runtimePlatform.cpuArchitecture, "ARM64");
|
||||
const c = task.containerDefinitions[0];
|
||||
assert.match(c.image, /^docker\.io\/library\/node@sha256:[a-f0-9]{64}$/);
|
||||
assert.equal(c.secrets, undefined);
|
||||
assert.equal(c.repositoryCredentials, undefined);
|
||||
assert.equal(c.portMappings, undefined);
|
||||
assert.equal(c.mountPoints, undefined);
|
||||
assert.equal(c.readonlyRootFilesystem, true);
|
||||
assert.deepEqual(c.entryPoint, ["timeout", "-s", "KILL", "210", "node"]);
|
||||
assert.deepEqual(c.environment.map((e) => e.name), ["ORIGIN_TLS_TASK", "ORIGIN_TLS_TARGETS"]);
|
||||
assert.equal(c.logConfiguration.options["awslogs-create-group"], undefined);
|
||||
});
|
||||
|
||||
test("only the exact active ALB, restricted listener, managed private ENIs and existing task network are accepted", async (t) => {
|
||||
const changes = [
|
||||
["describe-load-balancers", (r) => { r.LoadBalancers[0].VpcId = "vpc-other"; }],
|
||||
["describe-listeners", (r) => { r.Listeners[0].SslPolicy = "other"; }],
|
||||
["describe-network-interfaces", (r) => { r.NetworkInterfaces.pop(); }],
|
||||
["describe-network-interfaces", (r) => { r.NetworkInterfaces[0].Description = "another ALB"; }],
|
||||
["describe-network-interfaces", (r) => { r.NetworkInterfaces[0].Groups[0].GroupId = SG; }],
|
||||
["describe-network-interfaces", (r) => { r.NetworkInterfaces[0].RequesterManaged = false; }],
|
||||
["describe-network-interfaces", (r) => { r.NetworkInterfaces[0].OwnerId = "000000000000"; }],
|
||||
["describe-network-interfaces", (r) => { r.NetworkInterfaces[0].VpcId = "vpc-other"; }],
|
||||
["describe-network-interfaces", (r) => { r.NetworkInterfaces[0].Status = "available"; }],
|
||||
["describe-network-interfaces", (r) => { r.NetworkInterfaces[0].SubnetId = "subnet-other"; }],
|
||||
["describe-network-interfaces", (r) => { r.NetworkInterfaces[0].AvailabilityZone = "us-east-1c"; }],
|
||||
["describe-network-interfaces", (r) => { r.NetworkInterfaces[0].NetworkInterfaceId = r.NetworkInterfaces[1].NetworkInterfaceId; }],
|
||||
["describe-network-interfaces", (r) => { r.NetworkInterfaces[0].PrivateIpAddress = r.NetworkInterfaces[1].PrivateIpAddress; }],
|
||||
["describe-network-interfaces", (r) => { delete r.NetworkInterfaces[0].NetworkInterfaceId; }],
|
||||
["describe-network-interfaces", (r) => { r.NetworkInterfaces[0].PrivateIpAddress = "10.42.0.999"; }],
|
||||
["describe-services", (r) => { r.services[0].networkConfiguration.awsvpcConfiguration.securityGroups = ["sg-worker"]; }],
|
||||
["describe-services", (r) => { r.services[0].networkConfiguration.awsvpcConfiguration.subnets = ["subnet-a", "subnet-a"]; }],
|
||||
["describe-subnets", (r) => { r.Subnets[0].VpcId = "vpc-other"; }],
|
||||
["describe-subnets", (r) => { r.Subnets[0] = r.Subnets[1]; }],
|
||||
];
|
||||
for (const [target, mutate] of changes) {
|
||||
const f = fixture(t, (action, result) => { if (action === target) mutate(result); });
|
||||
await assert.rejects(discover(f.aws));
|
||||
assert.ok(!f.calls.some((c) => c.action === "run-task"));
|
||||
}
|
||||
});
|
||||
|
||||
test("all current ALB interfaces across both zones are pinned, verified and privately archived", async (t) => {
|
||||
let reads = 0;
|
||||
const f = fixture(t, (action, result) => {
|
||||
if (action === "describe-network-interfaces" && ++reads % 2) result.NetworkInterfaces.reverse();
|
||||
}, scaledTargets);
|
||||
const oldSummary = process.env.GITHUB_STEP_SUMMARY;
|
||||
process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary");
|
||||
t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; });
|
||||
await execute(f.aws, f.config, async () => {});
|
||||
const evidence = f.evidence();
|
||||
assert.equal(evidence.before.enis.length, 4);
|
||||
const targets = JSON.parse(evidence.definition.containerDefinitions[0].environment.find((e) => e.name === "ORIGIN_TLS_TARGETS").value);
|
||||
assert.deepEqual(targets, [...scaledTargets].sort());
|
||||
await finish(f.aws, f.config, async () => {});
|
||||
assert.equal(f.evidence().success, true);
|
||||
assert.equal(verifiedLogs(f.evidence().logs, targets), true);
|
||||
for (const ip of targets) {
|
||||
assert.equal(verifiedLogs(f.evidence().logs.filter((e) => JSON.parse(e.message).ip !== ip), targets), false);
|
||||
}
|
||||
assert.equal(verifiedLogs(f.evidence().logs, [...targets, targets[0]]), false);
|
||||
assert.equal(verifiedLogs([...f.evidence().logs, ...logFixture(["10.42.0.87", "10.42.1.14"])], targets), false);
|
||||
});
|
||||
|
||||
test("every interface remains stable before launch and after the diagnostic", async (t) => {
|
||||
for (const phase of [2, 3]) {
|
||||
for (const mutate of [
|
||||
(enis) => { enis.pop(); },
|
||||
(enis) => { enis.push({ ...enis[0], NetworkInterfaceId: "eni-a", PrivateIpAddress: "10.42.0.87" }); },
|
||||
(enis) => { enis[0].NetworkInterfaceId = "eni-b"; },
|
||||
(enis) => { enis[0].PrivateIpAddress = "10.42.0.87"; },
|
||||
]) {
|
||||
let reads = 0;
|
||||
const f = fixture(t, (action, result) => {
|
||||
if (action === "describe-network-interfaces" && ++reads === phase) mutate(result.NetworkInterfaces);
|
||||
}, scaledTargets);
|
||||
await assert.rejects(execute(f.aws, f.config, async () => {}), /changed/);
|
||||
assert.equal(f.evidence().success, false);
|
||||
assert.equal(f.calls.filter((c) => c.action === "run-task").length, phase === 2 ? 0 : 1);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("archive requires encryption, checksum and a real version before admitting a task", async (t) => {
|
||||
for (const mutate of [(r) => { r.VersionId = "null"; }, (r) => { r.ChecksumSHA256 = "bad"; }, (r) => { r.ServerSideEncryption = ""; }]) {
|
||||
const f = fixture(t, (action, result) => { if (action === "put-object") mutate(result); });
|
||||
await assert.rejects(execute(f.aws, f.config, async () => {}), /versioned/);
|
||||
assert.ok(!f.calls.some((c) => c.action === "register-task-definition"));
|
||||
}
|
||||
});
|
||||
|
||||
test("successful lifecycle archives intent first, launches one secretless task, confirms cleanup and retains private logs", async (t) => {
|
||||
const f = fixture(t);
|
||||
const oldSummary = process.env.GITHUB_STEP_SUMMARY;
|
||||
process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary");
|
||||
t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; });
|
||||
await execute(f.aws, f.config, async () => {});
|
||||
await finish(f.aws, f.config, async () => {});
|
||||
assert.equal(f.evidence().success, true);
|
||||
const actions = f.calls.map((c) => c.action);
|
||||
assert.ok(actions.indexOf("put-object") < actions.indexOf("register-task-definition"));
|
||||
assert.equal(actions.filter((a) => a === "run-task").length, 1);
|
||||
const request = JSON.parse(f.calls.find((c) => c.action === "run-task").args[1]);
|
||||
assert.equal(request.taskDefinition, f.arn);
|
||||
assert.equal(request.enableExecuteCommand, false);
|
||||
assert.equal(request.clientToken, f.config.startedBy);
|
||||
assert.equal(request.overrides, undefined);
|
||||
assert.deepEqual(request.networkConfiguration.awsvpcConfiguration.securityGroups, [SG]);
|
||||
assert.ok(!actions.includes("stop-task"));
|
||||
assert.ok(actions.indexOf("describe-tasks") < actions.indexOf("deregister-task-definition"));
|
||||
assert.equal(f.evidence().cleanup.stopped, true);
|
||||
assert.equal(f.evidence().cleanup.deregistered, true);
|
||||
assert.ok(f.evidence().logs.length > 0);
|
||||
assert.ok(!readFileSync(process.env.GITHUB_STEP_SUMMARY, "utf8").includes("10.42."));
|
||||
});
|
||||
|
||||
for (const failure of ["register-task-definition", "run-task", "describe-tasks"]) {
|
||||
test(`lost ${failure} response still permits diagnostic-only recovery and private failure evidence`, async (t) => {
|
||||
let lost = false;
|
||||
const f = fixture(t, (action) => { if (action === failure && !lost) { lost = true; throw new Error("Fixture lost response"); } });
|
||||
const oldSummary = process.env.GITHUB_STEP_SUMMARY;
|
||||
process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary");
|
||||
t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; });
|
||||
await assert.rejects(execute(f.aws, f.config, async () => {}), /lost response/);
|
||||
if (failure !== "register-task-definition") f.state.lastStatus = "RUNNING";
|
||||
await assert.rejects(finish(f.aws, f.config, async () => {}), /incomplete/);
|
||||
assert.ok(f.calls.some((c) => c.action === "deregister-task-definition"));
|
||||
if (failure !== "register-task-definition") assert.ok(f.calls.some((c) => c.action === "stop-task"));
|
||||
if (failure !== "register-task-definition") {
|
||||
const stop = f.calls.findIndex((c) => c.action === "stop-task");
|
||||
assert.ok(f.calls.slice(0, stop).some((c) => c.action === "describe-tasks"));
|
||||
assert.equal(f.evidence().cleanup.recovery, "resolved");
|
||||
assert.equal(f.evidence().cleanup.stopped, true);
|
||||
}
|
||||
assert.equal(f.evidence().success, false);
|
||||
assert.equal(f.calls.filter((c) => c.action === "put-object").length, 2);
|
||||
assert.equal(f.calls.filter((c) => c.action === "run-task").length, failure === "register-task-definition" ? 0 : 1);
|
||||
});
|
||||
}
|
||||
|
||||
test("stopped diagnostic recovery verifies exact identity and privately archives its logs", async (t) => {
|
||||
const f = fixture(t, (action) => { if (action === "run-task") throw new Error("Fixture lost response"); });
|
||||
const oldSummary = process.env.GITHUB_STEP_SUMMARY;
|
||||
process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary");
|
||||
t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; });
|
||||
await assert.rejects(execute(f.aws, f.config, async () => {}), /lost response/);
|
||||
assert.equal(f.evidence().taskArn, undefined);
|
||||
await assert.rejects(finish(f.aws, f.config, async () => {}), /incomplete/);
|
||||
const evidence = f.evidence();
|
||||
assert.equal(evidence.cleanup.recovery, "resolved");
|
||||
assert.equal(evidence.cleanup.stopped, true);
|
||||
assert.deepEqual(evidence.cleanup.taskArns, [f.task]);
|
||||
assert.deepEqual(evidence.cleanup.tasks.tasks, [f.state]);
|
||||
assert.equal(verifiedLogs(evidence.logs, evidence.before.enis.map((e) => e.PrivateIpAddress)), true);
|
||||
assert.ok(!f.calls.some((c) => c.action === "stop-task"));
|
||||
const described = f.calls.findIndex((c) => c.action === "describe-tasks");
|
||||
assert.ok(described < f.calls.findIndex((c) => c.action === "get-log-events"));
|
||||
assert.equal(evidence.success, false);
|
||||
const archived = JSON.parse(readFileSync(join(f.config.work, "result.json")));
|
||||
assert.deepEqual(archived, evidence);
|
||||
assert.equal(f.calls.at(-1).action, "put-object");
|
||||
});
|
||||
|
||||
test("ambiguous diagnostic recovery retains an unresolved private outcome within its discovery budget", async (t) => {
|
||||
const f = fixture(t, (action, result) => {
|
||||
if (action === "run-task") throw new Error("Fixture lost response");
|
||||
if (action === "list-tasks") result.taskArns = [];
|
||||
});
|
||||
const oldSummary = process.env.GITHUB_STEP_SUMMARY;
|
||||
process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary");
|
||||
t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; });
|
||||
await assert.rejects(execute(f.aws, f.config, async () => {}), /lost response/);
|
||||
let sleeps = 0;
|
||||
await assert.rejects(finish(f.aws, f.config, async () => { sleeps++; }), /incomplete/);
|
||||
const evidence = f.evidence();
|
||||
assert.equal(evidence.cleanup.recovery, "unresolved");
|
||||
assert.equal(evidence.cleanup.stopped, false);
|
||||
assert.deepEqual(evidence.cleanup.taskArns, []);
|
||||
assert.deepEqual(evidence.logs, []);
|
||||
assert.ok(evidence.cleanup.errors.includes("Diagnostic task identity unresolved"));
|
||||
assert.equal(sleeps, 3);
|
||||
assert.equal(f.calls.filter((c) => c.action === "list-tasks").length, 6);
|
||||
assert.ok(!f.calls.some((c) => ["describe-tasks", "stop-task", "get-log-events"].includes(c.action)));
|
||||
assert.deepEqual(f.calls.filter((c) => c.action === "deregister-task-definition").map((c) => c.args[1]), [f.arn]);
|
||||
assert.equal(evidence.success, false);
|
||||
assert.deepEqual(JSON.parse(readFileSync(join(f.config.work, "result.json"))), evidence);
|
||||
assert.equal(f.calls.at(-1).action, "put-object");
|
||||
});
|
||||
|
||||
for (const field of ["taskArn", "clusterArn", "startedBy", "taskDefinitionArn"]) {
|
||||
test(`diagnostic cleanup requires exact ${field} readback before stopping or collecting logs`, async (t) => {
|
||||
const f = fixture(t, (action, result) => {
|
||||
if (action === "run-task") throw new Error("Fixture lost response");
|
||||
if (action === "describe-tasks") result.tasks[0][field] += "7";
|
||||
});
|
||||
const oldSummary = process.env.GITHUB_STEP_SUMMARY;
|
||||
process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary");
|
||||
t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; });
|
||||
await assert.rejects(execute(f.aws, f.config, async () => {}), /lost response/);
|
||||
f.state.lastStatus = "RUNNING";
|
||||
await assert.rejects(finish(f.aws, f.config, async () => {}), /incomplete/);
|
||||
assert.ok(!f.calls.some((c) => ["stop-task", "get-log-events"].includes(c.action)));
|
||||
assert.equal(f.calls.filter((c) => c.action === "describe-tasks").length, 12);
|
||||
assert.deepEqual(f.evidence().cleanup.taskArns, []);
|
||||
assert.equal(f.evidence().cleanup.stopped, false);
|
||||
assert.equal(f.evidence().cleanup.recovery, "unresolved");
|
||||
assert.equal(f.calls.at(-1).action, "put-object");
|
||||
});
|
||||
}
|
||||
|
||||
test("diagnostic recovery cleans and archives only verified tasks among mixed candidates", async (t) => {
|
||||
const other = `${ECS}:task/warmbly-production/${"2".repeat(32)}`;
|
||||
const f = fixture(t, (action, result, calls) => {
|
||||
if (action === "run-task") throw new Error("Fixture lost response");
|
||||
if (action === "list-tasks" && calls.at(-1).args.includes("STOPPED")) result.taskArns.push(other);
|
||||
if (action === "describe-tasks") result.tasks.push({ ...f.state, taskArn: other, startedBy: `${f.config.startedBy}7`, lastStatus: "STOPPED" });
|
||||
});
|
||||
const oldSummary = process.env.GITHUB_STEP_SUMMARY;
|
||||
process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary");
|
||||
t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; });
|
||||
await assert.rejects(execute(f.aws, f.config, async () => {}), /lost response/);
|
||||
f.state.lastStatus = "RUNNING";
|
||||
await assert.rejects(finish(f.aws, f.config, async () => {}), /incomplete/);
|
||||
assert.deepEqual(f.calls.filter((c) => c.action === "stop-task").map((c) => c.args[3]), [f.task]);
|
||||
assert.ok(f.calls.filter((c) => c.action === "get-log-events").every((c) =>
|
||||
c.args[3] === `origin-tls-${f.config.run}/probe/${f.task.split("/").pop()}`));
|
||||
assert.deepEqual(f.evidence().cleanup.taskArns, [f.task]);
|
||||
assert.equal(verifiedLogs(f.evidence().logs, f.evidence().before.enis.map((e) => e.PrivateIpAddress)), true);
|
||||
assert.equal(f.evidence().cleanup.stopped, false);
|
||||
assert.equal(f.evidence().cleanup.recovery, "unresolved");
|
||||
assert.equal(f.calls.filter((c) => c.action === "stop-task").length, 1);
|
||||
assert.equal(f.calls.at(-1).action, "put-object");
|
||||
});
|
||||
|
||||
test("network drift after registration prevents launch and remains eligible for cleanup", async (t) => {
|
||||
let reads = 0;
|
||||
const f = fixture(t, (action, result) => { if (action === "describe-network-interfaces" && ++reads > 1) result.NetworkInterfaces[0].PrivateIpAddress = "10.42.0.86"; });
|
||||
await assert.rejects(execute(f.aws, f.config, async () => {}), /changed before launch/);
|
||||
assert.ok(!f.calls.some((c) => c.action === "run-task"));
|
||||
assert.equal(f.evidence().registerAttempted, true);
|
||||
});
|
||||
|
||||
test("bad image identity and nonzero exit never establish proof", async (t) => {
|
||||
for (const mutate of [(r) => { r.tasks[0].containers[0].exitCode = 1; }, (r) => { r.tasks[0].containers[0].imageDigest = "sha256:other"; }]) {
|
||||
const f = fixture(t, (action, result) => { if (action === "describe-tasks") mutate(result); });
|
||||
await assert.rejects(execute(f.aws, f.config, async () => {}), /inconclusive/);
|
||||
assert.equal(f.evidence().success, false);
|
||||
}
|
||||
});
|
||||
|
||||
test("missing or truncated raw handshake logs cannot be rescued by a successful completion marker", () => {
|
||||
const targets = ["10.42.0.85", "10.42.1.12"];
|
||||
assert.equal(verifiedLogs(logFixture(), targets), true);
|
||||
assert.equal(verifiedLogs(logFixture().filter((e) => JSON.parse(e.message).kind !== "handshake"), targets), false);
|
||||
assert.equal(verifiedLogs(logFixture().slice(0, -1), targets), false);
|
||||
const logs = logFixture();
|
||||
logs[2].message = logs[2].message.replace("return code: 0 (ok)", "return code: 62 (hostname mismatch)");
|
||||
assert.equal(verifiedLogs(logs, targets), false);
|
||||
});
|
||||
|
||||
test("private archive verification reclassifies ambiguous or altered negative evidence", () => {
|
||||
const targets = ["10.42.0.85", "10.42.1.12"];
|
||||
for (const alter of [
|
||||
(r) => { r.stdout = "CONNECTED\nclosed\nno peer certificate available\nNew, (NONE), Cipher is (NONE)\n"; r.status = 0; },
|
||||
(r) => { r.stdout = r.stdout.replace("<<<", ">>>"); },
|
||||
(r) => { r.stdout = r.stdout.replace("02 28", "01 00"); },
|
||||
(r) => { r.stdout = r.stdout.replace("c0 27", "c0 2f"); },
|
||||
]) {
|
||||
const logs = logFixture();
|
||||
const index = logs.findIndex((e) => JSON.parse(e.message).negative);
|
||||
const row = JSON.parse(logs[index].message);
|
||||
alter(row);
|
||||
assert.equal(row.outcome, "refused");
|
||||
logs[index].message = JSON.stringify(row);
|
||||
assert.equal(verifiedLogs(logs, targets), false);
|
||||
}
|
||||
});
|
||||
|
||||
test("refusal evidence accounts for complete traces, framing and both captured streams", () => {
|
||||
const targets = ["10.42.0.85", "10.42.1.12"];
|
||||
const trace = (direction, kind, name, bytes, version = "1.2") =>
|
||||
`${direction} TLS ${version}, ${kind} [length ${bytes.length.toString(16).padStart(4, "0")}]${name ? `, ${name}` : ""}\n` +
|
||||
` ${bytes.toString("hex").match(/../g).join(" ")}\n`;
|
||||
const check = (result, cipher, expected, label) => {
|
||||
assert.equal(classify(result, "TLSv1.2", cipher, true), expected ? "refused" : "inconclusive", label);
|
||||
const logs = logFixture();
|
||||
const index = logs.findIndex((e) => { const row = JSON.parse(e.message); return row.negative && row.cipher === cipher; });
|
||||
const row = JSON.parse(logs[index].message);
|
||||
assert.equal(row.outcome, "refused");
|
||||
logs[index].message = JSON.stringify({ ...row, ...result });
|
||||
assert.equal(verifiedLogs(logs, targets), expected, label);
|
||||
};
|
||||
for (const cipher of CBC) {
|
||||
for (const scsv of [false, true]) {
|
||||
const suites = [0xc0, cipher === CBC[0] ? 0x27 : 0x28, ...(scsv ? [0, 0xff] : [])];
|
||||
const bytes = Buffer.from([1, 0, 0, 39 + suites.length, 3, 3,
|
||||
...Array.from({ length: 32 }, (_, i) => 0x60 + i), 0, 0, suites.length, ...suites, 1, 0]);
|
||||
const hello = trace(">>>", "Handshake", "ClientHello", bytes);
|
||||
const alert = trace("<<<", "Alert", "fatal handshake_failure", Buffer.from([2, 40]));
|
||||
const sent = trace(">>>", "RecordHeader", "", Buffer.from([22, 3, 1, 0, bytes.length]), "1.0");
|
||||
const received = trace("<<<", "RecordHeader", "", Buffer.from([21, 3, 3, 0, 2]));
|
||||
const summary = "no peer certificate available\nNew, (NONE), Cipher is (NONE)\n";
|
||||
const result = { status: 1, stdout: hello + alert + summary, stderr: "SSL_connect:reading peer alert\n" };
|
||||
check(result, cipher, true, "complete message trace");
|
||||
check({ ...result, stdout: sent + hello + received + alert + summary }, cipher, true, "complete record trace");
|
||||
for (const size of [0, 32, 33]) {
|
||||
const message = Buffer.concat([bytes.subarray(0, 38), Buffer.from([size]), Buffer.alloc(size, 0x5a), bytes.subarray(39)]);
|
||||
message.writeUIntBE(message.length - 4, 1, 3);
|
||||
check({ ...result, stdout: trace(">>>", "Handshake", "ClientHello", message) + alert + summary },
|
||||
cipher, size <= 32, "bounded ClientHello session identifier");
|
||||
}
|
||||
for (const [expected, tails] of [
|
||||
[true, [[1, 0], [1, 0, 0, 0], [1, 0, 0, 5, 0xfa, 0xce, 0, 1, 0xaa]]],
|
||||
[false, [[], [0], [1], [2, 0], [1, 1], [1, 0, 0], [1, 0, 0, 1],
|
||||
[1, 0, 0, 1, 0], [1, 0, 0, 5, 0xfa, 0xce, 0, 2, 0xaa],
|
||||
[1, 0, 0, 8, 0xfa, 0xce, 0, 0, 0xfa, 0xce, 0, 0]]],
|
||||
]) {
|
||||
for (const tail of tails) {
|
||||
const message = Buffer.concat([bytes.subarray(0, -2), Buffer.from(tail)]);
|
||||
message.writeUIntBE(message.length - 4, 1, 3);
|
||||
check({ ...result, stdout: trace(">>>", "Handshake", "ClientHello", message) + alert + summary },
|
||||
cipher, expected, "complete ClientHello vectors");
|
||||
}
|
||||
}
|
||||
for (const [expected, versions] of [
|
||||
[true, [2, 3, 3]], [true, [4, 3, 4, 3, 3]], [true, [4, 3, 3, 3, 4]],
|
||||
[false, []], [false, [0]], [false, [1, 3]], [false, [2, 3]],
|
||||
[false, [2, 3, 4]], [false, [4, 3, 3]], [false, [2, 3, 3, 3, 4]],
|
||||
]) {
|
||||
const extensions = Buffer.from([0, 43, 0, versions.length, ...versions]);
|
||||
const message = Buffer.concat([bytes, Buffer.from([0, extensions.length]), extensions]);
|
||||
message.writeUIntBE(message.length - 4, 1, 3);
|
||||
check({ ...result, stdout: trace(">>>", "Handshake", "ClientHello", message) + alert + summary },
|
||||
cipher, expected, "ClientHello version selection includes TLS 1.2");
|
||||
}
|
||||
for (const extra of [
|
||||
alert.slice(0, alert.indexOf("[length") + 3),
|
||||
alert.slice(0, alert.indexOf("\n") + 1),
|
||||
trace("<<<", "Handshake", "ServerHello", Buffer.from([2, 0, 0, 0])),
|
||||
" 91 a2 b3\n",
|
||||
"[TLS message omitted]\n",
|
||||
]) {
|
||||
for (const stream of ["stdout", "stderr"]) {
|
||||
for (const position of ["before", "after"]) {
|
||||
const output = position === "before" ? extra + result[stream] : result[stream] + extra;
|
||||
check({ ...result, [stream]: output }, cipher, false, `${stream} ${position} envelope`);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const [label, stdout] of [
|
||||
["record count", sent + hello + alert + summary],
|
||||
["record order", sent + received + hello + alert + summary],
|
||||
["record direction", sent + hello + received.replace("<<<", ">>>") + alert + summary],
|
||||
["record content type", sent.replace("16 03", "15 03") + hello + received + alert + summary],
|
||||
["record version", sent.replace("TLS 1.0", "TLS 1.2") + hello + received + alert + summary],
|
||||
["record payload length", sent + hello + received.replace("00 02", "00 03") + alert + summary],
|
||||
["message declared length", hello + alert.replace("length 0002", "length 0003") + summary],
|
||||
["message line termination", summary + hello + alert.trimEnd()],
|
||||
["intervening message", hello + "[TLS message omitted]\n" + alert + summary],
|
||||
]) check({ ...result, stdout }, cipher, false, label);
|
||||
for (const stream of ["stdout", "stderr"]) {
|
||||
const ticket = trace("<<<", "Handshake", "NewSessionTicket", Buffer.from([4, 0, 0, 2, 0x95, 0xa6]));
|
||||
const sanitized = invoke([], () => ({ ...result, [stream]: result[stream] + ticket }));
|
||||
assert.match(sanitized[stream], /\[TLS message omitted\]/);
|
||||
check(sanitized, cipher, false, `${stream} omitted message`);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("delayed log delivery is retried within a fixed page budget before verification", async (t) => {
|
||||
let reads = 0;
|
||||
const f = fixture(t, (action, result) => { if (action === "get-log-events" && ++reads <= 2) result.events = []; });
|
||||
const oldSummary = process.env.GITHUB_STEP_SUMMARY;
|
||||
process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary");
|
||||
t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; });
|
||||
await execute(f.aws, f.config, async () => {});
|
||||
await finish(f.aws, f.config, async () => {});
|
||||
assert.equal(f.evidence().success, true);
|
||||
assert.equal(reads, 4);
|
||||
});
|
||||
|
||||
test("a task that never stops and absent logs fail within bounded polling and preserve cleanup evidence", async (t) => {
|
||||
let sleeps = 0;
|
||||
const f = fixture(t, (action, result) => {
|
||||
if (action === "describe-tasks") result.tasks[0].lastStatus = "RUNNING";
|
||||
if (action === "get-log-events") result.events = [];
|
||||
});
|
||||
const oldSummary = process.env.GITHUB_STEP_SUMMARY;
|
||||
process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary");
|
||||
t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; });
|
||||
await assert.rejects(execute(f.aws, f.config, async () => { sleeps++; }), /inconclusive/);
|
||||
await assert.rejects(finish(f.aws, f.config, async () => { sleeps++; }), /cleanup failed/);
|
||||
assert.equal(f.calls.filter((c) => c.action === "describe-tasks").length, 60);
|
||||
assert.equal(f.calls.filter((c) => c.action === "get-log-events").length, 6);
|
||||
assert.equal(sleeps, 62);
|
||||
assert.equal(f.evidence().cleanup.stopped, false);
|
||||
assert.equal(f.calls.at(-1).action, "put-object");
|
||||
});
|
||||
|
||||
test("definition recovery confirms exact run identities within a fixed discovery budget and archives every outcome", async (t) => {
|
||||
const oldSummary = process.env.GITHUB_STEP_SUMMARY;
|
||||
t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; });
|
||||
for (const [name, discoveredAt, includeInvalid] of [
|
||||
["empty discovery remains unresolved", Infinity, false],
|
||||
["neighboring and malformed identities remain unresolved", Infinity, true],
|
||||
["exact identity on second discovery is confirmed", 2, true],
|
||||
["exact identity on final discovery is confirmed", 3, true],
|
||||
]) {
|
||||
await t.test(name, async (t) => {
|
||||
let reads = 0;
|
||||
const f = fixture(t, (action, result, calls) => {
|
||||
if (action === "register-task-definition") throw new Error("Fixture registration response unavailable");
|
||||
if (action === "list-task-definitions") {
|
||||
assert.deepEqual(calls.at(-1).args, ["--family-prefix", f.config.family, "--status", "ACTIVE"]);
|
||||
const invalid = [
|
||||
`${ECS}:task-definition/${f.config.family}7:1`,
|
||||
`${ECS}:task-definition/${f.config.family}-other:1`,
|
||||
`arn:aws:ecs:us-west-2:${ACCOUNT}:task-definition/${f.config.family}:1`,
|
||||
`arn:aws:ecs:us-east-1:000000000000:task-definition/${f.config.family}:1`,
|
||||
`${ECS}:task-definition/${f.config.family}:latest`,
|
||||
`${f.arn}/suffix`, `${f.arn}\n`, `${f.arn}\r\n`, null, 42,
|
||||
];
|
||||
result.taskDefinitionArns = [
|
||||
...(includeInvalid ? invalid : []), ...(++reads >= discoveredAt ? [f.arn, f.arn] : []),
|
||||
];
|
||||
}
|
||||
});
|
||||
process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary");
|
||||
await assert.rejects(execute(f.aws, f.config, async () => {}), /registration response unavailable/);
|
||||
const delays = [];
|
||||
await assert.rejects(finish(f.aws, f.config, async (ms) => { delays.push(ms); }), /incomplete/);
|
||||
const resolved = Number.isFinite(discoveredAt);
|
||||
const evidence = f.evidence();
|
||||
assert.equal(reads, Math.min(discoveredAt, 3));
|
||||
assert.deepEqual(delays, Array(reads - 1).fill(5000));
|
||||
assert.deepEqual(evidence.cleanup.definitionArns, resolved ? [f.arn] : []);
|
||||
assert.equal(evidence.cleanup.definitionRecovery, resolved ? "resolved" : "unresolved");
|
||||
assert.equal(evidence.cleanup.deregistered, resolved);
|
||||
assert.equal(evidence.cleanup.errors.includes("Diagnostic definition identity unresolved"), !resolved);
|
||||
assert.deepEqual(f.calls.filter((c) => c.action === "deregister-task-definition").map((c) => c.args),
|
||||
resolved ? [["--task-definition", f.arn]] : []);
|
||||
assert.equal(f.calls.filter((c) => c.action === "register-task-definition").length, 1);
|
||||
assert.ok(!f.calls.some((c) => ["run-task", "stop-task", "get-log-events"].includes(c.action)));
|
||||
assert.equal(evidence.success, false);
|
||||
assert.deepEqual(JSON.parse(readFileSync(join(f.config.work, "result.json"))), evidence);
|
||||
assert.equal(f.calls.filter((c) => c.action === "put-object").length, 2);
|
||||
assert.equal(f.calls.at(-1).action, "put-object");
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test("definition discovery errors remain inconclusive even when a later exact identity can be cleaned", async (t) => {
|
||||
const oldSummary = process.env.GITHUB_STEP_SUMMARY;
|
||||
t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; });
|
||||
for (const malformed of [false, true]) {
|
||||
let reads = 0;
|
||||
const f = fixture(t, (action, result) => {
|
||||
if (action === "register-task-definition") throw new Error("Fixture registration response unavailable");
|
||||
if (action === "list-task-definitions" && ++reads === 1) {
|
||||
if (malformed) result.taskDefinitionArns = {};
|
||||
else throw new Error("Fixture discovery response unavailable");
|
||||
}
|
||||
});
|
||||
process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary");
|
||||
await assert.rejects(execute(f.aws, f.config, async () => {}), /registration response unavailable/);
|
||||
await assert.rejects(finish(f.aws, f.config, async () => {}), /incomplete/);
|
||||
assert.equal(reads, 2);
|
||||
assert.equal(f.evidence().cleanup.definitionRecovery, "resolved");
|
||||
assert.equal(f.evidence().cleanup.deregistered, false);
|
||||
assert.ok(f.evidence().cleanup.errors.includes(malformed ? "Diagnostic definition discovery unconfirmed" : "Fixture discovery response unavailable"));
|
||||
assert.deepEqual(f.calls.filter((c) => c.action === "deregister-task-definition").map((c) => c.args[1]), [f.arn]);
|
||||
assert.ok(!f.calls.some((c) => c.action === "run-task"));
|
||||
assert.equal(f.evidence().success, false);
|
||||
assert.deepEqual(JSON.parse(readFileSync(join(f.config.work, "result.json"))), f.evidence());
|
||||
assert.equal(f.calls.at(-1).action, "put-object");
|
||||
}
|
||||
});
|
||||
|
||||
test("definition cleanup is not required when registration was never attempted", async (t) => {
|
||||
const f = fixture(t, (action, result) => { if (action === "get-caller-identity") result.Account = "000000000000"; });
|
||||
const oldSummary = process.env.GITHUB_STEP_SUMMARY;
|
||||
process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary");
|
||||
t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; });
|
||||
await assert.rejects(execute(f.aws, f.config, async () => {}), /identity required/);
|
||||
await assert.rejects(finish(f.aws, f.config, async () => { assert.fail("No registration needs no discovery delay"); }), /incomplete/);
|
||||
assert.ok(!f.calls.some((c) => ["register-task-definition", "list-task-definitions", "deregister-task-definition", "run-task"].includes(c.action)));
|
||||
assert.deepEqual(f.evidence().cleanup.definitionArns, []);
|
||||
assert.equal(f.evidence().cleanup.definitionRecovery, "not-required");
|
||||
assert.equal(f.evidence().cleanup.deregistered, true);
|
||||
assert.equal(f.evidence().success, false);
|
||||
assert.deepEqual(JSON.parse(readFileSync(join(f.config.work, "result.json"))), f.evidence());
|
||||
assert.equal(f.calls.at(-1).action, "put-object");
|
||||
});
|
||||
|
||||
test("a saved exact definition permits confirmed cleanup with empty active discovery", async (t) => {
|
||||
const f = fixture(t, (action, result) => { if (action === "list-task-definitions") result.taskDefinitionArns = []; });
|
||||
const oldSummary = process.env.GITHUB_STEP_SUMMARY;
|
||||
process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary");
|
||||
t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; });
|
||||
await execute(f.aws, f.config, async () => {});
|
||||
await finish(f.aws, f.config, async () => { assert.fail("Saved identity needs no discovery delay"); });
|
||||
assert.equal(f.calls.filter((c) => c.action === "list-task-definitions").length, 1);
|
||||
assert.deepEqual(f.calls.filter((c) => c.action === "deregister-task-definition").map((c) => c.args[1]), [f.arn]);
|
||||
assert.equal(f.evidence().cleanup.definitionRecovery, "resolved");
|
||||
assert.equal(f.evidence().cleanup.deregistered, true);
|
||||
assert.equal(f.evidence().success, true);
|
||||
assert.equal(f.calls.filter((c) => c.action === "run-task").length, 1);
|
||||
});
|
||||
|
||||
test("definition cleanup confirms only matching inactive readbacks and privately archives unconfirmed responses", async (t) => {
|
||||
const oldSummary = process.env.GITHUB_STEP_SUMMARY;
|
||||
t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; });
|
||||
for (const response of ["unavailable", "neighbor", "active"]) {
|
||||
const f = fixture(t, (action, result) => {
|
||||
if (action === "deregister-task-definition") {
|
||||
if (response === "unavailable") throw new Error("Fixture deregistration response unavailable");
|
||||
if (response === "neighbor") result.taskDefinition.taskDefinitionArn = `${ECS}:task-definition/${f.config.family}7:1`;
|
||||
if (response === "active") result.taskDefinition.status = "ACTIVE";
|
||||
}
|
||||
});
|
||||
process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary");
|
||||
await execute(f.aws, f.config, async () => {});
|
||||
await assert.rejects(finish(f.aws, f.config, async () => {}), /incomplete/);
|
||||
assert.equal(f.evidence().cleanup.definitionRecovery, "resolved");
|
||||
assert.equal(f.evidence().cleanup.deregistered, false);
|
||||
assert.ok(f.evidence().cleanup.errors.includes("Diagnostic definition deregistration unconfirmed"));
|
||||
assert.equal(f.calls.filter((c) => c.action === "deregister-task-definition").length, 1);
|
||||
assert.equal(f.calls.filter((c) => c.action === "register-task-definition").length, 1);
|
||||
assert.equal(f.calls.filter((c) => c.action === "run-task").length, 1);
|
||||
assert.equal(f.evidence().success, false);
|
||||
assert.deepEqual(JSON.parse(readFileSync(join(f.config.work, "result.json"))), f.evidence());
|
||||
assert.equal(f.calls.at(-1).action, "put-object");
|
||||
}
|
||||
});
|
||||
|
||||
test("deregistration validates saved and discovered definitions against the exact run family, account, region and revision", async (t) => {
|
||||
const oldSummary = process.env.GITHUB_STEP_SUMMARY;
|
||||
t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; });
|
||||
const config = configuration(env());
|
||||
const invalid = [
|
||||
`${ECS}:task-definition/${config.family}7:1`,
|
||||
`${ECS}:task-definition/${config.family}-other:1`,
|
||||
`${ECS}:task-definition/warmbly-production-backend:1`,
|
||||
`arn:aws:ecs:us-west-2:${ACCOUNT}:task-definition/${config.family}:1`,
|
||||
`arn:aws:ecs:us-east-1:000000000000:task-definition/${config.family}:1`,
|
||||
`${ECS}:task-definition/${config.family}:latest`,
|
||||
`${ECS}:task-definition/${config.family}:1/suffix`,
|
||||
`${ECS}:task-definition/${config.family}:1\n`,
|
||||
];
|
||||
for (const saved of invalid) {
|
||||
const f = fixture(t, (action, result, calls) => {
|
||||
if (action === "register-task-definition") throw new Error("Fixture lost response");
|
||||
if (action === "list-task-definitions") {
|
||||
assert.deepEqual(calls.at(-1).args, ["--family-prefix", config.family, "--status", "ACTIVE"]);
|
||||
result.taskDefinitionArns = [f.arn, ...invalid, `${ECS}:task-definition/${config.family}:2`, f.arn, null, 42];
|
||||
}
|
||||
if (action === "deregister-task-definition") result.taskDefinition.taskDefinitionArn = calls.at(-1).args[1];
|
||||
});
|
||||
process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary");
|
||||
await assert.rejects(execute(f.aws, f.config, async () => {}), /lost response/);
|
||||
writeFileSync(join(f.config.work, "evidence.json"), JSON.stringify({ ...f.evidence(), definitionArn: saved }));
|
||||
await assert.rejects(finish(f.aws, f.config, async () => {}), /incomplete/);
|
||||
const expected = [f.arn, `${ECS}:task-definition/${config.family}:2`];
|
||||
assert.deepEqual(f.calls.filter((c) => c.action === "deregister-task-definition").map((c) => c.args),
|
||||
expected.map((arn) => ["--task-definition", arn]));
|
||||
assert.deepEqual(f.evidence().cleanup.definitionArns, expected);
|
||||
assert.equal(f.evidence().cleanup.deregistered, true);
|
||||
assert.equal(f.calls.at(-1).action, "put-object");
|
||||
}
|
||||
});
|
||||
|
||||
test("cleanup failure stays bounded, still deregisters and archives, and never touches a neighboring family", async (t) => {
|
||||
const f = fixture(t, (action, result) => {
|
||||
if (action === "stop-task") throw new Error("Fixture stop denied");
|
||||
if (action === "list-task-definitions") result.taskDefinitionArns.push(`${ECS}:task-definition/${f.config.family}7:1`);
|
||||
});
|
||||
const oldSummary = process.env.GITHUB_STEP_SUMMARY;
|
||||
process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary");
|
||||
t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; });
|
||||
await execute(f.aws, f.config, async () => {});
|
||||
f.state.lastStatus = "RUNNING";
|
||||
await assert.rejects(finish(f.aws, f.config, async () => {}), /cleanup failed/);
|
||||
assert.deepEqual(f.calls.filter((c) => c.action === "deregister-task-definition").map((c) => c.args[1]), [f.arn]);
|
||||
assert.ok(f.evidence().cleanup.errors.includes("Fixture stop denied"));
|
||||
assert.equal(f.calls.at(-1).action, "put-object");
|
||||
});
|
||||
@@ -0,0 +1,185 @@
|
||||
const { spawnSync } = require("node:child_process");
|
||||
const { existsSync } = require("node:fs");
|
||||
|
||||
const HOST = "api.warmbly.com";
|
||||
const CA = "/etc/ssl/certs/ca-certificates.crt";
|
||||
const CBC = ["ECDHE-RSA-AES128-SHA256", "ECDHE-RSA-AES256-SHA384"];
|
||||
const GCM = ["ECDHE-RSA-AES128-GCM-SHA256", "ECDHE-RSA-AES256-GCM-SHA384"];
|
||||
const TLS13 = "TLS_AES_128_GCM_SHA256";
|
||||
const TRACE_HEADER = /^(>>>|<<<) TLS (1\.[0-3]), (RecordHeader|Handshake|Alert) \[length ([a-f\d]{4})\](?:, ([^\r\n]+))?$/i;
|
||||
const OMITTED_MESSAGE = "[TLS message omitted]";
|
||||
const validTargets = (targets) => Array.isArray(targets) && targets.length >= 2 && new Set(targets).size === targets.length &&
|
||||
targets.every((ip) => typeof ip === "string" && /^10\.42\.(?:0|1)\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4])$/.test(ip));
|
||||
|
||||
function sanitize(output) {
|
||||
let session = false;
|
||||
let ticket = false;
|
||||
return output.split("\n").flatMap((line) => {
|
||||
if (/^SSL-Session:/.test(line)) session = true;
|
||||
if (/^---$/.test(line)) session = false;
|
||||
if (/^(?:>>>|<<<) .*\bNewSessionTicket\b/.test(line)) {
|
||||
ticket = true;
|
||||
return [OMITTED_MESSAGE];
|
||||
}
|
||||
if (TRACE_HEADER.test(line)) ticket = false;
|
||||
if (ticket) return [];
|
||||
return !session || /^\s*Verify return code:/.test(line) ? [line] : [];
|
||||
}).join("\n");
|
||||
}
|
||||
|
||||
function invoke(args, spawn = spawnSync) {
|
||||
const result = spawn("openssl", args, { encoding: "utf8", input: "", timeout: 12000,
|
||||
killSignal: "SIGKILL", maxBuffer: 128 * 1024 });
|
||||
return { at: new Date().toISOString(), command: ["openssl", ...args], status: result.status,
|
||||
signal: result.signal || null, error: result.error?.code || null,
|
||||
stdout: sanitize(result.stdout || ""), stderr: sanitize(result.stderr || "") };
|
||||
}
|
||||
|
||||
function traceMessages(output) {
|
||||
const lines = output.split("\n");
|
||||
const messages = [];
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
if (/^[ \t]*[<>]/.test(line)) {
|
||||
const header = TRACE_HEADER.exec(line);
|
||||
if (!header || i === lines.length - 1 || (header[3] === "RecordHeader" ? header[5] : !header[5])) return null;
|
||||
let hex = "";
|
||||
while (i + 1 < lines.length && /^[ \t]+\S/.test(lines[i + 1])) {
|
||||
const body = lines[++i];
|
||||
if (i === lines.length - 1 || !/^[ \t]+(?:[a-f\d]{2}[ \t]+)*[a-f\d]{2}[ \t]*$/i.test(body)) return null;
|
||||
hex += body.replace(/[ \t]/g, "");
|
||||
}
|
||||
const bytes = Buffer.from(hex, "hex");
|
||||
if (!bytes.length || bytes.length !== parseInt(header[4], 16)) return null;
|
||||
messages.push({ direction: header[1], version: header[2], kind: header[3], name: header[5], bytes });
|
||||
} else if (line === OMITTED_MESSAGE || (/^[ \t]+\S/.test(line) && !/^[ \t]+Verify return code:/.test(line)) ||
|
||||
/\b(?:RecordHeader|Handshake|Alert) \[length\b/.test(line) ||
|
||||
/^[a-f\d]+(?:[ \t]|$)/i.test(line)) return null;
|
||||
}
|
||||
return messages;
|
||||
}
|
||||
|
||||
function completeClientHelloTail(sent, offset) {
|
||||
if (offset + 2 > sent.length || sent[offset] !== 1 || sent[offset + 1] !== 0) return false;
|
||||
offset += 2;
|
||||
if (offset === sent.length) return true;
|
||||
if (offset + 2 > sent.length || offset + 2 + sent.readUInt16BE(offset) !== sent.length) return false;
|
||||
offset += 2;
|
||||
const extensions = new Set();
|
||||
while (offset < sent.length) {
|
||||
if (offset + 4 > sent.length) return false;
|
||||
const kind = sent.readUInt16BE(offset);
|
||||
const length = sent.readUInt16BE(offset + 2);
|
||||
if (extensions.has(kind) || offset + 4 + length > sent.length) return false;
|
||||
if (kind === 43) {
|
||||
if (length < 3 || sent[offset + 4] !== length - 1 || (length - 1) % 2) return false;
|
||||
let tls12 = false;
|
||||
for (let at = offset + 5; at < offset + 4 + length; at += 2) {
|
||||
if (sent.readUInt16BE(at) === 0x0303) tls12 = true;
|
||||
}
|
||||
if (!tls12) return false;
|
||||
}
|
||||
extensions.add(kind);
|
||||
offset += 4 + length;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function peerRefusal(stdout, stderr, cipher) {
|
||||
const trace = traceMessages(stdout);
|
||||
const diagnosticTrace = traceMessages(stderr);
|
||||
if (!trace || !diagnosticTrace || diagnosticTrace.length) return false;
|
||||
const messages = trace.filter((message) => message.kind !== "RecordHeader");
|
||||
if (messages.length !== 2 || ![2, 4].includes(trace.length)) return false;
|
||||
if (trace.length === 4 && !messages.every((message, i) => {
|
||||
const record = trace[i * 2];
|
||||
return trace[i * 2 + 1] === message && record.kind === "RecordHeader" && record.direction === message.direction &&
|
||||
record.bytes.length === 5 && record.bytes[0] === (i === 0 ? 22 : 21) &&
|
||||
record.bytes.readUInt16BE(1) === 0x0301 + Number(record.version.at(-1)) &&
|
||||
record.bytes.readUInt16BE(3) === message.bytes.length;
|
||||
})) return false;
|
||||
const [hello, alert] = messages;
|
||||
const sent = hello.bytes;
|
||||
const received = alert.bytes;
|
||||
if (hello.direction !== ">>>" || hello.version !== "1.2" || hello.kind !== "Handshake" || hello.name !== "ClientHello" ||
|
||||
sent.length < 41 || sent[0] !== 1 || sent[38] > 32 ||
|
||||
sent.readUIntBE(1, 3) !== sent.length - 4 || sent.readUInt16BE(4) !== 0x0303) return false;
|
||||
const offset = 39 + sent[38];
|
||||
if (offset + 2 > sent.length) return false;
|
||||
const length = sent.readUInt16BE(offset);
|
||||
const offers = sent.subarray(offset + 2, offset + 2 + length).toString("hex");
|
||||
const intended = { [CBC[0]]: "c027", [CBC[1]]: "c028" }[cipher];
|
||||
// The sole negotiable suite may be followed by the renegotiation signalling value.
|
||||
return intended && length >= 2 && offset + 2 + length < sent.length &&
|
||||
completeClientHelloTail(sent, offset + 2 + length) &&
|
||||
(offers === intended || offers === intended + "00ff") &&
|
||||
alert.direction === "<<<" && alert.version === "1.2" && alert.kind === "Alert" && alert.name === "fatal handshake_failure" &&
|
||||
received.equals(Buffer.from([2, 40]));
|
||||
}
|
||||
|
||||
function classify(result, version, cipher, negative = false) {
|
||||
const output = result.stdout + result.stderr;
|
||||
const negotiated = /New, (TLSv1\.[23]), Cipher is ([^\s]+)/.exec(output);
|
||||
if (negative) {
|
||||
if (/certificate verify failed|Verification error|verify error|no cipher match|unexpected eof|reset by peer|connect:errno/i.test(output)) return "inconclusive";
|
||||
const deadline = result.error === "ETIMEDOUT" && result.status === null && (!result.signal || result.signal === "SIGKILL");
|
||||
if (negotiated && negotiated[2] !== "(NONE)" && negotiated[2] !== "0000" &&
|
||||
((!result.error && !result.signal) || deadline)) return "accepted";
|
||||
if (result.error || result.signal) return "inconclusive";
|
||||
return result.status === 1 && peerRefusal(result.stdout || "", result.stderr || "", cipher) &&
|
||||
!/-----BEGIN CERTIFICATE-----/.test(output) && /no peer certificate available/.test(output) &&
|
||||
/New, \(NONE\), Cipher is \(NONE\)/.test(output) ? "refused" : "inconclusive";
|
||||
}
|
||||
if (result.error || result.signal) return "inconclusive";
|
||||
return result.status === 0 && negotiated?.[1] === version && negotiated[2] === cipher &&
|
||||
/Verify return code: 0 \(ok\)/.test(output) && /-----BEGIN CERTIFICATE-----/.test(output) ? "trusted" : "inconclusive";
|
||||
}
|
||||
|
||||
function probe(targets, run = invoke, emit = (row) => console.log(JSON.stringify(row)), now = () => performance.now()) {
|
||||
if (!validTargets(targets)) throw new Error("Unique pinned origin IPv4 targets required");
|
||||
const started = now();
|
||||
const bounded = (args) => {
|
||||
// Reserve one 12-second invocation within 180 seconds and the outer 210-second task limit.
|
||||
if (now() - started >= 168000) throw new Error("Origin TLS client runtime budget exhausted");
|
||||
return run(args);
|
||||
};
|
||||
const version = bounded(["version", "-a"]);
|
||||
emit({ kind: "client", ...version });
|
||||
if (version.status !== 0 || version.error || version.signal) throw new Error("OpenSSL unavailable");
|
||||
const support = bounded(["ciphers", "-s", "-tls1_2", CBC.join(":")]);
|
||||
emit({ kind: "support", ...support });
|
||||
if (support.status !== 0 || support.error || support.signal ||
|
||||
support.stdout.trim().split(":").sort().join(":") !== [...CBC].sort().join(":")) throw new Error("Both CBC offers must be locally supported");
|
||||
let success = true;
|
||||
for (const ip of targets) {
|
||||
const handshake = (cipher, negative = false) => {
|
||||
const tls13 = cipher === TLS13;
|
||||
const result = bounded(["s_client", "-connect", `${ip}:443`, "-servername", HOST, "-verify_hostname", HOST,
|
||||
"-verify_return_error", "-CAfile", CA, "-showcerts", "-no_ticket",
|
||||
...(negative ? ["-ign_eof", "-state", "-msg"] : []), tls13 ? "-tls1_3" : "-tls1_2",
|
||||
tls13 ? "-ciphersuites" : "-cipher", cipher]);
|
||||
const outcome = classify(result, tls13 ? "TLSv1.3" : "TLSv1.2", cipher, negative);
|
||||
emit({ kind: "handshake", ip, cipher, negative, outcome, ...result });
|
||||
return outcome;
|
||||
};
|
||||
const before = [handshake(GCM[0]), handshake(GCM[1]), handshake(TLS13)];
|
||||
const negatives = CBC.map((cipher) => handshake(cipher, true));
|
||||
const after = [handshake(GCM[0]), handshake(TLS13)];
|
||||
const passed = [...before, ...after].every((v) => v === "trusted") && negatives.every((v) => v === "refused");
|
||||
emit({ kind: "target", ip, outcome: passed ? "verified" : "inconclusive" });
|
||||
success = success && passed;
|
||||
}
|
||||
emit({ kind: "complete", success, at: new Date().toISOString() });
|
||||
return success;
|
||||
}
|
||||
|
||||
if (process.env.ORIGIN_TLS_TASK === "1") {
|
||||
try {
|
||||
if (!existsSync(CA)) throw new Error("System public CA bundle missing");
|
||||
process.exitCode = probe(JSON.parse(process.env.ORIGIN_TLS_TARGETS)) ? 0 : 1;
|
||||
} catch (error) {
|
||||
console.log(JSON.stringify({ kind: "inconclusive", message: error.message }));
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
module.exports = { HOST, CA, CBC, GCM, TLS13, invoke, classify, probe, validTargets };
|
||||
@@ -0,0 +1,15 @@
|
||||
const { CBC } = require("./origin-tls-client.cjs");
|
||||
|
||||
function refused(cipher = CBC[0]) {
|
||||
const suite = cipher === CBC[0] ? "c0 27" : "c0 28";
|
||||
const hello = `01 00 00 2b 03 03 ${"00 ".repeat(32)}00 00 04 ${suite} 00 ff 01 00`;
|
||||
return { status: 1, stdout: `>>> TLS 1.2, Handshake [length 002f], ClientHello
|
||||
${hello}
|
||||
<<< TLS 1.2, Alert [length 0002], fatal handshake_failure
|
||||
02 28
|
||||
no peer certificate available
|
||||
New, (NONE), Cipher is (NONE)
|
||||
`, stderr: "SSL_connect:SSLv3/TLS write client hello\nSSL3 alert read:fatal:handshake failure\n" };
|
||||
}
|
||||
|
||||
module.exports = { refused };
|
||||
@@ -0,0 +1,294 @@
|
||||
const { test } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const { spawnSync } = require("node:child_process");
|
||||
const { mkdtempSync, readFileSync, rmSync } = require("node:fs");
|
||||
const { tmpdir } = require("node:os");
|
||||
const { join } = require("node:path");
|
||||
const { Worker } = require("node:worker_threads");
|
||||
const { CBC, GCM, TLS13, HOST, CA, invoke, classify, probe } = require("./origin-tls-client.cjs");
|
||||
const { refused } = require("./origin-tls-client.fixture.cjs");
|
||||
const trusted = (cipher = GCM[0]) => ({ status: 0, stdout: `-----BEGIN CERTIFICATE-----\nfixture chain\n-----END CERTIFICATE-----\nNew, ${cipher === TLS13 ? "TLSv1.3" : "TLSv1.2"}, Cipher is ${cipher}\nVerify return code: 0 (ok)\n`, stderr: "" });
|
||||
|
||||
test("positive proof requires exact negotiation, chain, verification and successful bounded execution", () => {
|
||||
assert.equal(classify(trusted(), "TLSv1.2", GCM[0]), "trusted");
|
||||
for (const result of [
|
||||
{ ...trusted(), status: 1 }, { ...trusted(), error: "ETIMEDOUT" }, { ...trusted(), signal: "SIGKILL" },
|
||||
{ ...trusted(), stdout: trusted().stdout.replace("return code: 0 (ok)", "return code: 62 (hostname mismatch)") },
|
||||
{ ...trusted(), stdout: trusted().stdout.replace("-----BEGIN CERTIFICATE-----", "") },
|
||||
trusted(GCM[1]), trusted(TLS13),
|
||||
]) assert.equal(classify(result, "TLSv1.2", GCM[0]), "inconclusive");
|
||||
});
|
||||
|
||||
test("only an explicit peer handshake refusal without negotiation establishes a negative", () => {
|
||||
assert.equal(classify(refused(), "TLSv1.2", CBC[0], true), "refused");
|
||||
assert.equal(classify(trusted(CBC[0]), "TLSv1.2", CBC[0], true), "accepted");
|
||||
for (const result of [
|
||||
{ ...refused(), signal: "SIGTERM" }, { ...refused(), error: "ETIMEDOUT" },
|
||||
{ status: 1, stdout: "", stderr: "Connection reset by peer" },
|
||||
{ status: 1, stdout: "", stderr: "connect:errno=110" },
|
||||
{ status: 1, stdout: "", stderr: "no cipher match" },
|
||||
{ status: 1, stdout: "", stderr: "certificate verify failed" },
|
||||
{ status: 1, stdout: "", stderr: "tlsv1 alert protocol version:SSL alert number 70" },
|
||||
{ ...refused(), stdout: "", status: 0 },
|
||||
]) assert.equal(classify(result, "TLSv1.2", CBC[0], true), "inconclusive");
|
||||
});
|
||||
|
||||
function fixture(change = () => {}) {
|
||||
const rows = [];
|
||||
let handshakes = 0;
|
||||
const run = (args) => {
|
||||
if (args[0] === "version") return { status: 0, stdout: "OpenSSL 3.0 fixture", stderr: "" };
|
||||
if (args[0] === "ciphers") return { status: 0, stdout: CBC.join(":"), stderr: "" };
|
||||
handshakes++;
|
||||
const cipher = args.at(-1);
|
||||
const result = { ...(CBC.includes(cipher) ? refused(cipher) : trusted(cipher)), command: ["openssl", ...args] };
|
||||
change(result, handshakes);
|
||||
return result;
|
||||
};
|
||||
return { rows, run };
|
||||
}
|
||||
|
||||
test("completed negative negotiations retain their outcome at the process deadline", () => {
|
||||
for (const cipher of CBC) {
|
||||
const negotiated = { ...trusted(cipher), status: null, error: "ETIMEDOUT", signal: "SIGKILL" };
|
||||
assert.equal(classify(negotiated, "TLSv1.2", cipher, true), "accepted");
|
||||
assert.equal(classify({ ...negotiated, signal: null }, "TLSv1.2", cipher, true), "accepted");
|
||||
for (const altered of [
|
||||
{ ...negotiated, error: "ENOBUFS" }, { ...negotiated, error: "EIO" },
|
||||
{ ...negotiated, error: null }, { ...negotiated, signal: "SIGTERM" }, { ...negotiated, status: 0 },
|
||||
{ ...negotiated, stderr: "certificate verify failed" },
|
||||
{ ...negotiated, stdout: refused(cipher).stdout },
|
||||
]) assert.equal(classify(altered, "TLSv1.2", cipher, true), "inconclusive");
|
||||
assert.equal(classify(negotiated, "TLSv1.2", cipher), "inconclusive");
|
||||
}
|
||||
const f = fixture((row, index) => {
|
||||
if (index === 4) Object.assign(row, trusted(CBC[0]), { status: null, error: "ETIMEDOUT", signal: "SIGKILL" });
|
||||
});
|
||||
assert.equal(probe(["10.42.0.85", "10.42.1.12"], f.run, (row) => f.rows.push(row)), false);
|
||||
assert.equal(f.rows.find((row) => row.kind === "handshake" && row.negative).outcome, "accepted");
|
||||
assert.equal(f.rows.at(-1).success, false);
|
||||
});
|
||||
|
||||
test("every private target has fresh trusted positives around both explicit CBC offers", () => {
|
||||
const f = fixture();
|
||||
assert.equal(probe(["10.42.0.85", "10.42.1.12"], f.run, (row) => f.rows.push(row)), true);
|
||||
const hs = f.rows.filter((r) => r.kind === "handshake");
|
||||
assert.equal(hs.length, 14);
|
||||
for (const ip of ["10.42.0.85", "10.42.1.12"]) {
|
||||
const own = hs.filter((r) => r.ip === ip);
|
||||
assert.deepEqual(own.map((r) => r.cipher), [GCM[0], GCM[1], TLS13, ...CBC, GCM[0], TLS13]);
|
||||
for (const row of own) {
|
||||
const args = row.command;
|
||||
for (const [flag, value] of [["-connect", `${ip}:443`], ["-servername", HOST], ["-verify_hostname", HOST], ["-CAfile", CA]]) {
|
||||
assert.equal(args[args.indexOf(flag) + 1], value);
|
||||
}
|
||||
assert.ok(args.includes("-verify_return_error"));
|
||||
assert.ok(args.includes("-showcerts"));
|
||||
assert.ok(args.includes("-no_ticket"));
|
||||
for (const flag of ["-ign_eof", "-state", "-msg"]) assert.equal(args.includes(flag), row.negative);
|
||||
assert.ok(args.includes(row.cipher === TLS13 ? "-tls1_3" : "-tls1_2"));
|
||||
}
|
||||
}
|
||||
assert.deepEqual(f.rows.at(-1).success, true);
|
||||
});
|
||||
|
||||
test("all current private interfaces receive the full handshake sequence", () => {
|
||||
const targets = ["10.42.0.85", "10.42.1.12", "10.42.0.86", "10.42.1.13"];
|
||||
const f = fixture();
|
||||
assert.equal(probe(targets, f.run, (row) => f.rows.push(row)), true);
|
||||
const handshakes = f.rows.filter((r) => r.kind === "handshake");
|
||||
assert.equal(handshakes.length, 28);
|
||||
for (const ip of targets) {
|
||||
assert.deepEqual(handshakes.filter((r) => r.ip === ip).map((r) => r.cipher),
|
||||
[GCM[0], GCM[1], TLS13, ...CBC, GCM[0], TLS13]);
|
||||
}
|
||||
assert.equal(f.rows.at(-1).success, true);
|
||||
});
|
||||
|
||||
test("larger target sets share one fixed runtime budget and cannot complete with partial evidence", () => {
|
||||
const f = fixture();
|
||||
let elapsed = 0;
|
||||
let calls = 0;
|
||||
const run = (args) => {
|
||||
calls++;
|
||||
elapsed += 12000;
|
||||
return f.run(args);
|
||||
};
|
||||
assert.throws(() => probe(["10.42.0.85", "10.42.1.12", "10.42.0.86", "10.42.1.13"],
|
||||
run, (row) => f.rows.push(row), () => elapsed), /runtime budget exhausted/);
|
||||
assert.equal(calls, 14);
|
||||
assert.equal(elapsed, 168000);
|
||||
assert.ok(!f.rows.some((r) => r.kind === "complete"));
|
||||
});
|
||||
|
||||
test("timeout or broken trailing positive makes the whole run inconclusive", () => {
|
||||
for (const index of [4, 6, 14]) {
|
||||
const f = fixture((result, n) => { if (n === index) result.error = "ETIMEDOUT"; });
|
||||
assert.equal(probe(["10.42.0.85", "10.42.1.12"], f.run, (row) => f.rows.push(row)), false);
|
||||
assert.equal(f.rows.at(-1).success, false);
|
||||
}
|
||||
});
|
||||
|
||||
test("local CBC support is checked before network traffic and arbitrary destinations are refused", () => {
|
||||
const f = fixture();
|
||||
assert.throws(() => probe(["1.1.1.1", "10.42.1.12"], f.run), /pinned/);
|
||||
assert.throws(() => probe(["10.42.0.85", "10.42.0.85"], f.run), /pinned/);
|
||||
assert.throws(() => probe(["10.42.0.85", "10.42.1.12"], (args) => ({ status: 0, stdout: args[0] === "version" ? "OpenSSL" : CBC[0] }), () => {}), /Both CBC/);
|
||||
});
|
||||
|
||||
test("OpenSSL processes get empty stdin, a hard timeout, bounded output and no shell", () => {
|
||||
const result = invoke(["version"], (command, args, options) => {
|
||||
assert.equal(command, "openssl");
|
||||
assert.deepEqual(args, ["version"]);
|
||||
assert.equal(options.input, "");
|
||||
assert.equal(options.timeout, 12000);
|
||||
assert.equal(options.killSignal, "SIGKILL");
|
||||
assert.equal(options.shell, undefined);
|
||||
assert.equal(options.maxBuffer, 128 * 1024);
|
||||
return { status: null, error: { code: "ETIMEDOUT" }, signal: "SIGKILL" };
|
||||
});
|
||||
assert.equal(result.error, "ETIMEDOUT");
|
||||
assert.equal(result.signal, "SIGKILL");
|
||||
});
|
||||
|
||||
test("negative proof binds inbound alert bytes to the sole transmitted CBC suite", () => {
|
||||
for (const cipher of CBC) assert.equal(classify(refused(cipher), "TLSv1.2", cipher, true), "refused");
|
||||
for (const change of [
|
||||
(s) => s.replace("<<<", ">>>"),
|
||||
(s) => s.replace("02 28", "01 00"),
|
||||
(s) => s.replace("fatal handshake_failure", "warning close_notify"),
|
||||
(s) => s.replace("c0 27", "c0 28"),
|
||||
(s) => s.replace("c0 27", "c0 2f"),
|
||||
(s) => s.replace("00 04 c0 27 00 ff", "00 04 c0 27 c0 2f"),
|
||||
(s) => s.replace("length 002f", "length 0030"),
|
||||
(s) => s.replace("01 00 00 2b", "01 00 00 2c"),
|
||||
(s) => s.replace("New, (NONE)", "-----BEGIN CERTIFICATE-----\nNew, (NONE)"),
|
||||
(s) => s.replace("no peer certificate available", ""),
|
||||
(s) => s + "Connection reset by peer\n",
|
||||
(s) => s + "unexpected eof while reading\n",
|
||||
(s) => s + "<<< TLS 1.2, Handshake [length 0004], ServerHello\n 02 00 00 00\n",
|
||||
(s) => s.replace(/>>>[\s\S]*?<<< /, "<<< "),
|
||||
]) assert.equal(classify({ ...refused(), stdout: change(refused().stdout) }, "TLSv1.2", CBC[0], true), "inconclusive");
|
||||
for (const status of [0, null, 2]) assert.equal(classify({ ...refused(), status }, "TLSv1.2", CBC[0], true), "inconclusive");
|
||||
for (const stdout of ["CONNECTED\nclosed\nno peer certificate available\nNew, (NONE), Cipher is (NONE)\n",
|
||||
"SSL handshake has read 7 bytes\nNew, (NONE), Cipher is (NONE)\n"]) {
|
||||
assert.equal(classify({ status: 0, stdout, stderr: "" }, "TLSv1.2", CBC[0], true), "inconclusive");
|
||||
}
|
||||
});
|
||||
|
||||
test("archived output retains certificate and refusal evidence without session secrets or ticket bodies", () => {
|
||||
const proof = trusted().stdout + refused().stdout;
|
||||
const session = "SSL-Session:\n Protocol : TLSv1.2\n Master-Key: SECRET_KEY\n Resumption PSK: SECRET_PSK\n TLS session ticket:\n 0000 - ab cd ef ...\n Verify return code: 0 (ok)\n---\n";
|
||||
const ticket = "<<< TLS 1.2, Handshake [length 0004], NewSessionTicket\n 04 00 00 00\n";
|
||||
const result = invoke(["version"], () => ({ status: 0, stdout: proof + session + ticket + refused().stdout, stderr: session }));
|
||||
assert.ok(result.stdout.includes(proof));
|
||||
assert.ok(result.stdout.includes("Verify return code: 0 (ok)"));
|
||||
assert.ok(result.stdout.endsWith(refused().stdout));
|
||||
assert.doesNotMatch(result.stdout + result.stderr, /SECRET|Master-Key|Resumption PSK|session ticket|NewSessionTicket|04 00 00 00|ab cd ef/);
|
||||
});
|
||||
|
||||
test("captured ticket and session regions retain only approved evidence at every cutoff", () => {
|
||||
const prefix = trusted().stdout;
|
||||
const header = "<<< TLS 1.2, Handshake [length 000e], NewSessionTicket\n";
|
||||
const body = " 04 00 00 0a 71 82 93 a4\n b5 c6 d7 e8 f9 0a\ncapture-tail";
|
||||
const resumed = "<<< TLS 1.2, Alert [length 0002], warning close_notify\n 01 00\n";
|
||||
const session = "SSL-Session:\n Master-Key: SYNTHETIC_MAPLE\n Resumption PSK: SYNTHETIC_BIRCH\n";
|
||||
for (const stream of ["stdout", "stderr"]) {
|
||||
for (const execution of [{ status: 0 }, { status: null, error: { code: "ENOBUFS" } },
|
||||
{ status: null, error: { code: "ETIMEDOUT" }, signal: "SIGKILL" }]) {
|
||||
const capture = (output) => invoke([], () => ({ stdout: "", stderr: "", ...execution, [stream]: output }));
|
||||
for (let cutoff = 0; cutoff <= body.length; cutoff++) {
|
||||
const output = prefix + header + body.slice(0, cutoff);
|
||||
assert.equal(capture(output)[stream], prefix + "[TLS message omitted]", `${stream} ticket cutoff ${cutoff}`);
|
||||
assert.equal(capture(output + "\n" + resumed)[stream], prefix + "[TLS message omitted]\n" + resumed,
|
||||
`${stream} trace recovery ${cutoff}`);
|
||||
}
|
||||
for (let cutoff = 0; cutoff <= session.length; cutoff++) {
|
||||
const output = prefix + session.slice(0, cutoff);
|
||||
if (cutoff < "SSL-Session:\n".length) continue;
|
||||
assert.equal(capture(output)[stream], prefix.trimEnd(), `${stream} session cutoff ${cutoff}`);
|
||||
}
|
||||
const verification = " Verify return code: 0 (ok)\n";
|
||||
assert.equal(capture(prefix + session + verification + "---\n" + resumed)[stream],
|
||||
prefix + verification + "---\n" + resumed);
|
||||
assert.equal(classify(capture(prefix + session + verification), "TLSv1.2", GCM[0]),
|
||||
execution.status === 0 ? "trusted" : "inconclusive");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("loopback TLS and alert peers preserve strict refusal and trusted positive behavior", { timeout: 20000 }, async (t) => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "origin-tls-local-"));
|
||||
t.after(() => rmSync(dir, { recursive: true, force: true }));
|
||||
const cert = join(dir, "cert.pem");
|
||||
const key = join(dir, "key.pem");
|
||||
const generated = spawnSync("openssl", ["req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", key,
|
||||
"-out", cert, "-days", "1", "-subj", "/CN=localhost", "-addext", "subjectAltName=DNS:localhost"], { timeout: 10000, encoding: "utf8" });
|
||||
assert.equal(generated.status, 0, generated.stderr);
|
||||
const f = fixture();
|
||||
probe(["10.42.0.85", "10.42.1.12"], f.run, (row) => f.rows.push(row));
|
||||
for (const mode of ["tls", "tls_held", "fatal", "close_notify", "eof", "reset", "silent"]) {
|
||||
await t.test(mode, async () => {
|
||||
const worker = new Worker(`
|
||||
const { parentPort, workerData: d } = require("node:worker_threads");
|
||||
const net = require("node:net");
|
||||
const tls = require("node:tls");
|
||||
const server = d.mode.startsWith("tls") ? tls.createServer({ key: d.key, cert: d.cert,
|
||||
minVersion: "TLSv1.2", maxVersion: "TLSv1.2", ciphers: d.cipher }, (s) => {
|
||||
s.on("error", () => {});
|
||||
if (d.mode === "tls") s.end();
|
||||
}) : net.createServer((s) => {
|
||||
let input = Buffer.alloc(0);
|
||||
s.on("error", () => {});
|
||||
s.on("data", (b) => {
|
||||
input = Buffer.concat([input, b]);
|
||||
if (input.length < 5 || input.length < 5 + input.readUInt16BE(3)) return;
|
||||
if (d.mode === "silent") return;
|
||||
if (d.mode === "reset") { s.resetAndDestroy(); return; }
|
||||
setTimeout(() => s.end(d.mode === "eof" ? Buffer.alloc(0) :
|
||||
Buffer.from([21, 3, 3, 0, 2, ...(d.mode === "fatal" ? [2, 40] : [1, 0])])), 50);
|
||||
});
|
||||
});
|
||||
server.on("tlsClientError", () => {});
|
||||
server.listen(0, "127.0.0.1", () => parentPort.postMessage(server.address().port));
|
||||
`, { eval: true, workerData: { mode, key: readFileSync(key), cert: readFileSync(cert), cipher: mode === "tls_held" ? CBC.join(":") : GCM[0] } });
|
||||
try {
|
||||
const port = await new Promise((resolve, reject) => { worker.once("message", resolve); worker.once("error", reject); });
|
||||
const localArgs = (cipher) => {
|
||||
const args = f.rows.find((r) => r.kind === "handshake" && r.cipher === cipher).command.slice(1);
|
||||
for (const [flag, value] of [["-connect", `127.0.0.1:${port}`], ["-servername", "localhost"],
|
||||
["-verify_hostname", "localhost"], ["-CAfile", cert]]) args[args.indexOf(flag) + 1] = value;
|
||||
return args;
|
||||
};
|
||||
for (const cipher of CBC) {
|
||||
const result = invoke(localArgs(cipher), (command, args, options) => spawnSync(command, args,
|
||||
{ ...options, timeout: mode === "tls_held" ? 500 : mode === "silent" ? 300 : options.timeout }));
|
||||
assert.equal(classify(result, "TLSv1.2", cipher, true), mode === "tls_held" ? "accepted" : ["tls", "fatal"].includes(mode) ? "refused" : "inconclusive",
|
||||
JSON.stringify(result));
|
||||
if (mode === "tls_held") {
|
||||
assert.equal(result.error, "ETIMEDOUT");
|
||||
assert.equal(result.signal, "SIGKILL");
|
||||
assert.ok(result.stdout.includes(`New, TLSv1.2, Cipher is ${cipher}`));
|
||||
assert.match(result.stdout, /Verify return code: 0 \(ok\)/);
|
||||
}
|
||||
if (mode === "close_notify") {
|
||||
assert.match(result.stdout, /<<< TLS 1.2, Alert \[length 0002\], warning close_notify\n\s+01 00/);
|
||||
const summaryOnly = invoke(localArgs(cipher).filter((arg) => !["-ign_eof", "-state", "-msg"].includes(arg)));
|
||||
assert.equal(summaryOnly.status, 0);
|
||||
assert.match(summaryOnly.stdout, /SSL handshake has read 7 bytes/);
|
||||
assert.equal(classify(summaryOnly, "TLSv1.2", cipher, true), "inconclusive");
|
||||
}
|
||||
if (mode === "silent") assert.equal(result.error, "ETIMEDOUT");
|
||||
assert.doesNotMatch(result.stdout + result.stderr, /Master-Key|Resumption PSK|TLS session ticket:/);
|
||||
}
|
||||
if (mode === "tls") {
|
||||
const positive = invoke(localArgs(GCM[0]));
|
||||
assert.equal(classify(positive, "TLSv1.2", GCM[0]), "trusted", JSON.stringify(positive));
|
||||
const accepted = invoke([...localArgs(CBC[0]).slice(0, -1), GCM[0]]);
|
||||
assert.equal(classify(accepted, "TLSv1.2", CBC[0], true), "accepted");
|
||||
assert.doesNotMatch(positive.stdout + positive.stderr + accepted.stdout + accepted.stderr, /Master-Key|Resumption PSK|TLS session ticket:/);
|
||||
}
|
||||
} finally { await worker.terminate(); }
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
export function previewURL(entries, project, sha) {
|
||||
const matches = entries.filter(deployment => deployment.type === 'pages-deploy-detailed'
|
||||
&& deployment.version === 1
|
||||
&& deployment.pages_project === project
|
||||
&& deployment.environment === 'preview'
|
||||
&& deployment.deployment_trigger?.metadata?.commit_hash === sha
|
||||
&& typeof deployment.deployment_id === 'string' && deployment.deployment_id.length > 0);
|
||||
assert.equal(matches.length, 1, 'Require one Wrangler preview receipt for this project and commit');
|
||||
const url = new URL(matches[0].url);
|
||||
assert.equal(url.protocol, 'https:');
|
||||
assert.ok(url.hostname.endsWith(`.${project}.pages.dev`), 'Require the configured Pages project');
|
||||
assert.ok(!url.username && !url.password && url.pathname === '/' && !url.search && !url.hash);
|
||||
return url;
|
||||
}
|
||||
|
||||
export async function verifyPreview(url, policy, request = fetch, directory = new URL('../../site/dist/', import.meta.url)) {
|
||||
for (const [path, status, type] of [
|
||||
['/', 200, 'text/html'], ['/terms/', 200, 'text/html'], ['/privacy/', 200, 'text/html'],
|
||||
['/marketing-csp-missing-page', 404, 'text/html'],
|
||||
['/install.sh', 200, null], ['/cli.sh', 200, null],
|
||||
]) {
|
||||
const response = await request(new URL(path, url), { redirect: 'error', signal: AbortSignal.timeout(30000) });
|
||||
assert.equal(response.status, status, `Unexpected preview status for ${path}`);
|
||||
assert.equal(response.headers.get('content-security-policy'), policy, `Unexpected preview CSP for ${path}`);
|
||||
assert.equal(response.headers.get('x-content-type-options'), 'nosniff');
|
||||
if (type) assert.ok(response.headers.get('content-type')?.startsWith(type));
|
||||
else assert.equal(await response.text(), await readFile(new URL(path.slice(1), directory), 'utf8'));
|
||||
}
|
||||
}
|
||||
|
||||
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
||||
const { CLOUDFLARE_PAGES_PROJECT_NAME: project, WRANGLER_OUTPUT_FILE_PATH: receipt, GITHUB_SHA: sha } = process.env;
|
||||
assert.ok(project && receipt && sha, 'Require preview deployment configuration');
|
||||
const entries = (await readFile(receipt, 'utf8')).split(/\r?\n/).filter(line => line.trim()).map(line => JSON.parse(line));
|
||||
const url = previewURL(entries, project, sha);
|
||||
const headers = await readFile(new URL('../../site/dist/_headers', import.meta.url), 'utf8');
|
||||
const policies = [...headers.matchAll(/^\s+Content-Security-Policy: (.+)$/gm)];
|
||||
assert.equal(policies.length, 1, 'Require one built policy');
|
||||
await verifyPreview(url, policies[0][1]);
|
||||
console.log('Marketing preview headers, routes and published installers verified');
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { test } from 'node:test';
|
||||
import { previewURL, verifyPreview } from './pages-marketing-preview.mjs';
|
||||
|
||||
test('accepts only a versioned Wrangler preview receipt for the reviewed commit and project', () => {
|
||||
const deployment = { type: 'pages-deploy-detailed', version: 1, pages_project: 'marketing',
|
||||
deployment_id: 'deployment-id', environment: 'preview', url: 'https://abc.marketing.pages.dev',
|
||||
deployment_trigger: { metadata: { commit_hash: 'sha' } } };
|
||||
const select = value => previewURL([value], 'marketing', 'sha');
|
||||
assert.equal(select(deployment).origin, 'https://abc.marketing.pages.dev');
|
||||
for (const override of [
|
||||
{ environment: 'production' }, { url: 'https://abc.other.pages.dev' },
|
||||
{ type: 'pages-deploy' }, { version: 2 }, { pages_project: 'other' }, { deployment_id: null },
|
||||
{ deployment_trigger: { metadata: { commit_hash: 'old' } } },
|
||||
]) assert.throws(() => select({ ...deployment, ...override }));
|
||||
assert.throws(() => previewURL([deployment, deployment], 'marketing', 'sha'));
|
||||
assert.equal(previewURL([{ type: 'pages-deploy' }, deployment], 'marketing', 'sha').origin, 'https://abc.marketing.pages.dev');
|
||||
});
|
||||
|
||||
test('verifies page, error and byte-identical installer responses with the built policy', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'marketing-preview-'));
|
||||
try {
|
||||
for (const file of ['install.sh', 'cli.sh']) await writeFile(join(root, file), `# ${file}\n`);
|
||||
const paths = [];
|
||||
const request = async url => {
|
||||
paths.push(url.pathname);
|
||||
const script = url.pathname.endsWith('.sh');
|
||||
return new Response(script ? `# ${url.pathname.slice(1)}\n` : '<html>Page</html>', {
|
||||
status: url.pathname.includes('missing-page') ? 404 : 200,
|
||||
headers: { 'content-security-policy': 'policy', 'x-content-type-options': 'nosniff',
|
||||
'content-type': script ? 'text/plain' : 'text/html; charset=utf-8' },
|
||||
});
|
||||
};
|
||||
await verifyPreview('https://abc.marketing.pages.dev', 'policy', request, pathToFileURL(`${root}/`));
|
||||
assert.deepEqual(paths, ['/', '/terms/', '/privacy/', '/marketing-csp-missing-page', '/install.sh', '/cli.sh']);
|
||||
await writeFile(join(root, 'cli.sh'), 'different bytes');
|
||||
await assert.rejects(verifyPreview('https://abc.marketing.pages.dev', 'policy', request, pathToFileURL(`${root}/`)));
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('blocks promotion for absent or different policy, redirects and unexpected responses', async () => {
|
||||
for (const response of [
|
||||
new Response('', { status: 200 }),
|
||||
new Response('', { status: 200, headers: { 'content-security-policy': 'other' } }),
|
||||
new Response('', { status: 503 }),
|
||||
]) await assert.rejects(verifyPreview('https://abc.marketing.pages.dev', 'policy', async () => response));
|
||||
await assert.rejects(verifyPreview('https://abc.marketing.pages.dev', 'policy', async (url, options) => {
|
||||
assert.equal(options.redirect, 'error');
|
||||
throw new Error('redirect refused');
|
||||
}), /redirect refused/);
|
||||
});
|
||||
@@ -107,7 +107,6 @@ test("renders the imported production settings with the real dashboard entrypoin
|
||||
runInNewContext(readFileSync(output, "utf8"), { window });
|
||||
assert.equal(window.__WARMBLY_ENV__.API_URL, "production-WARMBLY_API_URL");
|
||||
assert.equal(window.__WARMBLY_ENV__.TURNSTILE_KEY, "production-WARMBLY_TURNSTILE_KEY");
|
||||
assert.equal(window.__WARMBLY_ENV__.GMAIL_OAUTH_CONNECT, "production-WARMBLY_GMAIL_OAUTH_CONNECT");
|
||||
assert.equal(window.__WARMBLY_ENV__.COMPANY_LOGOS, 'logos "quoted"\\path');
|
||||
} finally {
|
||||
rmSync(work, { recursive: true, force: true });
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import { appendFileSync, cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { resolve, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { deploymentMatrix } from "./pages-projects.mjs";
|
||||
|
||||
export function staticAssetsMatrix(projects, targets) {
|
||||
const pages = deploymentMatrix(projects).include;
|
||||
const configured = JSON.parse(targets || "[]");
|
||||
if (!Array.isArray(configured) || configured.length > pages.length) throw new Error("Invalid static asset targets");
|
||||
const seenProjects = new Set();
|
||||
const seenWorkers = new Set();
|
||||
const seenDomains = new Set();
|
||||
return { include: configured.map((target) => {
|
||||
if (!target || Object.keys(target).some((key) => !["project", "worker", "domains"].includes(key))) throw new Error("Invalid static asset target");
|
||||
const page = pages.find((entry) => entry.project === target.project);
|
||||
if (!page || typeof target.worker !== "string" || !/^[a-z0-9][a-z0-9-]{0,62}$/.test(target.worker)) throw new Error("Unknown project or invalid Worker name");
|
||||
if (!Array.isArray(target.domains) || target.domains.length > 10) throw new Error("Explicit domains required");
|
||||
for (const domain of target.domains) {
|
||||
if (typeof domain !== "string" || domain.length > 253 || !/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/.test(domain) || seenDomains.has(domain)) throw new Error("Invalid or duplicate custom domain");
|
||||
seenDomains.add(domain);
|
||||
}
|
||||
if (seenProjects.has(target.project) || seenWorkers.has(target.worker)) throw new Error("Duplicate static asset target");
|
||||
seenProjects.add(target.project);
|
||||
seenWorkers.add(target.worker);
|
||||
return { ...page, worker: target.worker, domains: target.domains };
|
||||
}) };
|
||||
}
|
||||
|
||||
export function prepareStaticAssets({ target, sourceRoot, destination, sourceSha, release }) {
|
||||
if (!/^[a-f0-9]{40}$/.test(sourceSha) || !/^v\d+\.\d+\.\d+$/.test(release)) throw new Error("Exact release identity required");
|
||||
const output = resolve(sourceRoot, target.output_dir);
|
||||
const dest = resolve(destination);
|
||||
if (existsSync(dest)) throw new Error("Use a new artifact directory");
|
||||
let files = 0;
|
||||
function check(path) {
|
||||
const stat = lstatSync(path);
|
||||
if (stat.isSymbolicLink()) throw new Error("Static artifacts must not contain symlinks");
|
||||
if (stat.isDirectory()) {
|
||||
for (const entry of readdirSync(path)) check(join(path, entry));
|
||||
} else if (!stat.isFile() || stat.size > 25 * 1024 * 1024 || ++files > 19999) {
|
||||
throw new Error("Artifact exceeds Workers Free asset limits");
|
||||
}
|
||||
}
|
||||
check(output);
|
||||
const isRegularFile = (name) => existsSync(join(output, name)) && lstatSync(join(output, name)).isFile();
|
||||
if (!isRegularFile("index.html") || !isRegularFile("_headers")) throw new Error("Frontend index and response headers required");
|
||||
if (existsSync(join(output, "_worker.js")) || existsSync(join(output, "_routes.json"))) throw new Error("Only static artifacts are supported");
|
||||
mkdirSync(dest, { recursive: true });
|
||||
cpSync(output, join(dest, "assets"), { recursive: true });
|
||||
if (target.app === "admin") {
|
||||
const redirects = join(dest, "assets", "_redirects");
|
||||
if (existsSync(redirects)) {
|
||||
const rules = readFileSync(redirects, "utf8").split("\n").map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
|
||||
if (rules.length !== 1 || !/^\/\*\s+\/index\.html\s+200$/.test(rules[0])) throw new Error("Review changed admin redirect rules before publishing static assets");
|
||||
// The asset platform's SPA mode replaces the Pages-only catch-all rewrite.
|
||||
rmSync(redirects);
|
||||
}
|
||||
}
|
||||
mkdirSync(join(dest, "assets", ".well-known"), { recursive: true });
|
||||
writeFileSync(join(dest, "assets", ".well-known", "warmbly-release.json"), JSON.stringify({ release, sourceSha, app: target.app, project: target.project }) + "\n");
|
||||
const config = {
|
||||
name: target.worker,
|
||||
compatibility_date: "2025-10-11",
|
||||
workers_dev: false,
|
||||
preview_urls: false,
|
||||
assets: { directory: "./assets", html_handling: "auto-trailing-slash", not_found_handling: target.app === "admin" ? "single-page-application" : "404-page" },
|
||||
routes: target.domains.map((pattern) => ({ pattern, custom_domain: true })),
|
||||
};
|
||||
writeFileSync(join(dest, "wrangler.json"), JSON.stringify(config, null, 2) + "\n");
|
||||
return config;
|
||||
}
|
||||
|
||||
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
||||
try {
|
||||
const matrix = staticAssetsMatrix(process.env.CLOUDFLARE_PAGES_PROJECTS, process.env.CLOUDFLARE_STATIC_ASSETS_TARGETS);
|
||||
if (["prepare", "prepare-if-configured"].includes(process.argv[2])) {
|
||||
const target = matrix.include.find((entry) => entry.project === process.env.CLOUDFLARE_PAGES_PROJECT_NAME);
|
||||
if (!target && process.argv[2] === "prepare") throw new Error("Project is not configured for static assets");
|
||||
if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, `enabled=${Boolean(target)}\n`);
|
||||
if (target) prepareStaticAssets({ target, sourceRoot: process.cwd(), destination: process.env.STATIC_ASSETS_ARTIFACT_DIR, sourceSha: process.env.SOURCE_SHA, release: process.env.RELEASE_TAG });
|
||||
} else {
|
||||
appendFileSync(process.env.GITHUB_OUTPUT, `matrix=${JSON.stringify(matrix)}\nenabled=${matrix.include.length > 0}\n`);
|
||||
}
|
||||
} catch {
|
||||
console.error("::error::Invalid static asset configuration or artifact. Require unique configured Pages projects, Worker names, explicit domains and an exact release identity.");
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { cpSync, existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { test } from "node:test";
|
||||
import { staticAssetsMatrix, prepareStaticAssets } from "./pages-static-assets.mjs";
|
||||
|
||||
const projects = JSON.stringify([{ app: "web", project: "dashboard" }, { app: "admin", project: "admin" }, { app: "docs", project: "docs" }]);
|
||||
const configured = [{ project: "dashboard", worker: "warmbly-dashboard", domains: ["stage.warmbly.com"] }];
|
||||
const sha = "a".repeat(40);
|
||||
|
||||
test("static assets are disabled unless exact Pages projects are configured", () => {
|
||||
assert.deepEqual(staticAssetsMatrix(projects), { include: [] });
|
||||
const target = staticAssetsMatrix(projects, JSON.stringify(configured)).include[0];
|
||||
assert.equal(target.output_dir, "web/dist");
|
||||
assert.equal(target.environment, "dashboard-production");
|
||||
assert.equal(target.worker, "warmbly-dashboard");
|
||||
assert.deepEqual(target.domains, ["stage.warmbly.com"]);
|
||||
});
|
||||
|
||||
test("rejects unknown projects, paths, domains, duplicate mappings and overrides", () => {
|
||||
for (const value of [null, {}, [null], [{ ...configured[0], project: "unknown" }], [{ ...configured[0], output_dir: "/tmp" }], [{ ...configured[0], worker: "../worker" }], [{ ...configured[0], domains: ["*.warmbly.com"] }], [{ ...configured[0], domains: ["stage.warmbly.com/path"] }], [{ ...configured[0], domains: ["stage.warmbly.com", "stage.warmbly.com"] }], [configured[0], configured[0]], [configured[0], { project: "admin", worker: "admin", domains: ["stage.warmbly.com"] }]]) {
|
||||
assert.throws(() => staticAssetsMatrix(projects, JSON.stringify(value)));
|
||||
}
|
||||
});
|
||||
|
||||
function fixture(app, fn) {
|
||||
const root = mkdtempSync(join(tmpdir(), "static-assets-"));
|
||||
try {
|
||||
const target = staticAssetsMatrix(projects, JSON.stringify([{ project: app === "web" ? "dashboard" : app, worker: "fixture", domains: [] }])).include[0];
|
||||
const output = join(root, target.output_dir);
|
||||
mkdirSync(output, { recursive: true });
|
||||
writeFileSync(join(output, "index.html"), "<h1>Warmbly fixture</h1>");
|
||||
for (const name of ["_headers", "_redirects", "404.html"]) {
|
||||
try { cpSync(new URL(`../../${app}/public/${name}`, import.meta.url), join(output, name)); } catch (error) { if (error.code !== "ENOENT") throw error; }
|
||||
}
|
||||
fn({ root, target, output, destination: join(root, "artifact") });
|
||||
} finally { rmSync(root, { recursive: true, force: true }); }
|
||||
}
|
||||
|
||||
test("publishes only assets and preserves exact route/header/404 files and release identity", () => {
|
||||
fixture("web", ({ root, target, output, destination }) => {
|
||||
const config = prepareStaticAssets({ target, sourceRoot: root, destination, sourceSha: sha, release: "v0.6.74" });
|
||||
assert.equal(config.main, undefined);
|
||||
assert.equal(config.workers_dev, false);
|
||||
assert.equal(config.preview_urls, false);
|
||||
assert.equal(config.assets.not_found_handling, "404-page");
|
||||
assert.deepEqual(config.routes, []);
|
||||
for (const name of ["index.html", "_headers", "_redirects", "404.html"]) assert.deepEqual(readFileSync(join(output, name)), readFileSync(join(destination, "assets", name)));
|
||||
assert.deepEqual(JSON.parse(readFileSync(join(destination, "assets/.well-known/warmbly-release.json"))), { release: "v0.6.74", sourceSha: sha, app: "web", project: "dashboard" });
|
||||
assert.throws(() => prepareStaticAssets({ target, sourceRoot: root, destination, sourceSha: sha, release: "v0.6.74" }));
|
||||
});
|
||||
});
|
||||
|
||||
test("admin preserves its SPA fallback and domains are explicit custom-domain bindings", () => {
|
||||
fixture("admin", ({ root, target, destination }) => {
|
||||
const config = prepareStaticAssets({ target: { ...target, domains: ["admin-stage.warmbly.com"] }, sourceRoot: root, destination, sourceSha: sha, release: "v0.6.74" });
|
||||
assert.equal(config.assets.not_found_handling, "single-page-application");
|
||||
assert.equal(existsSync(join(destination, "assets", "_redirects")), false);
|
||||
assert.deepEqual(config.routes, [{ pattern: "admin-stage.warmbly.com", custom_domain: true }]);
|
||||
});
|
||||
});
|
||||
|
||||
test("refuses unpinned releases, executable Pages functions and symlink artifacts", () => {
|
||||
for (const kind of ["sha", "tag", "function", "symlink"]) fixture("web", ({ root, target, output, destination }) => {
|
||||
if (kind === "function") writeFileSync(join(output, "_worker.js"), "export default {}");
|
||||
if (kind === "symlink") symlinkSync("/etc/hosts", join(output, "outside"));
|
||||
assert.throws(() => prepareStaticAssets({ target, sourceRoot: root, destination, sourceSha: kind === "sha" ? "main" : sha, release: kind === "tag" ? "latest" : "v0.6.74" }));
|
||||
});
|
||||
});
|
||||
|
||||
test("changed admin redirect behavior requires explicit review", () => {
|
||||
fixture("admin", ({ root, target, output, destination }) => {
|
||||
writeFileSync(join(output, "_redirects"), "/old /new 301\n");
|
||||
assert.throws(() => prepareStaticAssets({ target, sourceRoot: root, destination, sourceSha: sha, release: "v0.6.74" }));
|
||||
});
|
||||
});
|
||||
|
||||
test("requires regular frontend entrypoint and response header files", () => {
|
||||
for (const name of ["index.html", "_headers"]) fixture("web", ({ root, target, output, destination }) => {
|
||||
rmSync(join(output, name));
|
||||
mkdirSync(join(output, name));
|
||||
assert.throws(() => prepareStaticAssets({ target, sourceRoot: root, destination, sourceSha: sha, release: "v0.6.74" }), /Frontend index and response headers required/);
|
||||
assert.equal(existsSync(destination), false);
|
||||
});
|
||||
});
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env bash
|
||||
# Preserve recovery raw evidence only in the dedicated private diagnostic prefix.
|
||||
set -euo pipefail
|
||||
[ "${GITHUB_ACTIONS:-}" = true ] && [ "${GITHUB_REPOSITORY:-}" = warmbly/warmbly ] &&
|
||||
[ "${GITHUB_REF:-}" = refs/heads/main ] && [ "${GITHUB_RUN_ATTEMPT:-}" = 1 ] &&
|
||||
[[ "${GITHUB_RUN_ID:-}" =~ ^[1-9][0-9]*$ ]] || exit 1
|
||||
phase=${1:?}
|
||||
[[ "$phase" = plan || "$phase" = apply || "$phase" = verify ]]
|
||||
: "${WORK:?}"
|
||||
[ -d "$WORK" ] && [ ! -e "$WORK.evidence.tgz" ]
|
||||
umask 077
|
||||
aws sts get-caller-identity --region us-east-1 >"$WORK/archive-identity.json"
|
||||
jq -e '.Account == "925323749693" and (.Arn | test("^arn:aws:sts::925323749693:assumed-role/warmbly-production-tls-recovery-evidence/[^/]+$"))' \
|
||||
"$WORK/archive-identity.json" >/dev/null
|
||||
tar -czf "$WORK.evidence.tgz" -C "$WORK" .
|
||||
checksum=$(openssl dgst -sha256 -binary "$WORK.evidence.tgz" | openssl base64 -A)
|
||||
aws s3api put-object --region us-east-1 --bucket warmbly-terraform-use1-925323749693 \
|
||||
--key "warmbly/production/diagnostics/runtime-tls-recovery/$GITHUB_RUN_ID/1/$phase.tgz" \
|
||||
--expected-bucket-owner 925323749693 --server-side-encryption AES256 --if-none-match '*' \
|
||||
--checksum-algorithm SHA256 --checksum-sha256 "$checksum" --body "$WORK.evidence.tgz" >"$WORK.evidence-metadata.json"
|
||||
jq -e --arg checksum "$checksum" '.ServerSideEncryption == "AES256" and .ChecksumSHA256 == $checksum and
|
||||
(.VersionId | type == "string" and length > 0 and . != "null")' "$WORK.evidence-metadata.json" >/dev/null
|
||||
echo 'Full recovery evidence preserved in the private versioned diagnostic object'
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/../.."
|
||||
work=$(mktemp -d)
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
mkdir "$work/bin"
|
||||
cat >"$work/bin/aws" <<'SH'
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
if [ "$1 $2" = 'sts get-caller-identity' ]; then
|
||||
jq -n --arg mode "${MODE:-}" '{Account:"925323749693",Arn:("arn:aws:sts::925323749693:assumed-role/"+(if $mode=="role" then "other" else "warmbly-production-tls-recovery-evidence" end)+"/fixture")}'
|
||||
exit
|
||||
fi
|
||||
[ "$1 $2" = 's3api put-object' ]
|
||||
[[ "$*" == *'--expected-bucket-owner 925323749693'* && "$*" == *'--server-side-encryption AES256'* && "$*" == *'--if-none-match *'* ]]
|
||||
[[ "$*" == *'warmbly/production/diagnostics/runtime-tls-recovery/999/1/plan.tgz'* ]]
|
||||
checksum= body=
|
||||
while [ "$#" -gt 0 ]; do
|
||||
case "$1" in --checksum-sha256) checksum=$2; shift 2 ;; --body) body=$2; shift 2 ;; *) shift ;; esac
|
||||
done
|
||||
[ "$checksum" = "$(openssl dgst -sha256 -binary "$body" | openssl base64 -A)" ]
|
||||
tar -tzf "$body" | grep -Fx './full-raw.json' >/dev/null
|
||||
if [ "${MODE:-}" = upload ]; then exit 1; fi
|
||||
jq -n --arg checksum "$checksum" --arg mode "${MODE:-}" '{VersionId:"evidence-version",ServerSideEncryption:"AES256",ChecksumSHA256:(if $mode=="checksum" then "other" else $checksum end)}'
|
||||
SH
|
||||
chmod +x "$work/bin/aws"
|
||||
export PATH="$work/bin:$PATH" GITHUB_ACTIONS=true GITHUB_REPOSITORY=warmbly/warmbly GITHUB_REF=refs/heads/main GITHUB_RUN_ATTEMPT=1 GITHUB_RUN_ID=999
|
||||
guard=.github/scripts/runtime-tls-recovery-archive.sh
|
||||
for mode in good role upload checksum; do
|
||||
mkdir "$work/$mode"
|
||||
printf '{"raw":"private fixture"}\n' >"$work/$mode/full-raw.json"
|
||||
if [ "$mode" = good ]; then WORK="$work/$mode" bash "$guard" plan
|
||||
elif WORK="$work/$mode" MODE=$mode bash "$guard" plan 2>/dev/null; then echo "Archive accepted $mode" >&2; exit 1; fi
|
||||
done
|
||||
if WORK="$work/good" bash "$guard" plan 2>/dev/null; then echo 'Archive overwrote prior evidence' >&2; exit 1; fi
|
||||
if WORK="$work/unused" GITHUB_RUN_ATTEMPT=2 bash "$guard" plan 2>/dev/null; then echo 'Archive accepted a rerun' >&2; exit 1; fi
|
||||
echo 'Private evidence archive identity, prefix, encryption, integrity and overwrite checks passed'
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
#!/usr/bin/env bash
|
||||
# Keep partial cleanup separate from normal route, drain and ON transitions.
|
||||
set -euo pipefail
|
||||
scripts=$(cd "$(dirname "$0")" && pwd)
|
||||
|
||||
check_contract() {
|
||||
bash "$scripts/runtime-tls-recovery-inputs.sh" check-contract "$1"
|
||||
jq -e '
|
||||
.schemaVersion == 1 and .repository == "warmbly/warmbly" and .release.tag == .snapshot.releaseTag and
|
||||
(.release.imagesSha256 | type == "string" and test("^[a-f0-9]{64}$")) and
|
||||
(.planChangesSha256 | type == "string" and test("^[a-f0-9]{64}$"))
|
||||
' "$1" >/dev/null || { echo 'Recovery must bind the current release artifact and reviewed complete plan changes' >&2; return 1; }
|
||||
}
|
||||
|
||||
check_context() {
|
||||
if [ "${GITHUB_ACTIONS:-}" = true ] && [ "${GITHUB_REPOSITORY:-}" = warmbly/warmbly ] &&
|
||||
[ "${GITHUB_REF:-}" = refs/heads/main ] && [ "${GITHUB_EVENT_NAME:-}" = workflow_dispatch ] &&
|
||||
[ "${GITHUB_WORKFLOW_REF:-}" = warmbly/warmbly/.github/workflows/runtime-tls-recovery.yml@refs/heads/main ] &&
|
||||
[ "${GITHUB_RUN_ATTEMPT:-}" = 1 ] && [[ "${GITHUB_RUN_ID:-}" =~ ^[1-9][0-9]*$ ]]; then
|
||||
[ "${GITHUB_SHA:?}" = "$(git rev-parse HEAD)" ]
|
||||
return
|
||||
fi
|
||||
echo 'Recovery execution requires a new protected main workflow run; reruns are refused' >&2
|
||||
return 1
|
||||
}
|
||||
|
||||
check_approval_environment() {
|
||||
gh api repos/warmbly/warmbly/environments/aws-infrastructure-approval |
|
||||
jq -e '.can_admins_bypass == false and
|
||||
any(.protection_rules[]; .type == "required_reviewers" and .prevent_self_review == true and (.reviewers | length > 0))' >/dev/null || {
|
||||
echo 'Recovery requires a separate protected reviewer without self-review or administrator bypass' >&2; return 1;
|
||||
}
|
||||
}
|
||||
|
||||
check_final_state() {
|
||||
jq -e --slurpfile before "$2" '
|
||||
.version == 4 and .lineage == $before[0].lineage and
|
||||
(.serial | type == "number" and floor == .) and .serial > $before[0].serial and
|
||||
([.resources[] | select(.mode == "managed" and .type == "aws_lb_target_group" and .name == "service")] | length == 0) and
|
||||
(.resources | sort_by([.module,.mode,.type,.name])) ==
|
||||
($before[0].resources | map(select((.mode == "managed" and .type == "aws_lb_target_group" and .name == "service") | not)) | sort_by([.module,.mode,.type,.name]))
|
||||
' "$1" >/dev/null || { echo 'Post-cleanup state must preserve all other reviewed resources' >&2; return 1; }
|
||||
}
|
||||
|
||||
prepare() {
|
||||
: "${WORK:?}" "${CONTRACT_KEY:?}" "${CONTRACT_VERSION:?}" "${CONTRACT_SHA256:?}"
|
||||
[[ "$CONTRACT_KEY" =~ ^warmbly/production/vars/runtime-tls-recovery/[a-z0-9][a-z0-9-]{1,63}\.contract\.json$ ]]
|
||||
[[ "$CONTRACT_SHA256" =~ ^[a-f0-9]{64}$ && "$CONTRACT_VERSION" != null && -n "$CONTRACT_VERSION" && "$CONTRACT_VERSION" != *$'\n'* ]]
|
||||
umask 077
|
||||
mkdir "$WORK"
|
||||
export AWS_PAGER=""
|
||||
aws sts get-caller-identity --region us-east-1 >"$WORK/account.json"
|
||||
jq -e '.Account == "925323749693"' "$WORK/account.json" >/dev/null
|
||||
aws s3api get-object --region us-east-1 --bucket warmbly-terraform-use1-925323749693 --key "$CONTRACT_KEY" \
|
||||
--version-id "$CONTRACT_VERSION" --expected-bucket-owner 925323749693 "$WORK/contract.json" >"$WORK/contract-metadata.json"
|
||||
jq -e --arg version "$CONTRACT_VERSION" '.VersionId == $version and .DeleteMarker != true and
|
||||
(.ServerSideEncryption == "AES256" or .ServerSideEncryption == "aws:kms")' "$WORK/contract-metadata.json" >/dev/null
|
||||
[ "$(sha256sum "$WORK/contract.json" | cut -d' ' -f1)" = "$CONTRACT_SHA256" ]
|
||||
check_contract "$WORK/contract.json"
|
||||
check_approval_environment
|
||||
bash "$scripts/runtime-tls-recovery-lineage.sh" collect "$WORK/contract.json" "$WORK/lineage" . >"$WORK/lineage.log" 2>&1
|
||||
local input_action=collect
|
||||
if [ "$1" = verify ]; then input_action=collect-archived; fi
|
||||
bash "$scripts/runtime-tls-recovery-inputs.sh" "$input_action" "$WORK/contract.json" "$WORK/inputs" >"$WORK/inputs.log" 2>&1
|
||||
local release key digest
|
||||
release=$(jq -r '.release.tag' "$WORK/contract.json")
|
||||
gh release view "$release" --repo warmbly/warmbly --json tagName,isDraft,isPrerelease >"$WORK/release.json"
|
||||
jq -e --arg release "$release" '.tagName == $release and .isDraft == false and .isPrerelease == false' "$WORK/release.json" >/dev/null
|
||||
gh release download "$release" --repo warmbly/warmbly --pattern images.json --dir "$WORK/inputs"
|
||||
[ "$(sha256sum "$WORK/inputs/images.json" | cut -d' ' -f1)" = "$(jq -r '.release.imagesSha256' "$WORK/contract.json")" ]
|
||||
jq -e --arg release "$release" '.tag == $release and .registry == "ghcr.io/warmbly/warmbly"' "$WORK/inputs/images.json" >/dev/null
|
||||
for key in backend backend-kafka consumer consumer-kafka worker worker-kafka forms tracking tracking-kafka realtime; do
|
||||
digest=$(jq -er --arg key "$key" '.images[$key] | select(type == "string" and test("^sha256:[a-f0-9]{64}$"))' "$WORK/inputs/images.json")
|
||||
gh attestation verify "oci://ghcr.io/warmbly/warmbly/${key%-kafka}@$digest" --repo warmbly/warmbly \
|
||||
--signer-workflow warmbly/warmbly/.github/workflows/release.yml --source-ref "refs/tags/$release" \
|
||||
--source-digest "$(jq -r '.release.source' "$WORK/contract.json")" >>"$WORK/provenance.log" 2>&1
|
||||
done
|
||||
}
|
||||
|
||||
verify_final() {
|
||||
aws s3api get-object --region us-east-1 --bucket warmbly-terraform-use1-925323749693 \
|
||||
--key warmbly/production/runtime.tfstate --expected-bucket-owner 925323749693 "$WORK/final-state.json" >"$WORK/final-state-metadata.json"
|
||||
jq -e '.DeleteMarker != true and (.VersionId | type == "string" and length > 0 and . != "null") and
|
||||
(.ServerSideEncryption == "AES256" or .ServerSideEncryption == "aws:kms")' "$WORK/final-state-metadata.json" >/dev/null
|
||||
check_final_state "$WORK/final-state.json" "$WORK/inputs/state.json"
|
||||
bash "$scripts/runtime-tls-recovery-live.sh" collect-final "$WORK/contract.json" "$WORK/inputs" "$WORK/final-live" >"$WORK/final-live.log" 2>&1
|
||||
aws s3api head-object --region us-east-1 --bucket warmbly-terraform-use1-925323749693 \
|
||||
--key warmbly/production/runtime.tfstate --expected-bucket-owner 925323749693 >"$WORK/final-state-head.json"
|
||||
jq -e --slurpfile metadata "$WORK/final-state-metadata.json" '.VersionId == $metadata[0].VersionId' "$WORK/final-state-head.json" >/dev/null
|
||||
}
|
||||
|
||||
main() {
|
||||
local action=${1:-}
|
||||
if [ "$action" = check-contract ]; then check_contract "${2:?}"; return; fi
|
||||
if [ "$action" = check-final-state ]; then check_final_state "${2:?}" "${3:?}"; return; fi
|
||||
case "$action" in plan|apply|verify) ;; *) echo 'Unknown partial TLS recovery action' >&2; return 1 ;; esac
|
||||
check_context
|
||||
prepare "$action"
|
||||
if [ "$action" = verify ]; then verify_final; echo 'Final recovery state and effective live checks passed'; return; fi
|
||||
bash "$scripts/runtime-tls-recovery-live.sh" collect "$WORK/contract.json" "$WORK/inputs" "$WORK/live" >"$WORK/live.log" 2>&1
|
||||
local dir=deploy/terraform/aws/runtime changes digest
|
||||
terraform -chdir="$dir" init -input=false -no-color -backend-config=bucket=warmbly-terraform-use1-925323749693 >"$WORK/terraform.log" 2>&1
|
||||
terraform -chdir="$dir" plan -input=false -no-color -lock-timeout=5m -var-file="$WORK/inputs/snapshot.json" \
|
||||
-var=state_bucket=warmbly-terraform-use1-925323749693 -target=aws_lb_target_group.service \
|
||||
-out="$WORK/recovery.tfplan" >>"$WORK/terraform.log" 2>&1
|
||||
terraform -chdir="$dir" show -json "$WORK/recovery.tfplan" >"$WORK/plan.json"
|
||||
bash "$scripts/runtime-tls-recovery.sh" check-plan "$WORK/plan.json" "$WORK/contract.json"
|
||||
changes=$(jq -cS '{resource_changes:(.resource_changes | sort_by(.address)),resource_drift:(.resource_drift // [] | sort_by(.address))}' \
|
||||
"$WORK/plan.json" | sha256sum | cut -d' ' -f1)
|
||||
[ "$changes" = "$(jq -r '.planChangesSha256' "$WORK/contract.json")" ] || {
|
||||
echo 'The complete recovery changes differ from the privately reviewed plan; prepare a new contract' >&2; return 1;
|
||||
}
|
||||
digest=$(jq -cnS --arg contract "$CONTRACT_SHA256" --arg source "$GITHUB_SHA" --arg changes "$changes" \
|
||||
'{contract:$contract,workflowSource:$source,changes:$changes}' | sha256sum | cut -d' ' -f1)
|
||||
aws s3api head-object --region us-east-1 --bucket warmbly-terraform-use1-925323749693 \
|
||||
--key warmbly/production/runtime.tfstate --expected-bucket-owner 925323749693 >"$WORK/preapply-state-head.json"
|
||||
jq -e --slurpfile contract "$WORK/contract.json" '.VersionId == $contract[0].state.versionId' "$WORK/preapply-state-head.json" >/dev/null
|
||||
if [ "$action" = plan ]; then
|
||||
printf 'digest=%s\nrelease=%s\n' "$digest" "$(jq -r '.release.tag' "$WORK/contract.json")" >>"${GITHUB_OUTPUT:?}"
|
||||
printf 'Partial TLS cleanup: exactly four reviewed HTTP target-group deletions.\n\nContract SHA-256: %s\n\nComplete changes SHA-256: %s\n\nApproval digest: %s\n\nReview the matching complete private plan before approving.\n' \
|
||||
"$CONTRACT_SHA256" "$changes" "$digest" >>"${GITHUB_STEP_SUMMARY:?}"
|
||||
return
|
||||
fi
|
||||
[ "$digest" = "${APPROVED_DIGEST:?}" ] || { echo 'Recovery approval digest changed; a new reviewed run is required' >&2; return 1; }
|
||||
bash "$scripts/runtime-tls-recovery-live.sh" collect "$WORK/contract.json" "$WORK/inputs" "$WORK/preapply-live" >"$WORK/preapply-live.log" 2>&1
|
||||
terraform -chdir="$dir" apply -input=false -no-color -lock-timeout=5m "$WORK/recovery.tfplan" >>"$WORK/terraform.log" 2>&1 || {
|
||||
echo 'Partial cleanup failed; inspect private state before preparing any new recovery contract' >&2; return 1;
|
||||
}
|
||||
verify_final
|
||||
echo 'Reviewed partial cleanup and effective checks passed; attested same-release redeploy is still required'
|
||||
}
|
||||
main "$@"
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/../.."
|
||||
work=$(mktemp -d)
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
mkdir -p "$work/repository/.github/scripts" "$work/bin"
|
||||
cp .github/scripts/runtime-tls-recovery{,-inputs,-lineage,-execute}.sh "$work/repository/.github/scripts/"
|
||||
git -C "$work/repository" init -q
|
||||
git -C "$work/repository" config user.name 'Recovery fixture'
|
||||
git -C "$work/repository" config user.email 'fixture@example.invalid'
|
||||
git -C "$work/repository" commit -qm 'feat: establish recovery drain fixture' --allow-empty
|
||||
drain=$(git -C "$work/repository" rev-parse HEAD)
|
||||
git -C "$work/repository" commit -qm 'feat: establish recovery ON fixture' --allow-empty
|
||||
on=$(git -C "$work/repository" rev-parse HEAD)
|
||||
git -C "$work/repository" commit -qm 'feat: establish recovery release fixture' --allow-empty
|
||||
release=$(git -C "$work/repository" rev-parse HEAD)
|
||||
git -C "$work/repository" tag v1.2.3
|
||||
jq -n --arg digest "sha256:$(printf fixture | sha256sum | cut -d' ' -f1)" \
|
||||
-f .github/scripts/runtime-tls-recovery-live.fixture.jq >"$work/fixture.json"
|
||||
jq '.state' "$work/fixture.json" >"$work/state.json"
|
||||
jq '.state | .serial+=1 | .resources |= map(select(.type != "aws_lb_target_group" or .name != "service"))' "$work/fixture.json" >"$work/final-state.json"
|
||||
jq '.vars' "$work/fixture.json" >"$work/snapshot.json"
|
||||
jq '.images | .images += {"backend-kafka":.images.backend,"consumer-kafka":.images.consumer,"worker":.images.backend,"worker-kafka":.images.backend,"tracking-kafka":.images.tracking}' \
|
||||
"$work/fixture.json" >"$work/images.json"
|
||||
jq '.baseline | {resource_changes:[.httpGroups[] | {address:("aws_lb_target_group.service[\""+(.TargetGroupName|ltrimstr("warmbly-production-"))+"\"]"),
|
||||
change:{actions:["delete"],after:null,before:{arn:.TargetGroupArn,id:.TargetGroupArn,name:.TargetGroupName,protocol:.Protocol,port:.Port,vpc_id:.VpcId}}}]}' \
|
||||
"$work/fixture.json" >"$work/plan.json"
|
||||
changes=$(jq -cS '{resource_changes:(.resource_changes|sort_by(.address)),resource_drift:[]}' "$work/plan.json" | sha256sum | cut -d' ' -f1)
|
||||
jq --arg drain "$drain" --arg on "$on" --arg release "$release" --arg changes "$changes" \
|
||||
--arg state "$(sha256sum "$work/state.json" | cut -d' ' -f1)" --arg vars "$(sha256sum "$work/snapshot.json" | cut -d' ' -f1)" \
|
||||
--arg images "$(sha256sum "$work/images.json" | cut -d' ' -f1)" '
|
||||
.baseline + {schemaVersion:1,repository:"warmbly/warmbly",bucket:"warmbly-terraform-use1-925323749693",
|
||||
release:{tag:"v1.2.3",source:$release,runId:101,attempt:1,imagesSha256:$images},
|
||||
drain:{tag:"v1.2.2",source:$drain,runId:102,attempt:1},failedOn:{tag:"v1.2.2",source:$on,runId:103,attempt:1},planChangesSha256:$changes} |
|
||||
.state += {key:"warmbly/production/runtime.tfstate",sha256:$state} |
|
||||
.snapshot += {key:"warmbly/production/vars/runtime-tls-recovery/fixture.tfvars.json",versionId:"vars-version",sha256:$vars}' \
|
||||
"$work/fixture.json" >"$work/contract.json"
|
||||
jq '
|
||||
def run($path;$event;$branch;$conclusion): {id:.runId,run_attempt:.attempt,head_sha:.source,repository:{full_name:"warmbly/warmbly"},
|
||||
path:$path,event:$event,head_branch:$branch,status:"completed",conclusion:$conclusion};
|
||||
{runs:{release:(.release|run(".github/workflows/release.yml";"push";.tag;"success")),
|
||||
drain:(.drain|run(".github/workflows/runtime-tls.yml";"workflow_dispatch";"main";"success")+{display_title:("Runtime TLS drain "+.tag)}),
|
||||
failedOn:(.failedOn|run(".github/workflows/runtime-tls.yml";"workflow_dispatch";"main";"failure")+{display_title:("Runtime TLS on "+.tag)})},
|
||||
failedOnJobs:[{id:1,run_id:103,run_attempt:1,status:"completed",name:"apply",conclusion:"success"},
|
||||
{id:2,run_id:103,run_attempt:1,status:"completed",name:"redeploy / fixture",conclusion:"failure"}]}' \
|
||||
"$work/contract.json" >"$work/lineage.json"
|
||||
cat >"$work/repository/.github/scripts/runtime-tls-recovery-live.sh" <<'SH'
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
echo "live $1" >>"$FIXTURES/requests.log"
|
||||
[ "${MODE:-}" != live ] || exit 1
|
||||
mkdir "$4"
|
||||
echo '{}' >"$4/live.json"
|
||||
SH
|
||||
cat >"$work/bin/aws" <<'SH'
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
echo "aws $*" >>"$FIXTURES/requests.log"
|
||||
service=$1 operation=$2
|
||||
shift 2
|
||||
key= version= owner= bucket= region= output=
|
||||
while [ "$#" -gt 0 ]; do
|
||||
case "$1" in
|
||||
--key) key=$2; shift 2 ;; --version-id) version=$2; shift 2 ;; --expected-bucket-owner) owner=$2; shift 2 ;;
|
||||
--region) region=$2; shift 2 ;; --bucket) bucket=$2; shift 2 ;; *) output=$1; shift ;;
|
||||
esac
|
||||
done
|
||||
[ "$region" = us-east-1 ]
|
||||
case "$service $operation" in
|
||||
'sts get-caller-identity') echo '{"Account":"925323749693"}' ;;
|
||||
's3api get-object')
|
||||
[ "$owner" = 925323749693 ] && [ "$bucket" = warmbly-terraform-use1-925323749693 ]
|
||||
case "$key" in
|
||||
*/fixture.contract.json) kind=contract ;;
|
||||
*/fixture.tfvars.json) kind=snapshot ;;
|
||||
*/runtime.tfstate) kind=state ;;
|
||||
*) exit 1 ;;
|
||||
esac
|
||||
if [ -z "$version" ]; then kind=final-state; version=final-version; fi
|
||||
cp "$FIXTURES/$kind.json" "$output"
|
||||
jq -n --arg version "$version" '{VersionId:$version,ServerSideEncryption:"AES256"}' ;;
|
||||
's3api head-object')
|
||||
version=state-version
|
||||
if [ -e "$FIXTURES/applied" ] || [ "${MODE:-}" = advanced ]; then version=final-version; fi
|
||||
jq -n --arg version "$version" '{VersionId:$version}' ;;
|
||||
*) exit 1 ;;
|
||||
esac
|
||||
SH
|
||||
cat >"$work/bin/gh" <<'SH'
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
echo "gh $*" >>"$FIXTURES/requests.log"
|
||||
case "$1 $2" in
|
||||
'api repos/warmbly/warmbly/environments/aws-infrastructure-approval')
|
||||
jq -n --arg mode "${MODE:-}" '{can_admins_bypass:($mode=="bypass"),protection_rules:[{type:"required_reviewers",prevent_self_review:($mode!="self-review"),reviewers:[{type:"User"}]}]}' ;;
|
||||
'api repos/warmbly/warmbly/actions/runs/101/attempts/1') jq '.runs.release' "$FIXTURES/lineage.json" ;;
|
||||
'api repos/warmbly/warmbly/actions/runs/102/attempts/1') jq '.runs.drain' "$FIXTURES/lineage.json" ;;
|
||||
'api repos/warmbly/warmbly/actions/runs/103/attempts/1') jq '.runs.failedOn' "$FIXTURES/lineage.json" ;;
|
||||
'api repos/warmbly/warmbly/actions/runs/103/attempts/1/jobs?per_page=100') jq '[{total_count:2,jobs:.failedOnJobs}]' "$FIXTURES/lineage.json" ;;
|
||||
'release view') echo '{"tagName":"v1.2.3","isDraft":false,"isPrerelease":false}' ;;
|
||||
'release download')
|
||||
while [ "$1" != --dir ]; do shift; done
|
||||
cp "$FIXTURES/images.json" "$2/images.json"
|
||||
if [ "${MODE:-}" = artifact ]; then printf '\n' >>"$2/images.json"; fi ;;
|
||||
'attestation verify') [ "${MODE:-}" != provenance ] ;;
|
||||
*) exit 1 ;;
|
||||
esac
|
||||
SH
|
||||
cat >"$work/bin/terraform" <<'SH'
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
echo "terraform $*" >>"$FIXTURES/requests.log"
|
||||
case "$2" in
|
||||
init) ;;
|
||||
plan) [[ "$*" == *'-target=aws_lb_target_group.service'* && "$*" != *'-target=aws_ecs'* ]] ;;
|
||||
show)
|
||||
case "${MODE:-}" in
|
||||
scope) jq '.resource_changes|=.[1:]' "$FIXTURES/plan.json" ;;
|
||||
changes) jq '.resource_changes[0].change.before.tags={new:"tag"}' "$FIXTURES/plan.json" ;;
|
||||
*) cat "$FIXTURES/plan.json" ;;
|
||||
esac ;;
|
||||
apply) [ "${MODE:-}" != apply-failure ] && touch "$FIXTURES/applied" ;;
|
||||
*) exit 1 ;;
|
||||
esac
|
||||
SH
|
||||
chmod +x "$work/bin/"*
|
||||
export FIXTURES="$work" PATH="$work/bin:$PATH"
|
||||
export GITHUB_ACTIONS=true GITHUB_REPOSITORY=warmbly/warmbly GITHUB_REF=refs/heads/main GITHUB_EVENT_NAME=workflow_dispatch
|
||||
export GITHUB_WORKFLOW_REF=warmbly/warmbly/.github/workflows/runtime-tls-recovery.yml@refs/heads/main
|
||||
export GITHUB_RUN_ATTEMPT=1 GITHUB_RUN_ID=999 GITHUB_SHA="$release"
|
||||
export CONTRACT_KEY=warmbly/production/vars/runtime-tls-recovery/fixture.contract.json CONTRACT_VERSION=contract-version
|
||||
CONTRACT_SHA256=$(sha256sum "$work/contract.json" | cut -d' ' -f1)
|
||||
export CONTRACT_SHA256
|
||||
export GITHUB_OUTPUT="$work/output" GITHUB_STEP_SUMMARY="$work/summary"
|
||||
guard="$work/repository/.github/scripts/runtime-tls-recovery-execute.sh"
|
||||
cd "$work/repository"
|
||||
WORK="$work/plan" bash "$guard" plan
|
||||
approved=$(sed -n 's/^digest=//p' "$GITHUB_OUTPUT")
|
||||
[ -n "$approved" ]
|
||||
for mode in bypass self-review artifact provenance live advanced scope changes; do
|
||||
: >"$work/requests.log"
|
||||
if WORK="$work/$mode" MODE=$mode APPROVED_DIGEST="$approved" bash "$guard" apply 2>/dev/null; then
|
||||
echo "Recovery applied incompatible evidence: $mode" >&2; exit 1
|
||||
fi
|
||||
if grep -q '^terraform .* apply ' "$work/requests.log"; then echo "Recovery reached apply for $mode" >&2; exit 1; fi
|
||||
done
|
||||
if WORK="$work/wrong-approval" APPROVED_DIGEST=other bash "$guard" apply 2>/dev/null; then echo 'Recovery accepted another approval digest' >&2; exit 1; fi
|
||||
if WORK="$work/retry" GITHUB_RUN_ATTEMPT=2 bash "$guard" plan 2>/dev/null; then echo 'Recovery accepted a rerun' >&2; exit 1; fi
|
||||
if WORK="$work/local" GITHUB_ACTIONS=false bash "$guard" plan 2>/dev/null; then echo 'Recovery accepted local execution' >&2; exit 1; fi
|
||||
: >"$work/requests.log"
|
||||
if WORK="$work/apply-failure" MODE=apply-failure APPROVED_DIGEST="$approved" bash "$guard" apply 2>/dev/null; then
|
||||
echo 'Recovery continued after an apply failure' >&2; exit 1
|
||||
fi
|
||||
[ ! -e "$work/applied" ]
|
||||
if grep -q '^live collect-final$' "$work/requests.log"; then echo 'Recovery verified a failed apply as complete' >&2; exit 1; fi
|
||||
: >"$work/requests.log"
|
||||
WORK="$work/apply" APPROVED_DIGEST="$approved" bash "$guard" apply
|
||||
[ "$(grep -c '^live collect$' "$work/requests.log")" = 2 ]
|
||||
[ "$(grep -c '^live collect-final$' "$work/requests.log")" = 1 ]
|
||||
[ "$(grep -c '^gh attestation verify ' "$work/requests.log")" = 10 ]
|
||||
WORK="$work/verify" bash "$guard" verify
|
||||
jq '.resources[0].instances[0].attributes.arn="different"' "$work/final-state.json" >"$work/changed-state.json"
|
||||
if bash "$guard" check-final-state "$work/changed-state.json" "$work/state.json" 2>/dev/null; then
|
||||
echo 'Recovery accepted an unrelated retained-state change' >&2; exit 1
|
||||
fi
|
||||
echo 'Protected recovery plan, approval binding, apply and final-state orchestration checks passed'
|
||||
@@ -0,0 +1,66 @@
|
||||
#!/usr/bin/env bash
|
||||
# Bind private recovery inputs to their reviewed S3 versions and file hashes.
|
||||
set -euo pipefail
|
||||
guard="$(dirname "$0")/runtime-tls-recovery.sh"
|
||||
|
||||
check_contract() {
|
||||
bash "$guard" check-baseline "$1"
|
||||
jq -e '
|
||||
.bucket == "warmbly-terraform-use1-925323749693" and
|
||||
.state.key == "warmbly/production/runtime.tfstate" and
|
||||
(.snapshot.key | type == "string" and test("^warmbly/production/vars/runtime-tls-recovery/[a-z0-9][a-z0-9-]{1,63}\\.tfvars\\.json$")) and
|
||||
(.snapshot.versionId | type == "string" and length > 0 and . != "null" and (test("[\\r\\n]") | not)) and
|
||||
(.snapshot.sha256 | type == "string" and test("^[a-f0-9]{64}$")) and
|
||||
(.snapshot.releaseTag | type == "string" and test("^v[0-9]+\\.[0-9]+\\.[0-9]+$"))
|
||||
' "$1" >/dev/null || { echo 'Recovery requires separately versioned private state and cleanup inputs' >&2; return 1; }
|
||||
}
|
||||
|
||||
collect_inputs() {
|
||||
local baseline=$1 work=$2 require_latest=${3:-true} bucket key version digest kind
|
||||
check_contract "$baseline"
|
||||
umask 077
|
||||
mkdir "$work"
|
||||
cp "$baseline" "$work/baseline.json"
|
||||
baseline="$work/baseline.json"
|
||||
bucket=$(jq -r '.bucket' "$baseline")
|
||||
aws sts get-caller-identity --region us-east-1 >"$work/identity.json"
|
||||
jq -e '.Account == "925323749693"' "$work/identity.json" >/dev/null || {
|
||||
echo 'Recovery input collection requires the reviewed AWS account' >&2; return 1;
|
||||
}
|
||||
for kind in state snapshot; do
|
||||
key=$(jq -r --arg kind "$kind" '.[$kind].key' "$baseline")
|
||||
version=$(jq -r --arg kind "$kind" '.[$kind].versionId' "$baseline")
|
||||
aws s3api get-object --region us-east-1 --bucket "$bucket" --key "$key" \
|
||||
--version-id "$version" --expected-bucket-owner 925323749693 "$work/$kind.json" >"$work/$kind-metadata.json"
|
||||
jq -e --arg version "$version" '
|
||||
.VersionId == $version and .DeleteMarker != true and
|
||||
(.ServerSideEncryption == "AES256" or .ServerSideEncryption == "aws:kms")
|
||||
' "$work/$kind-metadata.json" >/dev/null || {
|
||||
echo 'Recovery object metadata differs from the reviewed version' >&2; return 1;
|
||||
}
|
||||
digest=$(sha256sum "$work/$kind.json" | cut -d' ' -f1)
|
||||
[ "$digest" = "$(jq -r --arg kind "$kind" '.[$kind].sha256' "$baseline")" ] || {
|
||||
echo 'Recovery object bytes differ from the reviewed hash' >&2; return 1;
|
||||
}
|
||||
done
|
||||
bash "$guard" check-state "$work/state.json" "$baseline"
|
||||
jq -e '.target_tls == "on" and .name == "warmbly-production"' "$work/snapshot.json" >/dev/null || {
|
||||
echo 'Recovery vars must select the reviewed production cleanup stage' >&2; return 1;
|
||||
}
|
||||
if [ "$require_latest" = true ]; then
|
||||
aws s3api head-object --region us-east-1 --bucket "$bucket" --key warmbly/production/runtime.tfstate \
|
||||
--expected-bucket-owner 925323749693 >"$work/latest-state.json"
|
||||
jq -e --slurpfile baseline "$baseline" '.VersionId == $baseline[0].state.versionId' "$work/latest-state.json" >/dev/null || {
|
||||
echo 'Recovery state advanced beyond the reviewed version' >&2; return 1;
|
||||
}
|
||||
fi
|
||||
jq '{account,region,bucket,state:{key:.state.key,versionId:.state.versionId,sha256:.state.sha256,lineage:.state.lineage,serial:.state.serial},snapshot}' \
|
||||
"$baseline" >"$work/inputs.json"
|
||||
}
|
||||
|
||||
case "${1:-}" in
|
||||
check-contract) check_contract "${2:?}" ;;
|
||||
collect) collect_inputs "${2:?}" "${3:?}" ;;
|
||||
collect-archived) collect_inputs "${2:?}" "${3:?}" false ;;
|
||||
*) echo 'Only read-only recovery input validation and collection are supported' >&2; exit 1 ;;
|
||||
esac
|
||||
@@ -0,0 +1,117 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/../.."
|
||||
work=$(mktemp -d)
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
guard=.github/scripts/runtime-tls-recovery-inputs.sh
|
||||
jq -n '
|
||||
["backend","forms","tracking","realtime"] | map({
|
||||
TargetGroupName:("warmbly-production-" + .),
|
||||
TargetGroupArn:("arn:aws:elasticloadbalancing:us-east-1:925323749693:targetgroup/warmbly-production-" + . + "/0123456789abcdef"),
|
||||
Protocol:"HTTP",Port:8080,VpcId:"vpc-0123456789abcdef0",LoadBalancerArns:[],targets:[]}) as $groups |
|
||||
{account:"925323749693",region:"us-east-1",bucket:"warmbly-terraform-use1-925323749693",httpGroups:$groups,
|
||||
state:{key:"warmbly/production/runtime.tfstate",versionId:"reviewed-state",lineage:"01234567-89ab-cdef-0123-456789abcdef",serial:1,httpGroups:$groups},
|
||||
snapshot:{key:"warmbly/production/vars/runtime-tls-recovery/reviewed-cleanup.tfvars.json",versionId:"reviewed-vars",releaseTag:"v1.0.1"}}
|
||||
' >"$work/baseline.json"
|
||||
jq '{version:4,lineage:.state.lineage,serial:.state.serial,resources:[{mode:"managed",type:"aws_lb_target_group",name:"service",
|
||||
instances:[.httpGroups[] | {index_key:(.TargetGroupName | ltrimstr("warmbly-production-")),attributes:{
|
||||
id:.TargetGroupArn,arn:.TargetGroupArn,name:.TargetGroupName,protocol:.Protocol,port:.Port,vpc_id:.VpcId}}]}]}' \
|
||||
"$work/baseline.json" >"$work/state.json"
|
||||
printf '%s\n' '{"name":"warmbly-production","target_tls":"on"}' >"$work/snapshot.json"
|
||||
state_digest=$(sha256sum "$work/state.json" | cut -d' ' -f1)
|
||||
vars_digest=$(sha256sum "$work/snapshot.json" | cut -d' ' -f1)
|
||||
jq --arg state "$state_digest" --arg vars "$vars_digest" '.state.sha256=$state | .snapshot.sha256=$vars' \
|
||||
"$work/baseline.json" >"$work/reviewed.json"
|
||||
bash "$guard" check-contract "$work/reviewed.json"
|
||||
for change in '.bucket="other-bucket"' '.state.key="other/state"' \
|
||||
'.snapshot.key="warmbly/production/vars/runtime-tls.tfvars.json"' \
|
||||
'.snapshot.key="warmbly/production/vars/runtime-tls-recovery/../default.tfvars.json"' \
|
||||
'.snapshot.versionId="null"' '.snapshot.sha256=""' '.snapshot.releaseTag="main"'; do
|
||||
jq "$change" "$work/reviewed.json" >"$work/changed.json"
|
||||
if bash "$guard" check-contract "$work/changed.json" 2>/dev/null; then
|
||||
echo "Recovery accepted an unbound input contract: $change" >&2; exit 1
|
||||
fi
|
||||
done
|
||||
mkdir "$work/bin"
|
||||
cat >"$work/bin/aws" <<'SH'
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
printf '%s\n' "$*" >>"$FIXTURES/requests.log"
|
||||
service=$1 operation=$2
|
||||
shift 2
|
||||
bucket= key= version= owner= region= output=
|
||||
while [ "$#" -gt 0 ]; do
|
||||
case "$1" in
|
||||
--bucket) bucket=$2; shift 2 ;;
|
||||
--key) key=$2; shift 2 ;;
|
||||
--version-id) version=$2; shift 2 ;;
|
||||
--expected-bucket-owner) owner=$2; shift 2 ;;
|
||||
--region) region=$2; shift 2 ;;
|
||||
*) output=$1; shift ;;
|
||||
esac
|
||||
done
|
||||
[ "$region" = us-east-1 ]
|
||||
case "$service $operation" in
|
||||
'sts get-caller-identity')
|
||||
if [ "${MODE:-}" = account ]; then echo '{"Account":"123456789012"}'; else echo '{"Account":"925323749693"}'; fi ;;
|
||||
's3api get-object')
|
||||
[ "$bucket" = warmbly-terraform-use1-925323749693 ] && [ "$owner" = 925323749693 ]
|
||||
case "$key $version" in
|
||||
'warmbly/production/runtime.tfstate reviewed-state') kind=state ;;
|
||||
'warmbly/production/vars/runtime-tls-recovery/reviewed-cleanup.tfvars.json reviewed-vars') kind=snapshot ;;
|
||||
*) exit 1 ;;
|
||||
esac
|
||||
[ "${MODE:-}" != api-failure ] || exit 1
|
||||
cp "$FIXTURES/$kind.json" "$output"
|
||||
if [ "${MODE:-}" = hash ]; then printf '\n' >>"$output"; fi
|
||||
if [ "${MODE:-}" = version ]; then version=other-version; fi
|
||||
encryption=AES256
|
||||
if [ "${MODE:-}" = kms ]; then encryption=aws:kms; fi
|
||||
if [ "${MODE:-}" = encryption ]; then encryption=none; fi
|
||||
jq -n --arg version "$version" --arg encryption "$encryption" --arg mode "${MODE:-}" \
|
||||
'{VersionId:$version,ServerSideEncryption:$encryption,DeleteMarker:($mode=="deleted")}' ;;
|
||||
's3api head-object')
|
||||
[ "$bucket" = warmbly-terraform-use1-925323749693 ] && [ "$owner" = 925323749693 ]
|
||||
[ "$key" = warmbly/production/runtime.tfstate ]
|
||||
version=reviewed-state
|
||||
if [ "${MODE:-}" = advanced ]; then version=advanced-state; fi
|
||||
jq -n --arg version "$version" '{VersionId:$version}' ;;
|
||||
*) echo 'Unexpected AWS operation' >&2; exit 1 ;;
|
||||
esac
|
||||
SH
|
||||
chmod +x "$work/bin/aws"
|
||||
PATH="$work/bin:$PATH" FIXTURES="$work" bash "$guard" collect "$work/reviewed.json" "$work/collected"
|
||||
jq -e --arg state "$state_digest" --arg vars "$vars_digest" '.state.sha256==$state and .snapshot.sha256==$vars' "$work/collected/inputs.json" >/dev/null
|
||||
PATH="$work/bin:$PATH" FIXTURES="$work" MODE=kms bash "$guard" collect "$work/reviewed.json" "$work/kms"
|
||||
for mode in account api-failure hash version encryption deleted advanced; do
|
||||
if PATH="$work/bin:$PATH" FIXTURES="$work" MODE=$mode bash "$guard" collect "$work/reviewed.json" "$work/$mode" 2>/dev/null; then
|
||||
echo "Recovery accepted incompatible collected inputs: $mode" >&2; exit 1
|
||||
fi
|
||||
[ ! -e "$work/$mode/inputs.json" ]
|
||||
done
|
||||
PATH="$work/bin:$PATH" FIXTURES="$work" MODE=advanced bash "$guard" collect-archived "$work/reviewed.json" "$work/archived"
|
||||
cmp "$work/state.json" "$work/archived/state.json"
|
||||
[ ! -e "$work/archived/latest-state.json" ]
|
||||
if PATH="$work/bin:$PATH" FIXTURES="$work" bash "$guard" collect "$work/reviewed.json" "$work/collected" 2>/dev/null; then
|
||||
echo 'Recovery overwrote an existing input collection' >&2; exit 1
|
||||
fi
|
||||
printf '%s\n' '{"name":"other-deployment","target_tls":"on"}' >"$work/snapshot.json"
|
||||
digest=$(sha256sum "$work/snapshot.json" | cut -d' ' -f1)
|
||||
jq --arg digest "$digest" '.snapshot.sha256=$digest' "$work/reviewed.json" >"$work/changed.json"
|
||||
if PATH="$work/bin:$PATH" FIXTURES="$work" bash "$guard" collect "$work/changed.json" "$work/wrong-deployment" 2>/dev/null; then
|
||||
echo 'Recovery accepted vars for a different deployment' >&2; exit 1
|
||||
fi
|
||||
for stage in drain route; do
|
||||
printf '%s\n' '{"name":"warmbly-production","target_tls":"on"}' >"$work/snapshot.json"
|
||||
jq --arg stage "$stage" '.target_tls=$stage' "$work/snapshot.json" >"$work/changed-vars.json"
|
||||
cp "$work/changed-vars.json" "$work/snapshot.json"
|
||||
digest=$(sha256sum "$work/snapshot.json" | cut -d' ' -f1)
|
||||
jq --arg digest "$digest" '.snapshot.sha256=$digest' "$work/reviewed.json" >"$work/changed.json"
|
||||
if PATH="$work/bin:$PATH" FIXTURES="$work" bash "$guard" collect "$work/changed.json" "$work/$stage" 2>/dev/null; then
|
||||
echo 'Recovery accepted vars for a different transition stage' >&2; exit 1
|
||||
fi
|
||||
done
|
||||
if bash "$guard" apply 2>/dev/null; then
|
||||
echo 'Recovery input collector accepted an execution action' >&2; exit 1
|
||||
fi
|
||||
echo 'Read-only recovery S3 input collection and checks passed'
|
||||
@@ -0,0 +1,81 @@
|
||||
#!/usr/bin/env bash
|
||||
# Preserve historical workflow identities when collecting recovery evidence.
|
||||
set -euo pipefail
|
||||
|
||||
check_contract() {
|
||||
jq -e '
|
||||
.schemaVersion == 1 and .repository == "warmbly/warmbly" and
|
||||
all(.release, .drain, .failedOn;
|
||||
(.tag | type == "string" and test("^v[0-9]+\\.[0-9]+\\.[0-9]+$")) and
|
||||
(.source | type == "string" and test("^[a-f0-9]{40}$")) and
|
||||
(.runId | type == "number" and . > 0 and floor == .) and
|
||||
(.attempt | type == "number" and . > 0 and floor == .)) and
|
||||
([.release.runId, .drain.runId, .failedOn.runId] | unique | length == 3) and
|
||||
.drain.tag == .failedOn.tag and .release.tag != .drain.tag
|
||||
' "$1" >/dev/null || { echo 'Recovery requires explicit current and historical workflow identities' >&2; return 1; }
|
||||
}
|
||||
|
||||
check_lineage() {
|
||||
local evidence=$1 contract=$2 repository=$3 tag source
|
||||
check_contract "$contract"
|
||||
jq -e --slurpfile contract "$contract" '
|
||||
$contract[0] as $expected |
|
||||
def run_matches($identity; $path; $event; $branch; $conclusion):
|
||||
.id == $identity.runId and .run_attempt == $identity.attempt and
|
||||
.head_sha == $identity.source and .repository.full_name == $expected.repository and
|
||||
.path == $path and .event == $event and .head_branch == $branch and
|
||||
.status == "completed" and .conclusion == $conclusion;
|
||||
(.runs.release | run_matches($expected.release; ".github/workflows/release.yml"; "push"; $expected.release.tag; "success")) and
|
||||
(.runs.drain | run_matches($expected.drain; ".github/workflows/runtime-tls.yml"; "workflow_dispatch"; "main"; "success") and
|
||||
.display_title == ("Runtime TLS drain " + $expected.drain.tag)) and
|
||||
(.runs.failedOn | run_matches($expected.failedOn; ".github/workflows/runtime-tls.yml"; "workflow_dispatch"; "main"; "failure") and
|
||||
.display_title == ("Runtime TLS on " + $expected.failedOn.tag)) and
|
||||
(.failedOnJobs | type == "array" and length > 0) and
|
||||
([.failedOnJobs[].id] | unique | length) == (.failedOnJobs | length) and
|
||||
all(.failedOnJobs[];
|
||||
.run_id == $expected.failedOn.runId and .run_attempt == $expected.failedOn.attempt and
|
||||
.status == "completed") and
|
||||
([.failedOnJobs[] | select(.name == "apply")] | length == 1) and
|
||||
any(.failedOnJobs[]; .name == "apply" and .conclusion == "success") and
|
||||
any(.failedOnJobs[]; (.name | startswith("redeploy / ")) and .conclusion == "failure")
|
||||
' "$evidence" >/dev/null || { echo 'Recovery workflow evidence differs from the reviewed lineage' >&2; return 1; }
|
||||
tag=$(jq -r '.release.tag' "$contract")
|
||||
source=$(git -C "$repository" rev-parse --verify "refs/tags/$tag^{commit}")
|
||||
[ "$source" = "$(jq -r '.release.source' "$contract")" ] || { echo 'Recovery release tag differs from its reviewed source' >&2; return 1; }
|
||||
git -C "$repository" merge-base --is-ancestor "$(jq -r '.drain.source' "$contract")" "$(jq -r '.failedOn.source' "$contract")" || {
|
||||
echo 'Recovery ON source does not descend from the reviewed drain source' >&2; return 1;
|
||||
}
|
||||
git -C "$repository" merge-base --is-ancestor "$(jq -r '.failedOn.source' "$contract")" "$source" || {
|
||||
echo 'Recovery release does not descend from the reviewed ON source' >&2; return 1;
|
||||
}
|
||||
}
|
||||
|
||||
collect_lineage() {
|
||||
local contract=$1 work=$2 repository=$3 repo identity run attempt
|
||||
check_contract "$contract"
|
||||
umask 077
|
||||
mkdir "$work"
|
||||
repo=$(jq -r '.repository' "$contract")
|
||||
for identity in release drain failedOn; do
|
||||
run=$(jq -r --arg identity "$identity" '.[$identity].runId' "$contract")
|
||||
attempt=$(jq -r --arg identity "$identity" '.[$identity].attempt' "$contract")
|
||||
gh api "repos/$repo/actions/runs/$run/attempts/$attempt" >"$work/$identity.json"
|
||||
done
|
||||
run=$(jq -r '.failedOn.runId' "$contract")
|
||||
attempt=$(jq -r '.failedOn.attempt' "$contract")
|
||||
gh api "repos/$repo/actions/runs/$run/attempts/$attempt/jobs?per_page=100" --paginate --slurp >"$work/job-pages.json"
|
||||
jq -e '.[0].total_count == ([.[].jobs[]] | length)' "$work/job-pages.json" >/dev/null || {
|
||||
echo 'Recovery requires the complete failed ON job inventory' >&2; return 1;
|
||||
}
|
||||
jq -n --slurpfile release "$work/release.json" --slurpfile drain "$work/drain.json" \
|
||||
--slurpfile failedOn "$work/failedOn.json" --slurpfile jobs "$work/job-pages.json" \
|
||||
'{runs:{release:$release[0],drain:$drain[0],failedOn:$failedOn[0]},failedOnJobs:[$jobs[0][].jobs[]]}' >"$work/candidate.json"
|
||||
check_lineage "$work/candidate.json" "$contract" "$repository"
|
||||
mv "$work/candidate.json" "$work/lineage.json"
|
||||
}
|
||||
|
||||
case "${1:-}" in
|
||||
check) check_lineage "${2:?}" "${3:?}" "${4:?}" ;;
|
||||
collect) collect_lineage "${2:?}" "${3:?}" "${4:?}" ;;
|
||||
*) echo 'Only read-only recovery lineage check and collection are supported' >&2; exit 1 ;;
|
||||
esac
|
||||
@@ -0,0 +1,109 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/../.."
|
||||
work=$(mktemp -d)
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
guard=.github/scripts/runtime-tls-recovery-lineage.sh
|
||||
mkdir "$work/repository"
|
||||
git -C "$work/repository" init -q
|
||||
git -C "$work/repository" config user.name 'Recovery fixture'
|
||||
git -C "$work/repository" config user.email 'fixture@example.invalid'
|
||||
git -C "$work/repository" commit -qm 'feat: establish drain fixture' --allow-empty
|
||||
drain=$(git -C "$work/repository" rev-parse HEAD)
|
||||
git -C "$work/repository" commit -qm 'feat: establish ON fixture' --allow-empty
|
||||
on=$(git -C "$work/repository" rev-parse HEAD)
|
||||
git -C "$work/repository" commit -qm 'feat: establish release fixture' --allow-empty
|
||||
release=$(git -C "$work/repository" rev-parse HEAD)
|
||||
git -C "$work/repository" tag v1.0.1
|
||||
jq -n --arg drain "$drain" --arg on "$on" --arg release "$release" '
|
||||
{schemaVersion:1,repository:"warmbly/warmbly",
|
||||
release:{tag:"v1.0.1",source:$release,runId:101,attempt:1},
|
||||
drain:{tag:"v1.0.0",source:$drain,runId:102,attempt:1},
|
||||
failedOn:{tag:"v1.0.0",source:$on,runId:103,attempt:1}}
|
||||
' >"$work/contract.json"
|
||||
jq '
|
||||
def run($path; $event; $branch; $conclusion):
|
||||
{id:.runId,run_attempt:.attempt,head_sha:.source,repository:{full_name:"warmbly/warmbly"},
|
||||
path:$path,event:$event,head_branch:$branch,status:"completed",conclusion:$conclusion};
|
||||
{runs:{
|
||||
release:(.release | run(".github/workflows/release.yml";"push";.tag;"success")),
|
||||
drain:(.drain | run(".github/workflows/runtime-tls.yml";"workflow_dispatch";"main";"success") + {display_title:("Runtime TLS drain " + .tag)}),
|
||||
failedOn:(.failedOn | run(".github/workflows/runtime-tls.yml";"workflow_dispatch";"main";"failure") + {display_title:("Runtime TLS on " + .tag)})},
|
||||
failedOnJobs:[{id:1,run_id:103,run_attempt:1,status:"completed",name:"apply",conclusion:"success"},
|
||||
{id:2,run_id:103,run_attempt:1,status:"completed",name:"redeploy / redeploy v1.0.0",conclusion:"failure"}]}
|
||||
' "$work/contract.json" >"$work/evidence.json"
|
||||
bash "$guard" check "$work/evidence.json" "$work/contract.json" "$work/repository"
|
||||
for change in '.schemaVersion=2' '.repository="other/repo"' '.release.runId=.drain.runId' \
|
||||
'.drain.tag=.release.tag' '.failedOn.tag="v0.9.0"' '.release.tag="main"' \
|
||||
'.failedOn.attempt=0' '.drain.source="unknown"'; do
|
||||
jq "$change" "$work/contract.json" >"$work/changed.json"
|
||||
if bash "$guard" check "$work/evidence.json" "$work/changed.json" "$work/repository" 2>/dev/null; then
|
||||
echo "Recovery accepted a different lineage contract: $change" >&2; exit 1
|
||||
fi
|
||||
done
|
||||
for change in '.runs.release.id=104' '.runs.release.head_sha=.runs.drain.head_sha' \
|
||||
'.runs.release.repository.full_name="other/repo"' '.runs.release.head_branch="main"' \
|
||||
'.runs.release.path=".github/workflows/deploy-aws.yml"' '.runs.release.conclusion="failure"' \
|
||||
'.runs.release.event="workflow_dispatch"' '.runs.release.status="in_progress"' \
|
||||
'.runs.drain.run_attempt=2' '.runs.drain.conclusion="failure"' \
|
||||
'.runs.drain.display_title="Runtime TLS drain v1.0.1"' \
|
||||
'.runs.failedOn.display_title="Runtime TLS on v1.0.1"' '.runs.failedOn.conclusion="success"' \
|
||||
'.failedOnJobs=[]' '.failedOnJobs += [.failedOnJobs[0]]' '.failedOnJobs[0].conclusion="failure"' \
|
||||
'.failedOnJobs[1].conclusion="success"' '.failedOnJobs[0].run_id=104' \
|
||||
'.failedOnJobs[0].run_attempt=2' '.failedOnJobs[1].status="in_progress"'; do
|
||||
jq "$change" "$work/evidence.json" >"$work/changed.json"
|
||||
if bash "$guard" check "$work/changed.json" "$work/contract.json" "$work/repository" 2>/dev/null; then
|
||||
echo "Recovery accepted different workflow evidence: $change" >&2; exit 1
|
||||
fi
|
||||
done
|
||||
git -C "$work/repository" tag -f v1.0.1 "$drain" >/dev/null
|
||||
if bash "$guard" check "$work/evidence.json" "$work/contract.json" "$work/repository" 2>/dev/null; then
|
||||
echo 'Recovery accepted a release tag on a different source' >&2; exit 1
|
||||
fi
|
||||
git -C "$work/repository" tag -f v1.0.1 "$release" >/dev/null
|
||||
jq --arg source "$release" '.drain.source=$source' "$work/contract.json" >"$work/reversed-contract.json"
|
||||
jq --arg source "$release" '.runs.drain.head_sha=$source' "$work/evidence.json" >"$work/reversed-evidence.json"
|
||||
if bash "$guard" check "$work/reversed-evidence.json" "$work/reversed-contract.json" "$work/repository" 2>/dev/null; then
|
||||
echo 'Recovery accepted reversed drain and ON ancestry' >&2; exit 1
|
||||
fi
|
||||
jq --arg source "$drain" '.release.source=$source' "$work/contract.json" >"$work/reversed-contract.json"
|
||||
jq --arg source "$drain" '.runs.release.head_sha=$source' "$work/evidence.json" >"$work/reversed-evidence.json"
|
||||
git -C "$work/repository" tag -f v1.0.1 "$drain" >/dev/null
|
||||
if bash "$guard" check "$work/reversed-evidence.json" "$work/reversed-contract.json" "$work/repository" 2>/dev/null; then
|
||||
echo 'Recovery accepted a release that predates the ON source' >&2; exit 1
|
||||
fi
|
||||
git -C "$work/repository" tag -f v1.0.1 "$release" >/dev/null
|
||||
mkdir "$work/bin"
|
||||
cat >"$work/bin/gh" <<'SH'
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
printf '%s\n' "$*" >>"$FIXTURES/requests.log"
|
||||
[ "${API_FAIL:-false}" = false ] || exit 1
|
||||
case "$2" in
|
||||
*/runs/101/attempts/1) jq '.runs.release' "$FIXTURES/evidence.json" ;;
|
||||
*/runs/102/attempts/1) jq '.runs.drain' "$FIXTURES/evidence.json" ;;
|
||||
*/runs/103/attempts/1) jq '.runs.failedOn' "$FIXTURES/evidence.json" ;;
|
||||
*/runs/103/attempts/1/jobs\?per_page=100)
|
||||
[ "$3 $4" = '--paginate --slurp' ]
|
||||
jq --arg mode "${JOB_MODE:-complete}" '[{total_count:2,jobs:(if $mode == "partial" then .failedOnJobs[:1] else .failedOnJobs end)}]' "$FIXTURES/evidence.json" ;;
|
||||
*) exit 1 ;;
|
||||
esac
|
||||
SH
|
||||
chmod +x "$work/bin/gh"
|
||||
PATH="$work/bin:$PATH" FIXTURES="$work" bash "$guard" collect "$work/contract.json" "$work/collected" "$work/repository"
|
||||
cmp "$work/evidence.json" "$work/collected/lineage.json"
|
||||
if PATH="$work/bin:$PATH" FIXTURES="$work" JOB_MODE=partial bash "$guard" collect "$work/contract.json" "$work/partial" "$work/repository" 2>/dev/null; then
|
||||
echo 'Recovery accepted an incomplete job collection' >&2; exit 1
|
||||
fi
|
||||
[ ! -e "$work/partial/lineage.json" ]
|
||||
if PATH="$work/bin:$PATH" FIXTURES="$work" API_FAIL=true bash "$guard" collect "$work/contract.json" "$work/api-failure" "$work/repository" 2>/dev/null; then
|
||||
echo 'Recovery accepted a failed GitHub API read' >&2; exit 1
|
||||
fi
|
||||
[ ! -e "$work/api-failure/lineage.json" ]
|
||||
if PATH="$work/bin:$PATH" FIXTURES="$work" bash "$guard" collect "$work/contract.json" "$work/collected" "$work/repository" 2>/dev/null; then
|
||||
echo 'Recovery overwrote an existing lineage collection' >&2; exit 1
|
||||
fi
|
||||
if bash "$guard" apply 2>/dev/null; then
|
||||
echo 'Recovery lineage collector accepted an execution action' >&2; exit 1
|
||||
fi
|
||||
echo 'Read-only recovery workflow lineage collection and checks passed'
|
||||
@@ -0,0 +1,56 @@
|
||||
def services: ["backend", "consumer", "forms", "tracking", "realtime"];
|
||||
def public_services: ["backend", "forms", "tracking", "realtime"];
|
||||
def arn($kind; $id): "arn:aws:elasticloadbalancing:us-east-1:925323749693:" + $kind + "/" + $id;
|
||||
def http($name): arn("targetgroup"; "warmbly-production-"+$name+"/0123456789abcdef");
|
||||
def tls($name): arn("targetgroup"; "warmbly-production-"+$name+"-tls/1123456789abcdef");
|
||||
def service($name): "arn:aws:ecs:us-east-1:925323749693:service/warmbly-production/warmbly-production-"+$name;
|
||||
def definition($name): "arn:aws:ecs:us-east-1:925323749693:task-definition/warmbly-production-"+$name+":47";
|
||||
def image($name): "ghcr.io/warmbly/warmbly/"+$name+"@"+$digest;
|
||||
"arn:aws:ecs:us-east-1:925323749693:cluster/warmbly-production" as $cluster |
|
||||
arn("loadbalancer"; "app/warmbly-production/0123456789abcdef") as $lb |
|
||||
arn("listener"; "app/warmbly-production/0123456789abcdef/0123456789abcdef") as $listener |
|
||||
"vpc-0123456789abcdef0" as $vpc | "sg-0123456789abcdef0" as $sg |
|
||||
"-----BEGIN CERTIFICATE-----\nfixture\n-----END CERTIFICATE-----" as $cert |
|
||||
([range(9) | . as $i | {arn:arn("listener-rule"; "app/warmbly-production/0123456789abcdef/0123456789abcdef/"+($i|tostring)),
|
||||
hosts:["host"+($i|tostring)+".example.com"],target:tls(public_services[$i%4])}]) as $routes |
|
||||
(public_services | map({TargetGroupName:("warmbly-production-"+.),TargetGroupArn:http(.),Protocol:"HTTP",Port:8080,VpcId:$vpc,LoadBalancerArns:[],targets:[]})) as $http |
|
||||
{baseline:{account:"925323749693",region:"us-east-1",httpGroups:$http,
|
||||
state:{lineage:"01234567-89ab-cdef-0123-456789abcdef",serial:64,versionId:"state-version",sha256:("a"*64),httpGroups:$http},
|
||||
snapshot:{sha256:("b"*64),releaseTag:"v1.2.3"}},
|
||||
vars:{name:"warmbly-production",target_tls:"on",backend_internal_certificate:$cert},
|
||||
images:{tag:"v1.2.3",registry:"ghcr.io/warmbly/warmbly",images:(services|map({key:.,value:$digest})|from_entries)},
|
||||
state:{version:4,lineage:"01234567-89ab-cdef-0123-456789abcdef",serial:64,resources:[
|
||||
{mode:"managed",type:"aws_lb_target_group",name:"service",instances:[$http[]|{
|
||||
index_key:(.TargetGroupName|ltrimstr("warmbly-production-")),attributes:{arn:.TargetGroupArn,id:.TargetGroupArn,name:.TargetGroupName,protocol:.Protocol,port:.Port,vpc_id:.VpcId}}]},
|
||||
{mode:"managed",type:"aws_lb_target_group",name:"service_tls",instances:[public_services[]|{index_key:.,attributes:{arn:tls(.),name:("warmbly-production-"+.+"-tls"),protocol:"HTTPS",port:8443,vpc_id:$vpc}}]},
|
||||
{mode:"managed",type:"aws_ecs_service",name:"service",instances:[services[]|{index_key:.,attributes:{id:service(.),cluster:$cluster,network_configuration:[{security_groups:[$sg]}]}}]},
|
||||
{mode:"managed",type:"aws_lb",name:"main",instances:[{attributes:{arn:$lb}}]},
|
||||
{mode:"managed",type:"aws_lb_listener",name:"https",instances:[{attributes:{arn:$listener}}]},
|
||||
{mode:"managed",type:"aws_lb_listener_rule",name:"service",instances:[$routes[]|{attributes:{arn:.arn,condition:[{host_header:[{values:.hosts}]}],action:[{target_group_arn:.target}]}}]}
|
||||
]},
|
||||
live:{account:{Account:"925323749693"},services:{failures:[],services:[services[]|. as $name|{
|
||||
serviceName:("warmbly-production-"+.),serviceArn:service(.),clusterArn:$cluster,taskDefinition:definition(.),status:"ACTIVE",desiredCount:1,runningCount:1,pendingCount:0,
|
||||
deployments:[{status:"PRIMARY",rolloutState:"COMPLETED",taskDefinition:definition(.)}],
|
||||
networkConfiguration:{awsvpcConfiguration:{securityGroups:[$sg]}},
|
||||
loadBalancers:(if .=="consumer" then [] else [{containerName:.,containerPort:8443,targetGroupArn:tls(.)}] end)}]},
|
||||
definitions:[services[]|. as $name|{taskDefinition:{taskDefinitionArn:definition(.),runtimePlatform:{cpuArchitecture:"X86_64"},containerDefinitions:[{
|
||||
name:.,image:image(.),environment:([
|
||||
{name:"SERVE_TLS",value:(if .=="backend" then "supplied" else "self-signed" end)},
|
||||
{name:"SERVE_TLS_PORT",value:"8443"},{name:"SERVE_HTTP_LOOPBACK_ONLY",value:"true"}]+
|
||||
(if .=="backend" then [{name:"SERVE_TLS_CERT",value:$cert}] elif .=="forms" or .=="tracking" then
|
||||
[{name:"BACKEND_INTERNAL_URL",value:"https://backend.warmbly.internal:8443"},{name:"BACKEND_INTERNAL_CA",value:$cert}] else [] end))}]},
|
||||
tags:[{key:"warmbly-release",value:"v1.2.3"},{key:"warmbly-image-variant",value:"default"}]}],
|
||||
tasks:[services[]|{taskArn:("task-"+.),group:("service:warmbly-production-"+.),taskDefinitionArn:definition(.),clusterArn:$cluster,
|
||||
lastStatus:"RUNNING",desiredStatus:"RUNNING",healthStatus:(if .=="consumer" then "UNKNOWN" else "HEALTHY" end),overrides:{containerOverrides:[]},
|
||||
containers:[{name:.,image:image(.),imageDigest:$digest,lastStatus:"RUNNING",healthStatus:(if .=="consumer" then "UNKNOWN" else "HEALTHY" end),networkInterfaces:[{privateIpv4Address:"10.0.0.1"}]}]}],
|
||||
manifests:[services[]|{image:image(.),digest:$digest,document:{schemaVersion:2}}],
|
||||
httpsGroups:[public_services[]|{TargetGroupArn:tls(.),TargetGroupName:("warmbly-production-"+.+"-tls"),Protocol:"HTTPS",Port:8443,HealthCheckProtocol:"HTTPS",VpcId:$vpc,LoadBalancerArns:[$lb],
|
||||
targets:[{Target:{Id:"10.0.0.1",Port:8443},TargetHealth:{State:"healthy"}}]}],httpGroups:$http,
|
||||
listeners:[{ListenerArn:$listener,LoadBalancerArn:$lb,Port:443,Protocol:"HTTPS"}],
|
||||
rules:([$routes[]|{RuleArn:.arn,IsDefault:false,Conditions:[{Field:"host-header",HostHeaderConfig:{Values:.hosts}}],Actions:[{Type:"forward",TargetGroupArn:.target}]}]+
|
||||
[{IsDefault:true,Actions:[{Type:"fixed-response",Order:1,FixedResponseConfig:{StatusCode:"404",ContentType:"text/plain",MessageBody:"Not found"}}]}]),
|
||||
securityGroups:[{GroupId:$sg,VpcId:$vpc,IpPermissions:[{IpProtocol:"tcp",FromPort:8443,ToPort:8443}]}],
|
||||
alarms:{CompositeAlarms:[],MetricAlarms:[public_services[] as $name|["target-5xx-rate","unhealthy-hosts"][]|
|
||||
{AlarmName:("warmbly-production-"+$name+"-"+.),StateValue:"OK",ActionsEnabled:true,
|
||||
Dimensions:[{Name:"TargetGroup",Value:(tls($name)|split(":")[-1])},{Name:"LoadBalancer",Value:($lb|split(":")[-1]|ltrimstr("loadbalancer/"))}]}]},
|
||||
public:(["https://api.warmbly.com/health","https://api.warmbly.com/v1/auth/config","https://forms.warmbly.com/health","https://realtime.warmbly.com/health","https://track.monitorably.com/health"]|map({url:.,status:200}))}}
|
||||
@@ -0,0 +1,131 @@
|
||||
def public_services: ["backend", "forms", "tracking", "realtime"];
|
||||
def services: ["backend", "consumer", "forms", "tracking", "realtime"];
|
||||
def instances($type; $name):
|
||||
[$state[0].resources[] | select(.mode == "managed" and .module == null and .type == $type and .name == $name) | .instances[]];
|
||||
def identity: {TargetGroupName,TargetGroupArn,Protocol,Port,VpcId};
|
||||
def environment: .environment | map({key:.name,value:.value}) | from_entries;
|
||||
def targets:
|
||||
[.Actions[] | select(.Type == "forward") |
|
||||
.TargetGroupArn?, .ForwardConfig.TargetGroups[]?.TargetGroupArn | select(. != null)] | unique;
|
||||
|
||||
$baseline[0] as $b | $vars[0] as $v | $images[0] as $images |
|
||||
instances("aws_ecs_service"; "service") as $expectedServices |
|
||||
instances("aws_lb_target_group"; "service_tls") as $tls |
|
||||
(instances("aws_lb"; "main") | map(.attributes.arn)) as $lbs |
|
||||
(instances("aws_lb_listener"; "https") | map(.attributes.arn)) as $listeners |
|
||||
([instances("aws_lb_listener_rule"; "service")[], instances("aws_lb_listener_rule"; "tracking_alias")[]] |
|
||||
map({arn:.attributes.arn, hosts:([.attributes.condition[].host_header[].values[]] | sort),
|
||||
target:.attributes.action[0].target_group_arn})) as $routes |
|
||||
($expectedServices | map(.attributes.network_configuration[].security_groups[]) | unique) as $sgs |
|
||||
($v.target_tls_port // 8443) as $port |
|
||||
. as $live |
|
||||
.account.Account == "925323749693" and
|
||||
($images.tag == $b.snapshot.releaseTag and $images.registry == "ghcr.io/warmbly/warmbly") and
|
||||
($expectedServices | map(.index_key) | sort) == (services | sort) and
|
||||
($tls | map(.index_key) | sort) == (public_services | sort) and
|
||||
($lbs | length == 1) and ($listeners | length == 1) and
|
||||
($routes | length == 9) and ($routes | map(.arn) | unique | length == 9) and
|
||||
all($routes[]; .hosts | length > 0) and
|
||||
all($tls[]; .attributes.protocol == "HTTPS" and .attributes.port == $port and
|
||||
.attributes.vpc_id == $b.httpGroups[0].VpcId) and
|
||||
all($routes[]; .target as $target | any($tls[]; .attributes.arn == $target)) and
|
||||
(.services.failures | length == 0) and
|
||||
(.services.services | map(.serviceName) | sort) == (services | map("warmbly-production-" + .) | sort) and
|
||||
all(.services.services[];
|
||||
. as $s | (.serviceName | ltrimstr("warmbly-production-")) as $name |
|
||||
any($expectedServices[]; .index_key == $name and .attributes.id == $s.serviceArn and .attributes.cluster == $s.clusterArn) and
|
||||
.status == "ACTIVE" and .desiredCount > 0 and .runningCount == .desiredCount and .pendingCount == 0 and
|
||||
(.deployments | length == 1) and .deployments[0].status == "PRIMARY" and
|
||||
.deployments[0].rolloutState == "COMPLETED" and .deployments[0].taskDefinition == .taskDefinition and
|
||||
(.networkConfiguration.awsvpcConfiguration.securityGroups | sort) == $sgs and
|
||||
(if $name == "consumer" then (.loadBalancers | length == 0) else
|
||||
(.loadBalancers | length == 1) and .loadBalancers[0].containerName == $name and
|
||||
.loadBalancers[0].containerPort == $port and
|
||||
any($tls[]; .index_key == $name and .attributes.arn == $s.loadBalancers[0].targetGroupArn) end) and
|
||||
([$live.definitions[] | select(.taskDefinition.taskDefinitionArn == $s.taskDefinition)] | length == 1) and
|
||||
([$live.definitions[] | select(.taskDefinition.taskDefinitionArn == $s.taskDefinition)][0] as $d |
|
||||
([$d.tags[] | select(.key == "warmbly-image-variant") | .value]) as $variant |
|
||||
($name + (if $variant == ["kafka"] then "-kafka" else "" end)) as $key |
|
||||
($images.registry + "/" + $name + "@" + $images.images[$key]) as $image |
|
||||
(if $name == "consumer" and $d.taskDefinition.containerDefinitions[0].healthCheck == null then "UNKNOWN" else "HEALTHY" end) as $health |
|
||||
([$d.tags[] | select(.key == "warmbly-release") | .value] == [$images.tag]) and
|
||||
($variant == ["default"] or $variant == ["kafka"]) and
|
||||
($images.images[$key] | type == "string" and test("^sha256:[a-f0-9]{64}$")) and
|
||||
($d.taskDefinition.containerDefinitions | length == 1) and
|
||||
(["X86_64", "ARM64"] | index($d.taskDefinition.runtimePlatform.cpuArchitecture // "X86_64") != null) and
|
||||
($d.taskDefinition.runtimePlatform.operatingSystemFamily // "LINUX") == "LINUX" and
|
||||
($d.taskDefinition.containerDefinitions[0] as $c |
|
||||
($c | environment) as $env |
|
||||
$c.name == $name and $c.image == $image and
|
||||
($c.environment | map(.name) | unique | length) == ($c.environment | length) and
|
||||
($c.environmentFiles // [] | length == 0) and
|
||||
all($c.secrets[]?; .name | test("^(SERVE_TLS|SERVE_TLS_PORT|SERVE_TLS_CERT|SERVE_HTTP_LOOPBACK_ONLY|BACKEND_INTERNAL_URL|BACKEND_INTERNAL_CA)$") | not) and
|
||||
(if $name == "consumer" then true else
|
||||
$env.SERVE_TLS == (if $name == "backend" then "supplied" else "self-signed" end) and
|
||||
$env.SERVE_TLS_PORT == ($port | tostring) and $env.SERVE_HTTP_LOOPBACK_ONLY == "true" and
|
||||
(if $name == "backend" then $env.SERVE_TLS_CERT == $v.backend_internal_certificate else true end) and
|
||||
(if $name == "forms" or $name == "tracking" then
|
||||
$env.BACKEND_INTERNAL_URL == ("https://backend." + ($v.namespace // "warmbly.internal") + ":" + ($port | tostring)) and
|
||||
$env.BACKEND_INTERNAL_CA == $v.backend_internal_certificate else true end) end)) and
|
||||
([$live.tasks[] | select(.group == ("service:" + $s.serviceName))] as $tasks |
|
||||
($tasks | length) == $s.desiredCount and
|
||||
all($tasks[]; .taskDefinitionArn == $s.taskDefinition and .clusterArn == $s.clusterArn and
|
||||
.lastStatus == "RUNNING" and .desiredStatus == "RUNNING" and .healthStatus == $health and
|
||||
(.overrides.containerOverrides | all(.[]; (.environment // [] | length == 0) and (.command // [] | length == 0) and (.environmentFiles // [] | length == 0))) and
|
||||
(.containers | length == 1) and .containers[0].name == $name and .containers[0].image == $image and
|
||||
.containers[0].lastStatus == "RUNNING" and .containers[0].healthStatus == $health and
|
||||
(.containers[0].imageDigest as $digest |
|
||||
any($live.manifests[]; .image == $image and .digest == ($image | split("@")[1]) and
|
||||
(if .document.manifests then
|
||||
.digest as $index |
|
||||
any(.document.manifests[]; (.digest == $digest or $index == $digest) and .platform.os == "linux" and
|
||||
.platform.architecture == (if ($d.taskDefinition.runtimePlatform.cpuArchitecture // "X86_64") == "ARM64" then "arm64" else "amd64" end))
|
||||
else .digest == $digest end))))))) and
|
||||
(.tasks | map(.taskArn) | unique | length) == (.tasks | length) and
|
||||
(.tasks | length) == ([.services.services[].desiredCount] | add) and
|
||||
(.definitions | length == 5) and
|
||||
(.httpsGroups | map(.TargetGroupArn) | sort) == ($tls | map(.attributes.arn) | sort) and
|
||||
all(.httpsGroups[];
|
||||
. as $g | .Protocol == "HTTPS" and .Port == $port and .HealthCheckProtocol == "HTTPS" and
|
||||
.VpcId == $b.httpGroups[0].VpcId and .LoadBalancerArns == $lbs and
|
||||
(.targets | length > 0) and all(.targets[]; .TargetHealth.State == "healthy" and .Target.Port == $port) and
|
||||
([.targets[].Target.Id] | sort) ==
|
||||
([$live.tasks[] | select(.group == ("service:" + ($g.TargetGroupName | rtrimstr("-tls")))) |
|
||||
.containers[0].networkInterfaces[].privateIpv4Address] | sort) and
|
||||
any($tls[]; .attributes.arn == $g.TargetGroupArn and .attributes.name == $g.TargetGroupName)) and
|
||||
(if $phase == "after" then .httpGroups == [] else
|
||||
(.httpGroups | map(identity) | sort_by(.TargetGroupArn)) == ($b.httpGroups | map(identity) | sort_by(.TargetGroupArn)) end) and
|
||||
all(.httpGroups[]; .LoadBalancerArns == [] and .targets == []) and
|
||||
(.listeners | length == 1) and .listeners[0].ListenerArn == $listeners[0] and
|
||||
.listeners[0].LoadBalancerArn == $lbs[0] and .listeners[0].Port == 443 and .listeners[0].Protocol == "HTTPS" and
|
||||
(.rules | length == 10) and
|
||||
([.rules[] | select(.IsDefault == true)] | length == 1) and
|
||||
all(.rules[] | select(.IsDefault == true); .Actions == [{Type:"fixed-response",Order:1,FixedResponseConfig:{StatusCode:"404",ContentType:"text/plain",MessageBody:"Not found"}}]) and
|
||||
([.rules[] | select(.IsDefault == false) | .RuleArn] | sort) == ($routes | map(.arn) | sort) and
|
||||
all(.rules[] | select(.IsDefault == false);
|
||||
. as $rule | (.Transforms // [] | length == 0) and (.Conditions | length == 1) and
|
||||
.Conditions[0].Field == "host-header" and (.Actions | length == 1) and .Actions[0].Type == "forward" and
|
||||
all(.Actions[0].ForwardConfig.TargetGroups[]?; (.Weight // 1) > 0) and
|
||||
any($routes[]; .arn == $rule.RuleArn and
|
||||
.hosts == ($rule.Conditions[0].HostHeaderConfig.Values | sort) and ($rule | targets) == [.target])) and
|
||||
(.securityGroups | map(.GroupId) | sort) == ($sgs | sort) and ($sgs | length > 0) and
|
||||
all(.securityGroups[]; .VpcId == $b.httpGroups[0].VpcId and
|
||||
all(.IpPermissions[]; . as $permission |
|
||||
.IpProtocol != "-1" and
|
||||
(if .IpProtocol == "tcp" or .IpProtocol == "6" then
|
||||
(.FromPort | type == "number") and (.ToPort | type == "number") and
|
||||
all($b.httpGroups[]; .Port < $permission.FromPort or .Port > $permission.ToPort) else true end))) and
|
||||
(.alarms.CompositeAlarms | length == 0) and
|
||||
(.alarms.MetricAlarms | map(.AlarmName) | sort) ==
|
||||
([public_services[] as $name | ["target-5xx-rate", "unhealthy-hosts"][] | "warmbly-production-" + $name + "-" + .] | sort) and
|
||||
all(.alarms.MetricAlarms[];
|
||||
. as $alarm | .StateValue == "OK" and .ActionsEnabled == true and
|
||||
any($tls[];
|
||||
. as $group | ($alarm.AlarmName | startswith("warmbly-production-" + $group.index_key + "-")) and
|
||||
([$alarm.Dimensions[]?, $alarm.Metrics[]?.MetricStat.Metric.Dimensions[]? | select(.Name == "TargetGroup") | .Value] | unique) ==
|
||||
[($group.attributes.arn | split(":")[-1])] and
|
||||
([$alarm.Dimensions[]?, $alarm.Metrics[]?.MetricStat.Metric.Dimensions[]? | select(.Name == "LoadBalancer") | .Value] | unique) ==
|
||||
[($lbs[0] | split(":")[-1] | ltrimstr("loadbalancer/"))])) and
|
||||
(.public | map(.url) | sort) == (["https://api.warmbly.com/health", "https://api.warmbly.com/v1/auth/config",
|
||||
"https://forms.warmbly.com/health", "https://realtime.warmbly.com/health", "https://track.monitorably.com/health"] | sort) and
|
||||
all(.public[]; .status == 200)
|
||||
Executable
+96
@@ -0,0 +1,96 @@
|
||||
#!/usr/bin/env bash
|
||||
# Collect fresh read-only service and traffic evidence from reviewed state identities.
|
||||
set -euo pipefail
|
||||
scripts=$(cd "$(dirname "$0")" && pwd)
|
||||
|
||||
check_live() {
|
||||
local evidence=$1 baseline=$2 vars=$3 state=$4 images=$5 phase=${6:-before}
|
||||
bash "$scripts/runtime-tls-recovery.sh" check-state "$state" "$baseline"
|
||||
[ "$(sha256sum "$vars" | cut -d' ' -f1)" = "$(jq -r '.snapshot.sha256' "$baseline")" ]
|
||||
jq -e '.name == "warmbly-production" and .target_tls == "on" and
|
||||
(.backend_internal_certificate | type == "string" and startswith("-----BEGIN CERTIFICATE-----"))' "$vars" >/dev/null
|
||||
jq -e --arg phase "$phase" --slurpfile baseline "$baseline" --slurpfile vars "$vars" --slurpfile state "$state" --slurpfile images "$images" \
|
||||
-f "$scripts/runtime-tls-recovery-live.jq" "$evidence" >/dev/null || {
|
||||
echo 'Recovery live service, TLS, traffic or health evidence does not match the reviewed inputs' >&2; return 1;
|
||||
}
|
||||
}
|
||||
|
||||
collect_live() {
|
||||
local baseline=$1 inputs=$2 work=$3 phase=${4:-before} cluster definition arn name image digest url status
|
||||
bash "$scripts/runtime-tls-recovery.sh" check-state "$inputs/state.json" "$baseline"
|
||||
umask 077
|
||||
mkdir "$work"
|
||||
export AWS_PAGER=""
|
||||
aws sts get-caller-identity --region us-east-1 >"$work/account.json"
|
||||
jq -e '.Account == "925323749693"' "$work/account.json" >/dev/null
|
||||
cluster=$(jq -er '[.resources[] | select(.mode=="managed" and .module==null and .type=="aws_ecs_service" and .name=="service") |
|
||||
.instances[].attributes.cluster] | unique | if length==1 then .[0] else error("cluster identity") end' "$inputs/state.json")
|
||||
aws ecs describe-services --region us-east-1 --cluster "$cluster" --services \
|
||||
warmbly-production-backend warmbly-production-consumer warmbly-production-forms warmbly-production-tracking warmbly-production-realtime >"$work/services.json"
|
||||
: >"$work/definitions.jsonl"
|
||||
: >"$work/tasks.jsonl"
|
||||
while IFS= read -r definition; do
|
||||
aws ecs describe-task-definition --region us-east-1 --task-definition "$definition" --include TAGS >>"$work/definitions.jsonl"
|
||||
done < <(jq -r '.services[].taskDefinition' "$work/services.json")
|
||||
while IFS= read -r name; do
|
||||
aws ecs list-tasks --region us-east-1 --cluster "$cluster" --service-name "$name" --desired-status RUNNING >"$work/task-list.json"
|
||||
while IFS= read -r arn; do
|
||||
aws ecs describe-tasks --region us-east-1 --cluster "$cluster" --tasks "$arn" >"$work/task.json"
|
||||
jq -e '.failures == [] and (.tasks | length == 1)' "$work/task.json" >/dev/null
|
||||
jq -c '.tasks[]' "$work/task.json" >>"$work/tasks.jsonl"
|
||||
done < <(jq -r '.taskArns[]' "$work/task-list.json")
|
||||
done < <(jq -r '.services[].serviceName' "$work/services.json")
|
||||
: >"$work/manifests.jsonl"
|
||||
while IFS= read -r image; do
|
||||
[[ "$image" =~ ^ghcr.io/warmbly/warmbly/(backend|consumer|forms|tracking|realtime)@sha256:[a-f0-9]{64}$ ]]
|
||||
docker buildx imagetools inspect "$image" --raw >"$work/manifest.json"
|
||||
digest="sha256:$(sha256sum "$work/manifest.json" | cut -d' ' -f1)"
|
||||
[ "$digest" = "${image##*@}" ] || { echo 'Registry manifest bytes differ from the pinned image' >&2; return 1; }
|
||||
jq -n --arg image "$image" --arg digest "$digest" --slurpfile document "$work/manifest.json" \
|
||||
'{image:$image,digest:$digest,document:$document[0]}' >>"$work/manifests.jsonl"
|
||||
done < <(jq -r '.taskDefinition.containerDefinitions[].image' "$work/definitions.jsonl" | sort -u)
|
||||
aws elbv2 describe-target-groups --region us-east-1 >"$work/all-groups.json"
|
||||
: >"$work/groups.jsonl"
|
||||
while IFS= read -r arn; do
|
||||
aws elbv2 describe-target-health --region us-east-1 --target-group-arn "$arn" >"$work/health.json"
|
||||
jq -c --arg arn "$arn" --slurpfile health "$work/health.json" \
|
||||
'.TargetGroups[] | select(.TargetGroupArn == $arn) | . + {targets:$health[0].TargetHealthDescriptions}' \
|
||||
"$work/all-groups.json" >>"$work/groups.jsonl"
|
||||
done < <(jq -r '.TargetGroups[] | select(.TargetGroupName | test("^warmbly-production-(backend|forms|tracking|realtime)(-tls)?$")) | .TargetGroupArn' "$work/all-groups.json")
|
||||
arn=$(jq -er '[.resources[] | select(.mode=="managed" and .module==null and .type=="aws_lb" and .name=="main") |
|
||||
.instances[].attributes.arn] | if length==1 then .[0] else error("load balancer identity") end' "$inputs/state.json")
|
||||
aws elbv2 describe-listeners --region us-east-1 --load-balancer-arn "$arn" >"$work/listeners.json"
|
||||
: >"$work/rules.jsonl"
|
||||
while IFS= read -r arn; do
|
||||
aws elbv2 describe-rules --region us-east-1 --listener-arn "$arn" | jq -c '.Rules[]' >>"$work/rules.jsonl"
|
||||
done < <(jq -r '.Listeners[].ListenerArn' "$work/listeners.json")
|
||||
: >"$work/security-groups.jsonl"
|
||||
while IFS= read -r arn; do
|
||||
aws ec2 describe-security-groups --region us-east-1 --group-ids "$arn" | jq -c '.SecurityGroups[]' >>"$work/security-groups.jsonl"
|
||||
done < <(jq -r '.services[].networkConfiguration.awsvpcConfiguration.securityGroups[]' "$work/services.json" | sort -u)
|
||||
aws cloudwatch describe-alarms --region us-east-1 --alarm-name-prefix warmbly-production- >"$work/alarms.json"
|
||||
: >"$work/public.jsonl"
|
||||
for url in https://api.warmbly.com/health https://api.warmbly.com/v1/auth/config https://forms.warmbly.com/health \
|
||||
https://realtime.warmbly.com/health https://track.monitorably.com/health; do
|
||||
status=$(curl --silent --show-error --proto '=https' --tlsv1.2 --connect-timeout 10 --max-time 30 --output /dev/null --write-out '%{http_code}' "$url")
|
||||
jq -n --arg url "$url" --argjson status "$status" '{url:$url,status:$status}' >>"$work/public.jsonl"
|
||||
done
|
||||
jq -n --slurpfile account "$work/account.json" --slurpfile services "$work/services.json" \
|
||||
--slurpfile definitions "$work/definitions.jsonl" --slurpfile tasks "$work/tasks.jsonl" \
|
||||
--slurpfile manifests "$work/manifests.jsonl" --slurpfile groups "$work/groups.jsonl" \
|
||||
--slurpfile listeners "$work/listeners.json" --slurpfile rules "$work/rules.jsonl" \
|
||||
--slurpfile securityGroups "$work/security-groups.jsonl" --slurpfile alarms "$work/alarms.json" --slurpfile public "$work/public.jsonl" \
|
||||
'{account:$account[0],services:$services[0],definitions:$definitions,tasks:$tasks,manifests:$manifests,
|
||||
httpsGroups:[$groups[]|select(.Protocol=="HTTPS")],httpGroups:[$groups[]|select(.Protocol=="HTTP")],
|
||||
listeners:$listeners[0].Listeners,rules:$rules,securityGroups:$securityGroups,alarms:$alarms[0],public:$public}' >"$work/candidate.json"
|
||||
check_live "$work/candidate.json" "$baseline" "$inputs/snapshot.json" "$inputs/state.json" "$inputs/images.json" "$phase"
|
||||
mv "$work/candidate.json" "$work/live.json"
|
||||
}
|
||||
|
||||
case "${1:-}" in
|
||||
check) check_live "${2:?}" "${3:?}" "${4:?}" "${5:?}" "${6:?}" ;;
|
||||
check-final) check_live "${2:?}" "${3:?}" "${4:?}" "${5:?}" "${6:?}" after ;;
|
||||
collect) collect_live "${2:?}" "${3:?}" "${4:?}" ;;
|
||||
collect-final) collect_live "${2:?}" "${3:?}" "${4:?}" after ;;
|
||||
*) echo 'Only read-only recovery live checks and collection are supported' >&2; exit 1 ;;
|
||||
esac
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/../.."
|
||||
work=$(mktemp -d)
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
guard=.github/scripts/runtime-tls-recovery-live.sh
|
||||
printf '{"schemaVersion":2}\n' >"$work/manifest.json"
|
||||
digest="sha256:$(sha256sum "$work/manifest.json" | cut -d' ' -f1)"
|
||||
jq -n --arg digest "$digest" -f .github/scripts/runtime-tls-recovery-live.fixture.jq >"$work/fixture.json"
|
||||
for kind in baseline state vars images live; do jq ".$kind" "$work/fixture.json" >"$work/$kind.json"; done
|
||||
state_hash=$(sha256sum "$work/state.json" | cut -d' ' -f1)
|
||||
vars_hash=$(sha256sum "$work/vars.json" | cut -d' ' -f1)
|
||||
jq --arg state "$state_hash" --arg vars "$vars_hash" '.state.sha256=$state | .snapshot.sha256=$vars' "$work/baseline.json" >"$work/reviewed.json"
|
||||
check() { bash "$guard" check "$1" "$work/reviewed.json" "$work/vars.json" "$work/state.json" "$work/images.json"; }
|
||||
check "$work/live.json"
|
||||
for change in \
|
||||
'.account.Account="123456789012"' '.services.failures=[{}]' '.services.services|=.[1:]' \
|
||||
'.services.services[0].clusterArn="other-cluster"' '.services.services[0].serviceArn="other-service"' \
|
||||
'.services.services[0].desiredCount=0' '.services.services[0].runningCount=0' '.services.services[0].pendingCount=1' \
|
||||
'.services.services[0].deployments[0].rolloutState="IN_PROGRESS"' '.services.services[0].deployments+=.services.services[0].deployments' \
|
||||
'.services.services[0].loadBalancers[0].targetGroupArn="other-group"' \
|
||||
'.services.services[0].networkConfiguration.awsvpcConfiguration.securityGroups+=["sg-extra"]' \
|
||||
'.definitions[0].tags[0].value="v1.2.2"' '.definitions[0].taskDefinition.containerDefinitions[0].image="other-image"' \
|
||||
'.definitions[0].taskDefinition.containerDefinitions[0].secrets=[{name:"SERVE_TLS",valueFrom:"other"}]' \
|
||||
'.definitions[0].taskDefinition.containerDefinitions[0].environmentFiles=[{value:"other"}]' \
|
||||
'.definitions[0].taskDefinition.containerDefinitions[0].environment[2].value="false"' \
|
||||
'.definitions[0].taskDefinition.containerDefinitions[0].environment[0].value="self-signed"' \
|
||||
'.definitions[0].taskDefinition.containerDefinitions[0].environment[3].value="other-cert"' \
|
||||
'.definitions[2].taskDefinition.containerDefinitions[0].environment[4].value="other-ca"' \
|
||||
'.definitions[2].taskDefinition.containerDefinitions[0].environment[3].value="http://backend.warmbly.internal:8080"' \
|
||||
'.tasks|=.[1:]' '.tasks+=.tasks' '.tasks[0].taskDefinitionArn="older-definition"' \
|
||||
'.tasks[0].healthStatus="UNHEALTHY"' '.tasks[0].containers[0].imageDigest="sha256:other"' \
|
||||
'.tasks[1].healthStatus="UNHEALTHY"' '.tasks[1].containers[0].lastStatus="STOPPED"' \
|
||||
'.tasks[0].overrides.containerOverrides=[{environment:[{name:"SERVE_TLS",value:"off"}]}]' \
|
||||
'.httpsGroups|=.[1:]' '.httpsGroups[0].Protocol="HTTP"' '.httpsGroups[0].targets=[]' \
|
||||
'.httpsGroups[0].targets[0].TargetHealth.State="unhealthy"' '.httpsGroups[0].LoadBalancerArns=[]' \
|
||||
'.httpsGroups[0].targets[0].Target.Id="10.0.0.2"' \
|
||||
'.httpGroups[0].targets=[{}]' '.httpGroups[0].LoadBalancerArns=["other-lb"]' '.httpGroups[0].TargetGroupArn="other-group"' \
|
||||
'.listeners[0].Protocol="HTTP"' '.listeners[0].Port=80' '.rules|=.[1:]' \
|
||||
'.rules[0].Actions[0].TargetGroupArn=.httpGroups[0].TargetGroupArn' \
|
||||
'.rules[0].Actions[0].ForwardConfig.TargetGroups=[{TargetGroupArn:.httpGroups[0].TargetGroupArn,Weight:0}]' \
|
||||
'.rules[0].Conditions[0].HostHeaderConfig.Values=["other.example.com"]' \
|
||||
'.rules[0].Transforms=[{}]' '.securityGroups=[]' \
|
||||
'.securityGroups[0].IpPermissions+=[{IpProtocol:"tcp",FromPort:8080,ToPort:8080}]' \
|
||||
'.securityGroups[0].IpPermissions+=[{IpProtocol:"-1"}]' \
|
||||
'.alarms.MetricAlarms|=.[1:]' '.alarms.MetricAlarms[0].StateValue="ALARM"' \
|
||||
'.alarms.MetricAlarms[0].StateValue="INSUFFICIENT_DATA"' '.public[0].status=503' '.public|=.[1:]'; do
|
||||
jq "$change" "$work/live.json" >"$work/changed.json"
|
||||
if check "$work/changed.json" 2>/dev/null; then
|
||||
echo "Recovery accepted incompatible live evidence: $change" >&2; exit 1
|
||||
fi
|
||||
done
|
||||
jq '.alarms.MetricAlarms[0].Dimensions[0].Value="targetgroup/old-http/0000000000000000"' "$work/live.json" >"$work/changed.json"
|
||||
if check "$work/changed.json" 2>/dev/null; then echo 'Recovery accepted an alarm on a different target group' >&2; exit 1; fi
|
||||
jq '.alarms.MetricAlarms[] |= (.Metrics=[{MetricStat:{Metric:{Dimensions:.Dimensions}}}] | del(.Dimensions))' "$work/live.json" >"$work/metric-math.json"
|
||||
check "$work/metric-math.json"
|
||||
jq --arg digest "$digest" '.tasks[].containers[0].imageDigest="sha256:platform" |
|
||||
.manifests[].document={manifests:[{digest:"sha256:platform",platform:{os:"linux",architecture:"amd64"}}]}' \
|
||||
"$work/live.json" >"$work/multiarch.json"
|
||||
check "$work/multiarch.json"
|
||||
jq --arg digest "$digest" '.tasks[].containers[0].imageDigest=$digest' "$work/multiarch.json" >"$work/index-reported.json"
|
||||
check "$work/index-reported.json"
|
||||
jq '.manifests[].document.manifests[0].platform.architecture="arm64"' "$work/multiarch.json" >"$work/changed.json"
|
||||
if check "$work/changed.json" 2>/dev/null; then echo 'Recovery accepted another platform manifest' >&2; exit 1; fi
|
||||
jq '.httpGroups=[]' "$work/live.json" >"$work/final.json"
|
||||
bash "$guard" check-final "$work/final.json" "$work/reviewed.json" "$work/vars.json" "$work/state.json" "$work/images.json"
|
||||
if bash "$guard" check-final "$work/live.json" "$work/reviewed.json" "$work/vars.json" "$work/state.json" "$work/images.json" 2>/dev/null; then
|
||||
echo 'Recovery final check accepted retained HTTP groups' >&2; exit 1
|
||||
fi
|
||||
mkdir "$work/bin" "$work/inputs"
|
||||
cp "$work/state.json" "$work/images.json" "$work/inputs/"
|
||||
cp "$work/vars.json" "$work/inputs/snapshot.json"
|
||||
cat >"$work/bin/aws" <<'SH'
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
printf '%s\n' "$*" >>"$FIXTURES/requests.log"
|
||||
service=$1 operation=$2
|
||||
shift 2
|
||||
region= definition= name= arn=
|
||||
while [ "$#" -gt 0 ]; do
|
||||
case "$1" in
|
||||
--region) region=$2; shift 2 ;;
|
||||
--task-definition) definition=$2; shift 2 ;;
|
||||
--service-name) name=$2; shift 2 ;;
|
||||
--tasks|--target-group-arn) arn=$2; shift 2 ;;
|
||||
*) shift ;;
|
||||
esac
|
||||
done
|
||||
[ "$region" = us-east-1 ]
|
||||
[ "${MODE:-}" != api-failure ] || [ "$service $operation" != 'ecs describe-tasks' ] || exit 1
|
||||
case "$service $operation" in
|
||||
'sts get-caller-identity')
|
||||
if [ "${MODE:-}" = account ]; then echo '{"Account":"123456789012"}'; else jq '.account' "$FIXTURES/live.json"; fi ;;
|
||||
'ecs describe-services') jq '.services' "$FIXTURES/live.json" ;;
|
||||
'ecs describe-task-definition') jq --arg definition "$definition" '.definitions[] | select(.taskDefinition.taskDefinitionArn==$definition)' "$FIXTURES/live.json" ;;
|
||||
'ecs list-tasks') jq --arg name "$name" '{taskArns:[.tasks[]|select(.group==("service:"+$name))|.taskArn]}' "$FIXTURES/live.json" ;;
|
||||
'ecs describe-tasks') jq --arg arn "$arn" '{failures:[],tasks:[.tasks[]|select(.taskArn==$arn)]}' "$FIXTURES/live.json" ;;
|
||||
'elbv2 describe-target-groups')
|
||||
if [ "${MODE:-}" = final ]; then jq '{TargetGroups:.httpsGroups}' "$FIXTURES/live.json"
|
||||
else jq '{TargetGroups:(.httpsGroups+.httpGroups)}' "$FIXTURES/live.json"; fi ;;
|
||||
'elbv2 describe-target-health')
|
||||
jq --arg arn "$arn" '{TargetHealthDescriptions:[(.httpsGroups+.httpGroups)[]|select(.TargetGroupArn==$arn)|.targets[]]}' "$FIXTURES/live.json" ;;
|
||||
'elbv2 describe-listeners') jq '{Listeners:.listeners}' "$FIXTURES/live.json" ;;
|
||||
'elbv2 describe-rules') jq '{Rules:.rules}' "$FIXTURES/live.json" ;;
|
||||
'ec2 describe-security-groups') jq '{SecurityGroups:.securityGroups}' "$FIXTURES/live.json" ;;
|
||||
'cloudwatch describe-alarms') jq '.alarms' "$FIXTURES/live.json" ;;
|
||||
*) echo 'Unexpected AWS operation in read-only collector' >&2; exit 1 ;;
|
||||
esac
|
||||
SH
|
||||
cat >"$work/bin/docker" <<'SH'
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
[[ "$*" == 'buildx imagetools inspect ghcr.io/warmbly/warmbly/'*' --raw' ]]
|
||||
cat "$FIXTURES/manifest.json"
|
||||
if [ "${MODE:-}" = manifest ]; then printf '\n'; fi
|
||||
SH
|
||||
cat >"$work/bin/curl" <<'SH'
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
[[ "$*" == *"--proto =https --tlsv1.2"* && "$*" != *insecure* ]]
|
||||
if [ "${MODE:-}" = public ]; then printf '503'; else printf '200'; fi
|
||||
SH
|
||||
chmod +x "$work/bin/aws" "$work/bin/docker" "$work/bin/curl"
|
||||
PATH="$work/bin:$PATH" FIXTURES="$work" bash "$guard" collect "$work/reviewed.json" "$work/inputs" "$work/collected"
|
||||
check "$work/collected/live.json"
|
||||
PATH="$work/bin:$PATH" FIXTURES="$work" MODE=final bash "$guard" collect-final "$work/reviewed.json" "$work/inputs" "$work/final-collected"
|
||||
for mode in account api-failure manifest public; do
|
||||
if PATH="$work/bin:$PATH" FIXTURES="$work" MODE=$mode bash "$guard" collect "$work/reviewed.json" "$work/inputs" "$work/$mode" 2>/dev/null; then
|
||||
echo "Recovery collector accepted failed read-only evidence: $mode" >&2; exit 1
|
||||
fi
|
||||
[ ! -e "$work/$mode/live.json" ]
|
||||
done
|
||||
if PATH="$work/bin:$PATH" FIXTURES="$work" bash "$guard" collect "$work/reviewed.json" "$work/inputs" "$work/collected" 2>/dev/null; then
|
||||
echo 'Recovery collector overwrote an earlier collection' >&2; exit 1
|
||||
fi
|
||||
if bash "$guard" apply 2>/dev/null; then echo 'Live collector accepted execution' >&2; exit 1; fi
|
||||
echo 'Recovery live service, TLS, traffic, health and platform checks passed'
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/../.."
|
||||
ruby -ryaml <<'RUBY'
|
||||
workflow = YAML.load_file('.github/workflows/runtime-tls-recovery.yml')
|
||||
jobs = workflow.fetch('jobs')
|
||||
plan, apply, redeploy, verify = jobs.values_at('plan', 'apply', 'redeploy', 'verify')
|
||||
raise 'plan must be manual and depend on offline checks' unless plan['if'] == "github.event_name == 'workflow_dispatch'" && plan['needs'] == 'check'
|
||||
raise 'plan must use the read-only environment' unless plan['environment'] == 'aws-infrastructure-plan'
|
||||
entry = plan.fetch('steps').first
|
||||
raise 'explicit enablement and new main run are required' unless entry.fetch('run').include?('[ "$RECOVERY_ENABLED" = true ]') && entry.fetch('run').include?('[ "$GITHUB_RUN_ATTEMPT" = 1 ]') && entry.fetch('run').include?('[ "$GITHUB_REF" = refs/heads/main ]')
|
||||
raise 'apply must follow plan approval' unless apply['needs'] == 'plan' && apply['environment'] == 'aws-infrastructure-approval'
|
||||
raise 'apply must compare the exact plan approval digest' unless apply['steps'].any? { |s| s.dig('env', 'APPROVED_DIGEST') == '${{ needs.plan.outputs.digest }}' }
|
||||
[apply, verify].each do |job|
|
||||
raise 'production serialization must be retained' unless job.dig('concurrency', 'group') == 'aws-production' && job.dig('concurrency', 'cancel-in-progress') == false
|
||||
end
|
||||
raise 'redeploy must follow both plan and apply' unless redeploy['needs'].sort == ['apply', 'plan']
|
||||
raise 'redeploy must use the normal local workflow' unless redeploy['uses'] == './.github/workflows/deploy-aws.yml'
|
||||
expected = {'tag'=>'${{ needs.plan.outputs.release }}', 'mode'=>'redeploy', 'services'=>'all', 'fleet'=>false, 'require_attestation'=>true, 'bake_seconds'=>'300'}
|
||||
raise 'same release, all services, provenance and full bakes are required without fleet or secret-drop overrides' unless redeploy['with'] == expected
|
||||
raise 'final verification must follow redeploy' unless verify['needs'] == 'redeploy' && verify['environment'] == 'aws-infrastructure-plan'
|
||||
jobs.each_value do |job|
|
||||
raise 'recovery cannot ignore job failures' if job['continue-on-error']
|
||||
(job['steps'] || []).each { |step| raise 'recovery cannot ignore step failures' if step['continue-on-error'] }
|
||||
end
|
||||
deploy = YAML.load_file('.github/workflows/deploy-aws.yml')
|
||||
call = (deploy['on'] || deploy[true]).fetch('workflow_call')
|
||||
raise 'existing deployment defaults must be retained' unless call.dig('inputs', 'bake_seconds', 'default') == ''
|
||||
raise 'dropped-secret allowance remains disabled by default' if call.fetch('inputs').key?('allow_dropped_secrets')
|
||||
puts 'Recovery workflow approval, sequencing, deployment and default compatibility checks passed'
|
||||
RUBY
|
||||
Executable
+89
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env bash
|
||||
# Read-only validators for a separately reviewed hosted TLS cleanup recovery.
|
||||
set -euo pipefail
|
||||
|
||||
check_baseline() {
|
||||
jq -e '
|
||||
def group_identity: {TargetGroupName, TargetGroupArn, Protocol, Port, VpcId};
|
||||
. as $baseline |
|
||||
.account == "925323749693" and .region == "us-east-1" and
|
||||
(.state.lineage | type == "string" and test("^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$")) and
|
||||
(.state.serial | type == "number" and . >= 0 and floor == .) and
|
||||
(.state.versionId | type == "string" and length > 0 and . != "null" and (test("[\\r\\n]") | not)) and
|
||||
(.state.sha256 | type == "string" and test("^[a-f0-9]{64}$")) and
|
||||
(.httpGroups | type == "array" and length == 4) and
|
||||
([.httpGroups[].TargetGroupName] | sort) ==
|
||||
(["backend", "forms", "tracking", "realtime"] | map("warmbly-production-" + .) | sort) and
|
||||
([.httpGroups[].TargetGroupArn] | unique | length == 4) and
|
||||
([.httpGroups[].VpcId] | unique | length == 1) and
|
||||
all(.httpGroups[];
|
||||
.Protocol == "HTTP" and
|
||||
(.Port | type == "number" and . > 0 and . <= 65535 and floor == .) and
|
||||
(.VpcId | type == "string" and test("^vpc-[a-f0-9]+$")) and
|
||||
.TargetGroupArn == ("arn:aws:elasticloadbalancing:us-east-1:925323749693:targetgroup/" + .TargetGroupName + "/" + (.TargetGroupArn | split("/")[-1])) and
|
||||
(.TargetGroupArn | split("/")[-1] | test("^[a-f0-9]{16}$")) and
|
||||
(.LoadBalancerArns | type == "array" and length == 0) and
|
||||
(.targets | type == "array" and length == 0)) and
|
||||
(.state.httpGroups | type == "array" and length == 4) and
|
||||
(.state.httpGroups | map(group_identity) | sort_by(.TargetGroupName)) ==
|
||||
($baseline.httpGroups | map(group_identity) | sort_by(.TargetGroupName))
|
||||
' "$1" >/dev/null || { echo 'Recovery requires four identified, drained HTTP groups matching reviewed state' >&2; return 1; }
|
||||
}
|
||||
|
||||
check_state() {
|
||||
check_baseline "$2"
|
||||
local digest
|
||||
digest=$(sha256sum "$1" | cut -d' ' -f1)
|
||||
[ "$digest" = "$(jq -r '.state.sha256' "$2")" ] || { echo 'Recovery state bytes differ from the reviewed hash' >&2; return 1; }
|
||||
jq -e --slurpfile baseline "$2" '
|
||||
.version == 4 and .lineage == $baseline[0].state.lineage and .serial == $baseline[0].state.serial and
|
||||
([.resources[] | select(.mode == "managed" and .type == "aws_lb_target_group" and .name == "service")] as $resources |
|
||||
[$resources[].instances[] | {
|
||||
key:.index_key, deposed:.deposed, status:.status,
|
||||
id:.attributes.id, TargetGroupArn:.attributes.arn, TargetGroupName:.attributes.name,
|
||||
Protocol:.attributes.protocol, Port:.attributes.port, VpcId:.attributes.vpc_id
|
||||
}] as $groups |
|
||||
($resources | length == 1) and
|
||||
all($resources[]; (.module == null) and (.instances | type == "array" and length == 4)) and
|
||||
($groups | map(.key) | sort) == (["backend", "forms", "tracking", "realtime"] | sort) and
|
||||
all($groups[];
|
||||
. as $group | .deposed == null and .status == null and .id == .TargetGroupArn and
|
||||
any($baseline[0].state.httpGroups[];
|
||||
.TargetGroupName == ("warmbly-production-" + $group.key) and
|
||||
.TargetGroupArn == $group.TargetGroupArn and .TargetGroupName == $group.TargetGroupName and
|
||||
.Protocol == $group.Protocol and .Port == $group.Port and .VpcId == $group.VpcId)))
|
||||
' "$1" >/dev/null || { echo 'Recovery state identity differs from the reviewed baseline' >&2; return 1; }
|
||||
}
|
||||
|
||||
check_plan() {
|
||||
check_baseline "$2"
|
||||
jq -e --slurpfile baseline "$2" '
|
||||
(.resource_changes | type == "array") and
|
||||
(
|
||||
[.resource_changes[]? | select(.change.actions != ["no-op"] and .change.actions != ["read"])] as $changes |
|
||||
($baseline[0].httpGroups | map({
|
||||
address:("aws_lb_target_group.service[\"" + (.TargetGroupName | ltrimstr("warmbly-production-")) + "\"]"),
|
||||
group:.
|
||||
})) as $expected |
|
||||
($changes | map(.address) | sort) == ($expected | map(.address) | sort) and
|
||||
all($changes[];
|
||||
. as $change |
|
||||
.change.actions == ["delete"] and (.change | has("after")) and .change.after == null and
|
||||
any($expected[];
|
||||
.address == $change.address and
|
||||
$change.change.before.arn == .group.TargetGroupArn and
|
||||
$change.change.before.id == .group.TargetGroupArn and
|
||||
$change.change.before.name == .group.TargetGroupName and
|
||||
$change.change.before.protocol == .group.Protocol and
|
||||
$change.change.before.port == .group.Port and
|
||||
$change.change.before.vpc_id == .group.VpcId)) and
|
||||
([.resource_drift[]? | select(.change.actions != ["no-op"])] | length == 0))
|
||||
' "$1" >/dev/null || { echo 'Recovery plan must contain only the four reviewed HTTP group deletions without drift' >&2; return 1; }
|
||||
}
|
||||
|
||||
case "${1:-}" in
|
||||
check-baseline) check_baseline "${2:?}" ;;
|
||||
check-state) check_state "${2:?}" "${3:?}" ;;
|
||||
check-plan) check_plan "${2:?}" "${3:?}" ;;
|
||||
*) echo 'Only read-only recovery validation is supported' >&2; exit 1 ;;
|
||||
esac
|
||||
Executable
+115
@@ -0,0 +1,115 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/../.."
|
||||
work=$(mktemp -d)
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
guard=.github/scripts/runtime-tls-recovery.sh
|
||||
jq -n '
|
||||
["backend", "forms", "tracking", "realtime"] |
|
||||
map({TargetGroupName:("warmbly-production-" + .),
|
||||
TargetGroupArn:("arn:aws:elasticloadbalancing:us-east-1:925323749693:targetgroup/warmbly-production-" + . + "/0123456789abcdef"),
|
||||
Protocol:"HTTP",Port:8080,VpcId:"vpc-0123456789abcdef0",LoadBalancerArns:[],targets:[]}) as $groups |
|
||||
{account:"925323749693",region:"us-east-1",httpGroups:$groups,
|
||||
state:{lineage:"01234567-89ab-cdef-0123-456789abcdef",serial:1,versionId:"reviewed-version",sha256:("a"*64),httpGroups:$groups}}
|
||||
' >"$work/baseline.json"
|
||||
jq '{resource_changes:[.httpGroups[] | {
|
||||
address:("aws_lb_target_group.service[\"" + (.TargetGroupName | ltrimstr("warmbly-production-")) + "\"]"),
|
||||
change:{actions:["delete"],after:null,before:{arn:.TargetGroupArn,id:.TargetGroupArn,name:.TargetGroupName,protocol:.Protocol,port:.Port,vpc_id:.VpcId}}
|
||||
}]}' "$work/baseline.json" >"$work/plan.json"
|
||||
bash "$guard" check-baseline "$work/baseline.json"
|
||||
bash "$guard" check-plan "$work/plan.json" "$work/baseline.json"
|
||||
jq '.httpGroups |= reverse' "$work/baseline.json" >"$work/reordered-baseline.json"
|
||||
jq '.resource_changes |= reverse |
|
||||
.resource_changes += [{address:"data.aws_caller_identity.current",change:{actions:["read"]}}]' "$work/plan.json" >"$work/reordered-plan.json"
|
||||
bash "$guard" check-plan "$work/reordered-plan.json" "$work/reordered-baseline.json"
|
||||
jq '{version:4,lineage:.state.lineage,serial:.state.serial,resources:[{
|
||||
mode:"managed",type:"aws_lb_target_group",name:"service",instances:[.state.httpGroups[] | {
|
||||
index_key:(.TargetGroupName | ltrimstr("warmbly-production-")),
|
||||
attributes:{arn:.TargetGroupArn,id:.TargetGroupArn,name:.TargetGroupName,protocol:.Protocol,port:.Port,vpc_id:.VpcId}
|
||||
}]
|
||||
}]}' "$work/baseline.json" >"$work/state.json"
|
||||
digest=$(sha256sum "$work/state.json" | cut -d' ' -f1)
|
||||
jq --arg digest "$digest" '.state.sha256=$digest' "$work/baseline.json" >"$work/state-baseline.json"
|
||||
bash "$guard" check-state "$work/state.json" "$work/state-baseline.json"
|
||||
jq -c . "$work/state.json" >"$work/reformatted-state.json"
|
||||
if bash "$guard" check-state "$work/reformatted-state.json" "$work/state-baseline.json" 2>/dev/null; then
|
||||
echo 'Recovery accepted changed state bytes under the original hash' >&2
|
||||
exit 1
|
||||
fi
|
||||
jq '.resources[0].instances |= reverse |
|
||||
.resources += [{mode:"managed",type:"aws_ecs_service",name:"service",instances:[]}]' \
|
||||
"$work/state.json" >"$work/reordered-state.json"
|
||||
digest=$(sha256sum "$work/reordered-state.json" | cut -d' ' -f1)
|
||||
jq --arg digest "$digest" '.state.sha256=$digest' "$work/baseline.json" >"$work/reordered-state-baseline.json"
|
||||
bash "$guard" check-state "$work/reordered-state.json" "$work/reordered-state-baseline.json"
|
||||
if bash "$guard" check-state "$work/state.json" "$work/baseline.json" 2>/dev/null; then
|
||||
echo 'Recovery accepted state bytes with a different reviewed hash' >&2
|
||||
exit 1
|
||||
fi
|
||||
for change in '.version=3' '.lineage="11111111-89ab-cdef-0123-456789abcdef"' '.serial+=1' \
|
||||
'.resources=[]' '.resources+=.resources' \
|
||||
'.resources[0].module="module.other"' '.resources[0].mode="data"' \
|
||||
'.resources[0].instances|=.[1:]' \
|
||||
'.resources[0].instances[0]=.resources[0].instances[1]' \
|
||||
'.resources[0].instances[0].index_key="other"' \
|
||||
'.resources[0].instances[0].deposed="old"' '.resources[0].instances[0].status="tainted"' \
|
||||
'.resources[0].instances[0].attributes.id="different"' \
|
||||
'.resources[0].instances[0].attributes.arn="different"' \
|
||||
'.resources[0].instances[0].attributes.name="different"' \
|
||||
'.resources[0].instances[0].attributes.protocol="HTTPS"' \
|
||||
'.resources[0].instances[0].attributes.port=465' \
|
||||
'.resources[0].instances[0].attributes.vpc_id="vpc-11111111"'; do
|
||||
jq "$change" "$work/state.json" >"$work/changed-state.json"
|
||||
digest=$(sha256sum "$work/changed-state.json" | cut -d' ' -f1)
|
||||
jq --arg digest "$digest" '.state.sha256=$digest' "$work/baseline.json" >"$work/changed-state-baseline.json"
|
||||
if bash "$guard" check-state "$work/changed-state.json" "$work/changed-state-baseline.json" 2>/dev/null; then
|
||||
echo "Recovery accepted different state identities despite a matching file hash: $change" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
for change in '.account="123456789012"' '.region="us-west-2"' \
|
||||
'.httpGroups|=.[1:]' '.httpGroups[0]=.httpGroups[1]' \
|
||||
'.httpGroups[0].LoadBalancerArns=["still-referenced"]' \
|
||||
'.httpGroups[0].targets=[{Target:{Id:"still-registered"}}]' \
|
||||
'.httpGroups[0].Protocol="HTTPS"' '.httpGroups[0].Port=0' \
|
||||
'.httpGroups[0].VpcId="vpc-11111111"' \
|
||||
'.httpGroups[0].TargetGroupArn="arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/warmbly-production-backend/0123456789abcdef"' \
|
||||
'.httpGroups[0].targets=null' '.httpGroups[0].LoadBalancerArns=null' \
|
||||
'.state.httpGroups[0].TargetGroupArn="changed"' '.state.httpGroups|=.[1:]' \
|
||||
'.state.versionId=""' '.state.versionId="null"' '.state.sha256=""' \
|
||||
'.state.lineage=null' '.state.lineage=("-"*36)' '.state.serial=-1'; do
|
||||
jq "$change" "$work/baseline.json" >"$work/changed.json"
|
||||
if bash "$guard" check-plan "$work/plan.json" "$work/changed.json" 2>/dev/null; then
|
||||
echo "Recovery accepted an invalid baseline: $change" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
for change in '.resource_changes=[]' '.resource_changes|=.[1:]' \
|
||||
'.resource_changes[0]=.resource_changes[1]' \
|
||||
'.resource_changes[0].change.actions=["no-op"]' \
|
||||
'.resource_changes[0].change.actions=["delete","create"]' \
|
||||
'.resource_changes[0].change.after={}' \
|
||||
'del(.resource_changes[0].change.after)' \
|
||||
'.resource_changes[0].change.before.arn="changed"' \
|
||||
'.resource_changes[0].change.before.id="changed"' \
|
||||
'.resource_changes[0].change.before.port=465' \
|
||||
'.resource_changes[0].change.before.protocol="HTTPS"' \
|
||||
'.resource_changes[0].change.before.name="different"' \
|
||||
'.resource_changes[0].change.before.vpc_id="vpc-11111111"' \
|
||||
'.resource_changes[0].address="aws_lb_target_group.service[\"consumer\"]"' \
|
||||
'.resource_changes += [{address:"aws_ecs_service.service[\"backend\"]",change:{actions:["update"]}}]' \
|
||||
'.resource_changes += [{address:"aws_vpc_security_group_ingress_rule.internal_backend[0]",change:{actions:["delete"]}}]' \
|
||||
'.resource_drift=[{address:"aws_lb_target_group.service[\"backend\"]",change:{actions:["update"]}}]'; do
|
||||
jq "$change" "$work/plan.json" >"$work/changed.json"
|
||||
if bash "$guard" check-plan "$work/changed.json" "$work/baseline.json" 2>/dev/null; then
|
||||
echo "Recovery accepted a different cleanup plan: $change" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
for action in plan apply delete; do
|
||||
if bash "$guard" "$action" 2>/dev/null; then
|
||||
echo 'Read-only recovery validator accepted an execution action' >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
echo 'Read-only TLS recovery identity and scope guards passed'
|
||||
Executable
+198
@@ -0,0 +1,198 @@
|
||||
#!/usr/bin/env bash
|
||||
# Finalize runtime TLS through the protected environment using a versioned private snapshot.
|
||||
set -euo pipefail
|
||||
|
||||
check_plan() {
|
||||
local stage=${2:-route}
|
||||
[[ "$stage" = route || "$stage" = drain || "$stage" = on ]]
|
||||
jq -e --arg stage "$stage" '
|
||||
def service: "\\[\\\"(backend|forms|tracking|realtime)\\\"\\]";
|
||||
def http_groups:
|
||||
["backend", "forms", "tracking", "realtime"] |
|
||||
map("aws_lb_target_group.service[\"" + . + "\"]") | sort;
|
||||
def normalize:
|
||||
map(.mountPoints //= [] | .systemControls //= [] | .volumesFrom //= [] |
|
||||
.portMappings = ((.portMappings // []) | map(.hostPort //= .containerPort)));
|
||||
def same_except($keys):
|
||||
(.change.before | delpaths($keys | map([.]))) == (.change.after | delpaths($keys | map([.])));
|
||||
def normalize_empty_description:
|
||||
.change.actions == ["update"] and same_except(["description"]) and
|
||||
.change.before.description == "" and .change.after.description == null;
|
||||
def normalize_registration:
|
||||
if .elb_name == "" then .elb_name = null else . end;
|
||||
def task_settings:
|
||||
del(.arn, .arn_without_revision, .id, .revision, .container_definitions) |
|
||||
.enable_fault_injection //= false | .ipc_mode //= "" | .pid_mode //= "";
|
||||
def same_task_settings:
|
||||
(.change.before | task_settings) == (.change.after | task_settings);
|
||||
def same_container_except_loopback:
|
||||
(.change.before.container_definitions | fromjson | normalize) as $before |
|
||||
(.change.after.container_definitions | fromjson | normalize) as $after |
|
||||
($after | map(.environment |= map(select(.name != "SERVE_HTTP_LOOPBACK_ONLY")))) ==
|
||||
($before | map(.environment |= map(select(.name != "SERVE_HTTP_LOOPBACK_ONLY")))) and
|
||||
all($after[]; if $stage == "on" then
|
||||
any(.environment[]; .name == "SERVE_HTTP_LOOPBACK_ONLY" and .value == "true")
|
||||
else all(.environment[]; .name != "SERVE_HTTP_LOOPBACK_ONLY") end);
|
||||
[.resource_changes[]? | select(.change.actions != ["no-op"] and .change.actions != ["read"])] as $changes |
|
||||
($stage != "on" or
|
||||
([$changes[] | select(.change.actions == ["delete"] and
|
||||
(.address | test("^aws_lb_target_group\\.service" + service + "$"))) | .address] | sort) == http_groups) and
|
||||
all($changes[];
|
||||
if (.address | test("^aws_ecs_task_definition\\.service" + service + "$")) then
|
||||
.change.actions == ["delete", "create"] and same_container_except_loopback and same_task_settings
|
||||
elif (.address | test("^aws_ecs_service\\.service" + service + "$")) then
|
||||
.change.actions == ["update"] and same_except(["load_balancer"]) and
|
||||
($stage == "drain") and
|
||||
(.change.before.load_balancer | length == 2) and
|
||||
(.change.after.load_balancer | length == 1) and
|
||||
((.change.after.load_balancer[0] | normalize_registration) as $tls |
|
||||
($tls.target_group_arn | contains("-tls/")) and
|
||||
(.change.before.load_balancer | map(normalize_registration) | index($tls) != null))
|
||||
elif (.address | test("^aws_cloudwatch_metric_alarm\\.target_5xx" + service + "$")) then
|
||||
.change.actions == ["update"] and same_except(["metric_query"])
|
||||
elif (.address | test("^aws_cloudwatch_metric_alarm\\.unhealthy_hosts" + service + "$")) then
|
||||
.change.actions == ["update"] and same_except(["dimensions"])
|
||||
elif (.address | test("^aws_lb_listener_rule\\.(service" + service + "|tracking_alias\\[\\\"[0-9]+\\\"\\])$")) then
|
||||
.change.actions == ["update"] and same_except(["action"])
|
||||
elif (.address | test("^aws_lb_target_group\\.service" + service + "$")) then
|
||||
$stage == "on" and .change.actions == ["delete"]
|
||||
elif (.address | test("^aws_vpc_security_group_ingress_rule\\.service" + service + "$")) or
|
||||
.address == "aws_vpc_security_group_ingress_rule.internal_backend[0]" then
|
||||
($stage == "on" and .change.actions == ["delete"]) or normalize_empty_description
|
||||
else false end)
|
||||
' "$1" >/dev/null || { echo 'Plan contains changes outside the runtime TLS switch' >&2; return 1; }
|
||||
}
|
||||
|
||||
check_live() {
|
||||
jq -e --arg stage "$2" --arg release "$3" --arg port "$4" --arg prefix "$5" '
|
||||
. as $live |
|
||||
(.services.failures | length == 0) and
|
||||
([.services.services[].serviceName] | sort) ==
|
||||
(["backend", "forms", "tracking", "realtime"] | map($prefix + "-" + .) | sort) and
|
||||
all(.services.services[];
|
||||
. as $service |
|
||||
.desiredCount > 0 and .runningCount == .desiredCount and .pendingCount == 0 and
|
||||
(.deployments | length == 1) and .deployments[0].rolloutState == "COMPLETED" and
|
||||
(.loadBalancers | length == (if $stage == "on" then 1 else 2 end)) and
|
||||
any(.loadBalancers[]; .containerPort == ($port | tonumber) and
|
||||
(.targetGroupArn | contains("-tls/"))) and
|
||||
any($live.definitions[];
|
||||
.taskDefinition.taskDefinitionArn == $service.taskDefinition and
|
||||
any(.tags[]; .key == "warmbly-release" and .value == $release) and
|
||||
(.taskDefinition.containerDefinitions | length > 0) and
|
||||
all(.taskDefinition.containerDefinitions[];
|
||||
(.environment | map({key:.name,value:.value}) | from_entries) as $env |
|
||||
($env.SERVE_TLS == "supplied" or $env.SERVE_TLS == "self-signed") and
|
||||
$env.SERVE_TLS_PORT == $port and $env.SERVE_HTTP_LOOPBACK_ONLY != "true")))
|
||||
' "$1" >/dev/null || { echo 'Live services must be stable on the expected release with compatible TLS listeners and registrations' >&2; return 1; }
|
||||
}
|
||||
|
||||
check_cleanup() {
|
||||
jq -e '
|
||||
(.tlsPort // 8443) as $port |
|
||||
(.services | length == 4) and (.httpGroups | length == 4) and
|
||||
all(.services[]; (.loadBalancers | length > 0) and
|
||||
all(.loadBalancers[]; .containerPort == $port and (.targetGroupArn | contains("-tls/")))) and
|
||||
all(.httpGroups[]; (.LoadBalancerArns | length == 0) and (.targets | length == 0))
|
||||
' "$1" >/dev/null || { echo 'HTTP listeners and registrations must be drained before cleanup' >&2; return 1; }
|
||||
}
|
||||
|
||||
main() {
|
||||
local action=${1:?}
|
||||
if [ "$action" = check-plan ]; then check_plan "${2:?}" "${3:-route}"; return; fi
|
||||
if [ "$action" = check-live ]; then check_live "${2:?}" "${3:?}" "${4:?}" "${5:?}" "${6:?}"; return; fi
|
||||
if [ "$action" = check-cleanup ]; then check_cleanup "${2:?}"; return; fi
|
||||
case "$action" in plan|apply) ;; *) echo 'Unknown action' >&2; return 1 ;; esac
|
||||
: "${STATE_BUCKET:?}" "${WORK:?}" "${VARS_VERSION:?}" "${RELEASE:?}"
|
||||
: "${STAGE:?}"
|
||||
[[ "$STAGE" = route || "$STAGE" = drain || "$STAGE" = on ]]
|
||||
[[ "$VARS_VERSION" != null && "$VARS_VERSION" != *$'\n'* && "$RELEASE" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]
|
||||
mkdir -p "$WORK"
|
||||
chmod 700 "$WORK"
|
||||
umask 077
|
||||
local dir=deploy/terraform/aws/runtime vars="$WORK/runtime.tfvars.json" log="$WORK/runtime.log"
|
||||
aws s3api get-object --bucket "$STATE_BUCKET" --key warmbly/production/vars/runtime-tls.tfvars.json \
|
||||
--version-id "$VARS_VERSION" "$vars" >/dev/null
|
||||
local previous=both
|
||||
case "$STAGE" in drain) previous=route ;; on) previous=drain ;; esac
|
||||
jq -e --arg previous "$previous" '.target_tls == $previous' "$vars" >/dev/null
|
||||
jq -r '.. | strings | select(length >= 6)' "$vars" | while IFS= read -r line; do
|
||||
printf '::add-mask::%s\n' "$line" >&2
|
||||
done
|
||||
local account cluster prefix definition port
|
||||
account=$(aws sts get-caller-identity --query Account --output text)
|
||||
[ "$account" = 925323749693 ]
|
||||
cluster=$(jq -r '.name // "warmbly-production"' "$vars")
|
||||
prefix=$cluster
|
||||
port=$(jq -r '.target_tls_port // 8443' "$vars")
|
||||
aws ecs describe-services --cluster "$cluster" --services \
|
||||
"$prefix-backend" "$prefix-forms" "$prefix-tracking" "$prefix-realtime" >"$WORK/services.json"
|
||||
: >"$WORK/definitions.jsonl"
|
||||
while IFS= read -r definition; do
|
||||
aws ecs describe-task-definition --task-definition "$definition" --include TAGS >>"$WORK/definitions.jsonl"
|
||||
done < <(jq -r '.services[].taskDefinition' "$WORK/services.json")
|
||||
jq -n --slurpfile services "$WORK/services.json" --slurpfile definitions "$WORK/definitions.jsonl" \
|
||||
'{services:$services[0],definitions:$definitions}' >"$WORK/live.json"
|
||||
check_live "$WORK/live.json" "$STAGE" "$RELEASE" "$port" "$prefix"
|
||||
local service arn count
|
||||
for service in backend forms tracking realtime; do
|
||||
arn=$(aws elbv2 describe-target-groups --names "$prefix-$service-tls" --query 'TargetGroups[0].TargetGroupArn' --output text)
|
||||
count=$(aws elbv2 describe-target-health --target-group-arn "$arn" --query 'TargetHealthDescriptions' --output json |
|
||||
jq 'if length > 0 and all(.[]; .TargetHealth.State == "healthy") then length else 0 end')
|
||||
[ "$count" -gt 0 ] || { echo "HTTPS targets are not healthy for $service" >&2; return 1; }
|
||||
if [ "$STAGE" = route ]; then
|
||||
arn=$(aws elbv2 describe-target-groups --names "$prefix-$service" --query 'TargetGroups[0].TargetGroupArn' --output text)
|
||||
count=$(aws elbv2 describe-target-health --target-group-arn "$arn" --query 'TargetHealthDescriptions' --output json |
|
||||
jq 'if length > 0 and all(.[]; .TargetHealth.State == "healthy") then length else 0 end')
|
||||
[ "$count" -gt 0 ] || { echo "HTTP fallback is not healthy for $service" >&2; return 1; }
|
||||
fi
|
||||
done
|
||||
if [ "$STAGE" != route ]; then
|
||||
: "${PREVIOUS_RUN:?}" "${GITHUB_REPOSITORY:?}"
|
||||
[[ "$PREVIOUS_RUN" =~ ^[0-9]+$ ]]
|
||||
gh api "repos/$GITHUB_REPOSITORY/actions/runs/$PREVIOUS_RUN" |
|
||||
jq -e --arg title "Runtime TLS $previous $RELEASE" '
|
||||
.conclusion == "success" and .head_branch == "main" and
|
||||
.path == ".github/workflows/runtime-tls.yml" and .display_title == $title
|
||||
' >/dev/null || { echo 'The preceding stage workflow and its release bakes must succeed first' >&2; return 1; }
|
||||
fi
|
||||
if [ "$STAGE" = on ]; then
|
||||
aws elbv2 describe-target-groups --names "$prefix-backend" "$prefix-forms" \
|
||||
"$prefix-tracking" "$prefix-realtime" >"$WORK/http-groups.json"
|
||||
: >"$WORK/http-health.jsonl"
|
||||
while IFS= read -r arn; do
|
||||
aws elbv2 describe-target-health --target-group-arn "$arn" |
|
||||
jq --arg arn "$arn" '{arn:$arn,targets:.TargetHealthDescriptions}' >>"$WORK/http-health.jsonl"
|
||||
done < <(jq -r '.TargetGroups[].TargetGroupArn' "$WORK/http-groups.json")
|
||||
jq -n --slurpfile services "$WORK/services.json" --slurpfile groups "$WORK/http-groups.json" \
|
||||
--argjson port "$(jq '.target_tls_port // 8443' "$vars")" \
|
||||
--slurpfile health "$WORK/http-health.jsonl" '{tlsPort:$port,services:$services[0].services,httpGroups:[
|
||||
$groups[0].TargetGroups[] | . as $group | . + {targets:[$health[] | select(.arn == $group.TargetGroupArn) | .targets[]]}]}' >"$WORK/cleanup.json"
|
||||
check_cleanup "$WORK/cleanup.json"
|
||||
fi
|
||||
terraform -chdir="$dir" init -input=false -no-color -backend-config="bucket=$STATE_BUCKET" >"$log" 2>&1
|
||||
terraform -chdir="$dir" plan -input=false -no-color -lock-timeout=5m -var-file="$vars" \
|
||||
-var="state_bucket=$STATE_BUCKET" -var="target_tls=$STAGE" \
|
||||
-target=aws_ecs_service.service -target=aws_lb_listener_rule.tracking_alias \
|
||||
-target=aws_lb_target_group.service \
|
||||
-target=aws_vpc_security_group_ingress_rule.service -target=aws_vpc_security_group_ingress_rule.internal_backend \
|
||||
-out="$WORK/runtime.tfplan" >>"$log" 2>&1 || { echo 'Runtime TLS plan failed; inspect the private runner log' >&2; return 1; }
|
||||
terraform -chdir="$dir" show -json "$WORK/runtime.tfplan" >"$WORK/runtime.json"
|
||||
check_plan "$WORK/runtime.json" "$STAGE"
|
||||
local digest
|
||||
digest=$(jq -cS '[.resource_changes[]? | select(.change.actions != ["no-op"] and .change.actions != ["read"])] | sort_by(.address)' "$WORK/runtime.json" | sha256sum | cut -d' ' -f1)
|
||||
if [ "$action" = plan ]; then
|
||||
printf 'digest=%s\n' "$digest" >>"${GITHUB_OUTPUT:?}"
|
||||
jq -r '.resource_changes[]? | select(.change.actions != ["no-op"] and .change.actions != ["read"]) | "\(.change.actions | join("/")) \(.address)"' "$WORK/runtime.json" >>"${GITHUB_STEP_SUMMARY:?}"
|
||||
else
|
||||
[ "$digest" = "${APPROVED_DIGEST:?}" ] || { echo 'Runtime TLS plan changed; start a new approval run' >&2; return 1; }
|
||||
if ! terraform -chdir="$dir" apply -input=false -no-color -lock-timeout=5m "$WORK/runtime.tfplan" >>"$log" 2>&1; then
|
||||
local diagnostic="warmbly/production/diagnostics/runtime-tls/${GITHUB_RUN_ID:?}/${GITHUB_RUN_ATTEMPT:?}/apply.log"
|
||||
aws s3 cp "$log" "s3://$STATE_BUCKET/$diagnostic" --only-show-errors || echo 'Private diagnostic upload failed' >&2
|
||||
echo "Runtime TLS apply failed; inspect state and private diagnostic $diagnostic before retrying" >&2
|
||||
return 1
|
||||
fi
|
||||
echo 'Runtime TLS apply completed'
|
||||
fi
|
||||
}
|
||||
main "$@"
|
||||
Executable
+143
@@ -0,0 +1,143 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/../.."
|
||||
work=$(mktemp -d)
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
complete_cleanup() {
|
||||
jq '
|
||||
[.resource_changes[].address] as $present |
|
||||
.resource_changes += [ ["backend", "forms", "tracking", "realtime"][] |
|
||||
{address:("aws_lb_target_group.service[\"" + . + "\"]"),change:{actions:["delete"]}} |
|
||||
select(.address as $address | $present | index($address) == null)]
|
||||
' "$1" >"$work/complete.json"
|
||||
mv "$work/complete.json" "$1"
|
||||
}
|
||||
expect() {
|
||||
local want=$1 address=$2 actions=$3 stage=${4:-route}
|
||||
jq -n --arg address "$address" --argjson actions "$actions" '{resource_changes:[{address:$address,change:{actions:$actions}}]}' >"$work/plan.json"
|
||||
if [ "$stage" = on ]; then complete_cleanup "$work/plan.json"; fi
|
||||
if bash .github/scripts/runtime-tls.sh check-plan "$work/plan.json" "$stage" 2>/dev/null; then
|
||||
[ "$want" = pass ]
|
||||
else
|
||||
[ "$want" = fail ]
|
||||
fi
|
||||
}
|
||||
expect fail 'aws_lb_target_group.service["backend"]' '["delete"]'
|
||||
expect pass 'aws_lb_target_group.service["backend"]' '["delete"]' on
|
||||
expect fail 'aws_ecs_service.service["forms"]' '["update"]'
|
||||
expect fail 'aws_vpc_security_group_ingress_rule.internal_backend[0]' '["delete"]'
|
||||
expect pass 'aws_vpc_security_group_ingress_rule.internal_backend[0]' '["delete"]' on
|
||||
expect fail 'aws_vpc_security_group_ingress_rule.service["backend"]' '["delete"]'
|
||||
expect pass 'aws_vpc_security_group_ingress_rule.service["backend"]' '["delete"]' on
|
||||
expect fail 'aws_ecs_task_definition.validation' '["delete","create"]'
|
||||
expect fail 'aws_s3_bucket.data' '["delete"]'
|
||||
expect fail 'aws_ecs_service.service["consumer"]' '["update"]'
|
||||
expect fail 'aws_lb_target_group.service["backend"]' '["delete","create"]'
|
||||
expect fail 'aws_lb_target_group.service["backend"]' '["delete"]' drain
|
||||
expect fail 'aws_vpc_security_group_ingress_rule.internal_backend[0]' '["delete"]' drain
|
||||
jq -n '{resource_changes:[{address:"aws_ecs_service.service[\"forms\"]",change:{actions:["update"],
|
||||
before:{load_balancer:[{target_group_arn:"forms/1",container_port:8090},{target_group_arn:"forms-tls/2",container_port:8443}]},
|
||||
after:{load_balancer:[{target_group_arn:"forms-tls/2",container_port:8443}]}}}]}' >"$work/plan.json"
|
||||
bash .github/scripts/runtime-tls.sh check-plan "$work/plan.json" drain
|
||||
for stage in route on; do
|
||||
cp "$work/plan.json" "$work/registration-$stage.json"
|
||||
if [ "$stage" = on ]; then complete_cleanup "$work/registration-$stage.json"; fi
|
||||
if bash .github/scripts/runtime-tls.sh check-plan "$work/registration-$stage.json" "$stage" 2>/dev/null; then
|
||||
echo 'Registration detached outside the drain stage' >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
jq '.resource_changes[0].change |= (
|
||||
.before.load_balancer |= map(. + {elb_name:"",advanced_configuration:[]}) |
|
||||
.after.load_balancer |= map(. + {elb_name:null,advanced_configuration:[]}))' "$work/plan.json" >"$work/normalized.json"
|
||||
bash .github/scripts/runtime-tls.sh check-plan "$work/normalized.json" drain
|
||||
for change in '.after.load_balancer[0].elb_name="classic-lb"' \
|
||||
'.before.load_balancer[1].elb_name="classic-lb"' \
|
||||
'.after.load_balancer[0].container_port=9443' \
|
||||
'.after.load_balancer[0].container_name="other"' \
|
||||
'.after.load_balancer[0].target_group_arn="other-tls/3"' \
|
||||
'.after.load_balancer[0].advanced_configuration=[{alternate_target_group_arn:"other-tls/3"}]'; do
|
||||
jq ".resource_changes[0].change |= ($change)" "$work/normalized.json" >"$work/changed.json"
|
||||
if bash .github/scripts/runtime-tls.sh check-plan "$work/changed.json" drain 2>/dev/null; then
|
||||
echo 'Changed HTTPS registration accepted as empty ELB name normalization' >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
jq -n '{resource_changes:[{address:"aws_vpc_security_group_ingress_rule.service[\"backend\"]",change:{actions:["update"],
|
||||
before:{description:"",from_port:8080},after:{description:null,from_port:8080}}}]}' >"$work/plan.json"
|
||||
bash .github/scripts/runtime-tls.sh check-plan "$work/plan.json" route
|
||||
jq '.resource_changes[0].change.after.from_port=8443' "$work/plan.json" >"$work/changed.json"
|
||||
if bash .github/scripts/runtime-tls.sh check-plan "$work/changed.json" route 2>/dev/null; then
|
||||
echo 'Network change accepted as metadata normalization' >&2
|
||||
exit 1
|
||||
fi
|
||||
jq -n '{resource_changes:[{address:"aws_ecs_task_definition.service[\"backend\"]",change:{actions:["delete","create"],before:{container_definitions:([{image:"pinned",environment:[]}]|tojson)},after:{container_definitions:([{image:"pinned",environment:[{name:"SERVE_HTTP_LOOPBACK_ONLY",value:"true"}]}]|tojson)}}}]}' >"$work/loopback-only.json"
|
||||
cp "$work/loopback-only.json" "$work/plan.json"
|
||||
complete_cleanup "$work/plan.json"
|
||||
bash .github/scripts/runtime-tls.sh check-plan "$work/plan.json" on
|
||||
if bash .github/scripts/runtime-tls.sh check-plan "$work/loopback-only.json" route 2>/dev/null; then
|
||||
echo 'Loopback-only listener accepted before HTTP registrations drained' >&2
|
||||
exit 1
|
||||
fi
|
||||
jq '.resource_changes |= map(select(.address | startswith("aws_ecs_task_definition"))) |
|
||||
.resource_changes[0].change |= ({actions:.actions,before:.after,after:.before})' "$work/plan.json" >"$work/route.json"
|
||||
bash .github/scripts/runtime-tls.sh check-plan "$work/route.json" route
|
||||
jq '.resource_changes[0].change.after.container_definitions |= (fromjson | .[0].image = "changed" | tojson)' "$work/plan.json" >"$work/changed.json"
|
||||
if bash .github/scripts/runtime-tls.sh check-plan "$work/changed.json" on 2>/dev/null; then
|
||||
echo 'Changed image was accepted' >&2
|
||||
exit 1
|
||||
fi
|
||||
jq '.resource_changes[0].change.before.cpu = "512" | .resource_changes[0].change.after.cpu = "1024"' "$work/plan.json" >"$work/changed.json"
|
||||
if bash .github/scripts/runtime-tls.sh check-plan "$work/changed.json" on 2>/dev/null; then
|
||||
echo 'Changed task settings were accepted' >&2
|
||||
exit 1
|
||||
fi
|
||||
jq -n '{resource_changes:[{address:"aws_ecs_service.service[\"backend\"]",change:{actions:["update"],before:{network_configuration:[]},after:{network_configuration:[{subnets:["other"]}]}}}]}' >"$work/changed.json"
|
||||
if bash .github/scripts/runtime-tls.sh check-plan "$work/changed.json" 2>/dev/null; then
|
||||
echo 'Changed service network was accepted' >&2
|
||||
exit 1
|
||||
fi
|
||||
jq -n '{services:[range(4) | {loadBalancers:[{containerPort:8443,targetGroupArn:"service-tls/123"}]}],
|
||||
httpGroups:[range(4) | {LoadBalancerArns:[],targets:[]}]}' >"$work/cleanup.json"
|
||||
bash .github/scripts/runtime-tls.sh check-cleanup "$work/cleanup.json"
|
||||
for change in '.services[0].loadBalancers[0].containerPort=8080' \
|
||||
'.httpGroups[0].LoadBalancerArns=["listener"]' '.httpGroups[0].targets=[{Id:"still-draining"}]' \
|
||||
'.services=[]'; do
|
||||
jq "$change" "$work/cleanup.json" >"$work/changed.json"
|
||||
if bash .github/scripts/runtime-tls.sh check-cleanup "$work/changed.json" 2>/dev/null; then
|
||||
echo 'HTTP cleanup accepted before all references drained' >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
jq -n '
|
||||
["backend","forms","tracking","realtime"] as $names |
|
||||
{services:{failures:[],services:[$names[] | {serviceName:("test-"+.),taskDefinition:.,desiredCount:1,runningCount:1,pendingCount:0,
|
||||
deployments:[{rolloutState:"COMPLETED"}],loadBalancers:[{containerPort:8080,targetGroupArn:(.+"/1")},{containerPort:8443,targetGroupArn:(.+"-tls/2")}]}]},
|
||||
definitions:[$names[] | {tags:[{key:"warmbly-release",value:"v0.6.70"}],taskDefinition:{taskDefinitionArn:.,containerDefinitions:[{
|
||||
environment:[{name:"SERVE_TLS",value:"supplied"},{name:"SERVE_TLS_PORT",value:"8443"}]}]}}]}' >"$work/live.json"
|
||||
bash .github/scripts/runtime-tls.sh check-live "$work/live.json" route v0.6.70 8443 test
|
||||
for change in '.services.services[0].pendingCount=1' '.services.services[0].deployments[0].rolloutState="IN_PROGRESS"' \
|
||||
'.services.services[0].loadBalancers|=.[0:1]' '.definitions[0].tags[0].value="v0.6.69"' \
|
||||
'.definitions[0].taskDefinition.containerDefinitions[0].environment=[]' \
|
||||
'.definitions[0].taskDefinition.containerDefinitions[0].environment += [{name:"SERVE_HTTP_LOOPBACK_ONLY",value:"true"}]' \
|
||||
'.services.services|=.[0:3]'; do
|
||||
jq "$change" "$work/live.json" >"$work/changed.json"
|
||||
if bash .github/scripts/runtime-tls.sh check-live "$work/changed.json" route v0.6.70 8443 test 2>/dev/null; then
|
||||
echo 'Incompatible or unstable live services accepted' >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
jq -n '{resource_changes:[]}' >"$work/deletions.json"
|
||||
complete_cleanup "$work/deletions.json"
|
||||
bash .github/scripts/runtime-tls.sh check-plan "$work/deletions.json" on
|
||||
for change in '.resource_changes=[]' '.resource_changes|=.[1:]' \
|
||||
'.resource_changes[0].change.actions=["no-op"]' \
|
||||
'.resource_changes[0].change.actions=["delete","create"]' \
|
||||
'.resource_changes[0].address="aws_lb_target_group.service[\"consumer\"]"'; do
|
||||
jq "$change" "$work/deletions.json" >"$work/changed.json"
|
||||
if bash .github/scripts/runtime-tls.sh check-plan "$work/changed.json" on 2>/dev/null; then
|
||||
echo 'ON accepted without the exact four HTTP group deletions' >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
echo 'Runtime TLS plan guards passed'
|
||||
@@ -10,13 +10,15 @@
|
||||
#
|
||||
# plan writes $WORK/<stack>.summary (one "action address" per line) and prints
|
||||
# safe, gated or none. Safe means only creates, in-place updates, and new
|
||||
# revisions of task definitions, which keep their old revision.
|
||||
# revisions of task definitions, excluding protected recovery evidence IAM changes.
|
||||
set -euo pipefail
|
||||
|
||||
classify() {
|
||||
jq -r '
|
||||
[.resource_changes[]? | select(.change.actions != ["no-op"] and .change.actions != ["read"])] as $c |
|
||||
if ($c | length) == 0 then "none"
|
||||
elif any($c[]; .name == "tls_recovery_evidence" and
|
||||
(.type == "aws_iam_role" or .type == "aws_iam_role_policy")) then "gated"
|
||||
elif any($c[]; (.change.actions | index("delete")) and
|
||||
((.type == "aws_ecs_task_definition" and (.change.actions | length) == 2) | not)) then "gated"
|
||||
else "safe" end' "$1"
|
||||
|
||||
Executable
+31
@@ -0,0 +1,31 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/../.."
|
||||
work=$(mktemp -d)
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
classifier=${CLASSIFIER:-.github/scripts/terraform-stack.sh}
|
||||
|
||||
check() {
|
||||
local expected=$1 type=$2 name=$3 actions=$4
|
||||
jq -n --arg type "$type" --arg name "$name" --argjson actions "$actions" \
|
||||
'{resource_changes:[{address:($type+"."+$name+"[0]"),type:$type,name:$name,change:{actions:$actions}}]}' >"$work/plan.json"
|
||||
local actual
|
||||
actual=$(bash "$classifier" classify "$work/plan.json")
|
||||
if [ "$actual" != "$expected" ]; then
|
||||
echo "Expected $expected for $type.$name $actions, received $actual" >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
for type in aws_iam_role aws_iam_role_policy; do
|
||||
for actions in '["create"]' '["update"]' '["delete"]' '["delete","create"]'; do
|
||||
check gated "$type" tls_recovery_evidence "$actions"
|
||||
done
|
||||
check none "$type" tls_recovery_evidence '["no-op"]'
|
||||
check none "$type" tls_recovery_evidence '["read"]'
|
||||
done
|
||||
check safe aws_iam_role existing_role '["create"]'
|
||||
check safe aws_ecs_task_definition service '["delete","create"]'
|
||||
check gated aws_lb_target_group service '["delete"]'
|
||||
check safe aws_cloudwatch_metric_alarm service '["update"]'
|
||||
echo 'Protected evidence IAM changes require approval; existing plan classifications remain unchanged'
|
||||
+36
-23
@@ -1,8 +1,8 @@
|
||||
name: CI
|
||||
|
||||
# main only receives what the merge queue already tested at the same commit,
|
||||
# so the merge_group run is the gate and nothing reruns it after the merge.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
merge_group:
|
||||
@@ -69,8 +69,10 @@ jobs:
|
||||
aws-deployment:
|
||||
- '.github/workflows/ci.yml'
|
||||
- '.github/workflows/deploy-aws.yml'
|
||||
- '.github/workflows/configure-backend-aws.yml'
|
||||
- '.github/workflows/rotate-keys.yml'
|
||||
- '.github/scripts/aws-deploy*.cjs'
|
||||
- '.github/scripts/aws-backend-config*.cjs'
|
||||
- '.github/scripts/aws-rotate*.cjs'
|
||||
- '.github/aws-deploy/**'
|
||||
- 'deploy/terraform/aws/runtime/rotate/**'
|
||||
@@ -109,6 +111,8 @@ jobs:
|
||||
- 'scripts/check-cli-installer.sh'
|
||||
- 'scripts/build-cli.sh'
|
||||
pages:
|
||||
- '.github/workflows/static-assets.yml'
|
||||
- 'deploy/cloudflare/**'
|
||||
- '.github/scripts/pages-*'
|
||||
- '.github/workflows/release.yml'
|
||||
- '.github/workflows/ci.yml'
|
||||
@@ -131,7 +135,7 @@ jobs:
|
||||
with:
|
||||
node-version: "22"
|
||||
- name: Check production configuration import
|
||||
run: node --test .github/scripts/pages-*.test.mjs
|
||||
run: node --test .github/scripts/pages-*.test.mjs deploy/cloudflare/static-edge.test.mjs
|
||||
|
||||
migrations-ci:
|
||||
name: Migrations
|
||||
@@ -223,10 +227,9 @@ jobs:
|
||||
if: matrix.suite == 'lint'
|
||||
run: go build -tags kafka ./...
|
||||
|
||||
- name: Run tests with coverage
|
||||
- name: Run tests
|
||||
if: matrix.suite == 'unit'
|
||||
run: |
|
||||
go test -race -coverprofile=coverage.out -covermode=atomic ./...
|
||||
run: go test -race ./...
|
||||
|
||||
- name: Prepare regression database
|
||||
if: startsWith(matrix.suite, 'live-')
|
||||
@@ -241,8 +244,8 @@ jobs:
|
||||
WARMBLY_TEST_DB: postgres://warmbly:warmbly@127.0.0.1:5432/warmbly_test?sslmode=disable
|
||||
run: |
|
||||
set -o pipefail
|
||||
go test -race -v -p 1 ./internal/repository ./internal/app/analytics -run '^TestLive(WarmupPartnerCountsMatchIndividualCandidates|WarmupSummariesMatchIndividualReads|LinkedMailboxStatusBatchPreservesDetails|WarmupPartnerWeekCacheMatchesExactReadAndKeepsTheCapLive|WarmupPartnerWeekCacheRefreshesDetachedAndServesStale|WarmupPartnerCandidatesCarryReciprocityAndHonourTheCap|AccountStatusPageMatchesSingleReadsInBoundedQueries|WarmupOffMailboxReceivesNothing|WarmupPauseRetiresIncomingWork|WarmupInboxHasRoomMatchesTheReservation)$' -count=1 | tee linked-mailbox-batch.log
|
||||
for test in TestLiveWarmupPartnerCountsMatchIndividualCandidates TestLiveWarmupSummariesMatchIndividualReads TestLiveLinkedMailboxStatusBatchPreservesDetails TestLiveWarmupPartnerWeekCacheMatchesExactReadAndKeepsTheCapLive TestLiveWarmupPartnerWeekCacheRefreshesDetachedAndServesStale TestLiveWarmupPartnerCandidatesCarryReciprocityAndHonourTheCap TestLiveAccountStatusPageMatchesSingleReadsInBoundedQueries TestLiveWarmupOffMailboxReceivesNothing TestLiveWarmupPauseRetiresIncomingWork TestLiveWarmupInboxHasRoomMatchesTheReservation; do
|
||||
go test -race -v -p 1 ./internal/repository ./internal/app/analytics -run '^TestLive(WarmupPartnerCountsMatchIndividualCandidates|WarmupSummariesMatchIndividualReads|LinkedMailboxStatusBatchPreservesDetails|WarmupPartnerWeekCacheMatchesExactReadAndKeepsTheCapLive|WarmupPartnerWeekCacheRefreshesDetachedAndServesStale|WarmupPartnerCandidatesCarryReciprocityAndHonourTheCap|AccountStatusPageMatchesSingleReadsInBoundedQueries|WarmupOffMailboxReceivesNothing|WarmupPauseRetiresIncomingWork|WarmupReservationHoldsEachTierToItsShare|WarmupReplyIsAdmittedToAFullInbox|WarmupRepliesLeaveTheNewThreadCapUntouched|OwedRepliesContinueTheDeepestConversationFirst)$' -count=1 | tee linked-mailbox-batch.log
|
||||
for test in TestLiveWarmupPartnerCountsMatchIndividualCandidates TestLiveWarmupSummariesMatchIndividualReads TestLiveLinkedMailboxStatusBatchPreservesDetails TestLiveWarmupPartnerWeekCacheMatchesExactReadAndKeepsTheCapLive TestLiveWarmupPartnerWeekCacheRefreshesDetachedAndServesStale TestLiveWarmupPartnerCandidatesCarryReciprocityAndHonourTheCap TestLiveAccountStatusPageMatchesSingleReadsInBoundedQueries TestLiveWarmupOffMailboxReceivesNothing TestLiveWarmupPauseRetiresIncomingWork TestLiveWarmupReservationHoldsEachTierToItsShare TestLiveWarmupReplyIsAdmittedToAFullInbox TestLiveWarmupRepliesLeaveTheNewThreadCapUntouched TestLiveOwedRepliesContinueTheDeepestConversationFirst; do
|
||||
grep -q -- "--- PASS: $test " linked-mailbox-batch.log
|
||||
done
|
||||
if grep -q -- '--- SKIP:' linked-mailbox-batch.log; then exit 1; fi
|
||||
@@ -258,6 +261,18 @@ jobs:
|
||||
grep -q '^--- PASS: TestLiveCampaignLoadingLogsKeepHistoryWithoutCustomerAlerts ' campaign-reconnect.log
|
||||
if grep -q -- '--- SKIP:' campaign-reconnect.log; then exit 1; fi
|
||||
|
||||
- name: Mailbox push channels and fleet usage (PostgreSQL)
|
||||
if: matrix.suite == 'live-1'
|
||||
env:
|
||||
WARMBLY_TEST_DB: postgres://warmbly:warmbly@127.0.0.1:5432/warmbly_test?sslmode=disable
|
||||
run: |
|
||||
set -o pipefail
|
||||
go test -race -v -p 1 ./internal/repository ./internal/app/fleetmetrics -run '^TestLive(MailboxPushChannelsRoundTripAndScopeToTheOwner|WakeTargetsSkipWorkersThatCannotActOnAWake|ReadTakesMemoryFromHeartbeats)$' -count=1 | tee mailbox-push.log
|
||||
for test in TestLiveMailboxPushChannelsRoundTripAndScopeToTheOwner TestLiveWakeTargetsSkipWorkersThatCannotActOnAWake TestLiveReadTakesMemoryFromHeartbeats; do
|
||||
grep -q -- "--- PASS: $test " mailbox-push.log
|
||||
done
|
||||
if grep -q -- '--- SKIP:' mailbox-push.log; then exit 1; fi
|
||||
|
||||
- name: Contact campaign empty-step regression (PostgreSQL)
|
||||
if: matrix.suite == 'live-1'
|
||||
env:
|
||||
@@ -283,6 +298,13 @@ jobs:
|
||||
run: |
|
||||
go test -race -p 1 ./internal/repository ./internal/scheduler ./internal/tasks -run '^TestLive(MailboxSendClaim(AdmitsOnePerGap|WaitsOutAReservedSend)|BookedSendsLeaveOutCampaignWakeups|ParkedCampaignDoesNotThrottleItsPoolMate|BookedSendsStillSpaceTheCampaign|ClaimedMailboxIsPassedOver|CampaignsSharingAMailboxSendOncePerGap|LostMailboxClaimReschedulesWithoutSending)$' -count=1
|
||||
|
||||
- name: Postgres queue claim regressions (PostgreSQL)
|
||||
if: matrix.suite == 'live-3'
|
||||
env:
|
||||
WARMBLY_TEST_DB: postgres://warmbly:warmbly@127.0.0.1:5432/warmbly_test?sslmode=disable
|
||||
run: |
|
||||
go test -race -p 1 ./internal/repository -run '^TestLive(ConcurrentDispatchersNeverClaimTheSameTask|SendResultEffectsBatchClaimsDeliverEachEffectOnce|CRMClaimTakesDueAndLapsedJobsOnce)$' -count=1
|
||||
|
||||
- name: Invited signup atomic provisioning regressions (PostgreSQL)
|
||||
if: matrix.suite == 'live-1'
|
||||
env:
|
||||
@@ -345,8 +367,8 @@ jobs:
|
||||
WARMBLY_TEST_DB: postgres://warmbly:warmbly@127.0.0.1:5432/warmbly_test?sslmode=disable
|
||||
run: |
|
||||
set -o pipefail
|
||||
go test -race ./internal/repository -run '^TestLive(Monitoring|LastWarmupSendFailure|PersistentMailboxLoadingFailure|DispatchRetry|LineageQueueRevisions|AdminPlatformOverview|WarmupRecoversOldPreparation|WarmupPreparationRecoveryRetains|WarmupFilingRequiresAcknowledgement|WarmupFilingAuthority|WarmupTimeWindow|WarmupInvalidWindow|StoppedRecipientIsNeverAddressed)' -count=1
|
||||
go test -race -v ./internal/tasks -run '^Test(LiveWarmup(SafetyHoldReschedules|Recovery|UnknownRetirement|TaskDoesNotApplyResults|DispatchDefersInvalidHours)|WarmupSenderDistinguishes)' -count=1 | tee warmup-recovery.log
|
||||
go test -race ./internal/repository -run '^TestLive(Monitoring|LastWarmupSendFailure|PersistentMailboxLoadingFailure|DispatchRetry|LineageQueueRevisions|ReplyShare|AdminPlatformOverview|WarmupRecoversOldPreparation|WarmupPreparationRecoveryRetains|WarmupFilingRequiresAcknowledgement|WarmupFilingAuthority|WarmupTimeWindow|WarmupInvalidWindow|StoppedRecipientIsNeverAddressed)' -count=1
|
||||
go test -race -v ./internal/tasks -run '^Test(LiveWarmup(SafetyHoldReschedules|Recovery|UnknownRetirement|TaskDoesNotApplyResults|DispatchDefersInvalidHours|ReplyShare)|WarmupSenderDistinguishes)' -count=1 | tee warmup-recovery.log
|
||||
if grep -q -- '--- SKIP: TestLiveWarmupUnknownRetirement' warmup-recovery.log; then exit 1; fi
|
||||
for test in TestLiveWarmupUnknownRetirementPreservesEvidenceAndFencesReplayOnce TestLiveWarmupUnknownRetirementAllowsDistinctNewSendAndKeepsCooldown TestLiveWarmupUnknownRetirementAndDefinitiveResultSerialize TestLiveWarmupUnknownRetirementSkipsProtectedRowsWithoutStarvingLaterMailboxes TestLiveWarmupUnknownRetirementReconcilerSeedsOnceAndClearsActiveWarnings; do
|
||||
grep -q -- "--- PASS: $test " warmup-recovery.log || exit 1
|
||||
@@ -558,6 +580,8 @@ jobs:
|
||||
grep -q "^--- PASS: $test " mailbox-transport-runtime.log
|
||||
done
|
||||
if grep -q -- '--- SKIP:' mailbox-transport-runtime.log; then exit 1; fi
|
||||
go test -race -v -p 1 ./internal/repository -run '^TestLiveAuthenticatorStepRequiresActiveEnrollment$' -count=1 | tee authenticator-verification.log
|
||||
grep -q '^--- PASS: TestLiveAuthenticatorStepRequiresActiveEnrollment ' authenticator-verification.log
|
||||
grep -q '^--- PASS: TestLiveImportMailTransportWholeArchiveSendResultLockOrder ' mailbox-transport-runtime.log
|
||||
for logfile in mailbox-transport-upgrade.log mailbox-transport-runtime.log; do
|
||||
test "$(grep -c '^=== RUN' "$logfile")" -gt 0
|
||||
@@ -621,7 +645,7 @@ jobs:
|
||||
if: matrix.suite == 'live-1'
|
||||
env:
|
||||
WARMBLY_TEST_DB: postgres://warmbly:warmbly@127.0.0.1:5432/warmbly_test?sslmode=disable
|
||||
run: go test -race -v -p 1 ./internal/repository ./internal/infrastructure/db -run '^TestLiveUnibox(Search|ReadStream|SearchUpgrade|GetBySender)' -count=1
|
||||
run: go test -race -v -p 1 ./internal/repository ./internal/infrastructure/db -run '^TestLiveUnibox(Search|ReadStream|SearchUpgrade|GetBySender|ScopeDraftsCount)' -count=1
|
||||
|
||||
- name: Notification digest authorization retries (Redis)
|
||||
if: matrix.suite == 'live-3'
|
||||
@@ -633,17 +657,6 @@ jobs:
|
||||
if: matrix.suite == 'live-2'
|
||||
run: go test -race -tags kafka ./internal/infrastructure/codec/ ./internal/infrastructure/kafka/ ./internal/infrastructure/eventbus/
|
||||
|
||||
# fail_ci_if_error does not cover the uploader crashing before it runs
|
||||
# (a TLS handshake failure to Codecov failed jobs whose tests passed).
|
||||
- name: Upload coverage
|
||||
if: matrix.suite == 'unit'
|
||||
uses: codecov/codecov-action@v4
|
||||
continue-on-error: true
|
||||
with:
|
||||
files: coverage.out
|
||||
flags: go
|
||||
fail_ci_if_error: false
|
||||
|
||||
web-ci:
|
||||
name: Web CI
|
||||
needs: changes
|
||||
@@ -1016,7 +1029,7 @@ jobs:
|
||||
- name: Check deploy, rollback and rotation gates
|
||||
env:
|
||||
NODE_PATH: ${{ github.workspace }}/.github/aws-deploy/node_modules
|
||||
run: node --test .github/scripts/aws-deploy.test.cjs .github/scripts/aws-rotate.test.cjs deploy/terraform/aws/runtime/rotate/rotate.test.cjs
|
||||
run: node --test .github/scripts/aws-deploy.test.cjs .github/scripts/aws-backend-config.test.cjs .github/scripts/aws-rotate.test.cjs deploy/terraform/aws/runtime/rotate/rotate.test.cjs
|
||||
|
||||
ci-status:
|
||||
name: CI Status
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
name: Configure AWS backend
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: Published stable release already running on every backend (v0.6.75 or newer)
|
||||
required: true
|
||||
type: string
|
||||
expected_task_definition:
|
||||
description: Exact currently running backend task definition ARN
|
||||
required: true
|
||||
type: string
|
||||
expected_backend_tasks:
|
||||
description: JSON array of every current RUNNING backend task ARN from the read-only preflight
|
||||
required: true
|
||||
type: string
|
||||
attachment_download_proxy:
|
||||
description: Serve private campaign attachments through the backend download route
|
||||
required: true
|
||||
type: boolean
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
configure:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
environment: aws-production
|
||||
concurrency:
|
||||
group: aws-production
|
||||
cancel-in-progress: false
|
||||
permissions:
|
||||
contents: read
|
||||
attestations: read
|
||||
id-token: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
fetch-depth: 0
|
||||
- name: Verify main and the published release provenance
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
TAG: ${{ inputs.tag }}
|
||||
ENABLED: ${{ vars.AWS_DEPLOY_ENABLED }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
[ "$GITHUB_REF" = refs/heads/main ] && [ "$ENABLED" = true ] || {
|
||||
echo "::error::Backend configuration requires main and AWS_DEPLOY_ENABLED=true"; exit 1; }
|
||||
printf '%s\n' "$TAG" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+$' || {
|
||||
echo "::error::A stable release tag is required"; exit 1; }
|
||||
git merge-base --is-ancestor "refs/tags/$TAG^{commit}" origin/main
|
||||
state=$(gh release view "$TAG" --json isDraft,isPrerelease --jq '"\(.isDraft) \(.isPrerelease)"')
|
||||
[ "$state" = "false false" ] || { echo "::error::A published stable release is required"; exit 1; }
|
||||
mkdir -p /tmp/backend-config-release
|
||||
gh release download "$TAG" --pattern images.json --dir /tmp/backend-config-release
|
||||
manifest=/tmp/backend-config-release/images.json
|
||||
jq -e --arg tag "$TAG" '.tag == $tag and .registry == "ghcr.io/warmbly/warmbly"' "$manifest" >/dev/null
|
||||
registry=$(jq -r .registry "$manifest")
|
||||
for key in backend backend-kafka consumer consumer-kafka worker worker-kafka forms tracking tracking-kafka realtime; do
|
||||
digest=$(jq -er --arg key "$key" '.images[$key] | select(test("^sha256:[a-f0-9]{64}$"))' "$manifest")
|
||||
gh attestation verify "oci://$registry/${key%-kafka}@$digest" \
|
||||
--repo "$GITHUB_REPOSITORY" \
|
||||
--signer-workflow "$GITHUB_REPOSITORY/.github/workflows/release.yml" \
|
||||
--source-ref "refs/tags/$TAG" >/dev/null
|
||||
echo "verified provenance of $key"
|
||||
done
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
- name: Install deployment client
|
||||
run: npm ci --prefix .github/aws-deploy --omit=dev --ignore-scripts --no-audit --no-fund
|
||||
- uses: aws-actions/configure-aws-credentials@v4
|
||||
with:
|
||||
role-to-assume: ${{ vars.AWS_DEPLOY_ROLE_ARN }}
|
||||
aws-region: us-east-1
|
||||
- name: Configure and bake the backend
|
||||
env:
|
||||
NODE_PATH: ${{ github.workspace }}/.github/aws-deploy/node_modules
|
||||
AWS_ECS_CLUSTER: ${{ vars.AWS_ECS_CLUSTER }}
|
||||
AWS_ECS_SERVICE_PREFIX: ${{ vars.AWS_ECS_SERVICE_PREFIX }}
|
||||
DEPLOY_TAG: ${{ inputs.tag }}
|
||||
DEPLOY_IMAGES_JSON: /tmp/backend-config-release/images.json
|
||||
CONFIG_EXPECTED_TASK_DEFINITION: ${{ inputs.expected_task_definition }}
|
||||
CONFIG_EXPECTED_TASKS: ${{ inputs.expected_backend_tasks }}
|
||||
CONFIG_ATTACHMENT_DOWNLOAD_PROXY: ${{ inputs.attachment_download_proxy }}
|
||||
run: node .github/scripts/aws-backend-config.cjs
|
||||
@@ -0,0 +1,82 @@
|
||||
name: Configure AWS origin ALB policy
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- '.github/workflows/configure-origin-alb-aws.yml'
|
||||
- '.github/scripts/aws-origin-alb*'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
mode:
|
||||
description: Plan only by default; apply or rollback consumes an exact private plan
|
||||
type: choice
|
||||
options: [plan, apply, rollback]
|
||||
default: plan
|
||||
required: true
|
||||
plan_run_id:
|
||||
description: Run ID that produced the reviewed private plan (apply and rollback only)
|
||||
type: string
|
||||
plan_version:
|
||||
description: Exact private S3 plan version ID (apply and rollback only)
|
||||
type: string
|
||||
plan_sha256:
|
||||
description: SHA-256 of the complete reviewed private plan (apply and rollback only)
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
check:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
- run: node --test .github/scripts/aws-origin-alb.test.cjs
|
||||
- run: shellcheck .github/scripts/aws-origin-alb-workflow.test.sh
|
||||
- run: bash .github/scripts/aws-origin-alb-workflow.test.sh
|
||||
|
||||
configure:
|
||||
needs: check
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
environment: aws-infrastructure
|
||||
concurrency:
|
||||
group: aws-production
|
||||
cancel-in-progress: false
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
env:
|
||||
ORIGIN_ALB_MODE: ${{ inputs.mode }}
|
||||
ORIGIN_ALB_PLAN_RUN_ID: ${{ inputs.plan_run_id }}
|
||||
ORIGIN_ALB_PLAN_VERSION: ${{ inputs.plan_version }}
|
||||
ORIGIN_ALB_PLAN_SHA256: ${{ inputs.plan_sha256 }}
|
||||
STATE_BUCKET: ${{ vars.AWS_TERRAFORM_STATE_BUCKET }}
|
||||
APPLY_ROLE: ${{ vars.AWS_TERRAFORM_APPLY_ROLE_ARN }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
- name: Check main, ordinary role configuration and exact input scope
|
||||
id: scope
|
||||
env:
|
||||
WORK: ${{ runner.temp }}/origin-alb-policy
|
||||
run: node .github/scripts/aws-origin-alb.cjs session-policy
|
||||
- uses: aws-actions/configure-aws-credentials@v4
|
||||
with:
|
||||
role-to-assume: ${{ vars.AWS_TERRAFORM_APPLY_ROLE_ARN }}
|
||||
aws-region: us-east-1
|
||||
inline-session-policy: ${{ steps.scope.outputs.policy }}
|
||||
- name: Plan or execute the exact listener policy change
|
||||
env:
|
||||
WORK: ${{ runner.temp }}/origin-alb-policy
|
||||
run: node .github/scripts/aws-origin-alb.cjs configure
|
||||
@@ -12,8 +12,6 @@ on:
|
||||
- deploy/docker-compose.coolify.yml
|
||||
- deploy/check-coolify.sh
|
||||
- .github/workflows/coolify.yml
|
||||
merge_group:
|
||||
types: [checks_requested]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
@@ -22,6 +22,14 @@ on:
|
||||
description: Start a canary rollout of the workers and consumers after the services
|
||||
default: true
|
||||
type: boolean
|
||||
require_attestation:
|
||||
description: Refuse images without build provenance (only releases before provenance need false)
|
||||
default: true
|
||||
type: boolean
|
||||
bake_seconds:
|
||||
description: Optional explicit service bake duration; empty retains the configured default
|
||||
default: ""
|
||||
type: string
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
@@ -41,6 +49,10 @@ on:
|
||||
description: Seconds each service is watched against its alarms after it is stable
|
||||
default: "300"
|
||||
type: string
|
||||
fleet_bake_seconds:
|
||||
description: Healthy uptime per worker rollout stage (300 through 3600 seconds)
|
||||
default: "300"
|
||||
type: string
|
||||
fleet:
|
||||
description: Start a canary rollout of the workers and consumers after the services
|
||||
default: true
|
||||
@@ -139,6 +151,7 @@ jobs:
|
||||
DEPLOY_MODE: ${{ inputs.mode || 'deploy' }}
|
||||
DEPLOY_SERVICES: ${{ inputs.services || 'all' }}
|
||||
DEPLOY_BAKE_SECONDS: ${{ inputs.bake_seconds || vars.AWS_DEPLOY_BAKE_SECONDS || '300' }}
|
||||
DEPLOY_FLEET_BAKE_SECONDS: ${{ inputs.fleet_bake_seconds || vars.AWS_FLEET_BAKE_SECONDS || '300' }}
|
||||
DEPLOY_FLEET: ${{ inputs.fleet != false }}
|
||||
DEPLOY_ALLOW_DROPPED_SECRETS: ${{ inputs.allow_dropped_secrets == true }}
|
||||
DEPLOY_IMAGES_JSON: ${{ steps.release.outputs.images }}
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
name: Deploy marketing Pages
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- '.github/workflows/marketing-pages.yml'
|
||||
- '.github/scripts/pages-*'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
expected_sha:
|
||||
description: Reviewed main commit to deploy (full SHA)
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.event_name == 'workflow_dispatch' && 'release' || format('marketing-pages-check-{0}', github.ref) }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
check:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: "22"
|
||||
- run: node --test .github/scripts/pages-*.test.mjs
|
||||
|
||||
deploy:
|
||||
needs: check
|
||||
if: github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && vars.CLOUDFLARE_PAGES_DEPLOY_ENABLED == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
environment: site-production
|
||||
env:
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
|
||||
PAGES_APP: site
|
||||
WRANGLER_SEND_METRICS: "false"
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
ref: ${{ github.sha }}
|
||||
persist-credentials: false
|
||||
- name: Require the reviewed main commit
|
||||
env:
|
||||
EXPECTED_SHA: ${{ inputs.expected_sha }}
|
||||
run: test "$EXPECTED_SHA" = "$GITHUB_SHA"
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: "22"
|
||||
- name: Select only the configured marketing project
|
||||
env:
|
||||
CLOUDFLARE_PAGES_PROJECTS: ${{ vars.CLOUDFLARE_PAGES_PROJECTS }}
|
||||
run: |
|
||||
node --input-type=module <<'JS'
|
||||
import { appendFileSync } from 'node:fs';
|
||||
import { deploymentMatrix } from './.github/scripts/pages-projects.mjs';
|
||||
const sites = deploymentMatrix(process.env.CLOUDFLARE_PAGES_PROJECTS).include.filter(target => target.app === 'site');
|
||||
if (sites.length !== 1) throw new Error('Configure exactly one marketing Pages project');
|
||||
appendFileSync(process.env.GITHUB_ENV, `CLOUDFLARE_PAGES_PROJECT_NAME=${sites[0].project}\n`);
|
||||
JS
|
||||
- name: Load existing marketing production configuration
|
||||
id: config
|
||||
env:
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
run: |
|
||||
for name in CLOUDFLARE_API_TOKEN CLOUDFLARE_ACCOUNT_ID CLOUDFLARE_PAGES_PROJECT_NAME; do
|
||||
test -n "${!name}"
|
||||
done
|
||||
curl --fail --silent --show-error \
|
||||
--header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
|
||||
"https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/pages/projects/$CLOUDFLARE_PAGES_PROJECT_NAME" \
|
||||
| node .github/scripts/pages-production-config.mjs
|
||||
- uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1 # v4
|
||||
with:
|
||||
version: "11.9.0"
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: pnpm
|
||||
cache-dependency-path: site/pnpm-lock.yaml
|
||||
- name: Install marketing dependencies
|
||||
working-directory: site
|
||||
run: pnpm install --frozen-lockfile
|
||||
- name: Check marketing behavior and CSP
|
||||
working-directory: site
|
||||
run: pnpm test
|
||||
- name: Build marketing with production configuration
|
||||
working-directory: site
|
||||
run: pnpm build
|
||||
- name: Deploy an isolated preview
|
||||
env:
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
PREVIEW_BRANCH: marketing-check-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
PRODUCTION_BRANCH: ${{ steps.config.outputs.production_branch }}
|
||||
WRANGLER_OUTPUT_FILE_PATH: ${{ runner.temp }}/marketing-preview-${{ github.run_id }}-${{ github.run_attempt }}.ndjson
|
||||
run: |
|
||||
test "$PREVIEW_BRANCH" != "$PRODUCTION_BRANCH"
|
||||
test ! -e "$WRANGLER_OUTPUT_FILE_PATH"
|
||||
pnpm dlx wrangler@4.45.0 pages deploy site/dist \
|
||||
--project-name "$CLOUDFLARE_PAGES_PROJECT_NAME" \
|
||||
--branch "$PREVIEW_BRANCH" --commit-hash "$GITHUB_SHA"
|
||||
- name: Verify preview responses before production
|
||||
env:
|
||||
WRANGLER_OUTPUT_FILE_PATH: ${{ runner.temp }}/marketing-preview-${{ github.run_id }}-${{ github.run_attempt }}.ndjson
|
||||
run: node .github/scripts/pages-marketing-preview.mjs
|
||||
- name: Publish the verified marketing artifact
|
||||
env:
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
PRODUCTION_BRANCH: ${{ steps.config.outputs.production_branch }}
|
||||
run: |
|
||||
pnpm dlx wrangler@4.45.0 pages deploy site/dist \
|
||||
--project-name "$CLOUDFLARE_PAGES_PROJECT_NAME" \
|
||||
--branch "$PRODUCTION_BRANCH" --commit-hash "$GITHUB_SHA" \
|
||||
--commit-message "Marketing $GITHUB_SHA"
|
||||
@@ -0,0 +1,84 @@
|
||||
name: Probe AWS origin TLS
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- '.github/workflows/probe-origin-tls-aws.yml'
|
||||
- '.github/scripts/aws-origin-tls*'
|
||||
- '.github/scripts/origin-tls-client*'
|
||||
- '.github/scripts/aws-origin-alb.cjs'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
check:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
- run: node --test .github/scripts/aws-origin-tls.test.cjs .github/scripts/origin-tls-client.test.cjs
|
||||
- run: shellcheck .github/scripts/aws-origin-tls-workflow.test.sh
|
||||
- run: bash .github/scripts/aws-origin-tls-workflow.test.sh
|
||||
|
||||
probe:
|
||||
needs: check
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 25
|
||||
environment: aws-infrastructure
|
||||
concurrency:
|
||||
group: aws-production
|
||||
cancel-in-progress: false
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
env:
|
||||
STATE_BUCKET: ${{ vars.AWS_TERRAFORM_STATE_BUCKET }}
|
||||
APPLY_ROLE: ${{ vars.AWS_TERRAFORM_APPLY_ROLE_ARN }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
- name: Check main and ordinary infrastructure configuration
|
||||
id: scope
|
||||
env:
|
||||
WORK: ${{ runner.temp }}/origin-tls
|
||||
run: node .github/scripts/aws-origin-tls.cjs session-policy
|
||||
- uses: aws-actions/configure-aws-credentials@v4
|
||||
id: credentials
|
||||
with:
|
||||
role-to-assume: ${{ vars.AWS_TERRAFORM_APPLY_ROLE_ARN }}
|
||||
aws-region: us-east-1
|
||||
unset-current-credentials: true
|
||||
inline-session-policy: ${{ steps.scope.outputs.probe_policy }}
|
||||
- name: Run disposable secretless TLS diagnostic
|
||||
if: success() && steps.credentials.outcome == 'success'
|
||||
timeout-minutes: 10
|
||||
env:
|
||||
WORK: ${{ runner.temp }}/origin-tls
|
||||
run: node .github/scripts/aws-origin-tls.cjs probe
|
||||
- name: Acquire cleanup-only diagnostic credentials
|
||||
if: always() && steps.scope.outcome == 'success'
|
||||
timeout-minutes: 2
|
||||
uses: aws-actions/configure-aws-credentials@v4
|
||||
id: cleanup_credentials
|
||||
with:
|
||||
role-to-assume: ${{ vars.AWS_TERRAFORM_APPLY_ROLE_ARN }}
|
||||
aws-region: us-east-1
|
||||
unset-current-credentials: true
|
||||
inline-session-policy: ${{ steps.scope.outputs.cleanup_policy }}
|
||||
- name: Stop, deregister and privately archive diagnostic evidence
|
||||
if: always() && steps.cleanup_credentials.outcome == 'success'
|
||||
timeout-minutes: 8
|
||||
env:
|
||||
WORK: ${{ runner.temp }}/origin-tls
|
||||
run: node .github/scripts/aws-origin-tls.cjs finish
|
||||
@@ -657,3 +657,34 @@ jobs:
|
||||
--branch "$CLOUDFLARE_PAGES_PRODUCTION_BRANCH" \
|
||||
--commit-hash "$GITHUB_SHA" \
|
||||
--commit-message "$RELEASE_TAG"
|
||||
|
||||
- name: Prepare optional static asset mirror
|
||||
id: static-assets
|
||||
if: vars.CLOUDFLARE_STATIC_ASSETS_DEPLOY_ENABLED == 'true'
|
||||
env:
|
||||
CLOUDFLARE_PAGES_PROJECTS: ${{ vars.CLOUDFLARE_PAGES_PROJECTS }}
|
||||
CLOUDFLARE_STATIC_ASSETS_TARGETS: ${{ vars.CLOUDFLARE_STATIC_ASSETS_TARGETS }}
|
||||
SOURCE_SHA: ${{ github.sha }}
|
||||
RELEASE_TAG: ${{ github.ref_name }}
|
||||
run: |
|
||||
export STATIC_ASSETS_ARTIFACT_DIR="$RUNNER_TEMP/static-assets"
|
||||
node .github/scripts/pages-static-assets.mjs prepare-if-configured
|
||||
|
||||
- name: Publish the same artifact to the configured static asset host
|
||||
if: steps.static-assets.outputs.enabled == 'true'
|
||||
env:
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_STATIC_ASSETS_ACCOUNT_ID }}
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_STATIC_ASSETS_API_TOKEN }}
|
||||
WRANGLER_SEND_METRICS: "false"
|
||||
run: |
|
||||
test -n "$CLOUDFLARE_ACCOUNT_ID"
|
||||
test -n "$CLOUDFLARE_API_TOKEN"
|
||||
pnpm dlx wrangler@4.45.0 deploy --config "$RUNNER_TEMP/static-assets/wrangler.json"
|
||||
|
||||
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
if: steps.static-assets.outputs.enabled == 'true'
|
||||
with:
|
||||
name: static-assets-${{ matrix.project }}-${{ github.ref_name }}-${{ github.run_id }}
|
||||
path: ${{ runner.temp }}/static-assets
|
||||
include-hidden-files: true
|
||||
retention-days: 30
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
name: Recover partial runtime TLS cleanup
|
||||
run-name: Reviewed partial runtime TLS cleanup
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- '.github/workflows/runtime-tls-recovery.yml'
|
||||
- '.github/workflows/deploy-aws.yml'
|
||||
- '.github/scripts/runtime-tls*'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
contract_key:
|
||||
description: New private reviewed recovery contract key under runtime-tls-recovery/
|
||||
required: true
|
||||
type: string
|
||||
contract_version:
|
||||
description: Exact version ID of the reviewed contract
|
||||
required: true
|
||||
type: string
|
||||
contract_sha256:
|
||||
description: SHA-256 of the exact reviewed contract bytes
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
AWS_REGION: us-east-1
|
||||
TF_IN_AUTOMATION: "1"
|
||||
TF_INPUT: "0"
|
||||
|
||||
jobs:
|
||||
check:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
- run: shellcheck .github/scripts/runtime-tls*.sh
|
||||
- run: |
|
||||
for suite in .github/scripts/runtime-tls*.test.sh; do
|
||||
bash "$suite"
|
||||
done
|
||||
|
||||
plan:
|
||||
needs: check
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
runs-on: ubuntu-latest
|
||||
environment: aws-infrastructure-plan
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
attestations: read
|
||||
id-token: write
|
||||
outputs:
|
||||
digest: ${{ steps.plan.outputs.digest }}
|
||||
release: ${{ steps.plan.outputs.release }}
|
||||
steps:
|
||||
- name: Require an explicitly enabled new main run
|
||||
env:
|
||||
RECOVERY_ENABLED: ${{ vars.AWS_TLS_RECOVERY_ENABLED }}
|
||||
EVIDENCE_ROLE: ${{ vars.AWS_TLS_RECOVERY_EVIDENCE_ROLE_ARN }}
|
||||
run: |
|
||||
[ "$GITHUB_REF" = refs/heads/main ]
|
||||
[ "$GITHUB_RUN_ATTEMPT" = 1 ]
|
||||
[ "$RECOVERY_ENABLED" = true ]
|
||||
[ "$EVIDENCE_ROLE" = arn:aws:iam::925323749693:role/warmbly-production-tls-recovery-evidence ]
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
fetch-depth: 0
|
||||
- uses: hashicorp/setup-terraform@v3
|
||||
with:
|
||||
terraform_version: "1.16.5"
|
||||
terraform_wrapper: false
|
||||
- uses: aws-actions/configure-aws-credentials@v4
|
||||
with:
|
||||
role-to-assume: ${{ vars.AWS_TERRAFORM_PLAN_ROLE_ARN }}
|
||||
aws-region: us-east-1
|
||||
- id: plan
|
||||
env:
|
||||
WORK: ${{ runner.temp }}/runtime-tls-recovery-plan
|
||||
CONTRACT_KEY: ${{ inputs.contract_key }}
|
||||
CONTRACT_VERSION: ${{ inputs.contract_version }}
|
||||
CONTRACT_SHA256: ${{ inputs.contract_sha256 }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: bash .github/scripts/runtime-tls-recovery-execute.sh plan
|
||||
- uses: aws-actions/configure-aws-credentials@v4
|
||||
if: always() && steps.plan.outcome != 'skipped'
|
||||
with:
|
||||
role-to-assume: ${{ vars.AWS_TLS_RECOVERY_EVIDENCE_ROLE_ARN }}
|
||||
aws-region: us-east-1
|
||||
- name: Preserve full private plan evidence
|
||||
if: always() && steps.plan.outcome != 'skipped'
|
||||
env:
|
||||
WORK: ${{ runner.temp }}/runtime-tls-recovery-plan
|
||||
run: bash .github/scripts/runtime-tls-recovery-archive.sh plan
|
||||
|
||||
apply:
|
||||
needs: plan
|
||||
runs-on: ubuntu-latest
|
||||
environment: aws-infrastructure-approval
|
||||
concurrency:
|
||||
group: aws-production
|
||||
cancel-in-progress: false
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
attestations: read
|
||||
id-token: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
fetch-depth: 0
|
||||
- uses: hashicorp/setup-terraform@v3
|
||||
with:
|
||||
terraform_version: "1.16.5"
|
||||
terraform_wrapper: false
|
||||
- uses: aws-actions/configure-aws-credentials@v4
|
||||
with:
|
||||
role-to-assume: ${{ vars.AWS_TERRAFORM_APPLY_ROLE_ARN }}
|
||||
aws-region: us-east-1
|
||||
- id: apply
|
||||
env:
|
||||
WORK: ${{ runner.temp }}/runtime-tls-recovery-apply
|
||||
CONTRACT_KEY: ${{ inputs.contract_key }}
|
||||
CONTRACT_VERSION: ${{ inputs.contract_version }}
|
||||
CONTRACT_SHA256: ${{ inputs.contract_sha256 }}
|
||||
APPROVED_DIGEST: ${{ needs.plan.outputs.digest }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: bash .github/scripts/runtime-tls-recovery-execute.sh apply
|
||||
- uses: aws-actions/configure-aws-credentials@v4
|
||||
if: always() && steps.apply.outcome != 'skipped'
|
||||
with:
|
||||
role-to-assume: ${{ vars.AWS_TLS_RECOVERY_EVIDENCE_ROLE_ARN }}
|
||||
aws-region: us-east-1
|
||||
- name: Preserve full private apply evidence
|
||||
if: always() && steps.apply.outcome != 'skipped'
|
||||
env:
|
||||
WORK: ${{ runner.temp }}/runtime-tls-recovery-apply
|
||||
run: bash .github/scripts/runtime-tls-recovery-archive.sh apply
|
||||
|
||||
redeploy:
|
||||
needs: [plan, apply]
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
attestations: read
|
||||
uses: ./.github/workflows/deploy-aws.yml
|
||||
with:
|
||||
tag: ${{ needs.plan.outputs.release }}
|
||||
mode: redeploy
|
||||
services: all
|
||||
fleet: false
|
||||
require_attestation: true
|
||||
bake_seconds: "300"
|
||||
secrets: inherit
|
||||
|
||||
verify:
|
||||
needs: redeploy
|
||||
runs-on: ubuntu-latest
|
||||
environment: aws-infrastructure-plan
|
||||
concurrency:
|
||||
group: aws-production
|
||||
cancel-in-progress: false
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
attestations: read
|
||||
id-token: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
fetch-depth: 0
|
||||
- uses: aws-actions/configure-aws-credentials@v4
|
||||
with:
|
||||
role-to-assume: ${{ vars.AWS_TERRAFORM_PLAN_ROLE_ARN }}
|
||||
aws-region: us-east-1
|
||||
- id: verify
|
||||
env:
|
||||
WORK: ${{ runner.temp }}/runtime-tls-recovery-verify
|
||||
CONTRACT_KEY: ${{ inputs.contract_key }}
|
||||
CONTRACT_VERSION: ${{ inputs.contract_version }}
|
||||
CONTRACT_SHA256: ${{ inputs.contract_sha256 }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: bash .github/scripts/runtime-tls-recovery-execute.sh verify
|
||||
- uses: aws-actions/configure-aws-credentials@v4
|
||||
if: always() && steps.verify.outcome != 'skipped'
|
||||
with:
|
||||
role-to-assume: ${{ vars.AWS_TLS_RECOVERY_EVIDENCE_ROLE_ARN }}
|
||||
aws-region: us-east-1
|
||||
- name: Preserve full private final evidence
|
||||
if: always() && steps.verify.outcome != 'skipped'
|
||||
env:
|
||||
WORK: ${{ runner.temp }}/runtime-tls-recovery-verify
|
||||
run: bash .github/scripts/runtime-tls-recovery-archive.sh verify
|
||||
@@ -0,0 +1,135 @@
|
||||
name: Finalize runtime TLS
|
||||
run-name: Runtime TLS ${{ inputs.stage }} ${{ inputs.release }}
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
vars_version:
|
||||
description: S3 version ID of the reviewed runtime-tls.tfvars.json snapshot at the previous stage
|
||||
required: true
|
||||
type: string
|
||||
stage:
|
||||
description: Advance one verified stage while preserving the previous traffic path
|
||||
required: true
|
||||
default: route
|
||||
type: choice
|
||||
options: ["route", "drain", "on"]
|
||||
previous_run:
|
||||
description: Successful preceding stage workflow run ID (required for drain and on)
|
||||
required: false
|
||||
type: string
|
||||
release:
|
||||
description: Currently deployed release, retained for the service redeploy
|
||||
required: true
|
||||
type: string
|
||||
pull_request:
|
||||
paths:
|
||||
- '.github/workflows/runtime-tls.yml'
|
||||
- '.github/scripts/runtime-tls*'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
AWS_REGION: us-east-1
|
||||
TF_IN_AUTOMATION: "1"
|
||||
TF_INPUT: "0"
|
||||
|
||||
jobs:
|
||||
check:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
- run: shellcheck .github/scripts/runtime-tls.sh .github/scripts/runtime-tls.test.sh
|
||||
- run: bash .github/scripts/runtime-tls.test.sh
|
||||
- run: shellcheck .github/scripts/runtime-tls-recovery.sh .github/scripts/runtime-tls-recovery.test.sh
|
||||
- run: bash .github/scripts/runtime-tls-recovery.test.sh
|
||||
- run: shellcheck .github/scripts/runtime-tls-recovery-lineage.sh .github/scripts/runtime-tls-recovery-lineage.test.sh
|
||||
- run: bash .github/scripts/runtime-tls-recovery-lineage.test.sh
|
||||
- run: shellcheck .github/scripts/runtime-tls-recovery-inputs.sh .github/scripts/runtime-tls-recovery-inputs.test.sh
|
||||
- run: bash .github/scripts/runtime-tls-recovery-inputs.test.sh
|
||||
|
||||
plan:
|
||||
needs: check
|
||||
if: github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main'
|
||||
runs-on: ubuntu-latest
|
||||
environment: aws-infrastructure-plan
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
actions: read
|
||||
outputs:
|
||||
digest: ${{ steps.plan.outputs.digest }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: hashicorp/setup-terraform@v3
|
||||
with:
|
||||
terraform_version: "1.16.5"
|
||||
terraform_wrapper: false
|
||||
- uses: aws-actions/configure-aws-credentials@v4
|
||||
with:
|
||||
role-to-assume: ${{ vars.AWS_TERRAFORM_PLAN_ROLE_ARN }}
|
||||
aws-region: us-east-1
|
||||
- id: plan
|
||||
env:
|
||||
STATE_BUCKET: ${{ vars.AWS_TERRAFORM_STATE_BUCKET }}
|
||||
WORK: ${{ runner.temp }}/runtime-tls
|
||||
VARS_VERSION: ${{ inputs.vars_version }}
|
||||
RELEASE: ${{ inputs.release }}
|
||||
STAGE: ${{ inputs.stage }}
|
||||
PREVIOUS_RUN: ${{ inputs.previous_run }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: .github/scripts/runtime-tls.sh plan
|
||||
|
||||
apply:
|
||||
needs: plan
|
||||
runs-on: ubuntu-latest
|
||||
environment: aws-infrastructure-approval
|
||||
concurrency:
|
||||
group: aws-production
|
||||
cancel-in-progress: false
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
actions: read
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: hashicorp/setup-terraform@v3
|
||||
with:
|
||||
terraform_version: "1.16.5"
|
||||
terraform_wrapper: false
|
||||
- uses: aws-actions/configure-aws-credentials@v4
|
||||
with:
|
||||
role-to-assume: ${{ vars.AWS_TERRAFORM_APPLY_ROLE_ARN }}
|
||||
aws-region: us-east-1
|
||||
- env:
|
||||
STATE_BUCKET: ${{ vars.AWS_TERRAFORM_STATE_BUCKET }}
|
||||
WORK: ${{ runner.temp }}/runtime-tls
|
||||
VARS_VERSION: ${{ inputs.vars_version }}
|
||||
RELEASE: ${{ inputs.release }}
|
||||
APPROVED_DIGEST: ${{ needs.plan.outputs.digest }}
|
||||
STAGE: ${{ inputs.stage }}
|
||||
PREVIOUS_RUN: ${{ inputs.previous_run }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: .github/scripts/runtime-tls.sh apply
|
||||
|
||||
redeploy:
|
||||
needs: apply
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
attestations: read
|
||||
uses: ./.github/workflows/deploy-aws.yml
|
||||
with:
|
||||
tag: ${{ inputs.release }}
|
||||
mode: redeploy
|
||||
services: backend,forms,tracking,realtime
|
||||
fleet: false
|
||||
require_attestation: true
|
||||
secrets: inherit
|
||||
@@ -0,0 +1,125 @@
|
||||
name: Publish released static assets
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
release_tag:
|
||||
description: Existing stable release tag to rebuild (no new release)
|
||||
required: true
|
||||
type: string
|
||||
expected_sha:
|
||||
description: Full commit SHA of that release
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: release
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
targets:
|
||||
if: github.ref == 'refs/heads/main' && vars.CLOUDFLARE_STATIC_ASSETS_DEPLOY_ENABLED == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
matrix: ${{ steps.targets.outputs.matrix }}
|
||||
enabled: ${{ steps.targets.outputs.enabled }}
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: "22"
|
||||
- run: node --test .github/scripts/pages-*.test.mjs
|
||||
- id: targets
|
||||
env:
|
||||
CLOUDFLARE_PAGES_PROJECTS: ${{ vars.CLOUDFLARE_PAGES_PROJECTS }}
|
||||
CLOUDFLARE_STATIC_ASSETS_TARGETS: ${{ vars.CLOUDFLARE_STATIC_ASSETS_TARGETS }}
|
||||
run: node .github/scripts/pages-static-assets.mjs
|
||||
|
||||
publish:
|
||||
needs: targets
|
||||
if: needs.targets.outputs.enabled == 'true'
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix: ${{ fromJSON(needs.targets.outputs.matrix) }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
environment: ${{ matrix.environment }}
|
||||
env:
|
||||
PAGES_APP: ${{ matrix.app }}
|
||||
CLOUDFLARE_PAGES_PROJECT_NAME: ${{ matrix.project }}
|
||||
SOURCE_SHA: ${{ inputs.expected_sha }}
|
||||
RELEASE_TAG: ${{ inputs.release_tag }}
|
||||
WRANGLER_SEND_METRICS: "false"
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
- name: Pin the existing release source
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
[[ "$RELEASE_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]
|
||||
[[ "$SOURCE_SHA" =~ ^[0-9a-f]{40}$ ]]
|
||||
gh release view "$RELEASE_TAG" --json isDraft,isPrerelease,publishedAt \
|
||||
| jq -e '.isDraft == false and .isPrerelease == false and .publishedAt != null' >/dev/null
|
||||
test "$(git rev-parse "refs/tags/$RELEASE_TAG^{commit}")" = "$SOURCE_SHA"
|
||||
git merge-base --is-ancestor "$SOURCE_SHA" origin/main
|
||||
if ! git cat-file -e "$SOURCE_SHA:.github/scripts/pages-production-config.mjs"; then
|
||||
echo '::error::Release does not support public Pages configuration import; select a supported release.'
|
||||
exit 1
|
||||
fi
|
||||
git worktree add --detach "$RUNNER_TEMP/frontend-source" "$SOURCE_SHA"
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: "22"
|
||||
- name: Load existing public frontend configuration
|
||||
env:
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
CLOUDFLARE_PAGES_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
|
||||
run: |
|
||||
test -n "$CLOUDFLARE_API_TOKEN"
|
||||
test -n "$CLOUDFLARE_PAGES_ACCOUNT_ID"
|
||||
curl --fail --silent --show-error \
|
||||
--header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
|
||||
"https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_PAGES_ACCOUNT_ID/pages/projects/$CLOUDFLARE_PAGES_PROJECT_NAME" \
|
||||
| node "$RUNNER_TEMP/frontend-source/.github/scripts/pages-production-config.mjs"
|
||||
- uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1 # v4
|
||||
with:
|
||||
version: "11.9.0"
|
||||
- name: Build the released frontend artifact
|
||||
env:
|
||||
APP_DIRECTORY: ${{ matrix.directory }}
|
||||
BUILD_SCRIPT: ${{ matrix.build_script }}
|
||||
VITE_SENTRY_RELEASE: ${{ inputs.release_tag }}
|
||||
run: |
|
||||
cd "$RUNNER_TEMP/frontend-source/$APP_DIRECTORY"
|
||||
pnpm install --frozen-lockfile
|
||||
pnpm run "$BUILD_SCRIPT"
|
||||
- name: Prepare the configured static asset deployment
|
||||
env:
|
||||
CLOUDFLARE_PAGES_PROJECTS: ${{ vars.CLOUDFLARE_PAGES_PROJECTS }}
|
||||
CLOUDFLARE_STATIC_ASSETS_TARGETS: ${{ vars.CLOUDFLARE_STATIC_ASSETS_TARGETS }}
|
||||
run: |
|
||||
export STATIC_ASSETS_ARTIFACT_DIR="$RUNNER_TEMP/static-assets"
|
||||
cd "$RUNNER_TEMP/frontend-source"
|
||||
node "$GITHUB_WORKSPACE/.github/scripts/pages-static-assets.mjs" prepare
|
||||
- name: Publish assets without a request Worker
|
||||
env:
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_STATIC_ASSETS_ACCOUNT_ID }}
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_STATIC_ASSETS_API_TOKEN }}
|
||||
run: |
|
||||
test -n "$CLOUDFLARE_ACCOUNT_ID"
|
||||
test -n "$CLOUDFLARE_API_TOKEN"
|
||||
pnpm dlx wrangler@4.45.0 deploy --config "$RUNNER_TEMP/static-assets/wrangler.json"
|
||||
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: static-assets-${{ matrix.project }}-${{ inputs.release_tag }}-${{ github.run_id }}
|
||||
path: ${{ runner.temp }}/static-assets
|
||||
include-hidden-files: true
|
||||
retention-days: 30
|
||||
@@ -1,21 +1,21 @@
|
||||
name: Terraform AWS
|
||||
|
||||
# Pull requests get a plan summary comment. On main, a stack whose plan only
|
||||
# creates or updates applies on its own; one that replaces or destroys waits in
|
||||
# the aws-infrastructure-approval environment. Var files live in the private
|
||||
# creates or updates applies on its own; destructive or protected evidence IAM
|
||||
# changes wait in aws-infrastructure-approval. Var files live in the private
|
||||
# state bucket, and no plan body ever reaches a log, a comment or an artifact.
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- 'deploy/terraform/aws/**'
|
||||
- '.github/workflows/terraform-aws.yml'
|
||||
- '.github/scripts/terraform-stack.sh'
|
||||
- '.github/scripts/terraform-stack*.sh'
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- 'deploy/terraform/aws/**'
|
||||
- '.github/workflows/terraform-aws.yml'
|
||||
- '.github/scripts/terraform-stack.sh'
|
||||
- '.github/scripts/terraform-stack*.sh'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -42,11 +42,16 @@ jobs:
|
||||
- name: Validate
|
||||
run: |
|
||||
set -euo pipefail
|
||||
for stack in bootstrap foundation runtime workers; do
|
||||
for stack in bootstrap foundation runtime workers nats; do
|
||||
terraform -chdir="deploy/terraform/aws/$stack" init -backend=false -input=false >/dev/null
|
||||
terraform -chdir="deploy/terraform/aws/$stack" validate -no-color
|
||||
done
|
||||
- run: shellcheck .github/scripts/terraform-stack.sh
|
||||
# Mocked provider: no credentials, nothing created.
|
||||
- run: terraform -chdir=deploy/terraform/aws/runtime test -no-color
|
||||
- run: terraform -chdir=deploy/terraform/aws/workers test -no-color
|
||||
- run: node --test deploy/terraform/aws/runtime/checks/credentials.test.cjs
|
||||
- run: shellcheck .github/scripts/terraform-stack*.sh
|
||||
- run: bash .github/scripts/terraform-stack.test.sh
|
||||
|
||||
plan:
|
||||
name: Plan summary
|
||||
@@ -90,7 +95,7 @@ jobs:
|
||||
case "$class" in
|
||||
none) echo "**$stack**: no changes" ;;
|
||||
safe) echo "**$stack**: applies on merge" ;;
|
||||
gated) echo "**$stack**: replaces or destroys, so it waits for approval in aws-infrastructure-approval" ;;
|
||||
gated) echo "**$stack**: destructive or protected IAM changes wait for approval in aws-infrastructure-approval" ;;
|
||||
esac
|
||||
if [ "$class" != none ]; then
|
||||
echo '```'
|
||||
|
||||
@@ -32,6 +32,12 @@ linters-settings:
|
||||
|
||||
issues:
|
||||
exclude-rules:
|
||||
# Keep the pinned upstream reader tests byte-for-byte.
|
||||
- path: ^internal/pkg/boundedcsv/reader_test\.go$
|
||||
text: 'deepequalerrors: avoid using reflect\.DeepEqual with errors'
|
||||
linters:
|
||||
- govet
|
||||
|
||||
- path: _test\.go
|
||||
linters:
|
||||
- errcheck
|
||||
|
||||
@@ -255,7 +255,7 @@ Record proof only for a UI change a reviewer should actually see; most changes n
|
||||
|
||||
## Security And Compliance Invariants
|
||||
|
||||
Warmbly's Google OAuth client is assessed against **ADA CASA v2.1.1 at Assurance Level 1**, which maps to OWASP ASVS 4.0.3. The evidence pack is a claim about the code on `main`: a change that breaks one of the invariants below does not just introduce a bug, it makes a submitted statement untrue and puts the OAuth client's verification at risk. Treat them as constraints on every change, not as a checklist run before an audit.
|
||||
Warmbly's security invariants are written against **ADA CASA v2.1.1 at Assurance Level 1**, which maps to OWASP ASVS 4.0.3. The Google OAuth client is in production but unverified and has not been assessed: it is held to Google's 100-new-user cap, except on Workspace domains whose admin marks it Trusted, which is how Workspace and reseller mailboxes connect. The evidence pack is a claim about the code on `main`: a change that breaks one of the invariants below does not just introduce a bug, it makes the pack untrue and puts any future verification at risk. Treat them as constraints on every change, not as a checklist run before an audit.
|
||||
|
||||
**The pack is not in this repository and must not be added to it.** It maps every control to the file that implements it and lists the advisories still open with the exact conditions under which each is reachable. That is a reconnaissance document for anyone attacking a self-hosted instance that has not updated, which is the same reason the disclosure rule below exists. It lives outside the tree, at `CASA_EVIDENCE_DIR` (default `~/warmbly-casa-private/casa`), and `make casa-evidence` refuses to write anywhere inside the repository.
|
||||
|
||||
@@ -557,7 +557,7 @@ Migration 000156 guarantees exactly one pool per type on every instance, under `
|
||||
|
||||
Crossing tiers is an exchange and lives in one place: `WarmupPartnerCandidates` in `pg_warmup.go` returns a sender's own tier plus, when the sender has fewer recipients outside its own workspace than `max(WarmupPoolTierFallbackFloor, warmup_max)`, that many proven free mailboxes from other workspaces (healthy, never blocked, members for `WarmupPoolFallbackMinAgeDays`, workspace not restricted or suspended), best first (Google or Microsoft, then members for `WarmupPoolBorrowSeasonedDays`, then actively sending; random within a rank), and for a free sender that meets the same bar, the premium mailboxes that verifiably wrote to it within `WarmupPoolReturnVisitDays`. Siblings never count toward the floor: a customer with many mailboxes and few premium peers otherwise never borrows and warms against itself. `models.WarmupPoolBorrowsFrom` and `models.WarmupPoolReturnsTo` are the two directions and mirror each other, so nothing unsolicited from the free tier reaches a paying inbox: the paying side always opens the exchange. Before this half existed a thin premium tier sent into the free tier and received almost nothing (#633). Every candidate carries the pool it was drawn from (`PoolType`) and how it got there (`Origin`); the selector and the scheduler both read that one method, so they cannot disagree about who is reachable. A routing rule of weight 0 is an exclusion, not a weight: the candidate is dropped before the draw (and refused on the reply-back path), so a pool of one cannot smuggle it back, and a tick with nothing left ends in `errAllPartnersExcluded` rather than mailing an excluded address (#501). The selector draws its own tier's fresh partners before a borrowed one, but a return visit ranks with the own tier, or a free mailbox with a hundred fresh siblings would never pay a paying inbox back. Every candidate is gated with `CanParticipate` pinned to the pool it was drawn from; gating a borrowed recipient against the sender's pool is what made borrowing dead for months (#495). The reply-back (`directedWarmupPartner`) crosses tiers on the same terms (a free mailbox answers a paid one only while healthy, the bar the return cohort holds it to) and is refused when the free workspace is restricted. It crosses on `CanParticipate`'s `not_in_pool`, so that reason must stay distinct from an ineligible member, or every cross-tier reply is closed unsent.
|
||||
|
||||
Reciprocity is a weight and a cap, both read off the candidate. Each carries its verified sends and arrivals over seven days; `Starvation` (how far behind an inbox is on what it sent) multiplies its draw weight by up to `1 + reciprocityBoostK`, fading to nothing at parity, so the pool's traffic flows to whoever is owed the most and settles there instead of overshooting. `InboundDailyCap` (`WarmupInboundDailyMultiple` times daily sends, between `WarmupInboundDailyFloor` and `WarmupInboundDailyCeiling`) is applied inside `WarmupPartnerCandidates`, and a free sender sees every inbox as full at `WarmupFreeInboundSharePercent` of it, so the rest of each inbox's day is kept for premium senders. A recipient at its cap is offered to nobody for the rest of the day and the scheduler's per-day volume cap (`min(target, len(candidates))`) sees the same set. A sender with nobody left to write to sends nothing that tick and rechecks later; do not add a fallback that mails somebody anyway.
|
||||
Reciprocity is a weight and a cap, both read off the candidate. Each carries its verified sends and arrivals over seven days; `Starvation` (how far behind an inbox is on what it sent) multiplies its draw weight by up to `1 + reciprocityBoostK`, fading to nothing at parity, so the pool's traffic flows to whoever is owed the most and settles there instead of overshooting. `InboundDailyCap` (`WarmupInboundDailyMultiple` times daily sends, between `WarmupInboundDailyFloor` and `WarmupInboundDailyCeiling`) is applied inside `WarmupPartnerCandidates`, and a free sender sees every inbox as full at `WarmupFreeInboundSharePercent` of it, so the rest of each inbox's day is kept for premium senders. The cap counts new threads only: a reply answers mail its recipient sent, so it is neither refused by the cap nor counted against it (`newThreadSQL`), and a reply to a full inbox is sent, not closed. A recipient at its cap is offered to nobody for the rest of the day and the scheduler's per-day volume cap (`min(target, len(candidates))`) sees the same set. A sender with nobody left to write to sends nothing that tick and rechecks later; do not add a fallback that mails somebody anyway.
|
||||
|
||||
Reachability is read off the same candidate: `Delivered7d` is the pool's handed-off warmup mail to it (past `config.WarmupRecipientArrivalGraceHours`) and `Arrived7d` what its own sync verified (`warmup_tokens.consumed_at`). The draw multiplies by `ArrivalRate`, and `models.WarmupRecipientUnreachable` (none arrived, at least `WarmupRecipientUnreachableMinDelivered` from at least `WarmupRecipientUnreachableMinSenderOrgs` workspaces) drops the candidate in `capPartnerCandidates`, so the selector, the scheduler and the counts agree, and the Advisor's `warmup_mail_not_arriving` reads the same rule. A send the sender's provider accepted and later bounced looks like success to the worker, so arrival, not the send result, is the evidence. Keep the two-workspace floor: without it one broken sender takes its recipients out of the pool.
|
||||
|
||||
|
||||
@@ -697,10 +697,16 @@ consumer:
|
||||
#
|
||||
# The worker reads encrypted DEKs through the backend's /internal/dek
|
||||
# endpoint (the prod `http` provider, no worker DB), so `make backend`
|
||||
# must be running and INTERNAL_API_TOKEN must match.
|
||||
# must be running and INTERNAL_API_TOKEN must match. The seeded dev worker
|
||||
# also presents its own NODE_CREDENTIAL (internal/seed.DevNodeCredential), so it
|
||||
# keeps working with NODE_REQUIRE_NODE_CREDENTIAL=true on the backend.
|
||||
DEV_WORKER_ID := 10c8f5e4-1c39-5b2a-9c8b-3d2f0a8b1a01
|
||||
NODE_CREDENTIAL_DEV := dev-node-credential-not-for-production
|
||||
WORKER_ID ?= $(DEV_WORKER_ID)
|
||||
worker:
|
||||
$(WORKER_DEV_ENV) \
|
||||
WORKER_ID=10c8f5e4-1c39-5b2a-9c8b-3d2f0a8b1a01 \
|
||||
WORKER_ID=$(WORKER_ID) \
|
||||
$(if $(filter $(DEV_WORKER_ID),$(WORKER_ID)),NODE_CREDENTIAL=$(NODE_CREDENTIAL_DEV),) \
|
||||
ENCRYPTED_KEYS_PROVIDER=http \
|
||||
ENCRYPTED_KEYS_BACKEND_URL=http://localhost:8080 \
|
||||
ENCRYPTED_KEYS_WORKER_TOKEN=local-dev-internal-token \
|
||||
|
||||
Generated
+116
-112
@@ -9,8 +9,8 @@ overrides:
|
||||
js-yaml: ^4.3.1
|
||||
nanoid: ^3.3.17
|
||||
dompurify: ^3.4.17
|
||||
follow-redirects: ^1.16.1
|
||||
seroval: ^1.6.3
|
||||
follow-redirects: ^1.16.2
|
||||
seroval: ^1.6.11
|
||||
source-map-js: ^1.2.2
|
||||
|
||||
importers:
|
||||
@@ -67,7 +67,7 @@ importers:
|
||||
version: 5.103.1(@tanstack/react-query@5.103.1(react@19.3.0))(@types/react@19.3.0)(csstype@3.2.3)(react@19.3.0)
|
||||
axios:
|
||||
specifier: ^1.20.0
|
||||
version: 1.20.0
|
||||
version: 1.20.0(debug@4.4.3(supports-color@7.2.0))(supports-color@7.2.0)
|
||||
class-variance-authority:
|
||||
specifier: ^0.7.1
|
||||
version: 0.7.1
|
||||
@@ -119,7 +119,7 @@ importers:
|
||||
version: 9.39.5
|
||||
'@sentry/vite-plugin':
|
||||
specifier: ^5.4.0
|
||||
version: 5.4.0(rollup@4.65.0)
|
||||
version: 5.4.0(rollup@4.65.0)(supports-color@7.2.0)
|
||||
'@types/node':
|
||||
specifier: ^24.13.5
|
||||
version: 24.13.5
|
||||
@@ -131,22 +131,22 @@ importers:
|
||||
version: 19.3.0(@types/react@19.3.0)
|
||||
'@vitejs/plugin-react':
|
||||
specifier: ^5.2.0
|
||||
version: 5.2.0(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0))
|
||||
version: 5.2.0(supports-color@7.2.0)(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0))
|
||||
eslint:
|
||||
specifier: ^9.39.5
|
||||
version: 9.39.5(jiti@2.7.0)
|
||||
version: 9.39.5(jiti@2.7.0)(supports-color@7.2.0)
|
||||
eslint-plugin-react-hooks:
|
||||
specifier: ^5.2.0
|
||||
version: 5.2.0(eslint@9.39.5(jiti@2.7.0))
|
||||
version: 5.2.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))
|
||||
eslint-plugin-react-refresh:
|
||||
specifier: ^0.4.26
|
||||
version: 0.4.26(eslint@9.39.5(jiti@2.7.0))
|
||||
version: 0.4.26(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))
|
||||
globals:
|
||||
specifier: ^16.5.0
|
||||
version: 16.5.0
|
||||
jsdom:
|
||||
specifier: ^27.4.0
|
||||
version: 27.4.0
|
||||
version: 27.4.0(supports-color@7.2.0)
|
||||
tw-animate-css:
|
||||
specifier: ^1.4.0
|
||||
version: 1.4.0
|
||||
@@ -155,13 +155,13 @@ importers:
|
||||
version: 5.9.3
|
||||
typescript-eslint:
|
||||
specifier: ^8.70.0
|
||||
version: 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3)
|
||||
version: 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)
|
||||
vite:
|
||||
specifier: ^7.3.7
|
||||
version: 7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)
|
||||
vitest:
|
||||
specifier: ^4.1.11
|
||||
version: 4.1.11(@types/node@24.13.5)(jsdom@27.4.0)(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0))
|
||||
version: 4.1.11(@types/node@24.13.5)(jsdom@27.4.0(supports-color@7.2.0))(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0))
|
||||
|
||||
packages:
|
||||
|
||||
@@ -1889,8 +1889,8 @@ packages:
|
||||
flatted@3.4.4:
|
||||
resolution: {integrity: sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==}
|
||||
|
||||
follow-redirects@1.16.1:
|
||||
resolution: {integrity: sha512-FNvFGzoMLWmE6Yj9spb/zjd7yiNCHiAW9/Tg9CXrQ8wuu32HtlJOwWO11OJafl5FfY3DxTdQ0vj42zU1kvv5jg==}
|
||||
follow-redirects@1.16.2:
|
||||
resolution: {integrity: sha512-/kVP2U8z596Ia0gwFrwyIeo74ta5aVmSeU1FfAUMAmcEP5EP7zydmag3SLiN64NaRKef3lxsq7i/g7ltJQDGow==}
|
||||
engines: {node: '>=4.0'}
|
||||
peerDependencies:
|
||||
debug: '*'
|
||||
@@ -2440,11 +2440,11 @@ packages:
|
||||
resolution: {integrity: sha512-HXuLAX2pu/UByPpaeo/TaMfvMIi+1QqIoPJYCcAtU8QkVNwgR6MPlGuCQTErV1JwraaMbYaWVIBX7mppzGLATQ==}
|
||||
engines: {node: '>=10'}
|
||||
peerDependencies:
|
||||
seroval: ^1.6.3
|
||||
seroval: ^1.6.11
|
||||
|
||||
seroval@1.6.8:
|
||||
resolution: {integrity: sha512-HlSgSAkTk4EqHcje1ptJjfZi1YDv5KbhVJ/d3P7T/nAXua2VmDu+AKDX5VTdFfZf48nDkWB2TKYt0DrCSa+3wg==}
|
||||
engines: {node: '>=10'}
|
||||
seroval@1.7.5:
|
||||
resolution: {integrity: sha512-UdNgpHdq0gVpme5JdQF+S3jNscnjFr4NTwUWOc1qcOa8OuWZmbV0+YX2hsqxkUZshBpHnpxDZfAKVZG2ugbrJA==}
|
||||
engines: {node: '>=20'}
|
||||
|
||||
set-cookie-parser@2.7.2:
|
||||
resolution: {integrity: sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==}
|
||||
@@ -2800,20 +2800,20 @@ snapshots:
|
||||
|
||||
'@babel/compat-data@7.29.7': {}
|
||||
|
||||
'@babel/core@7.29.7':
|
||||
'@babel/core@7.29.7(supports-color@7.2.0)':
|
||||
dependencies:
|
||||
'@babel/code-frame': 7.29.7
|
||||
'@babel/generator': 7.29.8
|
||||
'@babel/helper-compilation-targets': 7.29.7
|
||||
'@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7)
|
||||
'@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7(supports-color@7.2.0))(supports-color@7.2.0)
|
||||
'@babel/helpers': 7.29.7
|
||||
'@babel/parser': 7.29.8
|
||||
'@babel/template': 7.29.7
|
||||
'@babel/traverse': 7.29.8
|
||||
'@babel/traverse': 7.29.8(supports-color@7.2.0)
|
||||
'@babel/types': 7.29.8
|
||||
'@jridgewell/remapping': 2.3.5
|
||||
convert-source-map: 2.0.0
|
||||
debug: 4.4.3
|
||||
debug: 4.4.3(supports-color@7.2.0)
|
||||
gensync: 1.0.0-beta.2
|
||||
json5: 2.2.3
|
||||
semver: 6.3.1
|
||||
@@ -2838,19 +2838,19 @@ snapshots:
|
||||
|
||||
'@babel/helper-globals@7.29.7': {}
|
||||
|
||||
'@babel/helper-module-imports@7.29.7':
|
||||
'@babel/helper-module-imports@7.29.7(supports-color@7.2.0)':
|
||||
dependencies:
|
||||
'@babel/traverse': 7.29.8
|
||||
'@babel/traverse': 7.29.8(supports-color@7.2.0)
|
||||
'@babel/types': 7.29.8
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
'@babel/helper-module-transforms@7.29.7(@babel/core@7.29.7)':
|
||||
'@babel/helper-module-transforms@7.29.7(@babel/core@7.29.7(supports-color@7.2.0))(supports-color@7.2.0)':
|
||||
dependencies:
|
||||
'@babel/core': 7.29.7
|
||||
'@babel/helper-module-imports': 7.29.7
|
||||
'@babel/core': 7.29.7(supports-color@7.2.0)
|
||||
'@babel/helper-module-imports': 7.29.7(supports-color@7.2.0)
|
||||
'@babel/helper-validator-identifier': 7.29.7
|
||||
'@babel/traverse': 7.29.8
|
||||
'@babel/traverse': 7.29.8(supports-color@7.2.0)
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
@@ -2871,14 +2871,14 @@ snapshots:
|
||||
dependencies:
|
||||
'@babel/types': 7.29.8
|
||||
|
||||
'@babel/plugin-transform-react-jsx-self@7.29.7(@babel/core@7.29.7)':
|
||||
'@babel/plugin-transform-react-jsx-self@7.29.7(@babel/core@7.29.7(supports-color@7.2.0))':
|
||||
dependencies:
|
||||
'@babel/core': 7.29.7
|
||||
'@babel/core': 7.29.7(supports-color@7.2.0)
|
||||
'@babel/helper-plugin-utils': 7.29.7
|
||||
|
||||
'@babel/plugin-transform-react-jsx-source@7.29.7(@babel/core@7.29.7)':
|
||||
'@babel/plugin-transform-react-jsx-source@7.29.7(@babel/core@7.29.7(supports-color@7.2.0))':
|
||||
dependencies:
|
||||
'@babel/core': 7.29.7
|
||||
'@babel/core': 7.29.7(supports-color@7.2.0)
|
||||
'@babel/helper-plugin-utils': 7.29.7
|
||||
|
||||
'@babel/template@7.29.7':
|
||||
@@ -2887,7 +2887,7 @@ snapshots:
|
||||
'@babel/parser': 7.29.8
|
||||
'@babel/types': 7.29.8
|
||||
|
||||
'@babel/traverse@7.29.8':
|
||||
'@babel/traverse@7.29.8(supports-color@7.2.0)':
|
||||
dependencies:
|
||||
'@babel/code-frame': 7.29.7
|
||||
'@babel/generator': 7.29.8
|
||||
@@ -2895,7 +2895,7 @@ snapshots:
|
||||
'@babel/parser': 7.29.8
|
||||
'@babel/template': 7.29.7
|
||||
'@babel/types': 7.29.8
|
||||
debug: 4.4.3
|
||||
debug: 4.4.3(supports-color@7.2.0)
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
@@ -3011,17 +3011,17 @@ snapshots:
|
||||
'@esbuild/win32-x64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@eslint-community/eslint-utils@4.10.1(eslint@9.39.5(jiti@2.7.0))':
|
||||
'@eslint-community/eslint-utils@4.10.1(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))':
|
||||
dependencies:
|
||||
eslint: 9.39.5(jiti@2.7.0)
|
||||
eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0)
|
||||
eslint-visitor-keys: 3.4.3
|
||||
|
||||
'@eslint-community/regexpp@4.12.2': {}
|
||||
|
||||
'@eslint/config-array@0.21.2':
|
||||
'@eslint/config-array@0.21.2(supports-color@7.2.0)':
|
||||
dependencies:
|
||||
'@eslint/object-schema': 2.1.7
|
||||
debug: 4.4.3
|
||||
debug: 4.4.3(supports-color@7.2.0)
|
||||
minimatch: 3.1.5
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
@@ -3034,10 +3034,10 @@ snapshots:
|
||||
dependencies:
|
||||
'@types/json-schema': 7.0.15
|
||||
|
||||
'@eslint/eslintrc@3.3.7':
|
||||
'@eslint/eslintrc@3.3.7(supports-color@7.2.0)':
|
||||
dependencies:
|
||||
ajv: 6.15.0
|
||||
debug: 4.4.3
|
||||
debug: 4.4.3(supports-color@7.2.0)
|
||||
espree: 10.4.0
|
||||
globals: 14.0.0
|
||||
ignore: 5.3.2
|
||||
@@ -3656,10 +3656,10 @@ snapshots:
|
||||
'@sentry/replay': 10.75.0
|
||||
'@sentry/replay-canvas': 10.75.0
|
||||
|
||||
'@sentry/bundler-plugins@10.75.0(rollup@4.65.0)':
|
||||
'@sentry/bundler-plugins@10.75.0(rollup@4.65.0)(supports-color@7.2.0)':
|
||||
dependencies:
|
||||
'@babel/core': 7.29.7
|
||||
'@sentry/cli': 2.58.6
|
||||
'@babel/core': 7.29.7(supports-color@7.2.0)
|
||||
'@sentry/cli': 2.58.6(supports-color@7.2.0)
|
||||
'@sentry/core': 10.75.0
|
||||
dotenv: 17.4.2
|
||||
find-up: 5.0.0
|
||||
@@ -3695,9 +3695,9 @@ snapshots:
|
||||
'@sentry/cli-win32-x64@2.58.6':
|
||||
optional: true
|
||||
|
||||
'@sentry/cli@2.58.6':
|
||||
'@sentry/cli@2.58.6(supports-color@7.2.0)':
|
||||
dependencies:
|
||||
https-proxy-agent: 5.0.1
|
||||
https-proxy-agent: 5.0.1(supports-color@7.2.0)
|
||||
node-fetch: 2.7.0
|
||||
progress: 2.0.3
|
||||
proxy-from-env: 1.1.0
|
||||
@@ -3742,9 +3742,9 @@ snapshots:
|
||||
'@sentry/browser-utils': 10.75.0
|
||||
'@sentry/core': 10.75.0
|
||||
|
||||
'@sentry/vite-plugin@5.4.0(rollup@4.65.0)':
|
||||
'@sentry/vite-plugin@5.4.0(rollup@4.65.0)(supports-color@7.2.0)':
|
||||
dependencies:
|
||||
'@sentry/bundler-plugins': 10.75.0(rollup@4.65.0)
|
||||
'@sentry/bundler-plugins': 10.75.0(rollup@4.65.0)(supports-color@7.2.0)
|
||||
transitivePeerDependencies:
|
||||
- encoding
|
||||
- rollup
|
||||
@@ -3976,15 +3976,15 @@ snapshots:
|
||||
'@types/trusted-types@2.0.7':
|
||||
optional: true
|
||||
|
||||
'@typescript-eslint/eslint-plugin@8.70.0(@typescript-eslint/parser@8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3)':
|
||||
'@typescript-eslint/eslint-plugin@8.70.0(@typescript-eslint/parser@8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)':
|
||||
dependencies:
|
||||
'@eslint-community/regexpp': 4.12.2
|
||||
'@typescript-eslint/parser': 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3)
|
||||
'@typescript-eslint/parser': 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)
|
||||
'@typescript-eslint/scope-manager': 8.70.0
|
||||
'@typescript-eslint/type-utils': 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3)
|
||||
'@typescript-eslint/utils': 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3)
|
||||
'@typescript-eslint/type-utils': 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)
|
||||
'@typescript-eslint/utils': 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)
|
||||
'@typescript-eslint/visitor-keys': 8.70.0
|
||||
eslint: 9.39.5(jiti@2.7.0)
|
||||
eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0)
|
||||
ignore: 7.0.9
|
||||
natural-compare: 1.4.0
|
||||
ts-api-utils: 2.5.0(typescript@5.9.3)
|
||||
@@ -3992,23 +3992,23 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
'@typescript-eslint/parser@8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3)':
|
||||
'@typescript-eslint/parser@8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)':
|
||||
dependencies:
|
||||
'@typescript-eslint/scope-manager': 8.70.0
|
||||
'@typescript-eslint/types': 8.70.0
|
||||
'@typescript-eslint/typescript-estree': 8.70.0(typescript@5.9.3)
|
||||
'@typescript-eslint/typescript-estree': 8.70.0(supports-color@7.2.0)(typescript@5.9.3)
|
||||
'@typescript-eslint/visitor-keys': 8.70.0
|
||||
debug: 4.4.3
|
||||
eslint: 9.39.5(jiti@2.7.0)
|
||||
debug: 4.4.3(supports-color@7.2.0)
|
||||
eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0)
|
||||
typescript: 5.9.3
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
'@typescript-eslint/project-service@8.70.0(typescript@5.9.3)':
|
||||
'@typescript-eslint/project-service@8.70.0(supports-color@7.2.0)(typescript@5.9.3)':
|
||||
dependencies:
|
||||
'@typescript-eslint/tsconfig-utils': 8.70.0(typescript@5.9.3)
|
||||
'@typescript-eslint/types': 8.70.0
|
||||
debug: 4.4.3
|
||||
debug: 4.4.3(supports-color@7.2.0)
|
||||
typescript: 5.9.3
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
@@ -4022,13 +4022,13 @@ snapshots:
|
||||
dependencies:
|
||||
typescript: 5.9.3
|
||||
|
||||
'@typescript-eslint/type-utils@8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3)':
|
||||
'@typescript-eslint/type-utils@8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)':
|
||||
dependencies:
|
||||
'@typescript-eslint/types': 8.70.0
|
||||
'@typescript-eslint/typescript-estree': 8.70.0(typescript@5.9.3)
|
||||
'@typescript-eslint/utils': 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3)
|
||||
debug: 4.4.3
|
||||
eslint: 9.39.5(jiti@2.7.0)
|
||||
'@typescript-eslint/typescript-estree': 8.70.0(supports-color@7.2.0)(typescript@5.9.3)
|
||||
'@typescript-eslint/utils': 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)
|
||||
debug: 4.4.3(supports-color@7.2.0)
|
||||
eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0)
|
||||
ts-api-utils: 2.5.0(typescript@5.9.3)
|
||||
typescript: 5.9.3
|
||||
transitivePeerDependencies:
|
||||
@@ -4036,13 +4036,13 @@ snapshots:
|
||||
|
||||
'@typescript-eslint/types@8.70.0': {}
|
||||
|
||||
'@typescript-eslint/typescript-estree@8.70.0(typescript@5.9.3)':
|
||||
'@typescript-eslint/typescript-estree@8.70.0(supports-color@7.2.0)(typescript@5.9.3)':
|
||||
dependencies:
|
||||
'@typescript-eslint/project-service': 8.70.0(typescript@5.9.3)
|
||||
'@typescript-eslint/project-service': 8.70.0(supports-color@7.2.0)(typescript@5.9.3)
|
||||
'@typescript-eslint/tsconfig-utils': 8.70.0(typescript@5.9.3)
|
||||
'@typescript-eslint/types': 8.70.0
|
||||
'@typescript-eslint/visitor-keys': 8.70.0
|
||||
debug: 4.4.3
|
||||
debug: 4.4.3(supports-color@7.2.0)
|
||||
minimatch: 10.2.6
|
||||
semver: 7.8.5
|
||||
tinyglobby: 0.2.17
|
||||
@@ -4051,13 +4051,13 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
'@typescript-eslint/utils@8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3)':
|
||||
'@typescript-eslint/utils@8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)':
|
||||
dependencies:
|
||||
'@eslint-community/eslint-utils': 4.10.1(eslint@9.39.5(jiti@2.7.0))
|
||||
'@eslint-community/eslint-utils': 4.10.1(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))
|
||||
'@typescript-eslint/scope-manager': 8.70.0
|
||||
'@typescript-eslint/types': 8.70.0
|
||||
'@typescript-eslint/typescript-estree': 8.70.0(typescript@5.9.3)
|
||||
eslint: 9.39.5(jiti@2.7.0)
|
||||
'@typescript-eslint/typescript-estree': 8.70.0(supports-color@7.2.0)(typescript@5.9.3)
|
||||
eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0)
|
||||
typescript: 5.9.3
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
@@ -4067,11 +4067,11 @@ snapshots:
|
||||
'@typescript-eslint/types': 8.70.0
|
||||
eslint-visitor-keys: 5.0.1
|
||||
|
||||
'@vitejs/plugin-react@5.2.0(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0))':
|
||||
'@vitejs/plugin-react@5.2.0(supports-color@7.2.0)(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0))':
|
||||
dependencies:
|
||||
'@babel/core': 7.29.7
|
||||
'@babel/plugin-transform-react-jsx-self': 7.29.7(@babel/core@7.29.7)
|
||||
'@babel/plugin-transform-react-jsx-source': 7.29.7(@babel/core@7.29.7)
|
||||
'@babel/core': 7.29.7(supports-color@7.2.0)
|
||||
'@babel/plugin-transform-react-jsx-self': 7.29.7(@babel/core@7.29.7(supports-color@7.2.0))
|
||||
'@babel/plugin-transform-react-jsx-source': 7.29.7(@babel/core@7.29.7(supports-color@7.2.0))
|
||||
'@rolldown/pluginutils': 1.0.0-rc.3
|
||||
'@types/babel__core': 7.20.5
|
||||
react-refresh: 0.18.0
|
||||
@@ -4126,9 +4126,9 @@ snapshots:
|
||||
|
||||
acorn@8.18.0: {}
|
||||
|
||||
agent-base@6.0.2:
|
||||
agent-base@6.0.2(supports-color@7.2.0):
|
||||
dependencies:
|
||||
debug: 4.4.3
|
||||
debug: 4.4.3(supports-color@7.2.0)
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
@@ -4155,11 +4155,11 @@ snapshots:
|
||||
|
||||
asynckit@0.4.0: {}
|
||||
|
||||
axios@1.20.0:
|
||||
axios@1.20.0(debug@4.4.3(supports-color@7.2.0))(supports-color@7.2.0):
|
||||
dependencies:
|
||||
follow-redirects: 1.16.1
|
||||
follow-redirects: 1.16.2(debug@4.4.3(supports-color@7.2.0))
|
||||
form-data: 4.0.6
|
||||
https-proxy-agent: 5.0.1
|
||||
https-proxy-agent: 5.0.1(supports-color@7.2.0)
|
||||
proxy-from-env: 2.1.0
|
||||
transitivePeerDependencies:
|
||||
- debug
|
||||
@@ -4273,9 +4273,11 @@ snapshots:
|
||||
|
||||
date-fns@4.4.0: {}
|
||||
|
||||
debug@4.4.3:
|
||||
debug@4.4.3(supports-color@7.2.0):
|
||||
dependencies:
|
||||
ms: 2.1.3
|
||||
optionalDependencies:
|
||||
supports-color: 7.2.0
|
||||
|
||||
decimal.js@10.6.0: {}
|
||||
|
||||
@@ -4358,13 +4360,13 @@ snapshots:
|
||||
|
||||
escape-string-regexp@4.0.0: {}
|
||||
|
||||
eslint-plugin-react-hooks@5.2.0(eslint@9.39.5(jiti@2.7.0)):
|
||||
eslint-plugin-react-hooks@5.2.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0)):
|
||||
dependencies:
|
||||
eslint: 9.39.5(jiti@2.7.0)
|
||||
eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0)
|
||||
|
||||
eslint-plugin-react-refresh@0.4.26(eslint@9.39.5(jiti@2.7.0)):
|
||||
eslint-plugin-react-refresh@0.4.26(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0)):
|
||||
dependencies:
|
||||
eslint: 9.39.5(jiti@2.7.0)
|
||||
eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0)
|
||||
|
||||
eslint-scope@8.4.0:
|
||||
dependencies:
|
||||
@@ -4377,14 +4379,14 @@ snapshots:
|
||||
|
||||
eslint-visitor-keys@5.0.1: {}
|
||||
|
||||
eslint@9.39.5(jiti@2.7.0):
|
||||
eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0):
|
||||
dependencies:
|
||||
'@eslint-community/eslint-utils': 4.10.1(eslint@9.39.5(jiti@2.7.0))
|
||||
'@eslint-community/eslint-utils': 4.10.1(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))
|
||||
'@eslint-community/regexpp': 4.12.2
|
||||
'@eslint/config-array': 0.21.2
|
||||
'@eslint/config-array': 0.21.2(supports-color@7.2.0)
|
||||
'@eslint/config-helpers': 0.4.2
|
||||
'@eslint/core': 0.17.0
|
||||
'@eslint/eslintrc': 3.3.7
|
||||
'@eslint/eslintrc': 3.3.7(supports-color@7.2.0)
|
||||
'@eslint/js': 9.39.5
|
||||
'@eslint/plugin-kit': 0.4.1
|
||||
'@humanfs/node': 0.16.8
|
||||
@@ -4394,7 +4396,7 @@ snapshots:
|
||||
ajv: 6.15.0
|
||||
chalk: 4.1.2
|
||||
cross-spawn: 7.0.6
|
||||
debug: 4.4.3
|
||||
debug: 4.4.3(supports-color@7.2.0)
|
||||
escape-string-regexp: 4.0.0
|
||||
eslint-scope: 8.4.0
|
||||
eslint-visitor-keys: 4.2.1
|
||||
@@ -4470,7 +4472,9 @@ snapshots:
|
||||
|
||||
flatted@3.4.4: {}
|
||||
|
||||
follow-redirects@1.16.1: {}
|
||||
follow-redirects@1.16.2(debug@4.4.3(supports-color@7.2.0)):
|
||||
optionalDependencies:
|
||||
debug: 4.4.3(supports-color@7.2.0)
|
||||
|
||||
form-data@4.0.6:
|
||||
dependencies:
|
||||
@@ -4556,24 +4560,24 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- '@noble/hashes'
|
||||
|
||||
http-proxy-agent@7.0.2:
|
||||
http-proxy-agent@7.0.2(supports-color@7.2.0):
|
||||
dependencies:
|
||||
agent-base: 7.1.4
|
||||
debug: 4.4.3
|
||||
debug: 4.4.3(supports-color@7.2.0)
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
https-proxy-agent@5.0.1:
|
||||
https-proxy-agent@5.0.1(supports-color@7.2.0):
|
||||
dependencies:
|
||||
agent-base: 6.0.2
|
||||
debug: 4.4.3
|
||||
agent-base: 6.0.2(supports-color@7.2.0)
|
||||
debug: 4.4.3(supports-color@7.2.0)
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
https-proxy-agent@7.0.6:
|
||||
https-proxy-agent@7.0.6(supports-color@7.2.0):
|
||||
dependencies:
|
||||
agent-base: 7.1.4
|
||||
debug: 4.4.3
|
||||
debug: 4.4.3(supports-color@7.2.0)
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
@@ -4611,7 +4615,7 @@ snapshots:
|
||||
dependencies:
|
||||
argparse: 2.0.1
|
||||
|
||||
jsdom@27.4.0:
|
||||
jsdom@27.4.0(supports-color@7.2.0):
|
||||
dependencies:
|
||||
'@acemir/cssom': 0.9.31
|
||||
'@asamuzakjp/dom-selector': 6.8.1
|
||||
@@ -4620,8 +4624,8 @@ snapshots:
|
||||
data-urls: 6.0.1
|
||||
decimal.js: 10.6.0
|
||||
html-encoding-sniffer: 6.0.0
|
||||
http-proxy-agent: 7.0.2
|
||||
https-proxy-agent: 7.0.6
|
||||
http-proxy-agent: 7.0.2(supports-color@7.2.0)
|
||||
https-proxy-agent: 7.0.6(supports-color@7.2.0)
|
||||
is-potential-custom-element-name: 1.0.1
|
||||
parse5: 8.0.1
|
||||
saxes: 6.0.0
|
||||
@@ -4956,11 +4960,11 @@ snapshots:
|
||||
|
||||
semver@7.8.5: {}
|
||||
|
||||
seroval-plugins@1.5.6(seroval@1.6.8):
|
||||
seroval-plugins@1.5.6(seroval@1.7.5):
|
||||
dependencies:
|
||||
seroval: 1.6.8
|
||||
seroval: 1.7.5
|
||||
|
||||
seroval@1.6.8: {}
|
||||
seroval@1.7.5: {}
|
||||
|
||||
set-cookie-parser@2.7.2: {}
|
||||
|
||||
@@ -4975,8 +4979,8 @@ snapshots:
|
||||
solid-js@1.9.15:
|
||||
dependencies:
|
||||
csstype: 3.2.3
|
||||
seroval: 1.6.8
|
||||
seroval-plugins: 1.5.6(seroval@1.6.8)
|
||||
seroval: 1.7.5
|
||||
seroval-plugins: 1.5.6(seroval@1.7.5)
|
||||
|
||||
solid-presence@0.2.0(solid-js@1.9.15):
|
||||
dependencies:
|
||||
@@ -5064,13 +5068,13 @@ snapshots:
|
||||
dependencies:
|
||||
prelude-ls: 1.2.1
|
||||
|
||||
typescript-eslint@8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3):
|
||||
typescript-eslint@8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3):
|
||||
dependencies:
|
||||
'@typescript-eslint/eslint-plugin': 8.70.0(@typescript-eslint/parser@8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3)
|
||||
'@typescript-eslint/parser': 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3)
|
||||
'@typescript-eslint/typescript-estree': 8.70.0(typescript@5.9.3)
|
||||
'@typescript-eslint/utils': 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3)
|
||||
eslint: 9.39.5(jiti@2.7.0)
|
||||
'@typescript-eslint/eslint-plugin': 8.70.0(@typescript-eslint/parser@8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)
|
||||
'@typescript-eslint/parser': 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)
|
||||
'@typescript-eslint/typescript-estree': 8.70.0(supports-color@7.2.0)(typescript@5.9.3)
|
||||
'@typescript-eslint/utils': 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)
|
||||
eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0)
|
||||
typescript: 5.9.3
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
@@ -5118,7 +5122,7 @@ snapshots:
|
||||
jiti: 2.7.0
|
||||
lightningcss: 1.32.0
|
||||
|
||||
vitest@4.1.11(@types/node@24.13.5)(jsdom@27.4.0)(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)):
|
||||
vitest@4.1.11(@types/node@24.13.5)(jsdom@27.4.0(supports-color@7.2.0))(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)):
|
||||
dependencies:
|
||||
'@vitest/expect': 4.1.11
|
||||
'@vitest/mocker': 4.1.11(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0))
|
||||
@@ -5142,7 +5146,7 @@ snapshots:
|
||||
why-is-node-running: 2.3.0
|
||||
optionalDependencies:
|
||||
'@types/node': 24.13.5
|
||||
jsdom: 27.4.0
|
||||
jsdom: 27.4.0(supports-color@7.2.0)
|
||||
transitivePeerDependencies:
|
||||
- msw
|
||||
|
||||
|
||||
@@ -20,6 +20,6 @@ overrides:
|
||||
js-yaml: ^4.3.1
|
||||
nanoid: ^3.3.17
|
||||
dompurify: ^3.4.17
|
||||
follow-redirects: ^1.16.1
|
||||
seroval: ^1.6.3
|
||||
follow-redirects: ^1.16.2
|
||||
seroval: ^1.6.11
|
||||
source-map-js: ^1.2.2
|
||||
|
||||
@@ -6,7 +6,7 @@ import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Callout, Panel, Property, PropertyList, StatusBadge } from "@/components/ui/kit";
|
||||
import { ErrorState } from "@/components/ErrorState";
|
||||
import { APIError, promptForReauth } from "@/lib/api/client";
|
||||
import { APIError, promptForReauth, ReauthCancelledError } from "@/lib/api/client";
|
||||
import { describeAdminDevice, decideAdminDevice, type DeviceDescription } from "@/lib/api/client/admin/device";
|
||||
import { API_URL } from "@/lib/env";
|
||||
import { AdminPerm } from "@/lib/auth/permissions";
|
||||
@@ -90,7 +90,7 @@ export default function DeviceApprovalPage() {
|
||||
try {
|
||||
await promptForReauth();
|
||||
if (mounted.current) setNeedsReauth(false);
|
||||
} catch (err) { if (mounted.current) setError(err); }
|
||||
} catch (err) { if (mounted.current && !(err instanceof ReauthCancelledError)) setError(err); }
|
||||
finally { inFlight.current = false; if (mounted.current) setBusy(false); }
|
||||
}
|
||||
|
||||
|
||||
@@ -270,7 +270,8 @@ function FilterField({ label, children }: { label: string; children: React.React
|
||||
function Row({ row }: { row: AdminAuditLog }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const hasDetails = row.details && Object.keys(row.details).length > 0;
|
||||
const systemActor = row.admin_user_id === NIL_UUID;
|
||||
// The actor's id is cleared when their account is deleted.
|
||||
const deletedActor = row.admin_user_id === NIL_UUID;
|
||||
const tone = ACTION_TONE[row.action] ?? "neutral";
|
||||
return (
|
||||
<>
|
||||
@@ -290,8 +291,8 @@ function Row({ row }: { row: AdminAuditLog }) {
|
||||
{new Date(row.created_at).toLocaleString()}
|
||||
</td>
|
||||
<td className="px-3 py-2">
|
||||
{systemActor ? (
|
||||
<span className="text-subtle-foreground">system</span>
|
||||
{deletedActor ? (
|
||||
<span className="text-subtle-foreground">Deleted account</span>
|
||||
) : row.admin_user ? (
|
||||
<div className="min-w-0">
|
||||
<div className="whitespace-nowrap text-foreground">
|
||||
|
||||
@@ -3,6 +3,7 @@ import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { LoginCodeExemption } from "@/lib/api/models/admin";
|
||||
import { ConfirmProvider } from "@/components/ConfirmDialog";
|
||||
import TestersPage from "./TestersPage";
|
||||
|
||||
const access = vi.hoisted(() => ({ canManage: true }));
|
||||
@@ -15,12 +16,24 @@ function render(tester: Partial<LoginCodeExemption>) {
|
||||
client.setQueryData(["admin", "testers"], {
|
||||
data: [{ user_id: "reviewer", email: "reviewer@example.test", password_expires_at: "2100-01-01T00:00:00Z", ...tester }],
|
||||
});
|
||||
const html = renderToStaticMarkup(<QueryClientProvider client={client}><MemoryRouter initialEntries={["/testers"]}><TestersPage /></MemoryRouter></QueryClientProvider>);
|
||||
const html = renderToStaticMarkup(<QueryClientProvider client={client}><MemoryRouter initialEntries={["/testers"]}><ConfirmProvider><TestersPage /></ConfirmProvider></MemoryRouter></QueryClientProvider>);
|
||||
client.clear();
|
||||
const document = new DOMParser().parseFromString(html, "text/html");
|
||||
return document;
|
||||
}
|
||||
|
||||
describe("tester password re-issue", () => {
|
||||
beforeEach(() => { access.canManage = true; });
|
||||
|
||||
it("offers a new password only on accounts created as testers, to managers", () => {
|
||||
const selector = 'button[aria-label^="Issue new password for"]';
|
||||
expect(render({ created_as_tester: true }).querySelector(selector)).not.toBeNull();
|
||||
expect(render({ created_as_tester: false }).querySelector(selector)).toBeNull();
|
||||
access.canManage = false;
|
||||
expect(render({ created_as_tester: true }).querySelector(selector)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("tester sample-data controls", () => {
|
||||
beforeEach(() => { access.canManage = true; });
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
import { useState } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { AlertTriangle, CopyIcon, FlaskConicalIcon, RotateCw, TrashIcon } from "lucide-react";
|
||||
import { AlertTriangle, CopyIcon, FlaskConicalIcon, KeyRoundIcon, RotateCw, TrashIcon } from "lucide-react";
|
||||
import { PageHeader } from "@/components/layout/PageHeader";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
@@ -29,10 +29,11 @@ import { Callout, EmptyState, Panel, Segmented, StatusBadge } from "@/components
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useAdminPerm } from "@/hooks/useAdminPerm";
|
||||
import { AdminPerm } from "@/lib/auth/permissions";
|
||||
import { createTester, listTesters, listOrganizationRoles, revokeTester, seedTesterWorkspace } from "@/lib/api/client/admin/testers";
|
||||
import { createTester, listTesters, listOrganizationRoles, reissueTesterPassword, revokeTester, seedTesterWorkspace } from "@/lib/api/client/admin/testers";
|
||||
import { useConfirm } from "@/components/ConfirmDialog";
|
||||
import { listOrganizations } from "@/lib/api/client/admin/organizations";
|
||||
import { DASHBOARD_URL } from "@/lib/env";
|
||||
import type { AdminOrgListItem, CreatedTester } from "@/lib/api/models/admin";
|
||||
import type { AdminOrgListItem, CreatedTester, ReissuedTesterPassword } from "@/lib/api/models/admin";
|
||||
|
||||
function fmt(ts?: string | null) {
|
||||
if (!ts) return "—";
|
||||
@@ -54,6 +55,9 @@ export default function TestersPage() {
|
||||
// Held in state, never refetched: the server returns it once and cannot
|
||||
// produce it again.
|
||||
const [created, setCreated] = useState<CreatedTester | null>(null);
|
||||
// Same rule for a re-issued password: shown once, from state only.
|
||||
const [reissued, setReissued] = useState<(ReissuedTesterPassword & { email: string }) | null>(null);
|
||||
const confirm = useConfirm();
|
||||
const [sampleTarget, setSampleTarget] = useState<{ organizationID: string; email: string } | null>(null);
|
||||
|
||||
const testers = useQuery({
|
||||
@@ -116,6 +120,27 @@ export default function TestersPage() {
|
||||
onError: (e: Error) => toast.error(e.message || "Could not revoke the exemption"),
|
||||
});
|
||||
|
||||
const reissue = useMutation({
|
||||
mutationFn: (t: { id: string; email: string }) => reissueTesterPassword(t.id),
|
||||
onSuccess: (r, t) => {
|
||||
setReissued({ ...r, email: t.email });
|
||||
qc.invalidateQueries({ queryKey: ["admin", "testers"] });
|
||||
toast.success("New initial password issued; every session was signed out");
|
||||
},
|
||||
onError: (e: Error) => toast.error(e.message || "Could not issue a new password"),
|
||||
});
|
||||
|
||||
async function onReissue(id: string, email: string) {
|
||||
const ok = await confirm({
|
||||
title: `Issue a new password for ${email}?`,
|
||||
description:
|
||||
"The account's current password stops working and every session it holds is signed out. The new password is shown once, is valid for 48 hours and must be changed at first sign-in.",
|
||||
confirmLabel: "Issue new password",
|
||||
destructive: true,
|
||||
});
|
||||
if (ok) await reissue.mutateAsync({ id, email }).catch(() => undefined);
|
||||
}
|
||||
|
||||
const seed = useMutation({
|
||||
mutationFn: (orgID: string) => seedTesterWorkspace(orgID),
|
||||
onSuccess: (result) => {
|
||||
@@ -156,8 +181,9 @@ export default function TestersPage() {
|
||||
holder cannot read this instance's mail, and arrives with onboarding complete. Authentication still requires the password,
|
||||
the captcha and the sign-in risk assessment. A tester either gets a workspace of its own
|
||||
or joins one that already exists. A new Test workspace includes paid-feature access and 100 test credits until the password expires.
|
||||
An existing workspace keeps its plan and the role you select. Its password stops working on the date you choose, and
|
||||
revoking it ends the password and signs out every session at once.
|
||||
An existing workspace keeps its plan and the role you select. The password it is issued is an initial password: valid
|
||||
for at most 48 hours, it cannot be extended, and the holder must replace it with their own at first sign-in.
|
||||
Revoking a tester ends its password, issued or chosen, and signs out every session at once.
|
||||
Use Add sample data on an active dedicated Test workspace to populate contacts, a draft campaign, templates and CRM examples.
|
||||
Mailboxes must be connected separately.
|
||||
</>
|
||||
@@ -177,6 +203,10 @@ export default function TestersPage() {
|
||||
? "This account is a member of an existing workspace and will land in it on sign-in."
|
||||
: "This account owns a new Test workspace with paid-feature access and 100 test credits until the password expires."}
|
||||
</div>
|
||||
<div className="mt-0.5 text-[12.5px] text-muted-foreground">
|
||||
This is an initial password. It is valid until {fmt(created.password_expires_at)} (48 hours at most) and
|
||||
must be changed at first sign-in, when the holder is asked to choose their own.
|
||||
</div>
|
||||
</div>
|
||||
<Button size="sm" variant="outline" onClick={() => setCreated(null)}>
|
||||
Done
|
||||
@@ -187,7 +217,7 @@ export default function TestersPage() {
|
||||
["Sign in at", DASHBOARD_URL],
|
||||
["Email", created.email],
|
||||
["Password", created.password],
|
||||
["Expires", fmt(created.password_expires_at)],
|
||||
["Valid until", fmt(created.password_expires_at)],
|
||||
].map(([k, v]) => (
|
||||
<div key={k} className="flex min-h-10 items-center gap-3 px-4 py-1.5 text-[13px]">
|
||||
<dt className="w-24 shrink-0 text-muted-foreground">{k}</dt>
|
||||
@@ -218,6 +248,46 @@ export default function TestersPage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{reissued && (
|
||||
<div className="mb-8 overflow-hidden rounded-lg border border-amber-500/25 bg-amber-500/[0.07]">
|
||||
<div className="flex items-start gap-3 px-4 py-3">
|
||||
<AlertTriangle className="mt-0.5 size-4 shrink-0 text-amber-600 dark:text-amber-400" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-[13px] font-medium text-foreground">
|
||||
Copy this now. The password is not stored anywhere readable.
|
||||
</div>
|
||||
<div className="mt-0.5 text-[12.5px] text-muted-foreground">
|
||||
A new initial password for {reissued.email}. It is valid until {fmt(reissued.password_expires_at)} (48
|
||||
hours) and must be changed at first sign-in. The previous password no longer works.
|
||||
</div>
|
||||
</div>
|
||||
<Button size="sm" variant="outline" onClick={() => setReissued(null)}>
|
||||
Done
|
||||
</Button>
|
||||
</div>
|
||||
<dl className="divide-y divide-border/70 border-t border-amber-500/20 bg-card">
|
||||
{[
|
||||
["Email", reissued.email],
|
||||
["Password", reissued.password],
|
||||
["Valid until", fmt(reissued.password_expires_at)],
|
||||
].map(([k, v]) => (
|
||||
<div key={k} className="flex min-h-10 items-center gap-3 px-4 py-1.5 text-[13px]">
|
||||
<dt className="w-24 shrink-0 text-muted-foreground">{k}</dt>
|
||||
<dd
|
||||
className="min-w-0 flex-1 font-mono text-[12.5px] break-all text-foreground"
|
||||
data-ph-mask={k === "Password" ? "" : undefined}
|
||||
>
|
||||
{v}
|
||||
</dd>
|
||||
<Button size="icon-xs" variant="ghost" onClick={() => copy(String(v))} aria-label={`Copy ${k}`}>
|
||||
<CopyIcon className="size-3" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={cn("grid items-start gap-8", canManage && "lg:grid-cols-[minmax(0,1fr)_380px]")}>
|
||||
<section className="min-w-0">
|
||||
<h2 className="mb-3 text-[13px] font-semibold text-foreground">
|
||||
@@ -292,7 +362,7 @@ export default function TestersPage() {
|
||||
dot={expired}
|
||||
className="hidden sm:inline-flex"
|
||||
>
|
||||
Password {expired ? "expired" : "expires"} {fmt(t.password_expires_at)}
|
||||
Initial password {expired ? "expired" : "valid until"} {fmt(t.password_expires_at)}
|
||||
</StatusBadge>
|
||||
)}
|
||||
{canManage && (
|
||||
@@ -308,6 +378,17 @@ export default function TestersPage() {
|
||||
{t.sample_data_seeded_at ? "Sample data added" : "Add sample data"}
|
||||
</Button>
|
||||
)}
|
||||
{t.created_as_tester && (
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={reissue.isPending || revoke.isPending || seed.isPending}
|
||||
aria-label={`Issue new password for ${t.email}`}
|
||||
onClick={() => void onReissue(t.user_id, t.email)}
|
||||
>
|
||||
<KeyRoundIcon className="size-3" /> Issue new password
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
@@ -462,6 +543,9 @@ export default function TestersPage() {
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p className="mt-1.5 text-xs text-muted-foreground">
|
||||
Valid 48 hours at most and never extendable. The holder must change it at first sign-in.
|
||||
</p>
|
||||
</Field>
|
||||
|
||||
<div className="flex justify-end border-t border-border pt-4">
|
||||
|
||||
@@ -71,7 +71,7 @@ export function UserLoginCodeCard({ user }: { user: AdminUserDetail }) {
|
||||
title: `Require the emailed sign-in code for ${user.email} again?`,
|
||||
description: user.password_expires_at
|
||||
? "Every session this account holds is signed out, and the password handed out with it stops working."
|
||||
: "Every session this account holds is signed out. Its password is kept.",
|
||||
: "Every session this account holds is signed out. An account created under Testers also loses the password its holder chose; any other keeps its password.",
|
||||
confirmLabel: "Remove exemption",
|
||||
destructive: true,
|
||||
});
|
||||
|
||||
@@ -5,18 +5,20 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { Check, Save } from "lucide-react";
|
||||
import { Check, Plus, Save, Trash2 } from "lucide-react";
|
||||
import { ErrorState } from "@/components/ErrorState";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { StatusDot } from "@/components/ui/kit";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { TONE_TEXT } from "@/lib/tones";
|
||||
import { cn } from "@/lib/utils";
|
||||
import {
|
||||
getInstanceSettings,
|
||||
putInstanceSettings,
|
||||
type InstanceSettings,
|
||||
type UsageSettings,
|
||||
} from "@/lib/api/client/admin/instance";
|
||||
import { RangeHint, SettingsGroup, SettingsRow } from "./SettingsLayout";
|
||||
|
||||
@@ -109,7 +111,28 @@ const RETENTION_FIELDS = [
|
||||
setting: "warmup_event_days",
|
||||
label: "Warmup records (days)",
|
||||
min: 30,
|
||||
help: "Per-message warmup records: tokens, receipts, tampering events and spam reports. The pool health bands read the last 30 days, which is the floor. The daily sent and received counts behind the analytics are separate and never pruned.",
|
||||
help: "Per-message warmup records: tokens, receipts, tampering events, spam reports and the record of which messages belong to a warmup thread. The pool health bands read the last 30 days, which is the floor. The daily sent and received counts behind the analytics are separate and never pruned.",
|
||||
},
|
||||
{
|
||||
key: "campaignLogDays",
|
||||
setting: "campaign_log_days",
|
||||
label: "Campaign activity feed (days)",
|
||||
min: 0,
|
||||
help: "Entries in each campaign's activity feed: sends that failed or were deferred, pauses and the reasons for them. Campaign stats, progress and sent mail are separate and unaffected. 0 keeps every entry, which is the default.",
|
||||
},
|
||||
{
|
||||
key: "notificationDays",
|
||||
setting: "notification_days",
|
||||
label: "Notifications (days)",
|
||||
min: 0,
|
||||
help: "In-app notifications, read or unread. One still waiting to be emailed is kept until it is sent or skipped. 0 keeps every entry, which is the default.",
|
||||
},
|
||||
{
|
||||
key: "webhookDeliveryDays",
|
||||
setting: "webhook_delivery_days",
|
||||
label: "Webhook delivery log (days)",
|
||||
min: 0,
|
||||
help: "Delivered and abandoned webhook deliveries, with the payload and the endpoint's response excerpt. A delivery still being retried is kept until it settles. A delivery past this window can no longer be redelivered from the log. 0 keeps every entry, which is the default.",
|
||||
},
|
||||
] as const;
|
||||
|
||||
@@ -120,25 +143,31 @@ const RETENTION_PRESETS = [
|
||||
{
|
||||
id: "default",
|
||||
label: "Defaults",
|
||||
description: "365 / 180 / 90 days, warmup 30 / 365",
|
||||
description: "365 / 180 / 90 days, warmup 30 / 365, feeds kept",
|
||||
values: {
|
||||
engagementDays: "365",
|
||||
formDays: "180",
|
||||
auditDays: "90",
|
||||
warmupMailDays: "30",
|
||||
warmupEventDays: "365",
|
||||
campaignLogDays: "0",
|
||||
notificationDays: "0",
|
||||
webhookDeliveryDays: "0",
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "minimal",
|
||||
label: "Minimal retention",
|
||||
description: "30 / 30 / 30 days, warmup 7 / 30",
|
||||
description: "30 / 30 / 30 days, warmup 7 / 30, feeds 30 / 30 / 30",
|
||||
values: {
|
||||
engagementDays: "30",
|
||||
formDays: "30",
|
||||
auditDays: "30",
|
||||
warmupMailDays: "7",
|
||||
warmupEventDays: "30",
|
||||
campaignLogDays: "30",
|
||||
notificationDays: "30",
|
||||
webhookDeliveryDays: "30",
|
||||
},
|
||||
},
|
||||
] as const;
|
||||
@@ -191,7 +220,7 @@ const PLACEMENT_FIELDS = [
|
||||
label: "Free tests per month on trial",
|
||||
min: 1,
|
||||
max: 100000,
|
||||
help: "How many free tests a workspace without a paid plan may run on the metered panels each calendar month. A trial has no credits, so it waits for next month after these.",
|
||||
help: "How many free tests a workspace without a paid plan may run on the metered panels each calendar month. A trial has no balance to pay from, so it waits for next month after these.",
|
||||
},
|
||||
{
|
||||
key: "testsPaid",
|
||||
@@ -199,7 +228,7 @@ const PLACEMENT_FIELDS = [
|
||||
label: "Free tests per month on paid plans",
|
||||
min: 1,
|
||||
max: 100000,
|
||||
help: "The same free allowance for a workspace with an active subscription. Past it, a test on the instance panel costs credits.",
|
||||
help: "The same free allowance for a workspace with an active subscription. Past it, a test on the instance panel is charged to the workspace's balance at the placement test price under Usage pricing.",
|
||||
},
|
||||
{
|
||||
key: "seedsPerTest",
|
||||
@@ -217,14 +246,6 @@ const PLACEMENT_FIELDS = [
|
||||
max: 600,
|
||||
help: "The gap between two copies from one mailbox, jittered, so a test never leaves as a burst. A test someone starts as quick uses the smaller of this and 8 seconds.",
|
||||
},
|
||||
{
|
||||
key: "creditsPerTest",
|
||||
setting: "credits_per_test",
|
||||
label: "Credits per paid test",
|
||||
min: 0,
|
||||
max: 10000,
|
||||
help: "What a test costs in credits once a workspace has used its free tests for the month. The workspace agrees to the price before each paid test, and a test that delivers no copy is refunded. 0 turns paid tests off, so a workspace waits for next month instead. Only a hosted (DEPLOYMENT_MODE=cloud) instance charges.",
|
||||
},
|
||||
{
|
||||
key: "batchSendersMax",
|
||||
setting: "batch_senders_max",
|
||||
@@ -267,13 +288,148 @@ const PLACEMENT_DEFAULTS: InstanceSettings["placement"] = {
|
||||
tests_per_month_paid: 40,
|
||||
seeds_per_test: 20,
|
||||
spacing_seconds: 60,
|
||||
credits_per_test: 25,
|
||||
batch_senders_max: 10000,
|
||||
batch_sender_concurrency: 20,
|
||||
batch_instance_concurrency: 200,
|
||||
batch_starts_per_minute: 10,
|
||||
};
|
||||
|
||||
// Usage pricing bounds and compiled defaults, mirroring internal/app/instancesettings/usage.go.
|
||||
const MARKUP_MIN = 0;
|
||||
const MARKUP_MAX = 500;
|
||||
const ANY_MODEL = "*";
|
||||
|
||||
// A backend from before the balance omits the usage section; the form shows the compiled defaults.
|
||||
const USAGE_DEFAULTS: UsageSettings = {
|
||||
markup_percent: 25,
|
||||
models: [
|
||||
{ model: "claude-sonnet-4", input_per_mtok: 3, output_per_mtok: 15 },
|
||||
{ model: "claude-haiku-4", input_per_mtok: 1, output_per_mtok: 5 },
|
||||
{ model: "claude-3-5-haiku", input_per_mtok: 0.8, output_per_mtok: 4 },
|
||||
{ model: "gpt-6-luna", input_per_mtok: 0.1, output_per_mtok: 0.5 },
|
||||
{ model: ANY_MODEL, input_per_mtok: 3, output_per_mtok: 15 },
|
||||
],
|
||||
units: {
|
||||
web_search: 0.01,
|
||||
placement_test: 0.4,
|
||||
lead_website_read: 0.016,
|
||||
lead_person_email: 0.016,
|
||||
lead_search_page: 0.032,
|
||||
},
|
||||
};
|
||||
|
||||
// Known units first, in this order; any other unit the backend prices is listed after them by key.
|
||||
const UNIT_LABELS: Record<string, { label: string; help: string }> = {
|
||||
web_search: {
|
||||
label: "Web search",
|
||||
help: "One web search made by contact research, an AI variable, or an AI step in a campaign or automation.",
|
||||
},
|
||||
placement_test: {
|
||||
label: "Placement test",
|
||||
help: "One inbox placement test past the workspace's free tests for the month. The workspace agrees to the price before each paid test, and a test that delivers no copy is refunded. 0 turns paid tests off, so a workspace waits for next month instead.",
|
||||
},
|
||||
lead_website_read: {
|
||||
label: "Lead website read",
|
||||
help: "The lead finder reading one business's website, including the people it names and their addresses. A site that never answers is refunded.",
|
||||
},
|
||||
lead_person_email: {
|
||||
label: "Lead person email",
|
||||
help: "Finding one named person's email in the lead finder on request. A search that finds no address is refunded.",
|
||||
},
|
||||
lead_search_page: {
|
||||
label: "Lead search page",
|
||||
help: "One page of a lead finder search through a source this instance pays for. The default is Google Places' Text Search list price; set it to what your provider charges. A workspace using its own key is not charged.",
|
||||
},
|
||||
};
|
||||
|
||||
interface ModelRow {
|
||||
// Stable React key; a model name is edited in place, so it cannot be the key.
|
||||
id: string;
|
||||
model: string;
|
||||
input: string;
|
||||
output: string;
|
||||
}
|
||||
|
||||
interface UsageForm {
|
||||
markup: string;
|
||||
models: ModelRow[];
|
||||
units: Record<string, string>;
|
||||
}
|
||||
|
||||
let modelRowSeq = 0;
|
||||
function nextModelRowId(): string {
|
||||
modelRowSeq += 1;
|
||||
return `model-${modelRowSeq}`;
|
||||
}
|
||||
|
||||
function toUsageForm(u: UsageSettings | undefined): UsageForm {
|
||||
const usage = u ?? USAGE_DEFAULTS;
|
||||
const models = usage.models.map((m) => ({
|
||||
id: nextModelRowId(),
|
||||
model: m.model,
|
||||
input: String(m.input_per_mtok),
|
||||
output: String(m.output_per_mtok),
|
||||
}));
|
||||
// The "*" row is required; the backend adds it, so this only covers an odd document.
|
||||
if (!models.some((m) => m.model === ANY_MODEL)) {
|
||||
const fallback = USAGE_DEFAULTS.models[USAGE_DEFAULTS.models.length - 1];
|
||||
models.push({
|
||||
id: nextModelRowId(),
|
||||
model: ANY_MODEL,
|
||||
input: String(fallback.input_per_mtok),
|
||||
output: String(fallback.output_per_mtok),
|
||||
});
|
||||
}
|
||||
const units: Record<string, string> = {};
|
||||
for (const [k, v] of Object.entries({ ...USAGE_DEFAULTS.units, ...usage.units })) {
|
||||
units[k] = String(v);
|
||||
}
|
||||
return { markup: String(usage.markup_percent ?? USAGE_DEFAULTS.markup_percent), models, units };
|
||||
}
|
||||
|
||||
// Compared without row ids, so reseeding the form does not read as an edit.
|
||||
function usageSignature(u: UsageForm): string {
|
||||
return JSON.stringify({
|
||||
markup: u.markup,
|
||||
models: u.models.map((m) => [m.model, m.input, m.output]),
|
||||
units: Object.entries(u.units).sort(([a], [b]) => a.localeCompare(b)),
|
||||
});
|
||||
}
|
||||
|
||||
function unitKeys(units: Record<string, string>): string[] {
|
||||
const known = Object.keys(UNIT_LABELS).filter((k) => k in units);
|
||||
const other = Object.keys(units)
|
||||
.filter((k) => !(k in UNIT_LABELS))
|
||||
.sort();
|
||||
return [...known, ...other];
|
||||
}
|
||||
|
||||
function priceValid(raw: string): boolean {
|
||||
const n = Number(raw);
|
||||
return raw.trim() !== "" && Number.isFinite(n) && n >= 0;
|
||||
}
|
||||
|
||||
function modelNameError(rows: ModelRow[], row: ModelRow): string | undefined {
|
||||
const name = row.model.trim().toLowerCase();
|
||||
if (name === "") return "Enter a model name, or remove the row.";
|
||||
if (rows.filter((r) => r.model.trim().toLowerCase() === name).length > 1) {
|
||||
return "Each model is listed once.";
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// What a workspace is charged for a provider price after the markup.
|
||||
function withMarkup(raw: string, markup: string): string | null {
|
||||
const price = Number(raw);
|
||||
const pct = Number(markup);
|
||||
if (!priceValid(raw) || !Number.isFinite(pct)) return null;
|
||||
return formatUSD((price * (100 + pct)) / 100);
|
||||
}
|
||||
|
||||
function formatUSD(n: number): string {
|
||||
return `$${n.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 4 })}`;
|
||||
}
|
||||
|
||||
interface FormState {
|
||||
linksEnabled: boolean;
|
||||
ttlHours: string;
|
||||
@@ -284,6 +440,8 @@ interface FormState {
|
||||
placement: Record<PlacementFieldKey, string>;
|
||||
enforceDomainAuth: boolean;
|
||||
authGraceHours: string;
|
||||
autoVendorReconnect: boolean;
|
||||
usage: UsageForm;
|
||||
}
|
||||
|
||||
function toForm(s: InstanceSettings): FormState {
|
||||
@@ -304,6 +462,9 @@ function toForm(s: InstanceSettings): FormState {
|
||||
auditDays: String(s.retention.audit_log_days),
|
||||
warmupMailDays: String(s.retention.warmup_mail_days),
|
||||
warmupEventDays: String(s.retention.warmup_event_days),
|
||||
campaignLogDays: String(s.retention.campaign_log_days ?? 0),
|
||||
notificationDays: String(s.retention.notification_days ?? 0),
|
||||
webhookDeliveryDays: String(s.retention.webhook_delivery_days ?? 0),
|
||||
},
|
||||
tracking: {
|
||||
machineWindowOpen: String(s.tracking.machine_window_open_seconds),
|
||||
@@ -315,7 +476,6 @@ function toForm(s: InstanceSettings): FormState {
|
||||
testsPaid: String(placement.tests_per_month_paid),
|
||||
seedsPerTest: String(placement.seeds_per_test),
|
||||
spacingSeconds: String(placement.spacing_seconds),
|
||||
creditsPerTest: String(placement.credits_per_test ?? PLACEMENT_DEFAULTS.credits_per_test),
|
||||
batchSendersMax: String(placement.batch_senders_max ?? PLACEMENT_DEFAULTS.batch_senders_max),
|
||||
batchSenderConcurrency: String(placement.batch_sender_concurrency ?? PLACEMENT_DEFAULTS.batch_sender_concurrency),
|
||||
batchInstanceConcurrency: String(placement.batch_instance_concurrency ?? PLACEMENT_DEFAULTS.batch_instance_concurrency),
|
||||
@@ -323,6 +483,8 @@ function toForm(s: InstanceSettings): FormState {
|
||||
},
|
||||
enforceDomainAuth: s.deliverability.enforce_domain_auth,
|
||||
authGraceHours: String(s.deliverability.auth_grace_hours),
|
||||
autoVendorReconnect: s.mailbox_signin?.auto_vendor_reconnect ?? true,
|
||||
usage: toUsageForm(s.usage),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -373,7 +535,7 @@ export function SettingsTab({ onDirtyChange, onSwitchTab }: SettingsTabProps) {
|
||||
!!server &&
|
||||
!!form &&
|
||||
RETENTION_FIELDS.some(
|
||||
(f) => form.retention[f.key] !== String(server.retention[f.setting]),
|
||||
(f) => form.retention[f.key] !== String(server.retention[f.setting] ?? 0),
|
||||
);
|
||||
const trackingDirty =
|
||||
!!server &&
|
||||
@@ -386,6 +548,8 @@ export function SettingsTab({ onDirtyChange, onSwitchTab }: SettingsTabProps) {
|
||||
(f) =>
|
||||
form.placement[f.key] !== String(server.placement?.[f.setting] ?? PLACEMENT_DEFAULTS[f.setting]),
|
||||
);
|
||||
const usageDirty =
|
||||
!!server && !!form && usageSignature(form.usage) !== usageSignature(toUsageForm(server.usage));
|
||||
const dirty =
|
||||
!!server &&
|
||||
!!form &&
|
||||
@@ -394,9 +558,11 @@ export function SettingsTab({ onDirtyChange, onSwitchTab }: SettingsTabProps) {
|
||||
form.allowInvitedSignup !== server.access.allow_invited_signup ||
|
||||
form.enforceDomainAuth !== server.deliverability.enforce_domain_auth ||
|
||||
form.authGraceHours !== String(server.deliverability.auth_grace_hours) ||
|
||||
form.autoVendorReconnect !== (server.mailbox_signin?.auto_vendor_reconnect ?? true) ||
|
||||
retentionDirty ||
|
||||
trackingDirty ||
|
||||
placementDirty ||
|
||||
usageDirty ||
|
||||
syncDirty);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -417,6 +583,15 @@ export function SettingsTab({ onDirtyChange, onSwitchTab }: SettingsTabProps) {
|
||||
form !== null &&
|
||||
PLACEMENT_FIELDS.every((f) => syncFieldValid(form.placement[f.key], f.min, f.max));
|
||||
|
||||
const usageValid =
|
||||
form !== null &&
|
||||
syncFieldValid(form.usage.markup, MARKUP_MIN, MARKUP_MAX) &&
|
||||
form.usage.models.every(
|
||||
(m) =>
|
||||
!modelNameError(form.usage.models, m) && priceValid(m.input) && priceValid(m.output),
|
||||
) &&
|
||||
Object.values(form.usage.units).every(priceValid);
|
||||
|
||||
const authGrace = form ? Number(form.authGraceHours) : NaN;
|
||||
const authGraceValid =
|
||||
form !== null &&
|
||||
@@ -461,6 +636,12 @@ export function SettingsTab({ onDirtyChange, onSwitchTab }: SettingsTabProps) {
|
||||
toast.error("Every placement test setting must be a whole number inside the range shown under it");
|
||||
return;
|
||||
}
|
||||
if (!usageValid) {
|
||||
toast.error(
|
||||
`The markup must be a whole number from ${MARKUP_MIN} to ${MARKUP_MAX}, and every model needs a unique name and prices of zero or more`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!authGraceValid) {
|
||||
toast.error(
|
||||
`The authentication grace period must be a whole number of hours between ${AUTH_GRACE_MIN_HOURS} and ${AUTH_GRACE_MAX_HOURS}`,
|
||||
@@ -482,6 +663,9 @@ export function SettingsTab({ onDirtyChange, onSwitchTab }: SettingsTabProps) {
|
||||
audit_log_days: Number(form.retention.auditDays),
|
||||
warmup_mail_days: Number(form.retention.warmupMailDays),
|
||||
warmup_event_days: Number(form.retention.warmupEventDays),
|
||||
campaign_log_days: Number(form.retention.campaignLogDays),
|
||||
notification_days: Number(form.retention.notificationDays),
|
||||
webhook_delivery_days: Number(form.retention.webhookDeliveryDays),
|
||||
},
|
||||
tracking: {
|
||||
machine_window_open_seconds: Number(form.tracking.machineWindowOpen),
|
||||
@@ -492,17 +676,28 @@ export function SettingsTab({ onDirtyChange, onSwitchTab }: SettingsTabProps) {
|
||||
enforce_domain_auth: form.enforceDomainAuth,
|
||||
auth_grace_hours: authGrace,
|
||||
},
|
||||
mailbox_signin: { auto_vendor_reconnect: form.autoVendorReconnect },
|
||||
placement: {
|
||||
tests_per_month_trial: Number(form.placement.testsTrial),
|
||||
tests_per_month_paid: Number(form.placement.testsPaid),
|
||||
seeds_per_test: Number(form.placement.seedsPerTest),
|
||||
spacing_seconds: Number(form.placement.spacingSeconds),
|
||||
credits_per_test: Number(form.placement.creditsPerTest),
|
||||
batch_senders_max: Number(form.placement.batchSendersMax),
|
||||
batch_sender_concurrency: Number(form.placement.batchSenderConcurrency),
|
||||
batch_instance_concurrency: Number(form.placement.batchInstanceConcurrency),
|
||||
batch_starts_per_minute: Number(form.placement.batchStartsPerMinute),
|
||||
},
|
||||
usage: {
|
||||
markup_percent: Number(form.usage.markup),
|
||||
models: form.usage.models.map((m) => ({
|
||||
model: m.model.trim(),
|
||||
input_per_mtok: Number(m.input),
|
||||
output_per_mtok: Number(m.output),
|
||||
})),
|
||||
units: Object.fromEntries(
|
||||
Object.entries(form.usage.units).map(([k, v]) => [k, Number(v)]),
|
||||
),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -723,6 +918,11 @@ export function SettingsTab({ onDirtyChange, onSwitchTab }: SettingsTabProps) {
|
||||
))}
|
||||
</SettingsGroup>
|
||||
|
||||
<UsagePricingGroup
|
||||
usage={form.usage}
|
||||
onChange={(usage) => setForm({ ...form, usage })}
|
||||
/>
|
||||
|
||||
<SettingsGroup
|
||||
title="Sending-domain authentication"
|
||||
description="Gmail, Yahoo, and Outlook reject or spam-filter mail from a domain without SPF and DMARC, and one unauthenticated sender damages the reputation of every mailbox in the shared warmup pool. Warmbly checks each sending domain daily and can stop cold sending and warmup from a domain that keeps failing. The grace period is how long a domain may keep failing first, so a DNS outage cannot stop a customer's campaigns and the owner is warned throughout it."
|
||||
@@ -748,6 +948,21 @@ export function SettingsTab({ onDirtyChange, onSwitchTab }: SettingsTabProps) {
|
||||
error={`Enter a whole number between ${AUTH_GRACE_MIN_HOURS} and ${AUTH_GRACE_MAX_HOURS.toLocaleString()}.`}
|
||||
/>
|
||||
</SettingsGroup>
|
||||
|
||||
<SettingsGroup
|
||||
title="Mailbox sign-in"
|
||||
description="Google mailboxes imported from InboxKit or Zapmail can be reconnected in place with full mail access by the vendor itself: it marks Warmbly trusted on the domain and signs in as each mailbox. The mailbox, its history, campaigns and warmup stay the same, and one that cannot be reconnected keeps working on its current sign-in."
|
||||
>
|
||||
<SettingsRow
|
||||
label="Reconnect vendor mailboxes automatically"
|
||||
description="On, Warmbly asks the vendor on its own for each linked Google mailbox on the older Google sign-in or a legacy domain grant, at most once a week per mailbox. Off leaves it to a member to click Reconnect."
|
||||
>
|
||||
<Switch
|
||||
checked={form.autoVendorReconnect}
|
||||
onCheckedChange={(v) => setForm({ ...form, autoVendorReconnect: v })}
|
||||
/>
|
||||
</SettingsRow>
|
||||
</SettingsGroup>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -775,7 +990,164 @@ export function SettingsTab({ onDirtyChange, onSwitchTab }: SettingsTabProps) {
|
||||
);
|
||||
}
|
||||
|
||||
// One whole-number setting: the field sits on the right, the range under the help.
|
||||
// The price list a workspace's balance is charged from: provider price plus the markup.
|
||||
function UsagePricingGroup({
|
||||
usage,
|
||||
onChange,
|
||||
}: {
|
||||
usage: UsageForm;
|
||||
onChange: (u: UsageForm) => void;
|
||||
}) {
|
||||
const markupValid = syncFieldValid(usage.markup, MARKUP_MIN, MARKUP_MAX);
|
||||
const setModel = (id: string, patch: Partial<ModelRow>) =>
|
||||
onChange({
|
||||
...usage,
|
||||
models: usage.models.map((m) => (m.id === id ? { ...m, ...patch } : m)),
|
||||
});
|
||||
const addModel = () => {
|
||||
// New rows go above the "*" row, which reads as the fallback at the end.
|
||||
const rows = usage.models.filter((m) => m.model !== ANY_MODEL);
|
||||
const any = usage.models.filter((m) => m.model === ANY_MODEL);
|
||||
onChange({
|
||||
...usage,
|
||||
models: [...rows, { id: nextModelRowId(), model: "", input: "0", output: "0" }, ...any],
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<SettingsGroup
|
||||
title="Usage pricing"
|
||||
description="What a workspace's balance is charged for AI and other metered work: the provider's own price for what a call used, plus the markup. Prices are in US dollars before the markup. A change applies to charges made after it. A self-hosted instance with billing off charges nothing, so these prices do nothing there."
|
||||
actions={
|
||||
<Button type="button" size="sm" variant="outline" onClick={addModel}>
|
||||
<Plus />
|
||||
Add model
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<NumberRow
|
||||
id="usage-markup"
|
||||
label="Markup (%)"
|
||||
help="Added on top of every provider price below. 25 charges $1.25 for each $1.00 of provider cost."
|
||||
range={`Between ${MARKUP_MIN} and ${MARKUP_MAX}.`}
|
||||
value={usage.markup}
|
||||
onChange={(v) => onChange({ ...usage, markup: v })}
|
||||
valid={markupValid}
|
||||
error={`Enter a whole number between ${MARKUP_MIN} and ${MARKUP_MAX}.`}
|
||||
/>
|
||||
<div className="px-4 py-3.5">
|
||||
<div className="text-[13px] font-medium text-foreground">Models</div>
|
||||
<div className="mt-0.5 text-[12.5px] leading-relaxed text-muted-foreground">
|
||||
Dollars per million input and output tokens. A model is priced by the row with
|
||||
its exact name, then by the longest row its name starts with, then by{" "}
|
||||
<code className="font-mono text-[12px]">*</code>, which prices every model
|
||||
without a row of its own and cannot be removed.
|
||||
</div>
|
||||
<div className="mt-3 hidden grid-cols-[minmax(0,1fr)_7rem_7rem_1.75rem] gap-2 text-[11px] font-medium uppercase tracking-wide text-subtle-foreground sm:grid">
|
||||
<span>Model</span>
|
||||
<span className="text-right">Input / Mtok</span>
|
||||
<span className="text-right">Output / Mtok</span>
|
||||
<span />
|
||||
</div>
|
||||
<div className="mt-2 space-y-3 sm:mt-1.5 sm:space-y-2">
|
||||
{usage.models.map((m) => {
|
||||
const isAny = m.model === ANY_MODEL;
|
||||
const nameError = isAny ? undefined : modelNameError(usage.models, m);
|
||||
const inputOk = priceValid(m.input);
|
||||
const outputOk = priceValid(m.output);
|
||||
const chargedIn = withMarkup(m.input, usage.markup);
|
||||
const chargedOut = withMarkup(m.output, usage.markup);
|
||||
return (
|
||||
<div key={m.id}>
|
||||
<div className="grid grid-cols-[minmax(0,1fr)_1.75rem] gap-2 sm:grid-cols-[minmax(0,1fr)_7rem_7rem_1.75rem]">
|
||||
<Input
|
||||
aria-label="Model name"
|
||||
placeholder="e.g. claude-sonnet-4"
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
value={m.model}
|
||||
readOnly={isAny}
|
||||
onChange={(e) => setModel(m.id, { model: e.target.value })}
|
||||
aria-invalid={!!nameError}
|
||||
className={cn("font-mono text-[12.5px]", isAny && "text-muted-foreground")}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-sm"
|
||||
variant="ghost"
|
||||
aria-label={isAny ? "The * row cannot be removed" : `Remove ${m.model || "model"}`}
|
||||
title={isAny ? "Prices every model without a row; required" : "Remove"}
|
||||
disabled={isAny}
|
||||
className="hover:bg-destructive/10 hover:text-destructive sm:order-last"
|
||||
onClick={() =>
|
||||
onChange({
|
||||
...usage,
|
||||
models: usage.models.filter((r) => r.id !== m.id),
|
||||
})
|
||||
}
|
||||
>
|
||||
<Trash2 className="size-3.5" />
|
||||
</Button>
|
||||
<div className="col-span-2 grid grid-cols-2 gap-2 sm:col-span-2">
|
||||
<Input
|
||||
aria-label={`Input price per million tokens for ${m.model || "model"}`}
|
||||
inputMode="decimal"
|
||||
autoComplete="off"
|
||||
value={m.input}
|
||||
onChange={(e) => setModel(m.id, { input: e.target.value })}
|
||||
aria-invalid={!inputOk}
|
||||
className="text-right tabular-nums"
|
||||
/>
|
||||
<Input
|
||||
aria-label={`Output price per million tokens for ${m.model || "model"}`}
|
||||
inputMode="decimal"
|
||||
autoComplete="off"
|
||||
value={m.output}
|
||||
onChange={(e) => setModel(m.id, { output: e.target.value })}
|
||||
aria-invalid={!outputOk}
|
||||
className="text-right tabular-nums"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-1 text-xs text-subtle-foreground sm:text-right sm:pr-9">
|
||||
{chargedIn && chargedOut
|
||||
? `charged ${chargedIn} / ${chargedOut} per million tokens`
|
||||
: null}
|
||||
</div>
|
||||
{(nameError || !inputOk || !outputOk) && (
|
||||
<p className={cn("mt-0.5 text-xs", TONE_TEXT.danger)}>
|
||||
{nameError ?? "Enter a price of zero or more, in dollars."}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
{unitKeys(usage.units).map((key) => {
|
||||
const raw = usage.units[key];
|
||||
const charged = withMarkup(raw, usage.markup);
|
||||
const meta = UNIT_LABELS[key];
|
||||
return (
|
||||
<NumberRow
|
||||
key={key}
|
||||
id={`usage-unit-${key}`}
|
||||
label={`${meta?.label ?? key} ($ per unit)`}
|
||||
help={meta?.help ?? `The provider price of one ${key.replaceAll("_", " ")}.`}
|
||||
range={charged ? `A workspace is charged ${charged}.` : "Zero or more, in dollars."}
|
||||
value={raw}
|
||||
onChange={(v) => onChange({ ...usage, units: { ...usage.units, [key]: v } })}
|
||||
valid={priceValid(raw)}
|
||||
error="Enter a price of zero or more, in dollars."
|
||||
inputMode="decimal"
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</SettingsGroup>
|
||||
);
|
||||
}
|
||||
|
||||
// One numeric setting: the field sits on the right, the range under the help.
|
||||
function NumberRow({
|
||||
id,
|
||||
label,
|
||||
@@ -786,6 +1158,7 @@ function NumberRow({
|
||||
valid,
|
||||
error,
|
||||
disabled,
|
||||
inputMode = "numeric",
|
||||
}: {
|
||||
id: string;
|
||||
label: string;
|
||||
@@ -796,6 +1169,7 @@ function NumberRow({
|
||||
valid: boolean;
|
||||
error: string;
|
||||
disabled?: boolean;
|
||||
inputMode?: "numeric" | "decimal";
|
||||
}) {
|
||||
return (
|
||||
<SettingsRow
|
||||
@@ -812,7 +1186,7 @@ function NumberRow({
|
||||
<Input
|
||||
id={id}
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
inputMode={inputMode}
|
||||
autoComplete="off"
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { APIError } from "@/lib/api/client";
|
||||
import { ReauthDialog } from "./ReauthDialog";
|
||||
|
||||
const api = vi.hoisted(() => ({ reauth: vi.fn(), methods: vi.fn() }));
|
||||
vi.mock("@/lib/api/client/auth", () => ({ reauth: api.reauth, reauthMethods: api.methods }));
|
||||
vi.mock("@/lib/env", () => ({ API_URL: "http://localhost:8080" }));
|
||||
|
||||
let root: Root;
|
||||
let host: HTMLDivElement;
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
|
||||
api.methods.mockResolvedValue({ password: false, totp: true });
|
||||
host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
root = createRoot(host);
|
||||
});
|
||||
afterEach(async () => {
|
||||
await act(async () => root.unmount());
|
||||
host.remove();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe("ReauthDialog", () => {
|
||||
it.each([
|
||||
["two_fa_code_used", "Wait for a new authenticator code, then try again."],
|
||||
["internal_error", "We couldn't verify your confirmation right now. Try again shortly."],
|
||||
["service_unavailable", "We couldn't verify your confirmation right now. Try again shortly."],
|
||||
[undefined, "We couldn't verify your confirmation right now. Try again shortly."],
|
||||
["credentials", "That did not match. Try again."],
|
||||
])("explains %s without confirming the waiting action", async (code, message) => {
|
||||
api.reauth.mockRejectedValue(code ? new APIError("Failure", 400, { code }) : new Error("offline"));
|
||||
const resolve = vi.fn();
|
||||
const reject = vi.fn();
|
||||
await act(async () => root.render(<ReauthDialog />));
|
||||
await act(async () => window.dispatchEvent(new CustomEvent("reauth-required", { detail: { resolve, reject } })));
|
||||
const input = document.querySelector('input[autocomplete="one-time-code"]');
|
||||
if (!(input instanceof HTMLInputElement)) throw new Error("Missing code field");
|
||||
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;
|
||||
if (!setter) throw new Error("Missing input setter");
|
||||
await act(async () => {
|
||||
setter.call(input, "123456");
|
||||
input.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
const form = input.closest("form");
|
||||
if (!form) throw new Error("Missing confirmation form");
|
||||
await act(async () => form.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true })));
|
||||
expect(document.querySelector('[role="alert"]')?.textContent).toBe(message);
|
||||
expect(api.reauth).toHaveBeenCalledWith({ password: undefined, code: "123456" });
|
||||
expect(resolve).not.toHaveBeenCalled();
|
||||
expect(reject).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -56,12 +56,16 @@ export function ReauthDialog() {
|
||||
pending.resolve();
|
||||
setPending(null);
|
||||
} catch (err) {
|
||||
// One message for both factors; which one matched is not worth saying.
|
||||
setError(
|
||||
err instanceof APIError && (err.code === "reauth_no_factor" || err.code === "reauth_limited")
|
||||
? err.message
|
||||
: "That did not match. Try again.",
|
||||
);
|
||||
const errCode = err instanceof APIError ? err.code : undefined;
|
||||
if (err instanceof APIError && (errCode === "reauth_no_factor" || errCode === "reauth_limited" || errCode === "attempt_check_unavailable")) {
|
||||
setError(err.message);
|
||||
} else if (errCode === "two_fa_code_used") {
|
||||
setError("Wait for a new authenticator code, then try again.");
|
||||
} else if (!errCode || errCode === "internal_error" || errCode === "service_unavailable") {
|
||||
setError("We couldn't verify your confirmation right now. Try again shortly.");
|
||||
} else {
|
||||
setError("That did not match. Try again.");
|
||||
}
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
@@ -128,7 +132,7 @@ export function ReauthDialog() {
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
{error && <p className="text-sm text-[var(--admin-danger)]">{error}</p>}
|
||||
{error && <p role="alert" className="text-sm text-[var(--admin-danger)]">{error}</p>}
|
||||
<div className="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
|
||||
<Button type="button" variant="outline" onClick={cancel}>
|
||||
Cancel
|
||||
|
||||
@@ -10,16 +10,17 @@
|
||||
// say so and point at where to turn one on. The backend refuses these
|
||||
// routes either way; this is what turns that 403 into instructions.
|
||||
|
||||
import { useEffect } from "react";
|
||||
import { useEffect, useSyncExternalStore } from "react";
|
||||
import { Navigate, Outlet, useLocation } from "react-router-dom";
|
||||
import { useMe } from "@/hooks/useMe";
|
||||
import { getToken } from "@/lib/auth/storage";
|
||||
import { hasToken as tokenStored, subscribeToken } from "@/lib/auth/storage";
|
||||
import { noteStep, setErrorIdentity } from "@/lib/observability";
|
||||
import { AdminBadge } from "./AdminBadge";
|
||||
|
||||
export function RequireAdmin() {
|
||||
const loc = useLocation();
|
||||
const hasToken = !!getToken();
|
||||
// Live, so a session that lapses mid-visit signs out once and unmounts the socket and polls.
|
||||
const hasToken = useSyncExternalStore(subscribeToken, tokenStored);
|
||||
const { data: me, isLoading, isError } = useMe();
|
||||
|
||||
// Every admin route is behind this guard, so it is the one place that
|
||||
|
||||
@@ -17,6 +17,8 @@ export function RouteError() {
|
||||
useEffect(() => {
|
||||
if (reported.current) return;
|
||||
reported.current = true;
|
||||
// A lapsed session is the sign-in screen's job, not a fault to report.
|
||||
if (error instanceof SessionExpiredError) return;
|
||||
captureException(error);
|
||||
}, [error]);
|
||||
|
||||
|
||||
@@ -25,6 +25,14 @@ export class SessionExpiredError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
// The operator closed the confirm-it-is-you prompt: a choice, not a failure.
|
||||
export class ReauthCancelledError extends Error {
|
||||
constructor() {
|
||||
super("Confirmation cancelled");
|
||||
this.name = "ReauthCancelledError";
|
||||
}
|
||||
}
|
||||
|
||||
export class APIError<T = unknown> extends Error {
|
||||
status: number;
|
||||
// Machine-readable code + request id from the backend's standard error
|
||||
@@ -79,7 +87,7 @@ export function promptForReauth(): Promise<void> {
|
||||
new CustomEvent("reauth-required", {
|
||||
detail: {
|
||||
resolve: finish(resolve),
|
||||
reject: finish(() => reject(new Error("cancelled"))),
|
||||
reject: finish(() => reject(new ReauthCancelledError())),
|
||||
// A mounted prompt takes over; the operator may take as long as they need.
|
||||
ack: () => window.clearTimeout(timer),
|
||||
},
|
||||
|
||||
@@ -135,6 +135,11 @@ export interface InstanceSettings {
|
||||
// second. The daily warmup statistics are never pruned.
|
||||
warmup_mail_days: number;
|
||||
warmup_event_days: number;
|
||||
// History shown in the product: a campaign's activity feed, in-app
|
||||
// notifications, and each webhook endpoint's delivery log.
|
||||
campaign_log_days: number;
|
||||
notification_days: number;
|
||||
webhook_delivery_days: number;
|
||||
};
|
||||
// How soon after a send an open or click is recorded as automated. The
|
||||
// clock starts at dispatch to the worker, so the window also covers the
|
||||
@@ -161,17 +166,23 @@ export interface InstanceSettings {
|
||||
enforce_domain_auth: boolean;
|
||||
auth_grace_hours: number;
|
||||
};
|
||||
// Whether an inbox vendor that can sign in for Warmbly reconnects its
|
||||
// Google mailboxes without full mail access on its own. Optional so an
|
||||
// older backend that does not send the section reads as on, its default.
|
||||
mailbox_signin?: {
|
||||
auto_vendor_reconnect: boolean;
|
||||
};
|
||||
// Inbox placement tests. The monthly allowances count tests on the
|
||||
// instance and cloud panels only, and a self-hosted instance does not
|
||||
// meter at all. Zero or negative on write resolves to the default, except
|
||||
// credits_per_test, where zero turns paid tests off.
|
||||
// meter at all. Zero or negative on write resolves to the default. A test
|
||||
// past the allowance is priced by the placement_test unit under usage.
|
||||
placement: {
|
||||
tests_per_month_trial: number;
|
||||
tests_per_month_paid: number;
|
||||
seeds_per_test: number;
|
||||
spacing_seconds: number;
|
||||
/** Credits a test past the monthly allowance costs; 0 turns paid tests off. */
|
||||
credits_per_test: number;
|
||||
/** Legacy credit price, read by older backends; the form no longer sends it. */
|
||||
credits_per_test?: number;
|
||||
/** Most senders one placement batch may hold. */
|
||||
batch_senders_max: number;
|
||||
/** A workspace's batch senders sending probes at the same time. */
|
||||
@@ -191,6 +202,26 @@ export interface InstanceSettings {
|
||||
notifications?: {
|
||||
channels: NotifyChannel[];
|
||||
};
|
||||
// What a workspace's balance is charged for usage: the provider price
|
||||
// below plus the markup. Absent on a backend from before the balance.
|
||||
usage?: UsageSettings;
|
||||
}
|
||||
|
||||
export interface UsageSettings {
|
||||
/** Added on top of every provider price, 0 to 500. */
|
||||
markup_percent: number;
|
||||
/** Matched on the model name: exact, then longest prefix, then "*". */
|
||||
models: ModelPrice[];
|
||||
/** Dollars per unit before the markup, keyed by unit (web_search, placement_test). */
|
||||
units: Record<string, number>;
|
||||
}
|
||||
|
||||
export interface ModelPrice {
|
||||
model: string;
|
||||
/** Dollars per million input tokens, before the markup. */
|
||||
input_per_mtok: number;
|
||||
/** Dollars per million output tokens, before the markup. */
|
||||
output_per_mtok: number;
|
||||
}
|
||||
|
||||
export type NotifyChannelType = "discord" | "slack" | "webhook" | "email";
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
// exemptions are the same query.
|
||||
|
||||
import { Request } from "@/lib/api/client";
|
||||
import type { LoginCodeExemption, CreatedTester, AdminOrgRole } from "@/lib/api/models/admin";
|
||||
import type { LoginCodeExemption, CreatedTester, AdminOrgRole, ReissuedTesterPassword } from "@/lib/api/models/admin";
|
||||
|
||||
export function listTesters(): Promise<{ data: LoginCodeExemption[] }> {
|
||||
return Request({ method: "GET", url: "/admin/testers", authorization: true });
|
||||
@@ -38,3 +38,8 @@ export function revokeTester(id: string): Promise<{ revoked: boolean; password_c
|
||||
export function seedTesterWorkspace(orgID: string): Promise<{ organization_id: string; created: boolean; seeded_at: string }> {
|
||||
return Request({ method: "POST", url: `/admin/organizations/${orgID}/sample-data`, authorization: true });
|
||||
}
|
||||
|
||||
/** Issues a tester a fresh 48-hour initial password and signs out its sessions. Needs a recent confirmation. */
|
||||
export function reissueTesterPassword(id: string): Promise<ReissuedTesterPassword> {
|
||||
return Request({ method: "POST", url: `/admin/testers/${id}/password`, authorization: true });
|
||||
}
|
||||
|
||||
@@ -1010,11 +1010,22 @@ export interface LoginCodeExemption {
|
||||
email: string;
|
||||
reason?: string | null;
|
||||
granted_at?: string | null;
|
||||
/** When the handed-out password stops working; absent for an account
|
||||
* exempted without one. */
|
||||
/** When the issued initial password stops working; absent once the holder
|
||||
* has chosen their own, or for an account exempted without one. */
|
||||
password_expires_at?: string | null;
|
||||
test_workspace_id?: string | null;
|
||||
sample_data_seeded_at?: string | null;
|
||||
/** Created through the tester flow, so it can be issued a new password. */
|
||||
created_as_tester?: boolean;
|
||||
}
|
||||
|
||||
/** A fresh initial password for an existing tester, readable this once. */
|
||||
export interface ReissuedTesterPassword {
|
||||
user_id: string;
|
||||
password: string;
|
||||
/** 48 hours after issuance. */
|
||||
password_expires_at: string;
|
||||
password_change_required: boolean;
|
||||
}
|
||||
|
||||
/** The one time the password is readable. It is not stored in a form anyone
|
||||
@@ -1024,8 +1035,10 @@ export interface CreatedTester {
|
||||
email: string;
|
||||
organization_id: string;
|
||||
password: string;
|
||||
/** When the password stops working. */
|
||||
/** When the password stops working, 48 hours after issuance at most. */
|
||||
password_expires_at: string;
|
||||
/** Always true: the holder replaces this initial password at first sign-in. */
|
||||
password_change_required?: boolean;
|
||||
/** True when the tester joined a workspace that already existed rather
|
||||
* than one minted for it. */
|
||||
joined_existing: boolean;
|
||||
|
||||
@@ -6,7 +6,7 @@ vi.mock("@/lib/observability", () => ({
|
||||
noteStep: () => {},
|
||||
}));
|
||||
|
||||
import { APIError, SessionExpiredError } from "@/lib/api/client";
|
||||
import { APIError, ReauthCancelledError, SessionExpiredError } from "@/lib/api/client";
|
||||
import { reportFailure } from "./reportFailure";
|
||||
|
||||
function apiError(status: number): APIError {
|
||||
@@ -46,6 +46,11 @@ describe("reportFailure", () => {
|
||||
expect(captured).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("skips a confirmation the operator cancelled", () => {
|
||||
reportFailure(new ReauthCancelledError(), "mutation");
|
||||
expect(captured).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("reports an error thrown outside the API client", () => {
|
||||
reportFailure(new TypeError("x is undefined"), "query");
|
||||
expect(captured).toHaveLength(1);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Reports a failed query or mutation. react-query keeps these as error state
|
||||
// for the page to render, so without this nothing reaches PostHog or Sentry.
|
||||
|
||||
import { APIError, SessionExpiredError } from "@/lib/api/client";
|
||||
import { APIError, ReauthCancelledError, SessionExpiredError } from "@/lib/api/client";
|
||||
import { captureException, type StepProperties } from "@/lib/observability";
|
||||
|
||||
// Answers that are the expected outcome of a request, not a defect: a signed-out
|
||||
@@ -9,7 +9,7 @@ import { captureException, type StepProperties } from "@/lib/observability";
|
||||
const EXPECTED = new Set([401, 403, 404, 429]);
|
||||
|
||||
export function shouldReport(error: unknown, kind: "query" | "mutation"): boolean {
|
||||
if (error instanceof SessionExpiredError) return false;
|
||||
if (error instanceof SessionExpiredError || error instanceof ReauthCancelledError) return false;
|
||||
if (!(error instanceof APIError)) return true;
|
||||
// Status 0 is the network, not the panel.
|
||||
if (error.status === 0 || EXPECTED.has(error.status)) return false;
|
||||
|
||||
@@ -35,17 +35,41 @@ export function getToken(): AdminToken | null {
|
||||
|
||||
export function setToken(t: AdminToken | null) {
|
||||
if (!t) {
|
||||
clearAdminBrowse();
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
clearToken();
|
||||
return;
|
||||
}
|
||||
localStorage.setItem(TOKEN_KEY, JSON.stringify(t));
|
||||
resumeBrowse();
|
||||
notify();
|
||||
}
|
||||
|
||||
export function clearToken() {
|
||||
clearAdminBrowse();
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
notify();
|
||||
}
|
||||
|
||||
export function hasToken(): boolean {
|
||||
return localStorage.getItem(TOKEN_KEY) !== null;
|
||||
}
|
||||
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
function notify() {
|
||||
listeners.forEach((listener) => listener());
|
||||
}
|
||||
|
||||
// subscribeToken calls back when the token is stored or cleared, in this tab or another.
|
||||
export function subscribeToken(listener: () => void): () => void {
|
||||
listeners.add(listener);
|
||||
const onStorage = (e: StorageEvent) => {
|
||||
if (e.key === TOKEN_KEY || e.key === null) listener();
|
||||
};
|
||||
window.addEventListener("storage", onStorage);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
window.removeEventListener("storage", onStorage);
|
||||
};
|
||||
}
|
||||
|
||||
export function isExpired(iso: string): boolean {
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { CaptureResult } from "posthog-js";
|
||||
import { dropBrowserNoise } from "./observability";
|
||||
|
||||
const thrown = (type: string, value: string, filenames: string[] = []) => ({
|
||||
event: "$exception",
|
||||
properties: {
|
||||
$exception_list: [{
|
||||
type,
|
||||
value,
|
||||
mechanism: { handled: true, synthetic: false },
|
||||
stacktrace: { type: "raw", frames: filenames.map((filename) => ({ platform: "web:javascript", filename })) },
|
||||
}],
|
||||
},
|
||||
}) as unknown as CaptureResult;
|
||||
|
||||
describe("dropBrowserNoise", () => {
|
||||
it.each([
|
||||
["SessionExpiredError", "Session expired", ["https://admin.warmbly.com/assets/index-abc.js"]],
|
||||
["ReauthCancelledError", "Confirmation cancelled", ["https://admin.warmbly.com/assets/index-abc.js"]],
|
||||
["TypeError", "undefined is not an object (evaluating 'window.ethereum.selectedAddress = undefined')", ["https://admin.warmbly.com/"]],
|
||||
["Error", "Could not establish connection. Receiving end does not exist.", []],
|
||||
["TypeError", "x is undefined", ["chrome-extension://abcdef/inject.js"]],
|
||||
])("drops %s: %s", (type, value, filenames) => {
|
||||
expect(dropBrowserNoise(thrown(type, value, filenames))).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps a real error from the bundle", () => {
|
||||
const event = thrown("TypeError", "Cannot read properties of undefined (reading 'id')", ["https://admin.warmbly.com/assets/index-abc.js"]);
|
||||
expect(dropBrowserNoise(event)).toBe(event);
|
||||
});
|
||||
|
||||
it("keeps an injected-looking message that passed through the bundle", () => {
|
||||
const event = thrown("ReferenceError", "Can't find variable: CONFIG", ["https://admin.warmbly.com/assets/index-abc.js"]);
|
||||
expect(dropBrowserNoise(event)).toBe(event);
|
||||
});
|
||||
});
|
||||
@@ -184,14 +184,45 @@ const NOISE = [
|
||||
"ResizeObserver loop limit exceeded",
|
||||
];
|
||||
|
||||
function dropBrowserNoise(event: CaptureResult | null): CaptureResult | null {
|
||||
// Expected states, not faults: a lapsed session signs the operator out, and a closed confirm prompt is a choice.
|
||||
const NOISE_TYPES = ["SessionExpiredError", "ReauthCancelledError"];
|
||||
|
||||
// Thrown into the page by wallets, extensions and in-app browsers; none of these names exist in our code.
|
||||
const FOREIGN_MESSAGES = [
|
||||
/window\.ethereum\.selectedAddress = undefined/,
|
||||
/^Can't find variable: (CONFIG|currentInset)$/,
|
||||
/^No Listener: tabs:/,
|
||||
/^Could not establish connection\. Receiving end does not exist\.$/,
|
||||
];
|
||||
const EXTENSION_SOURCE = /^(?:(?:chrome|moz|safari|safari-web|ms-browser)-extension:|webkit-masked-url:)/;
|
||||
// Our bundle is served from /assets/; a frame there means the error passed through our code.
|
||||
const BUNDLE_SOURCE = /^(?:[a-z]+:\/\/[^/]+)?\/assets\//i;
|
||||
|
||||
// isForeign keeps anything with a frame in our bundle, so a real error with the same words still reports.
|
||||
function isForeign(entry: Record<string, unknown>): boolean {
|
||||
const trace = entry.stacktrace as { frames?: unknown } | undefined;
|
||||
const sources = (Array.isArray(trace?.frames) ? trace.frames : []).flatMap((frame) => {
|
||||
const f = frame as { filename?: unknown; abs_path?: unknown } | null;
|
||||
const source = f?.filename ?? f?.abs_path;
|
||||
return typeof source === "string" ? [source] : [];
|
||||
});
|
||||
if (sources.some((source) => BUNDLE_SOURCE.test(source))) return false;
|
||||
if (sources.some((source) => EXTENSION_SOURCE.test(source))) return true;
|
||||
const value = entry.value ?? entry.$exception_value;
|
||||
return typeof value === "string" && FOREIGN_MESSAGES.some((pattern) => pattern.test(value));
|
||||
}
|
||||
|
||||
export function dropBrowserNoise(event: CaptureResult | null): CaptureResult | null {
|
||||
if (event?.event !== "$exception") return event;
|
||||
const exceptionList = event.properties?.$exception_list;
|
||||
const structuredNoise = Array.isArray(exceptionList) && exceptionList.some((exception) => {
|
||||
if (!exception || typeof exception !== "object") return false;
|
||||
const entry = exception as Record<string, unknown>;
|
||||
const entries = (Array.isArray(exceptionList) ? exceptionList : [])
|
||||
.filter((exception): exception is Record<string, unknown> => Boolean(exception) && typeof exception === "object");
|
||||
if (entries.length > 0 && entries.every(isForeign)) return null;
|
||||
const structuredNoise = entries.some((entry) => {
|
||||
const value = entry.value ?? entry.$exception_value;
|
||||
return typeof value === "string" && NOISE.includes(value.trim());
|
||||
const type = entry.type ?? entry.$exception_type;
|
||||
return (typeof value === "string" && NOISE.includes(value.trim()))
|
||||
|| (typeof type === "string" && NOISE_TYPES.includes(type));
|
||||
});
|
||||
const message = event.properties?.$exception_message;
|
||||
const messageNoise = typeof message === "string" && NOISE.includes(message.trim());
|
||||
|
||||
@@ -2,8 +2,10 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
|
||||
vi.mock("@/lib/api/client", () => ({
|
||||
Request: vi.fn(async () => ({ url: "ws://localhost:4000/socket/websocket", expires_in: 600 })),
|
||||
SessionExpiredError: class SessionExpiredError extends Error {},
|
||||
}));
|
||||
|
||||
import { Request, SessionExpiredError } from "@/lib/api/client";
|
||||
import { startRealtime, stopRealtime, getStatus, getRefusal, onEvent, refusalMessage } from "./socket";
|
||||
|
||||
const TOPIC = "admin:platform";
|
||||
@@ -261,3 +263,34 @@ describe("status reporting", () => {
|
||||
expect(getStatus()).toBe("disconnected");
|
||||
});
|
||||
});
|
||||
|
||||
describe("an expired session", () => {
|
||||
it("stops asking for socket URLs and logs nothing as an error", async () => {
|
||||
const errors = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
vi.mocked(Request).mockClear();
|
||||
vi.mocked(Request).mockRejectedValueOnce(new SessionExpiredError());
|
||||
|
||||
sockets[sockets.length - 1].close();
|
||||
await tick(60_000);
|
||||
window.dispatchEvent(new Event("focus"));
|
||||
window.dispatchEvent(new Event("online"));
|
||||
await tick(60_000);
|
||||
|
||||
expect(Request).toHaveBeenCalledTimes(1);
|
||||
expect(errors).not.toHaveBeenCalled();
|
||||
expect(getStatus()).toBe("disconnected");
|
||||
});
|
||||
|
||||
it("connects again after the next sign-in", async () => {
|
||||
vi.mocked(Request).mockRejectedValueOnce(new SessionExpiredError());
|
||||
sockets[sockets.length - 1].close();
|
||||
await tick(1_000);
|
||||
const before = sockets.length;
|
||||
|
||||
stopRealtime();
|
||||
startRealtime();
|
||||
await tick(10);
|
||||
|
||||
expect(sockets.length).toBe(before + 1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
// The socket URL comes from POST /v1/getaway and embeds a short-lived auth
|
||||
// token (~10 min), so EVERY (re)connect fetches a fresh URL.
|
||||
|
||||
import { Request } from "@/lib/api/client";
|
||||
import { Request, SessionExpiredError } from "@/lib/api/client";
|
||||
|
||||
export type RealtimeStatus = "connecting" | "connected" | "disconnected" | "refused";
|
||||
|
||||
@@ -89,6 +89,7 @@ let rejoinAttempt = 0;
|
||||
let lastRejoinAt = 0;
|
||||
let connecting = false; // guards the async URL fetch window before ws exists
|
||||
let refusal: string | null = null; // a terminal join refusal; blocks every reconnect
|
||||
let signedOut = false; // the session is gone; no retry can mint a socket URL again
|
||||
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let rejoinTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let heartbeatTimer: ReturnType<typeof setInterval> | null = null;
|
||||
@@ -177,7 +178,7 @@ function startHeartbeat() {
|
||||
}
|
||||
|
||||
function scheduleReconnect() {
|
||||
if (!started || reconnectTimer || refusal) return;
|
||||
if (!started || reconnectTimer || refusal || signedOut) return;
|
||||
const base = RECONNECT_SCHEDULE[Math.min(reconnectAttempt, RECONNECT_SCHEDULE.length - 1)];
|
||||
// ±25% jitter so clients don't reconnect in lockstep after an outage.
|
||||
const delay = Math.round(base * (0.75 + Math.random() * 0.5));
|
||||
@@ -317,7 +318,7 @@ function teardownSocket() {
|
||||
}
|
||||
|
||||
async function connect(): Promise<void> {
|
||||
if (!started || connecting || refusal) return;
|
||||
if (!started || connecting || refusal || signedOut) return;
|
||||
if (
|
||||
ws &&
|
||||
(ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING)
|
||||
@@ -340,6 +341,12 @@ async function connect(): Promise<void> {
|
||||
} catch (err) {
|
||||
connecting = false;
|
||||
if (!started || myEpoch !== epoch) return;
|
||||
if (err instanceof SessionExpiredError) {
|
||||
// Expected, not a fault: RequireAdmin sends the operator to sign in.
|
||||
signedOut = true;
|
||||
setStatus("disconnected");
|
||||
return;
|
||||
}
|
||||
console.error("[realtime] Socket URL fetch failed:", err);
|
||||
setStatus("disconnected");
|
||||
scheduleReconnect();
|
||||
@@ -388,7 +395,7 @@ async function connect(): Promise<void> {
|
||||
// instead of waiting out a backoff timer. Also clears a socket stuck
|
||||
// CONNECTING (suspended background tab) so a fresh one can open.
|
||||
function wake() {
|
||||
if (!started || refusal) return;
|
||||
if (!started || refusal || signedOut) return;
|
||||
if (ws?.readyState === WebSocket.OPEN) return;
|
||||
teardownSocket();
|
||||
if (reconnectTimer) {
|
||||
@@ -406,6 +413,7 @@ export function startRealtime() {
|
||||
started = true;
|
||||
epoch += 1;
|
||||
refusal = null;
|
||||
signedOut = false;
|
||||
reconnectAttempt = 0;
|
||||
rejoinAttempt = 0;
|
||||
lastRejoinAt = 0;
|
||||
|
||||
+174
-47
@@ -5,6 +5,8 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/warmbly/warmbly/internal/app/fleetmetrics"
|
||||
"github.com/warmbly/warmbly/internal/app/mailpush"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -27,6 +29,7 @@ import (
|
||||
"github.com/warmbly/warmbly/internal/app/adminoutreach"
|
||||
"github.com/warmbly/warmbly/internal/app/advanced"
|
||||
"github.com/warmbly/warmbly/internal/app/appattest"
|
||||
"github.com/warmbly/warmbly/internal/app/attachmentdownload"
|
||||
"github.com/warmbly/warmbly/internal/app/unsublink"
|
||||
"github.com/warmbly/warmbly/internal/observability/errs"
|
||||
|
||||
@@ -41,6 +44,7 @@ import (
|
||||
"github.com/warmbly/warmbly/internal/app/appdirectory"
|
||||
"github.com/warmbly/warmbly/internal/app/audit"
|
||||
"github.com/warmbly/warmbly/internal/app/auth"
|
||||
"github.com/warmbly/warmbly/internal/app/balance"
|
||||
behaviorapp "github.com/warmbly/warmbly/internal/app/behavior"
|
||||
"github.com/warmbly/warmbly/internal/app/bootstrap"
|
||||
"github.com/warmbly/warmbly/internal/app/campaign"
|
||||
@@ -52,7 +56,6 @@ import (
|
||||
"github.com/warmbly/warmbly/internal/app/contact"
|
||||
"github.com/warmbly/warmbly/internal/app/contactimport"
|
||||
"github.com/warmbly/warmbly/internal/app/credits"
|
||||
"github.com/warmbly/warmbly/internal/app/creditwatch"
|
||||
"github.com/warmbly/warmbly/internal/app/crm"
|
||||
"github.com/warmbly/warmbly/internal/app/crmmode"
|
||||
"github.com/warmbly/warmbly/internal/app/customhost"
|
||||
@@ -60,6 +63,7 @@ import (
|
||||
"github.com/warmbly/warmbly/internal/app/dangerzone"
|
||||
"github.com/warmbly/warmbly/internal/app/delegation"
|
||||
"github.com/warmbly/warmbly/internal/app/discount"
|
||||
"github.com/warmbly/warmbly/internal/app/edgehost"
|
||||
"github.com/warmbly/warmbly/internal/app/email"
|
||||
"github.com/warmbly/warmbly/internal/app/emailsend"
|
||||
emailverifyapp "github.com/warmbly/warmbly/internal/app/emailverify"
|
||||
@@ -79,6 +83,7 @@ import (
|
||||
"github.com/warmbly/warmbly/internal/app/instancesettings"
|
||||
"github.com/warmbly/warmbly/internal/app/integration"
|
||||
"github.com/warmbly/warmbly/internal/app/keystatus"
|
||||
"github.com/warmbly/warmbly/internal/app/leadfinder"
|
||||
"github.com/warmbly/warmbly/internal/app/leadsync"
|
||||
"github.com/warmbly/warmbly/internal/app/mailboxavatar"
|
||||
"github.com/warmbly/warmbly/internal/app/mailboximport"
|
||||
@@ -87,6 +92,7 @@ import (
|
||||
"github.com/warmbly/warmbly/internal/app/monitoring"
|
||||
"github.com/warmbly/warmbly/internal/app/nativeactions"
|
||||
"github.com/warmbly/warmbly/internal/app/nodelogs"
|
||||
"github.com/warmbly/warmbly/internal/app/nodescope"
|
||||
"github.com/warmbly/warmbly/internal/app/notification"
|
||||
"github.com/warmbly/warmbly/internal/app/oauth"
|
||||
"github.com/warmbly/warmbly/internal/app/oidcauth"
|
||||
@@ -148,12 +154,14 @@ import (
|
||||
"github.com/warmbly/warmbly/internal/infrastructure/storage"
|
||||
"github.com/warmbly/warmbly/internal/jobrun"
|
||||
"github.com/warmbly/warmbly/internal/jobs"
|
||||
"github.com/warmbly/warmbly/internal/leader"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
"github.com/warmbly/warmbly/internal/notify"
|
||||
"github.com/warmbly/warmbly/internal/observability"
|
||||
productanalytics "github.com/warmbly/warmbly/internal/observability/analytics"
|
||||
"github.com/warmbly/warmbly/internal/pkg/appleauth"
|
||||
"github.com/warmbly/warmbly/internal/pkg/captcha"
|
||||
"github.com/warmbly/warmbly/internal/pkg/cfsaas"
|
||||
"github.com/warmbly/warmbly/internal/pkg/domainproof"
|
||||
"github.com/warmbly/warmbly/internal/pkg/emailverify"
|
||||
"github.com/warmbly/warmbly/internal/pkg/encrypt"
|
||||
@@ -162,6 +170,7 @@ import (
|
||||
"github.com/warmbly/warmbly/internal/pkg/idtoken"
|
||||
"github.com/warmbly/warmbly/internal/pkg/mailhost"
|
||||
"github.com/warmbly/warmbly/internal/pkg/mailvendor"
|
||||
"github.com/warmbly/warmbly/internal/pkg/servetls"
|
||||
"github.com/warmbly/warmbly/internal/pkg/typesafe"
|
||||
"github.com/warmbly/warmbly/internal/repository"
|
||||
"github.com/warmbly/warmbly/internal/scheduler"
|
||||
@@ -226,15 +235,18 @@ func main() {
|
||||
var fleetNodeRepo repository.FleetNodeRepository
|
||||
var fleetSettingsRepo repository.FleetSettingsRepository
|
||||
var fleetNodeService *fleetnode.Service
|
||||
var nodeScopeService *nodescope.Service
|
||||
var keyStatusDB keystatus.DB
|
||||
var tasksService tasks.TasksService
|
||||
var advancedService advanced.Service
|
||||
var unsubSigner *unsublink.Signer
|
||||
var attachmentDownloads *attachmentdownload.Signer
|
||||
var warmupContentRepo repository.WarmupContentRepository
|
||||
var warmupContentService warmupcontent.Service
|
||||
var creditRepository repository.CreditRepository
|
||||
var aiSettingsRepository repository.AISettingsRepository
|
||||
var creditService credits.CreditService
|
||||
var balanceService *balance.Service
|
||||
var aiDraftRepo repository.AIDraftRepository
|
||||
var writingGenerator generation.WritingGenerator
|
||||
var aiProvider generation.Provider
|
||||
@@ -266,7 +278,6 @@ func main() {
|
||||
var subscriptionService subscription.SubscriptionService
|
||||
var stripeService stripe.StripeService
|
||||
var discountService discount.DiscountService
|
||||
var referralService referral.Service
|
||||
var organizationService organization.OrganizationService
|
||||
// Private plan offers and the credential-free Cloud warmup grant; selfExecutionGrants is shared with the pool link.
|
||||
var planOfferService planoffer.Service
|
||||
@@ -334,6 +345,8 @@ func main() {
|
||||
|
||||
// Pub/Sub for realtime streaming
|
||||
var streamingPublisher *pubsub.StreamingPublisher
|
||||
var mailPushSettings *mailpush.Settings
|
||||
var mailPushWaker *mailpush.Waker
|
||||
|
||||
// Surfaced into the handler for avatar uploads and other direct
|
||||
// repository / object-storage needs. Declared up here so they
|
||||
@@ -377,6 +390,7 @@ func main() {
|
||||
var leadSyncServiceForHandler leadsync.Service
|
||||
var salesforceServiceForHandler *salesforce.Service
|
||||
var apolloServiceForHandler *apollo.Service
|
||||
var leadFinderServiceForHandler *leadfinder.Service
|
||||
var clayServiceForHandler *clay.Service
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
@@ -625,14 +639,10 @@ func main() {
|
||||
}
|
||||
}
|
||||
|
||||
// Event bus + codec. Kafka bootstrap/SASL is only loaded for
|
||||
// EVENTBUS_PROVIDER=kafka; the default NATS path needs none of it. The
|
||||
// codec (codec.FromEnv) owns serialization end-to-end — Avro pulls
|
||||
// SCHEMA_REGISTRY_URL from env, JSON needs nothing — so a NATS + JSON
|
||||
// self-host requires no Kafka or Schema Registry config.
|
||||
// Dual readers retain Kafka credentials until its backlog and rollback window close.
|
||||
var kafkaBootstrapServers string
|
||||
var kafkaSaslConfig *kafka.SASLConfig
|
||||
if config.EventBusProvider() == "kafka" {
|
||||
if config.EventBusUsesKafka() {
|
||||
kafkaBootstrapServers, err = cfg.LoadKafkaBootstrapServers(ctx)
|
||||
if err != nil {
|
||||
errs.CaptureFatal(err)
|
||||
@@ -710,7 +720,11 @@ func main() {
|
||||
inboxTagRepository = repository.NewInboxTagRepository(primaryDB.Pool)
|
||||
if key := config.TypeSafeAPIKey(); key != "" {
|
||||
// One TypeSafe client for every typed judgment in this process.
|
||||
typeSafeClient = typesafe.NewClient(key, typesafe.WithBillingRedis(cache.Client))
|
||||
endpoint, err := config.TypeSafeEndpoint()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
typeSafeClient = typesafe.NewClient(key, typesafe.WithBillingRedis(cache.Client), typesafe.WithEndpoint(endpoint))
|
||||
}
|
||||
unsubscribeLinkRepository = repository.NewUnsubscribeLinkRepository(primaryDB.Pool)
|
||||
customDomainRepository = repository.NewCustomDomainRepository(primaryDB.Pool)
|
||||
@@ -817,9 +831,9 @@ func main() {
|
||||
writingGenerator = generation.NewAnthropicClient(aiKey)
|
||||
}
|
||||
creditRepository = repository.NewCreditRepository(primaryDB)
|
||||
creditAutoTopUpAttemptRepository := repository.NewCreditAutoTopUpAttemptRepository(primaryDB)
|
||||
savedCardChargeRepository := repository.NewSavedCardChargeRepository(primaryDB)
|
||||
aiSettingsRepository = repository.NewAISettingsRepository(primaryDB)
|
||||
creditService = credits.NewService(creditRepository, aiSettingsRepository, cache)
|
||||
creditService = credits.NewService(creditRepository, aiSettingsRepository, instanceSettings, cache)
|
||||
webhookRepository := repository.NewWebhookRepositorySealed(primaryDB.Pool, credEncrypter)
|
||||
webhookService := webhook.NewService(webhookRepository)
|
||||
webhookServiceForHandler = webhookService
|
||||
@@ -861,6 +875,8 @@ func main() {
|
||||
Cache: cache,
|
||||
AppDomains: oauthService.AllowedWebhookDomains,
|
||||
})
|
||||
// An enqueue in any process wakes the worker, so an idle queue's slower poll never delays a delivery.
|
||||
go webhookWorker.Listen(ctx, primaryDB.ConnectSession)
|
||||
go webhookWorker.Run(ctx)
|
||||
campaignProgressRepository := repository.NewCampaignProgressRepository(primaryDB.Pool)
|
||||
warmupService = warmupapp.NewService(warmupRepository)
|
||||
@@ -872,7 +888,7 @@ func main() {
|
||||
// Initialize new services for trial, feature gates, and worker assignment.
|
||||
// The trial service seeds the free plan's monthly AI-credit allowance at
|
||||
// trial start (planRepo + creditService, both already constructed above).
|
||||
trialService = trial.NewService(subscriptionRepository, userRepostory, planRepository, creditService)
|
||||
trialService = trial.NewService(subscriptionRepository, planRepository, creditService)
|
||||
featureGateService = feature.NewService(subscriptionRepository, planRepository)
|
||||
// An approved daily-send increase must raise what is enforced, not
|
||||
// only what the dashboard shows.
|
||||
@@ -912,12 +928,15 @@ func main() {
|
||||
errs.CaptureFatal(err)
|
||||
log.Fatal(err)
|
||||
}
|
||||
stripeService = stripe.NewService(stripeCfg, subscriptionRepository, planRepository, workerAssignmentService, discountService, creditAutoTopUpAttemptRepository)
|
||||
stripeService = stripe.NewService(stripeCfg, subscriptionRepository, planRepository, workerAssignmentService, discountService, savedCardChargeRepository)
|
||||
} else {
|
||||
stripeService = stripe.NewDisabledService()
|
||||
}
|
||||
|
||||
tokenService = token.NewService(primaryDB, tokenRepostory, cache, geoloc, authCfg.AuthSecret)
|
||||
if os.Getenv("CAMPAIGN_ATTACHMENT_DOWNLOAD_PROXY") == "true" {
|
||||
attachmentDownloads = attachmentdownload.New(authCfg.AuthSecret)
|
||||
}
|
||||
adminDevice = admindevice.New(cache, tokenService, oauthPublicBaseURL(apiCfg.Hostname), authCfg.AuthSecret)
|
||||
// A revoked session takes the user's open sockets with it.
|
||||
if streamingPublisher != nil {
|
||||
@@ -963,11 +982,13 @@ func main() {
|
||||
// views refresh live via the spine.
|
||||
stripeService.WireCredits(creditService, auditService)
|
||||
|
||||
// Credit watch: after every fresh debit it fires the low-balance alert
|
||||
// (once per day) and, when enabled, buys the configured pack off-session
|
||||
// (auto top-up). Runs detached so charges are never slowed.
|
||||
creditWatch := creditwatch.New(aiSettingsRepository, creditRepository, cache, streamingPublisher, stripeService)
|
||||
creditService.SetMonitor(creditWatch.OnBalanceChanged)
|
||||
// Balance: after every fresh debit it sends the low and empty balance
|
||||
// notices and starts an automatic reload on the saved card. Runs
|
||||
// detached so charges are never slowed; a sweep resumes retries.
|
||||
balanceService = balance.New(creditService, aiSettingsRepository, savedCardChargeRepository, subscriptionRepository,
|
||||
stripeService, cache, streamingPublisher, nil, auditService)
|
||||
creditService.SetMonitor(balanceService.OnBalanceChanged)
|
||||
stripeService.WireBalance(balanceService)
|
||||
|
||||
authService = auth.NewService(
|
||||
authRepostory,
|
||||
@@ -1145,22 +1166,17 @@ func main() {
|
||||
GoogleIOSClientID: authCfg.GoogleIOSClientID,
|
||||
}
|
||||
|
||||
// Referral program. Wired bidirectionally with Stripe (webhooks reward and
|
||||
// claw back; the earnings ledger nets onto the referrer's customer balance)
|
||||
// and into auth so a signup carrying ?ref= is attributed to its referrer.
|
||||
referralRepository := repository.NewReferralRepository(primaryDB.Pool)
|
||||
referralService = referral.NewService(
|
||||
referralRepository,
|
||||
discountCodeRepository,
|
||||
// Referrals already attributed are still rewarded and clawed back by the
|
||||
// Stripe webhooks, onto the referrer's customer balance.
|
||||
referralService := referral.NewService(
|
||||
repository.NewReferralRepository(primaryDB.Pool),
|
||||
planRepository,
|
||||
subscriptionRepository,
|
||||
userRepostory,
|
||||
auditService,
|
||||
os.Getenv("APP_URL"),
|
||||
)
|
||||
stripeService.WireReferral(referralService)
|
||||
referralService.WireBalancer(stripeService)
|
||||
authService.WireReferral(referralService)
|
||||
var passkeyErr error
|
||||
passkeyService, passkeyErr = passkey.New(passkey.Deps{
|
||||
Repo: webauthnRepository,
|
||||
@@ -1202,6 +1218,7 @@ func main() {
|
||||
// Fan platform events (replies, bounces, warmup health, booked meetings)
|
||||
// out to integration actions alongside customer webhooks.
|
||||
webhookService.WireDispatchSink(integrationServiceForHandler.DispatchAny)
|
||||
integrationServiceForHandler.SetEvents(webhookService)
|
||||
|
||||
// Reflect the active infrastructure backends into storage_backends so
|
||||
// the admin UI can display what's running. Read-only entries — they
|
||||
@@ -1211,6 +1228,7 @@ func main() {
|
||||
fleetNodeRepo = repository.NewFleetNodeRepository(primaryDB)
|
||||
fleetSettingsRepo = repository.NewFleetSettingsRepository(primaryDB)
|
||||
fleetNodeService = fleetnode.New(fleetNodeRepo, workerRepository, fleetSettingsRepo)
|
||||
nodeScopeService = nodescope.New(repository.NewNodeScopeRepository(primaryDB), cache.Client)
|
||||
// Idle unless a staged rollout was started; every replica may run it.
|
||||
go fleetNodeService.RunRolloutLoop(ctx, 30*time.Second)
|
||||
settingsRegistrar := settings.NewRegistrar(storageBackendRepo)
|
||||
@@ -1276,6 +1294,14 @@ func main() {
|
||||
UpdaterToken: getenvDefault("UPDATER_TOKEN", os.Getenv("INTERNAL_API_TOKEN")),
|
||||
})
|
||||
updatesService.Start(ctx)
|
||||
// The worker Auto Scaling Group scales on this; unset on every other deployment.
|
||||
if fleet := fleetmetrics.FleetName(); fleet != "" {
|
||||
go func() {
|
||||
if err := fleetmetrics.Run(ctx, primaryDB, fleet); err != nil {
|
||||
log.Printf("Warning: fleet utilization metric disabled: %v", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// Warmup for a mailbox a linked instance runs is queued for that instance instead of a worker.
|
||||
eventsPublisher := poollink.NewSelfExecutionPublisher(events.NewPublisher(bus, s3, codecImpl, cipherService),
|
||||
@@ -1306,6 +1332,11 @@ func main() {
|
||||
emailService.WireMailboxCredentials(mailboxCredentials)
|
||||
// Seed Graph delta cursors when the reconciler reloads mailboxes.
|
||||
emailService.WireGraphDelta(repository.NewEmailGraphDeltaRepository(primaryDB))
|
||||
// Provider push: Graph webhooks and Gmail watches wake the worker holding the mailbox.
|
||||
mailPushRepository := repository.NewMailboxPushRepository(primaryDB)
|
||||
mailPushSettings = mailpush.NewSettings(authCfg.AuthSecret, mailPushRepository)
|
||||
mailPushWaker = mailpush.NewWaker(mailPushRepository, eventsPublisher, cache)
|
||||
emailService.WirePush(mailPushSettings)
|
||||
// The Gmail equivalent: without it a reloaded mailbox re-bootstraps its
|
||||
// history cursor and skips everything that arrived since the last sync.
|
||||
emailService.WireEmailHistoryID(repository.NewEmailHistoryIDRepository(primaryDB))
|
||||
@@ -1349,7 +1380,7 @@ func main() {
|
||||
// codes and runs enrolled mailboxes as warmup-only accounts; the
|
||||
// self-hosted side keeps the link and mirrors the cloud's state.
|
||||
poolLinkRepository := repository.NewPoolLinkRepository(primaryDB.Pool, primaryDB.ConnectSession)
|
||||
poolLinkService = poollink.NewService(poolLinkRepository, emailRepostory, emailService, analyticsService, warmupRepository, featureGateService, organizationService, planRepository)
|
||||
poolLinkService = poollink.NewService(poolLinkRepository, emailRepostory, emailService, analyticsService, warmupRepository, featureGateService, organizationService)
|
||||
emailService.WirePoolLink(poolLinkRepository)
|
||||
if g, ok := featureGateService.(interface{ WirePoolLink(feature.PoolLinkReader) }); ok {
|
||||
g.WirePoolLink(poolLinkService)
|
||||
@@ -1544,6 +1575,10 @@ func main() {
|
||||
if aware, ok := campaignService.(campaign.AudienceAware); ok {
|
||||
aware.WireAudience(campaignAudienceRepository)
|
||||
}
|
||||
// A start checks the copy of every active A/B variant, not only the steps.
|
||||
if aware, ok := campaignService.(campaign.VariantAware); ok {
|
||||
aware.WireVariants(advancedRepository)
|
||||
}
|
||||
// A start with nothing left to send says whether verification is why.
|
||||
if aware, ok := campaignService.(campaign.ProgressAware); ok {
|
||||
aware.WireProgress(campaignProgressRepository)
|
||||
@@ -1803,6 +1838,9 @@ func main() {
|
||||
}
|
||||
notificationService.WirePush(pushSender, repository.NewDeviceTokenRepository(primaryDB.Pool), cache.Client)
|
||||
advancedService.WireNotifier(notificationService)
|
||||
if balanceService != nil {
|
||||
balanceService.WireNotifier(notificationService)
|
||||
}
|
||||
// New-device sign-in alerts: the token service fires this on session
|
||||
// creation from an unrecognized device, delivered as a security
|
||||
// notification (in-app + email per the user's channels).
|
||||
@@ -1935,6 +1973,11 @@ func main() {
|
||||
Scopes: []string{"openid", "email"}, Endpoint: g.Endpoint,
|
||||
}
|
||||
}
|
||||
var googleMailboxClientID string
|
||||
// Named only when the client can complete a sign-in, so the dashboard offers no Google reconnect that cannot work.
|
||||
if g := oauth2Cfg.InboxAuthorization.Google; g != nil && g.ClientSecret != "" {
|
||||
googleMailboxClientID = g.ClientID
|
||||
}
|
||||
delegationService = delegation.NewService(delegation.Deps{
|
||||
Repo: repository.NewDomainGrantRepository(primaryDB),
|
||||
Mailboxes: emailService,
|
||||
@@ -1946,6 +1989,8 @@ func main() {
|
||||
MicrosoftRedirect: outlookApp.RedirectURL,
|
||||
GoogleSignin: googleSignin,
|
||||
Prover: domainProver,
|
||||
|
||||
GoogleMailboxClientID: googleMailboxClientID,
|
||||
})
|
||||
if w, ok := poolLinkService.(interface {
|
||||
WireDelegation(poollink.DelegatedTokenBroker)
|
||||
@@ -1968,6 +2013,7 @@ func main() {
|
||||
Mailboxes: emailRepostory,
|
||||
Reconnect: emailService,
|
||||
Grants: delegationService,
|
||||
Consent: emailService,
|
||||
Cache: cache,
|
||||
NewClient: sandboxVendors,
|
||||
})
|
||||
@@ -1975,8 +2021,18 @@ func main() {
|
||||
// Sending domains: tracking host per domain and the bare-domain redirect.
|
||||
sendingDomainService = sendingdomain.NewService(repository.NewDomainRedirectRepository(primaryDB), emailRepostory, nil, domainProver)
|
||||
sendingDomainService.WireAuditor(auditService)
|
||||
// A website the workspace proves with its TXT record becomes one of its own domains too.
|
||||
ownDomains.WireWebsites(repository.NewWebsiteDomainRepository(primaryDB), domainProver, nil)
|
||||
sendingDomainService.WireOwnDomains(ownDomains)
|
||||
sendingDomainService.WireCustomHosts(customHosts)
|
||||
// Behind a Cloudflare for SaaS zone, every served customer name is registered there as it verifies.
|
||||
if edge := cfsaas.New(cfsaas.Config{ZoneID: config.CloudflareSaaSZoneID(), APIToken: config.CloudflareSaaSAPIToken(), Origin: config.CloudflareSaaSOrigin()}); edge != nil {
|
||||
edgeHosts := edgehost.New(repository.NewEdgeHostnameRepository(primaryDB.Pool), edge, func() []string {
|
||||
return []string{config.TrackingHostname(), config.FormsHostname()}
|
||||
})
|
||||
sendingDomainService.WireEdge(edgeHosts)
|
||||
go edgeHosts.Start(ctx)
|
||||
}
|
||||
// A linked self-hosted instance can have Warmbly Cloud serve a redirect instead.
|
||||
sendingDomainService.WireCloud(cloudLinkService)
|
||||
cloudLinkService.OnDisconnect(sendingDomainService.MarkCloudUnlinked)
|
||||
@@ -2014,6 +2070,9 @@ func main() {
|
||||
go mailboxAvatars.Start(ctx)
|
||||
}
|
||||
vendorConnService.SetImporter(mailboxImportService)
|
||||
vendorConnService.WireSigninSwitch(auditService, func(ctx context.Context) bool {
|
||||
return instanceSettings == nil || instanceSettings.AutoVendorReconnect(ctx)
|
||||
})
|
||||
sendingDomainService.WireVendors(vendorConnService)
|
||||
go vendorConnService.StartReconnect(ctx)
|
||||
go mailboxImportService.Start(ctx)
|
||||
@@ -2077,6 +2136,9 @@ func main() {
|
||||
trialExpirationJob.WireNotifier(notificationService)
|
||||
trialScheduler := jobs.NewTrialExpirationScheduler(trialExpirationJob, 1*time.Hour)
|
||||
go trialScheduler.Start(ctx)
|
||||
if balanceService != nil {
|
||||
go balanceService.Start(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
// Local task dispatcher (TASKS_PROVIDER=local): the in-process poller
|
||||
@@ -2128,20 +2190,26 @@ func main() {
|
||||
go segmentService.StartCampaignSegmentSync(ctx, 2*time.Minute)
|
||||
}
|
||||
|
||||
// Loops that keep their place in memory run on one backend at a time, the
|
||||
// same one for as long as it holds the lock, so a fleet of replicas does
|
||||
// the work once instead of once per replica.
|
||||
elector := leader.New(primaryDB, "backend")
|
||||
|
||||
// Worker reconciler: assign + (re)load every active mailbox onto its
|
||||
// worker. Workers hold accounts in memory only, so this is what makes a
|
||||
// freshly onboarded account send/sync and re-seeds a restarted worker.
|
||||
go emailService.StartWorkerReconciler(ctx, 60*time.Second)
|
||||
elector.Go("worker_reconciler", func(ctx context.Context) { emailService.StartWorkerReconciler(ctx, 60*time.Second) })
|
||||
|
||||
// Unibox search backfill: record the searchable text of messages synced
|
||||
// before bodies were indexed, so search covers the whole archive and not
|
||||
// just new mail. Walks the table once, then returns.
|
||||
go uniboxService.StartBodyTextBackfill(ctx)
|
||||
elector.Go("unibox_body_backfill", uniboxService.StartBodyTextBackfill)
|
||||
|
||||
// Automation signing secrets live in each connection's sealed config.
|
||||
if m, ok := integrationServiceForHandler.(interface{ StartSigningSecretMigration(context.Context) }); ok {
|
||||
go m.StartSigningSecretMigration(ctx)
|
||||
elector.Go("signing_secret_migration", m.StartSigningSecretMigration)
|
||||
}
|
||||
go elector.Run(ctx)
|
||||
|
||||
// Danger zone: schedule + execute delayed deletions (orgs, accounts).
|
||||
dangerZoneRepository := repository.NewDangerZoneRepository(primaryDB.Pool)
|
||||
@@ -2152,6 +2220,7 @@ func main() {
|
||||
emailNotificationService,
|
||||
eventsPublisher,
|
||||
os.Getenv("FRONTEND_BASE_URL"),
|
||||
dangerZoneBilling(stripeService),
|
||||
)
|
||||
dangerZoneJob := jobs.NewDangerZoneJob(dangerZoneService)
|
||||
dangerZoneScheduler := jobs.NewDangerZoneScheduler(dangerZoneJob, 1*time.Hour)
|
||||
@@ -2195,6 +2264,9 @@ func main() {
|
||||
auditRetentionScheduler := jobs.NewAuditRetentionScheduler(auditRetentionJob, 6*time.Hour)
|
||||
go auditRetentionScheduler.Start(ctx)
|
||||
|
||||
// Feeds, logs and finished bookkeeping rows past their windows, in batches.
|
||||
go jobs.NewTableRetentionJob(repository.NewTableRetentionRepository(primaryDB.Pool), instanceSettings).Start(ctx, 6*time.Hour)
|
||||
|
||||
// Website tracking: the snippet's settings, the ingest path the tracking
|
||||
// service forwards page views to, and the per-workspace retention sweep
|
||||
// that keeps the window promised on the settings page.
|
||||
@@ -2246,11 +2318,35 @@ func main() {
|
||||
Repo: repository.NewContactImportRepository(primaryDB),
|
||||
Contacts: contactService,
|
||||
Publisher: streamingPublisher,
|
||||
Events: webhookServiceForHandler,
|
||||
// New addresses are checked right away rather than on the next tick.
|
||||
Kicked: emailVerifyService.Kick,
|
||||
})
|
||||
go contactImportService.Run(ctx)
|
||||
}
|
||||
if contactService != nil {
|
||||
// The lead finder's keyed providers read the workspace's own key first,
|
||||
// then the operator's; OpenStreetMap needs none.
|
||||
leadfinder.RegisterKeyChecks(integrationServiceForHandler)
|
||||
leadFinderServiceForHandler = leadfinder.NewService(leadfinder.Deps{
|
||||
Repo: repository.NewLeadFinderRepository(primaryDB.Pool),
|
||||
Integrations: integrationServiceForHandler,
|
||||
Contacts: contactService,
|
||||
Verifier: emailVerifyService,
|
||||
Credits: creditService,
|
||||
Audit: auditService,
|
||||
Config: leadfinder.Config{
|
||||
OverpassURL: cfg.GetStringOptional(ctx, "LEAD_FINDER_OVERPASS_URL", "lead_finder/overpass_url", ""),
|
||||
GeocoderURL: cfg.GetStringOptional(ctx, "LEAD_FINDER_GEOCODER_URL", "lead_finder/geocoder_url", ""),
|
||||
MapStyleLight: cfg.GetStringOptional(ctx, "LEAD_FINDER_MAP_STYLE_URL", "lead_finder/map_style_url", ""),
|
||||
MapStyleDark: cfg.GetStringOptional(ctx, "LEAD_FINDER_MAP_STYLE_DARK_URL", "lead_finder/map_style_dark_url", ""),
|
||||
GoogleKey: cfg.GetSecretOptional(ctx, "LEAD_FINDER_GOOGLE_PLACES_API_KEY", "lead_finder/google_places_api_key", ""),
|
||||
FoursquareKey: cfg.GetSecretOptional(ctx, "LEAD_FINDER_FOURSQUARE_API_KEY", "lead_finder/foursquare_api_key", ""),
|
||||
OutscraperKey: cfg.GetSecretOptional(ctx, "LEAD_FINDER_OUTSCRAPER_API_KEY", "lead_finder/outscraper_api_key", ""),
|
||||
},
|
||||
})
|
||||
go jobrun.Loop(ctx, "lead_enrichment_runs", time.Minute, true, leadFinderServiceForHandler.RunPendingEnrichment)
|
||||
}
|
||||
|
||||
// HubSpot as the workspace CRM: write-through for the CRM service, the
|
||||
// activity sink, and the outbox for automation-written records. The
|
||||
@@ -2521,7 +2617,6 @@ func main() {
|
||||
SubscriptionService: subscriptionService,
|
||||
StripeService: stripeService,
|
||||
DiscountService: discountService,
|
||||
ReferralService: referralService,
|
||||
PlanOfferService: planOfferService,
|
||||
|
||||
// Trial & feature gates
|
||||
@@ -2559,8 +2654,9 @@ func main() {
|
||||
EmailNotificationService: emailNotificationService,
|
||||
|
||||
// Advanced outreach controls
|
||||
AdvancedService: advancedService,
|
||||
UnsubscribeLinks: unsubSigner,
|
||||
AdvancedService: advancedService,
|
||||
UnsubscribeLinks: unsubSigner,
|
||||
AttachmentDownloads: attachmentDownloads,
|
||||
|
||||
// Warmup health
|
||||
WarmupService: warmupService,
|
||||
@@ -2573,6 +2669,7 @@ func main() {
|
||||
|
||||
// AI writing assistant + credit ledger
|
||||
CreditService: creditService,
|
||||
BalanceService: balanceService,
|
||||
WritingGenerator: writingGenerator,
|
||||
AIProvider: aiProvider,
|
||||
TypeSafe: typeSafeAsker(typeSafeClient),
|
||||
@@ -2580,6 +2677,9 @@ func main() {
|
||||
AITools: aiToolRegistry,
|
||||
AIAgentService: aiAgentService,
|
||||
SlackService: slackService,
|
||||
MailPush: mailPushSettings,
|
||||
MailPushWaker: mailPushWaker,
|
||||
GmailPush: mailpush.NewGmailPush(),
|
||||
ResearchService: researchService,
|
||||
SkillsService: skillsService,
|
||||
MCPService: mcpService,
|
||||
@@ -2614,6 +2714,7 @@ func main() {
|
||||
SalesforceService: salesforceServiceForHandler,
|
||||
ApolloService: apolloServiceForHandler,
|
||||
ClayService: clayServiceForHandler,
|
||||
LeadFinderService: leadFinderServiceForHandler,
|
||||
|
||||
WebsocketURI: websocketURI,
|
||||
|
||||
@@ -2639,6 +2740,7 @@ func main() {
|
||||
FleetNodeRepo: fleetNodeRepo,
|
||||
FleetSettingsRepo: fleetSettingsRepo,
|
||||
FleetNodes: fleetNodeService,
|
||||
NodeScope: nodeScopeService,
|
||||
KeyStatusDB: keyStatusDB,
|
||||
|
||||
// Danger zone
|
||||
@@ -2671,6 +2773,9 @@ func main() {
|
||||
Cache: authCache,
|
||||
PoolLinkService: poolLinkService,
|
||||
}
|
||||
if fleetNodeService != nil {
|
||||
m.NodeCredentials = fleetNodeService
|
||||
}
|
||||
|
||||
oidcH := &middleware.OidcHandler{
|
||||
ServiceAccount: serviceAccount,
|
||||
@@ -2683,19 +2788,30 @@ func main() {
|
||||
|
||||
router := api.Run(h, m, oidcH, addr, ginMode, allowedOrigins)
|
||||
|
||||
srv := &http.Server{
|
||||
Addr: addr,
|
||||
Handler: router,
|
||||
tlsListen, err := servetls.FromEnv(os.Getenv)
|
||||
if err != nil {
|
||||
log.Fatalf("Invalid TLS listener setting: %v", err)
|
||||
}
|
||||
srv, tlsSrv, err := tlsListen.Servers(addr, router)
|
||||
if err != nil {
|
||||
log.Fatalf("TLS listener: %v", err)
|
||||
}
|
||||
servers := []*http.Server{srv}
|
||||
if tlsSrv != nil {
|
||||
servers = append(servers, tlsSrv)
|
||||
if exp := servetls.Expiry(tlsSrv.TLSConfig); time.Until(exp) < 30*24*time.Hour {
|
||||
log.Printf("TLS listener certificate expires %s; replace it before then", exp.Format(time.RFC3339))
|
||||
}
|
||||
}
|
||||
|
||||
// Start server in a goroutine
|
||||
go func() {
|
||||
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
log.Fatalf("Server error: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
log.Println("Backend started on", addr)
|
||||
for _, s := range servers {
|
||||
go func(s *http.Server) {
|
||||
if err := servetls.ListenAndServe(s); err != nil && err != http.ErrServerClosed {
|
||||
log.Fatalf("Server error: %v", err)
|
||||
}
|
||||
}(s)
|
||||
log.Println("Backend started on", s.Addr)
|
||||
}
|
||||
|
||||
// Wait for interrupt signal for graceful shutdown
|
||||
sigCh := make(chan os.Signal, 1)
|
||||
@@ -2722,8 +2838,10 @@ func main() {
|
||||
}
|
||||
}()
|
||||
}
|
||||
if err := srv.Shutdown(shutdownCtx); err != nil {
|
||||
log.Printf("Server shutdown error: %v", err)
|
||||
for _, s := range servers {
|
||||
if err := s.Shutdown(shutdownCtx); err != nil {
|
||||
log.Printf("Server shutdown error: %v", err)
|
||||
}
|
||||
}
|
||||
drained.Wait()
|
||||
|
||||
@@ -2901,3 +3019,12 @@ func typeSafeAsker(c *typesafe.Client) typesafe.Asker {
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// dangerZoneBilling is the provider account deletion asks about owned
|
||||
// subscriptions, or nil when billing is off and the local record is the answer.
|
||||
func dangerZoneBilling(svc stripe.StripeService) dangerzone.BillingLookup {
|
||||
if config.BillingProvider() != "stripe" {
|
||||
return nil
|
||||
}
|
||||
return svc
|
||||
}
|
||||
|
||||
@@ -33,6 +33,7 @@ const (
|
||||
flagInt
|
||||
flagBool
|
||||
flagStrings
|
||||
flagFloat
|
||||
)
|
||||
|
||||
// argSpec is one positional argument, filling the next {} in the path.
|
||||
@@ -152,12 +153,15 @@ func buildEndpoint(f *Factory, r resource, e endpoint) *cobra.Command {
|
||||
// Flag values are held here so the runner reads whatever cobra parsed.
|
||||
strs := map[string]*string{}
|
||||
ints := map[string]*int{}
|
||||
floats := map[string]*float64{}
|
||||
bools := map[string]*bool{}
|
||||
slices := map[string]*[]string{}
|
||||
for _, fl := range e.Flag {
|
||||
switch fl.Kind {
|
||||
case flagInt:
|
||||
ints[fl.Name] = cmd.Flags().IntP(fl.Name, fl.Short, 0, fl.Help)
|
||||
case flagFloat:
|
||||
floats[fl.Name] = cmd.Flags().Float64P(fl.Name, fl.Short, 0, fl.Help)
|
||||
case flagBool:
|
||||
bools[fl.Name] = cmd.Flags().BoolP(fl.Name, fl.Short, false, fl.Help)
|
||||
case flagStrings:
|
||||
@@ -204,6 +208,8 @@ func buildEndpoint(f *Factory, r resource, e endpoint) *cobra.Command {
|
||||
switch fl.Kind {
|
||||
case flagInt:
|
||||
value = *ints[fl.Name]
|
||||
case flagFloat:
|
||||
value = *floats[fl.Name]
|
||||
case flagBool:
|
||||
value = *bools[fl.Name]
|
||||
case flagStrings:
|
||||
|
||||
+9
-5
@@ -144,7 +144,7 @@ ask before they do it.`,
|
||||
Name: "add-step", Short: "Add a sequence step",
|
||||
Method: http.MethodPost, Path: "/campaigns/{id}/steps", Body: bodyRequired,
|
||||
Args: []argSpec{{Name: "id", Help: "The campaign's id"}},
|
||||
Example: " $ warmbly campaign add-step CAMPAIGN_ID --subject \"Quick question\" --body-html \"<p>Hi {{first_name}}</p>\"",
|
||||
Example: " $ warmbly campaign add-step CAMPAIGN_ID --subject \"Quick question\" --body-html \"<p>Hi {{.FirstName}}</p>\"",
|
||||
Flag: []flagSpec{
|
||||
{Name: "subject", Help: "Subject line"},
|
||||
{Name: "body-html", Help: "HTML body"},
|
||||
@@ -896,8 +896,10 @@ Replying and composing put real mail on the wire, so both ask before they do.`,
|
||||
flagSpec{Name: "unseen", Help: "Only unread messages", Kind: flagBool, Query: true},
|
||||
flagSpec{Name: "awaiting-reply", Help: "Only threads waiting on a reply", Kind: flagBool, Query: true, Key: "awaiting_reply"},
|
||||
flagSpec{Name: "automated", Help: "true for only mail nobody wrote (alerts, bounces, auto-replies), false to leave it out", Query: true},
|
||||
flagSpec{Name: "since", Help: "Only messages after this time (RFC 3339)", Query: true},
|
||||
flagSpec{Name: "until", Help: "Only messages before this time (RFC 3339)", Query: true},
|
||||
flagSpec{Name: "campaign", Help: "Only conversations from this campaign's sends (campaign id)", Query: true, Key: "campaign_id"},
|
||||
flagSpec{Name: "contact", Help: "Only conversations with this contact (contact id)", Query: true, Key: "contact_id"},
|
||||
flagSpec{Name: "since", Help: "Only messages from this date (YYYY-MM-DD, UTC) or time (RFC 3339) on", Query: true},
|
||||
flagSpec{Name: "until", Help: "Only messages through this date (YYYY-MM-DD, UTC) or before this time (RFC 3339)", Query: true},
|
||||
),
|
||||
Table: output.Table{Root: "data", Columns: messageColumns, Empty: "Nothing in the inbox."},
|
||||
},
|
||||
@@ -1585,7 +1587,8 @@ func placementSpec() resource {
|
||||
{Name: "seed", Help: "Only this seed inbox's id, with --panel workspace (repeatable)", Kind: flagStrings, Key: "seed_ids"},
|
||||
{Name: "provider", Help: "Only seeds at this provider, e.g. gmail or outlook (repeatable)", Kind: flagStrings, Key: "families"},
|
||||
{Name: "on-unavailable", Help: "defer (retry a mailbox that cannot send yet, the default) or skip", Key: "on_unavailable"},
|
||||
{Name: "max-credits", Help: "Pay up to this many credits in total for tests past this month's free ones", Kind: flagInt, Key: "max_credits"},
|
||||
{Name: "max-usd", Help: "Pay up to this many dollars in total for tests past this month's free ones", Kind: flagFloat, Key: "max_usd"},
|
||||
{Name: "max-credits", Help: "Older form of --max-usd, counted in credits", Kind: flagInt, Key: "max_credits"},
|
||||
}
|
||||
return resource{
|
||||
Name: "placement",
|
||||
@@ -1629,7 +1632,8 @@ mailboxes, a few at a time.`,
|
||||
{Name: "seed", Help: "Only this seed inbox's id, with --panel workspace (repeatable)", Kind: flagStrings, Key: "seed_ids"},
|
||||
{Name: "provider", Help: "Only seeds at this provider, e.g. gmail or outlook (repeatable)", Kind: flagStrings, Key: "families"},
|
||||
{Name: "pace", Help: "spaced (about a minute apart) or quick (a few seconds apart)", Key: "pace"},
|
||||
{Name: "max-credits", Help: "Pay up to this many credits when this month's free tests are used up", Kind: flagInt, Key: "max_credits"},
|
||||
{Name: "max-usd", Help: "Pay up to this many dollars when this month's free tests are used up", Kind: flagFloat, Key: "max_usd"},
|
||||
{Name: "max-credits", Help: "Older form of --max-usd, counted in credits", Kind: flagInt, Key: "max_credits"},
|
||||
},
|
||||
Table: testTable,
|
||||
},
|
||||
|
||||
+65
-10
@@ -3,7 +3,9 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"github.com/warmbly/warmbly/internal/app/cloudlink"
|
||||
"github.com/warmbly/warmbly/internal/app/consumermetrics"
|
||||
emailverifyapp "github.com/warmbly/warmbly/internal/app/emailverify"
|
||||
"github.com/warmbly/warmbly/internal/app/mailpush"
|
||||
"github.com/warmbly/warmbly/internal/app/slackapp"
|
||||
"log"
|
||||
"os"
|
||||
@@ -20,11 +22,11 @@ import (
|
||||
"github.com/google/uuid"
|
||||
"github.com/warmbly/warmbly/internal/app/advanced"
|
||||
"github.com/warmbly/warmbly/internal/app/audit"
|
||||
"github.com/warmbly/warmbly/internal/app/balance"
|
||||
"github.com/warmbly/warmbly/internal/app/cipher"
|
||||
jobs "github.com/warmbly/warmbly/internal/app/consumer"
|
||||
"github.com/warmbly/warmbly/internal/app/contact"
|
||||
"github.com/warmbly/warmbly/internal/app/credits"
|
||||
"github.com/warmbly/warmbly/internal/app/creditwatch"
|
||||
"github.com/warmbly/warmbly/internal/app/crmmode"
|
||||
"github.com/warmbly/warmbly/internal/app/feature"
|
||||
"github.com/warmbly/warmbly/internal/app/hubspot"
|
||||
@@ -64,6 +66,7 @@ import (
|
||||
"github.com/warmbly/warmbly/internal/pkg/generation"
|
||||
"github.com/warmbly/warmbly/internal/pkg/geo"
|
||||
"github.com/warmbly/warmbly/internal/pkg/nodeagent"
|
||||
"github.com/warmbly/warmbly/internal/pkg/nodeauth"
|
||||
"github.com/warmbly/warmbly/internal/pkg/typesafe"
|
||||
"github.com/warmbly/warmbly/internal/repository"
|
||||
"github.com/warmbly/warmbly/internal/tasks"
|
||||
@@ -146,14 +149,10 @@ func main() {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// Event bus + codec. Kafka bootstrap/SASL is only loaded for
|
||||
// EVENTBUS_PROVIDER=kafka; codec.FromEnv owns serialization (Avro pulls
|
||||
// SCHEMA_REGISTRY_URL from env, JSON needs nothing). The bus drives both the
|
||||
// inbound worker-events subscription and outbound publishing, so a NATS +
|
||||
// JSON self-host needs no Kafka or Schema Registry config.
|
||||
// Dual readers retain Kafka credentials until its backlog and rollback window close.
|
||||
var kafkaBootstrapServers string
|
||||
var kafkaSaslConfig *kafka.SASLConfig
|
||||
if config.EventBusProvider() == "kafka" {
|
||||
if config.EventBusUsesKafka() {
|
||||
kafkaBootstrapServers, err = cfg.LoadKafkaBootstrapServers(ctx)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
@@ -222,6 +221,12 @@ func main() {
|
||||
emailGraphDeltaRepo := repository.NewEmailGraphDeltaRepository(primaryDB)
|
||||
emailAccountErrorRepo := repository.NewEmailAccountErrorRepository(primaryDB)
|
||||
warmupRepo := repository.NewWarmupRepository(primaryDB.Pool)
|
||||
// Behind a transaction pooler a receipt's lock waits on a direct session, never on a pooled connection.
|
||||
if locks, err := primaryDB.SessionLocks(); err != nil {
|
||||
log.Fatalf("Failed to prepare direct database sessions for warmup receipt locks: %v", err)
|
||||
} else if locks != nil {
|
||||
warmupRepo.(repository.WarmupSessionLocker).UseSessionLocks(locks)
|
||||
}
|
||||
warmupService := warmupapp.NewService(warmupRepo)
|
||||
// Push warmup-health transitions live to the dashboard. The health sweep
|
||||
// runs in this process, so the realtime publisher is wired here.
|
||||
@@ -256,6 +261,7 @@ func main() {
|
||||
integrationRepoC := repository.NewIntegrationRepository(primaryDB.Pool)
|
||||
integrationServiceC := integration.NewService(integrationRepoC, cipherService, integration.NewOAuthManager())
|
||||
webhookService.WireDispatchSink(integrationServiceC.DispatchAny)
|
||||
integrationServiceC.SetEvents(webhookService)
|
||||
// Replies, opens and clicks are raised here, so the Salesforce outbox
|
||||
// records them here too; the backend drains it. Automation upserts take
|
||||
// the native path as well.
|
||||
@@ -275,10 +281,14 @@ func main() {
|
||||
// optional model layer rides the same OpenAI-first provider.
|
||||
creditRepoC := repository.NewCreditRepository(primaryDB)
|
||||
aiSettingsRepoC := repository.NewAISettingsRepository(primaryDB)
|
||||
creditServiceC := credits.NewService(creditRepoC, aiSettingsRepoC, redisCache)
|
||||
creditServiceC := credits.NewService(creditRepoC, aiSettingsRepoC, instancesettings.NewService(instancesettings.NewStore(primaryDB.Pool)), redisCache)
|
||||
// Consumer-side debits (automation AI nodes) also feed the low-balance
|
||||
// alert. Auto top-up stays backend-only (no Stripe service here).
|
||||
creditServiceC.SetMonitor(creditwatch.New(aiSettingsRepoC, creditRepoC, redisCache, streamingPublisher, nil).OnBalanceChanged)
|
||||
// No Stripe here: the backend's sweep starts reloads for work charged in
|
||||
// this process; notices go out from here.
|
||||
balanceC := balance.New(creditServiceC, aiSettingsRepoC, repository.NewSavedCardChargeRepository(primaryDB),
|
||||
repository.NewSubscriptionRepository(primaryDB.Pool), nil, redisCache, streamingPublisher, nil, nil)
|
||||
creditServiceC.SetMonitor(balanceC.OnBalanceChanged)
|
||||
var aiProviderC generation.Provider
|
||||
// Pluggable web search (Serper/SearXNG) backs the AI switch's optional
|
||||
// company lookup on reply-triggered automations that run in the consumer.
|
||||
@@ -308,7 +318,11 @@ func main() {
|
||||
// no key is configured, and every feature that reads it stays off.
|
||||
var typeSafeClient *typesafe.Client
|
||||
if key := config.TypeSafeAPIKey(); key != "" {
|
||||
typeSafeClient = typesafe.NewClient(key, typesafe.WithBillingRedis(redisCache.Client))
|
||||
endpoint, err := config.TypeSafeEndpoint()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
typeSafeClient = typesafe.NewClient(key, typesafe.WithBillingRedis(redisCache.Client), typesafe.WithEndpoint(endpoint))
|
||||
}
|
||||
if aiProviderC != nil {
|
||||
replyclassify.SetModelClassifier(func(ctx context.Context, system, user string) (string, error) {
|
||||
@@ -463,6 +477,7 @@ func main() {
|
||||
}
|
||||
notificationService.WirePush(pushSender, repository.NewDeviceTokenRepository(primaryDB.Pool), redisCache.Client)
|
||||
advancedService.WireNotifier(notificationService)
|
||||
balanceC.WireNotifier(notificationService)
|
||||
// Reply pulses fire in THIS process too (inbox ingest classifies replies).
|
||||
advancedService.WireRealtime(streamingPublisher)
|
||||
// A lifted reply opt-out is recorded like a member lifting one by hand.
|
||||
@@ -544,6 +559,7 @@ func main() {
|
||||
|
||||
jobsService := &jobs.JobsService{
|
||||
CampaignIsolationEnabled: config.CampaignSendIsolationEnabled(),
|
||||
DBConns: primaryDB.Pool.Config().MaxConns,
|
||||
Bus: consumerBus,
|
||||
Codec: consumerCodec,
|
||||
UniboxRepository: uniboxRepo,
|
||||
@@ -552,6 +568,7 @@ func main() {
|
||||
EmailHistoryIDRepository: emailHistoryIDRepo,
|
||||
EmailGraphDeltaRepository: emailGraphDeltaRepo,
|
||||
EmailSyncStateRepository: repository.NewEmailSyncStateRepository(primaryDB),
|
||||
MailboxPushRepository: repository.NewMailboxPushRepository(primaryDB),
|
||||
ArrivalOutbox: repository.NewDurableEmailMessageMapRepository(primaryDB, cipherService),
|
||||
EmailAccountErrorRepository: emailAccountErrorRepo,
|
||||
WarmupRepo: warmupRepo,
|
||||
@@ -576,6 +593,7 @@ func main() {
|
||||
AdminRepo: repository.NewAdminRepository(primaryDB.Pool),
|
||||
AssignmentService: workerAssignmentSvc,
|
||||
Notifier: notificationService,
|
||||
UniboxAccess: feature.NewService(subscriptionRepoConsumer, planRepoConsumer),
|
||||
OpsNotifier: opsNotifierC,
|
||||
TaskRepo: taskRepo,
|
||||
CampaignRepo: campaignRepo,
|
||||
@@ -606,6 +624,9 @@ func main() {
|
||||
// Start DLQ auto-retry loop in background (every 60 seconds)
|
||||
go jobsService.StartDLQRetryLoop(ctx, 60*time.Second)
|
||||
|
||||
// Hand significant step A/B winners their step when auto-promote is on.
|
||||
go jobsService.StartABAutoPromoteLoop(ctx, 15*time.Minute)
|
||||
|
||||
// Start warmup health evaluation sweep (every hour)
|
||||
go jobsService.StartWarmupHealthSweep(ctx, 1*time.Hour)
|
||||
|
||||
@@ -649,6 +670,26 @@ func main() {
|
||||
// result never came back, so a lead is never held in flight forever.
|
||||
go jobsService.StartStuckSendReclaimer(ctx, 5*time.Minute)
|
||||
|
||||
// Gmail push: the watch notifications each Gmail mailbox's worker opened arrive on
|
||||
// this Pub/Sub subscription and wake that worker. Unset keeps Gmail polling.
|
||||
if subscription := config.GmailPushSubscription(); subscription != "" {
|
||||
waker := mailpush.NewWaker(repository.NewMailboxPushRepository(primaryDB), eventsPublisher, redisCache)
|
||||
go func() {
|
||||
for ctx.Err() == nil {
|
||||
err := mailpush.RunGmailSubscriber(ctx, subscription, os.Getenv("GOOGLE_APPLICATION_CREDENTIALS_JSON"), waker)
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
log.Printf("Warning: Gmail push subscriber stopped, restarting in 30s: %v", err)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-time.After(30 * time.Second):
|
||||
}
|
||||
}
|
||||
}()
|
||||
log.Println("Gmail push: reading watch notifications from " + subscription)
|
||||
}
|
||||
|
||||
if mailboxCredentials.Reseals() {
|
||||
// Moves credentials onto workspace keys, or seals legacy plaintext OAuth tokens under the instance key.
|
||||
go jobsService.StartMailboxCredentialReseal(ctx)
|
||||
@@ -740,6 +781,19 @@ func main() {
|
||||
newConsumerAgent().Run(ctx)
|
||||
}()
|
||||
|
||||
// The consumer's ECS service scales on this; unset on every other deployment.
|
||||
if name := consumermetrics.Name(); name != "" {
|
||||
if diagnostics, ok := consumerBus.(eventbus.Diagnostics); ok {
|
||||
go func() {
|
||||
if err := consumermetrics.Run(ctx, diagnostics, name); err != nil {
|
||||
log.Printf("Warning: worker event backlog metric disabled: %v", err)
|
||||
}
|
||||
}()
|
||||
} else {
|
||||
log.Printf("Warning: worker event backlog metric disabled: the %s bus reports no backlog", consumerBus.Name())
|
||||
}
|
||||
}
|
||||
|
||||
log.Println("Consumer started, listening on", kafka.TopicWorkerEvents)
|
||||
jobsService.Start(ctx)
|
||||
|
||||
@@ -768,6 +822,7 @@ func newConsumerAgent() *nodeagent.Agent {
|
||||
Version: os.Getenv("WARMBLY_VERSION"),
|
||||
BaseURL: consumerBackendURL(),
|
||||
Token: config.NodeAPIToken(),
|
||||
Credential: nodeauth.FromEnv().Credential,
|
||||
TargetVersionPath: os.Getenv("WARMBLY_TARGET_VERSION_PATH"),
|
||||
})
|
||||
}
|
||||
|
||||
+29
-7
@@ -8,6 +8,7 @@ package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -16,6 +17,7 @@ import (
|
||||
"github.com/warmbly/warmbly/internal/formserver"
|
||||
"github.com/warmbly/warmbly/internal/observability"
|
||||
"github.com/warmbly/warmbly/internal/observability/errs"
|
||||
"github.com/warmbly/warmbly/internal/pkg/servetls"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -37,6 +39,11 @@ func main() {
|
||||
log.Fatal("INTERNAL_API_TOKEN is required (must match the backend's)")
|
||||
}
|
||||
|
||||
backendRoots, err := servetls.ClientRoots(strings.TrimSpace(os.Getenv("BACKEND_INTERNAL_CA")), strings.TrimSpace(os.Getenv("BACKEND_INTERNAL_CA_FILE")))
|
||||
if err != nil {
|
||||
log.Fatalf("invalid BACKEND_INTERNAL_CA or BACKEND_INTERNAL_CA_FILE: %v", err)
|
||||
}
|
||||
|
||||
submitLimit := 0
|
||||
if v := os.Getenv("FORM_IP_RATE_LIMIT"); v != "" {
|
||||
parsed, err := strconv.Atoi(v)
|
||||
@@ -56,6 +63,7 @@ func main() {
|
||||
srv, err := formserver.New(formserver.Config{
|
||||
BackendURL: backendURL,
|
||||
InternalToken: token,
|
||||
BackendRoots: backendRoots,
|
||||
StaticDir: staticDir,
|
||||
SubmitLimit: submitLimit,
|
||||
// The browser half of analytics and error reporting, separate from
|
||||
@@ -82,14 +90,28 @@ func main() {
|
||||
if port == "" {
|
||||
port = "8090"
|
||||
}
|
||||
log.Printf("forms service listening on :%s (backend %s)", port, backendURL)
|
||||
if err := r.Run(":" + port); err != nil {
|
||||
// The listener dying is the one failure here worth reporting: the
|
||||
// boot-time checks above are operator configuration, not a bug.
|
||||
errs.CaptureException(err)
|
||||
errs.Flush(2 * time.Second)
|
||||
log.Fatal(err)
|
||||
tlsListen, err := servetls.FromEnv(os.Getenv)
|
||||
if err != nil {
|
||||
log.Fatalf("invalid TLS listener setting: %v", err)
|
||||
}
|
||||
plain, secure, err := tlsListen.Servers(":"+port, r)
|
||||
if err != nil {
|
||||
log.Fatalf("TLS listener: %v", err)
|
||||
}
|
||||
failed := make(chan error, 2)
|
||||
for _, s := range []*http.Server{plain, secure} {
|
||||
if s == nil {
|
||||
continue
|
||||
}
|
||||
log.Printf("forms service listening on %s (backend %s)", s.Addr, backendURL)
|
||||
go func(s *http.Server) { failed <- servetls.ListenAndServe(s) }(s)
|
||||
}
|
||||
// The listener dying is the one failure here worth reporting: the
|
||||
// boot-time checks above are operator configuration, not a bug.
|
||||
err = <-failed
|
||||
errs.CaptureException(err)
|
||||
errs.Flush(2 * time.Second)
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// browserPostHogErrorTracking is the WARMBLY_POSTHOG_ERROR_TRACKING switch the
|
||||
|
||||
+9
-3
@@ -47,6 +47,7 @@ import (
|
||||
"github.com/warmbly/warmbly/internal/infrastructure/db"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
"github.com/warmbly/warmbly/internal/pkg/argon2"
|
||||
"github.com/warmbly/warmbly/internal/pkg/crypt"
|
||||
"github.com/warmbly/warmbly/internal/repository"
|
||||
"github.com/warmbly/warmbly/internal/seed"
|
||||
)
|
||||
@@ -153,6 +154,11 @@ func seedBaseline(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
if err := upsertWorker(ctx, pool, workerShared, "worker-1", "10.0.0.11", "", true); err != nil {
|
||||
return fmt.Errorf("dev worker: %w", err)
|
||||
}
|
||||
// Its own node credential, so `make worker` also runs with NODE_REQUIRE_NODE_CREDENTIAL=true.
|
||||
if _, err := pool.Exec(ctx, `UPDATE fleet_nodes SET credential_hash = $2, updated_at = now() WHERE id = $1`,
|
||||
workerShared, crypt.SHA256(seed.DevNodeCredential)); err != nil {
|
||||
return fmt.Errorf("dev worker credential: %w", err)
|
||||
}
|
||||
|
||||
// Connect two email accounts on the dev org. Without these a fresh
|
||||
// stack has no mailboxes to test campaigns or warmup against, which
|
||||
@@ -342,12 +348,12 @@ func seedRich(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
}
|
||||
seq1 := uuid.MustParse("55555555-0000-0000-0000-000000000001")
|
||||
seq2 := uuid.MustParse("55555555-0000-0000-0000-000000000002")
|
||||
if err := upsertSequence(ctx, pool, seq1, campaignID, orgBeta, "Intro", "Quick question, {{first_name}}",
|
||||
"Hi {{first_name}}, ...intro body...", 0); err != nil {
|
||||
if err := upsertSequence(ctx, pool, seq1, campaignID, orgBeta, "Intro", "Quick question, {{.FirstName}}",
|
||||
"Hi {{.FirstName}}, ...intro body...", 0); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := upsertSequence(ctx, pool, seq2, campaignID, orgBeta, "Follow-up", "Re: Quick question",
|
||||
"Hi {{first_name}}, following up...", 3); err != nil {
|
||||
"Hi {{.FirstName}}, following up...", 3); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -127,7 +127,7 @@ var apiSpecs = []apiSpec{
|
||||
{name: "mailbox release", summary: "Put a held mailbox back into campaign sending", method: "POST", path: "/emails/{id}/release"},
|
||||
|
||||
// Unified inbox.
|
||||
{name: "inbox list", summary: "List inbox messages", method: "GET", path: "/unibox", query: []string{"limit", "cursor", "address", "direction", "folder", "from", "subject", "unseen", "awaiting_reply", "since", "until"}},
|
||||
{name: "inbox list", summary: "List inbox messages", method: "GET", path: "/unibox", query: []string{"limit", "cursor", "address", "direction", "folder", "from", "subject", "unseen", "awaiting_reply", "campaign_id", "contact_id", "since", "until"}},
|
||||
{name: "inbox count", summary: "The unseen message count", method: "GET", path: "/unibox/count"},
|
||||
{name: "inbox overview", summary: "Per-mailbox and per-tag inbox rollup", method: "GET", path: "/unibox/overview"},
|
||||
{name: "inbox thread", summary: "One conversation thread", method: "GET", path: "/unibox/thread", query: []string{"thread_id", "email_id", "limit", "cursor"}},
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/app/orgtransfer"
|
||||
)
|
||||
|
||||
func runOrgAttachmentsPreflight(ctx context.Context, args []string) error {
|
||||
fs := newFlagSet("org attachments-preflight")
|
||||
file := fs.String("file", "", "immutable local workspace archive to read (required; no database or network)")
|
||||
after := fs.Int("after", 0, "skip this many attachment rows, using next_after from the previous page")
|
||||
limit := fs.Int("limit", 25, "maximum attachment rows to inspect (1 to 100)")
|
||||
digest := fs.String("expect-sha256", "", "archive_sha256 from the previous page (required with --after)")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := noExtraArgs(fs); err != nil {
|
||||
return err
|
||||
}
|
||||
if *file == "" {
|
||||
return errors.New("--file is required")
|
||||
}
|
||||
pathInfo, err := os.Stat(*file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !pathInfo.Mode().IsRegular() {
|
||||
return errors.New("--file must name a regular local archive")
|
||||
}
|
||||
f, err := openInventoryFile(*file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
info, err := f.Stat()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return errors.New("--file must name a regular local archive")
|
||||
}
|
||||
if !os.SameFile(pathInfo, info) {
|
||||
return errors.New("archive changed before inventory; retry with an immutable file")
|
||||
}
|
||||
report, err := orgtransfer.InventoryAttachments(ctx, &fileArchive{f: f, size: info.Size()}, orgtransfer.AttachmentInventoryOptions{
|
||||
After: *after, Limit: *limit, SHA256: *digest,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
finalInfo, err := f.Stat()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if finalInfo.Size() != info.Size() || !finalInfo.ModTime().Equal(info.ModTime()) {
|
||||
return errors.New("archive changed during inventory; discard this page")
|
||||
}
|
||||
enc := json.NewEncoder(os.Stdout)
|
||||
enc.SetIndent("", " ")
|
||||
return enc.Encode(report)
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
//go:build !linux && !darwin && !freebsd && !openbsd && !netbsd && !dragonfly
|
||||
|
||||
package main
|
||||
|
||||
import "os"
|
||||
|
||||
func openInventoryFile(path string) (*os.File, error) {
|
||||
return os.Open(path)
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
//go:build linux || darwin || freebsd || openbsd || netbsd || dragonfly
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func openInventoryFile(path string) (*os.File, error) {
|
||||
// Keep descriptor verification reachable if the path changes to a FIFO.
|
||||
return os.OpenFile(path, os.O_RDONLY|syscall.O_NONBLOCK, 0)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
//go:build linux || darwin || freebsd || openbsd || netbsd || dragonfly
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestOrgAttachmentsPreflightRefusesFIFOWithoutWriter(t *testing.T) {
|
||||
name := filepath.Join(t.TempDir(), "input.fifo")
|
||||
if err := syscall.Mkfifo(name, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- dispatch(t.Context(), []string{"org", "attachments-preflight", "--file", name}) }()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err == nil || err.Error() != "--file must name a regular local archive" {
|
||||
t.Fatalf("regular-file refusal: %v", err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
// Release and join the dispatch before reporting a failed bounded wait.
|
||||
f, err := os.OpenFile(name, os.O_RDWR|syscall.O_NONBLOCK, 0600)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("dispatch did not return after opening the FIFO writer")
|
||||
}
|
||||
t.Fatal("regular-file refusal must complete without a FIFO writer")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/app/orgtransfer"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
)
|
||||
|
||||
func TestOrgAttachmentsPreflightRunsOfflineThroughDispatch(t *testing.T) {
|
||||
t.Setenv("PRIMARY_DB", "invalid-unused-database")
|
||||
t.Setenv("REDIS", "invalid-unused-cache")
|
||||
t.Setenv("KMS_PROVIDER", "invalid-unused-provider")
|
||||
path := filepath.Join(t.TempDir(), "workspace.warmbly.zip")
|
||||
f, err := os.Create(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
w := zip.NewWriter(f)
|
||||
org, campaign := uuid.New(), uuid.New()
|
||||
m := orgtransfer.Manifest{
|
||||
Kind: orgtransfer.ArchiveKind, FormatVersion: 1, OrganizationID: org,
|
||||
Tables: []orgtransfer.ManifestTable{{Name: "campaigns", Rows: 1}, {Name: "campaign_attachments", Rows: 2}},
|
||||
}
|
||||
var rows bytes.Buffer
|
||||
for i := range 2 {
|
||||
name := fmt.Sprintf("notes-%d.txt", i)
|
||||
body := []byte("archived original bytes\n")
|
||||
key := models.AttachmentObjectKey(campaign, name)
|
||||
blobPath := fmt.Sprintf("blobs/%d", i)
|
||||
m.Blobs = append(m.Blobs, orgtransfer.ManifestBlob{Key: key, Path: blobPath, Size: int64(len(body)), Table: "campaign_attachments", Column: "s3_key"})
|
||||
member, err := w.Create(blobPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := member.Write(body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := json.NewEncoder(&rows).Encode(models.CampaignAttachment{
|
||||
ID: uuid.New(), CampaignID: campaign, Filename: name, S3Key: key, Size: int64(len(body)), MimeType: "text/plain",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
campaignRow, err := json.Marshal(map[string]any{"id": campaign, "organization_id": org})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for name, body := range map[string][]byte{"data/campaigns.ndjson": campaignRow, "data/campaign_attachments.ndjson": rows.Bytes()} {
|
||||
member, err := w.Create(name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := member.Write(body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
manifest, err := w.Create("manifest.json")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := json.NewEncoder(manifest).Encode(m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := w.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out, err := os.CreateTemp(t.TempDir(), "report")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer out.Close()
|
||||
stdout := os.Stdout
|
||||
os.Stdout = out
|
||||
defer func() { os.Stdout = stdout }()
|
||||
if err := dispatch(t.Context(), []string{"org", "attachments-preflight", "--file", path, "--limit", "1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := out.Seek(0, io.SeekStart); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var report orgtransfer.AttachmentInventory
|
||||
if err := json.NewDecoder(out).Decode(&report); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if report.Done || report.TotalRows != 2 || len(report.Results) != 1 || report.NextAfter != 1 || len(report.ArchiveSHA256) != 64 {
|
||||
t.Fatalf("offline command report: %+v", report)
|
||||
}
|
||||
if report.Results[0].Status != "matches_upload_profile" {
|
||||
t.Fatalf("valid attachment result: %+v", report.Results[0])
|
||||
}
|
||||
after, err := os.ReadFile(path)
|
||||
if err != nil || string(after) != string(before) {
|
||||
t.Fatal("command changed the archive")
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
|
||||
"github.com/warmbly/warmbly/internal/app/cipher"
|
||||
"github.com/warmbly/warmbly/internal/app/credits"
|
||||
"github.com/warmbly/warmbly/internal/app/instancesettings"
|
||||
"github.com/warmbly/warmbly/internal/app/mailcred"
|
||||
"github.com/warmbly/warmbly/internal/app/organization"
|
||||
"github.com/warmbly/warmbly/internal/app/orgtransfer"
|
||||
@@ -122,11 +123,11 @@ func (c *conn) trialService() trial.TrialService {
|
||||
creditSvc := credits.NewService(
|
||||
repository.NewCreditRepository(c.db),
|
||||
repository.NewAISettingsRepository(c.db),
|
||||
instancesettings.NewService(instancesettings.NewStore(c.db.Pool)),
|
||||
c.cache,
|
||||
)
|
||||
return trial.NewService(
|
||||
repository.NewSubscriptionRepository(c.db.Pool),
|
||||
c.users,
|
||||
repository.NewPlanRepository(c.db.Pool),
|
||||
creditSvc,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"text/tabwriter"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func runDB(ctx context.Context, args []string) error {
|
||||
if len(args) == 0 {
|
||||
dbUsage(os.Stderr)
|
||||
return errors.New("`db` needs a subcommand. Pick one from the list above.")
|
||||
}
|
||||
switch args[0] {
|
||||
case "help", "-h", "--help":
|
||||
dbUsage(os.Stdout)
|
||||
return nil
|
||||
case "load":
|
||||
return runDBLoad(ctx, args[1:])
|
||||
}
|
||||
dbUsage(os.Stderr)
|
||||
return fmt.Errorf("unknown db subcommand %q", args[0])
|
||||
}
|
||||
|
||||
func dbUsage(w io.Writer) {
|
||||
fmt.Fprintln(w, "Usage:\n warmblyctl db load [--limit 15] [--json]")
|
||||
}
|
||||
|
||||
// dbLoad is what the database is busy with. Read-only: it reads the statistics views and changes nothing.
|
||||
type dbLoad struct {
|
||||
MaxConnections int `json:"max_connections"`
|
||||
Connections []dbConnections `json:"connections"`
|
||||
Busy []dbBusy `json:"busy"`
|
||||
Statements []dbStatement `json:"statements"`
|
||||
StatementsNote string `json:"statements_note,omitempty"`
|
||||
Tables []dbTable `json:"tables"`
|
||||
Since *time.Time `json:"statements_since,omitempty"`
|
||||
Settings map[string]string `json:"settings"`
|
||||
}
|
||||
|
||||
type dbConnections struct {
|
||||
Application string `json:"application"`
|
||||
State string `json:"state"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
// dbBusy carries no query text: pg_stat_activity holds literal values, pg_stat_statements does not.
|
||||
type dbBusy struct {
|
||||
PID int `json:"pid"`
|
||||
Application string `json:"application"`
|
||||
State string `json:"state"`
|
||||
Seconds float64 `json:"seconds"`
|
||||
Wait string `json:"wait"`
|
||||
}
|
||||
|
||||
type dbStatement struct {
|
||||
QueryID int64 `json:"queryid"`
|
||||
Calls int64 `json:"calls"`
|
||||
TotalMS float64 `json:"total_ms"`
|
||||
MeanMS float64 `json:"mean_ms"`
|
||||
Rows int64 `json:"rows"`
|
||||
Query string `json:"query"`
|
||||
}
|
||||
|
||||
type dbTable struct {
|
||||
Name string `json:"name"`
|
||||
Bytes int64 `json:"bytes"`
|
||||
Live int64 `json:"live_rows"`
|
||||
Dead int64 `json:"dead_rows"`
|
||||
SeqScans int64 `json:"seq_scans"`
|
||||
LastVacuum *time.Time `json:"last_autovacuum,omitempty"`
|
||||
}
|
||||
|
||||
func runDBLoad(ctx context.Context, args []string) error {
|
||||
fs := newFlagSet("db load")
|
||||
limit := fs.Int("limit", 15, "rows to show per section")
|
||||
asJSON := fs.Bool("json", false, "print the report as JSON")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := noExtraArgs(fs); err != nil {
|
||||
return err
|
||||
}
|
||||
if *limit < 1 || *limit > 200 {
|
||||
return errors.New("--limit must be between 1 and 200")
|
||||
}
|
||||
c, err := connect(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer c.close()
|
||||
load, err := readDBLoad(ctx, c.db.Pool, *limit)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if *asJSON {
|
||||
enc := json.NewEncoder(os.Stdout)
|
||||
enc.SetIndent("", " ")
|
||||
return enc.Encode(load)
|
||||
}
|
||||
printDBLoad(os.Stdout, load)
|
||||
return nil
|
||||
}
|
||||
|
||||
func readDBLoad(ctx context.Context, pool *pgxpool.Pool, limit int) (*dbLoad, error) {
|
||||
load := &dbLoad{Settings: map[string]string{}, Connections: []dbConnections{}, Busy: []dbBusy{}, Statements: []dbStatement{}, Tables: []dbTable{}}
|
||||
if err := pool.QueryRow(ctx, `SELECT current_setting('max_connections')::int`).Scan(&load.MaxConnections); err != nil {
|
||||
return nil, fmt.Errorf("read max_connections: %w", err)
|
||||
}
|
||||
for _, name := range []string{"shared_buffers", "work_mem", "statement_timeout", "idle_in_transaction_session_timeout", "autovacuum_vacuum_scale_factor"} {
|
||||
var v string
|
||||
if err := pool.QueryRow(ctx, `SELECT current_setting($1, true)`, name).Scan(&v); err == nil {
|
||||
load.Settings[name] = v
|
||||
}
|
||||
}
|
||||
|
||||
// A client session another role owns shows no state to a role without pg_read_all_stats.
|
||||
rows, err := pool.Query(ctx, `SELECT COALESCE(NULLIF(application_name, ''), '(unnamed)'),
|
||||
CASE WHEN backend_type IS DISTINCT FROM 'client backend' THEN '(background)' ELSE COALESCE(state, '(hidden)') END, count(*)::int
|
||||
FROM pg_stat_activity WHERE pid <> pg_backend_pid()
|
||||
GROUP BY 1, 2 ORDER BY 3 DESC, 1, 2`)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read connections: %w", err)
|
||||
}
|
||||
for rows.Next() {
|
||||
var r dbConnections
|
||||
if err := rows.Scan(&r.Application, &r.State, &r.Count); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
load.Connections = append(load.Connections, r)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err = pool.Query(ctx, `SELECT pid, COALESCE(NULLIF(application_name, ''), '(unnamed)'), state,
|
||||
EXTRACT(EPOCH FROM now() - COALESCE(xact_start, query_start))::float8,
|
||||
COALESCE(wait_event_type || ':' || wait_event, '')
|
||||
FROM pg_stat_activity
|
||||
WHERE datname = current_database() AND pid <> pg_backend_pid() AND state IS NOT NULL AND state <> 'idle'
|
||||
ORDER BY COALESCE(xact_start, query_start) LIMIT $1`, limit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read active sessions: %w", err)
|
||||
}
|
||||
for rows.Next() {
|
||||
var r dbBusy
|
||||
if err := rows.Scan(&r.PID, &r.Application, &r.State, &r.Seconds, &r.Wait); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
load.Busy = append(load.Busy, r)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := readStatements(ctx, pool, limit, load); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err = pool.Query(ctx, `SELECT relname, pg_total_relation_size(relid), n_live_tup, n_dead_tup, seq_scan, last_autovacuum
|
||||
FROM pg_stat_user_tables ORDER BY pg_total_relation_size(relid) DESC LIMIT $1`, limit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read tables: %w", err)
|
||||
}
|
||||
for rows.Next() {
|
||||
var r dbTable
|
||||
if err := rows.Scan(&r.Name, &r.Bytes, &r.Live, &r.Dead, &r.SeqScans, &r.LastVacuum); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
load.Tables = append(load.Tables, r)
|
||||
}
|
||||
return load, rows.Err()
|
||||
}
|
||||
|
||||
// readStatements reads pg_stat_statements when the server has it. Only a query's text has its constants replaced, so other statements show their queryid alone.
|
||||
func readStatements(ctx context.Context, pool *pgxpool.Pool, limit int, load *dbLoad) error {
|
||||
var schema string
|
||||
err := pool.QueryRow(ctx, `SELECT n.nspname FROM pg_extension e JOIN pg_namespace n ON n.oid = e.extnamespace WHERE e.extname = 'pg_stat_statements'`).Scan(&schema)
|
||||
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
|
||||
return fmt.Errorf("check pg_stat_statements: %w", err)
|
||||
}
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
load.StatementsNote = "pg_stat_statements is not installed; run CREATE EXTENSION pg_stat_statements as a superuser to see the costliest queries"
|
||||
return nil
|
||||
}
|
||||
rows, err := pool.Query(ctx, `SELECT COALESCE(queryid, 0), calls, total_exec_time, mean_exec_time, rows,
|
||||
CASE WHEN query ~* '^\s*(select|insert|update|delete|with|merge|values|table)\M'
|
||||
THEN left(regexp_replace(query, '\s+', ' ', 'g'), 200) ELSE '(not a query; text withheld)' END
|
||||
FROM `+pgx.Identifier{schema, "pg_stat_statements"}.Sanitize()+` WHERE dbid = (SELECT oid FROM pg_database WHERE datname = current_database())
|
||||
ORDER BY total_exec_time DESC LIMIT $1`, limit)
|
||||
if err != nil {
|
||||
load.StatementsNote = "pg_stat_statements could not be read by this role: " + err.Error()
|
||||
return nil
|
||||
}
|
||||
for rows.Next() {
|
||||
var r dbStatement
|
||||
if err := rows.Scan(&r.QueryID, &r.Calls, &r.TotalMS, &r.MeanMS, &r.Rows, &r.Query); err != nil {
|
||||
return err
|
||||
}
|
||||
load.Statements = append(load.Statements, r)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
var since time.Time
|
||||
if err := pool.QueryRow(ctx, `SELECT stats_reset FROM `+pgx.Identifier{schema, "pg_stat_statements_info"}.Sanitize()).Scan(&since); err == nil {
|
||||
load.Since = &since
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func printDBLoad(w io.Writer, load *dbLoad) {
|
||||
used := 0
|
||||
for _, c := range load.Connections {
|
||||
// Background processes have their own slots, outside max_connections.
|
||||
if c.State != "(background)" {
|
||||
used += c.Count
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(w, "Client connections to the server, not counting this one: %d of max_connections %d\n", used, load.MaxConnections)
|
||||
tw := tabwriter.NewWriter(w, 2, 4, 2, ' ', 0)
|
||||
fmt.Fprintln(tw, " APPLICATION\tSTATE\tCOUNT")
|
||||
for _, c := range load.Connections {
|
||||
fmt.Fprintf(tw, " %s\t%s\t%d\n", c.Application, c.State, c.Count)
|
||||
}
|
||||
tw.Flush()
|
||||
|
||||
fmt.Fprintln(w, "\nLongest-running sessions:")
|
||||
if len(load.Busy) == 0 {
|
||||
fmt.Fprintln(w, " none")
|
||||
} else {
|
||||
tw = tabwriter.NewWriter(w, 2, 4, 2, ' ', 0)
|
||||
fmt.Fprintln(tw, " PID\tAPPLICATION\tSTATE\tSECONDS\tWAITING ON")
|
||||
for _, b := range load.Busy {
|
||||
fmt.Fprintf(tw, " %d\t%s\t%s\t%.1f\t%s\n", b.PID, b.Application, b.State, b.Seconds, b.Wait)
|
||||
}
|
||||
tw.Flush()
|
||||
}
|
||||
|
||||
fmt.Fprint(w, "\nCostliest statements")
|
||||
if load.Since != nil {
|
||||
fmt.Fprintf(w, " since %s", load.Since.Format(time.RFC3339))
|
||||
}
|
||||
fmt.Fprintln(w, ":")
|
||||
if load.StatementsNote != "" {
|
||||
fmt.Fprintf(w, " %s\n", load.StatementsNote)
|
||||
}
|
||||
tw = tabwriter.NewWriter(w, 2, 4, 2, ' ', 0)
|
||||
if len(load.Statements) > 0 {
|
||||
fmt.Fprintln(tw, " TOTAL MS\tCALLS\tMEAN MS\tROWS\tQUERYID\tQUERY")
|
||||
}
|
||||
for _, s := range load.Statements {
|
||||
fmt.Fprintf(tw, " %.0f\t%d\t%.2f\t%d\t%d\t%s\n", s.TotalMS, s.Calls, s.MeanMS, s.Rows, s.QueryID, strings.TrimSpace(s.Query))
|
||||
}
|
||||
tw.Flush()
|
||||
|
||||
fmt.Fprintln(w, "\nLargest tables:")
|
||||
tw = tabwriter.NewWriter(w, 2, 4, 2, ' ', 0)
|
||||
fmt.Fprintln(tw, " TABLE\tSIZE\tLIVE ROWS\tDEAD ROWS\tSEQ SCANS\tLAST AUTOVACUUM")
|
||||
for _, t := range load.Tables {
|
||||
vacuum := "never"
|
||||
if t.LastVacuum != nil {
|
||||
vacuum = t.LastVacuum.Format(time.RFC3339)
|
||||
}
|
||||
fmt.Fprintf(tw, " %s\t%s\t%d\t%d\t%d\t%s\n", t.Name, humanBytes(t.Bytes), t.Live, t.Dead, t.SeqScans, vacuum)
|
||||
}
|
||||
tw.Flush()
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
|
||||
"github.com/warmbly/warmbly/internal/app/inboxtag"
|
||||
"github.com/warmbly/warmbly/internal/config"
|
||||
"github.com/warmbly/warmbly/internal/pkg/typesafe"
|
||||
"github.com/warmbly/warmbly/internal/repository"
|
||||
)
|
||||
|
||||
@@ -88,11 +89,18 @@ func runInboxTagBackfill(ctx context.Context, args []string) error {
|
||||
|
||||
repo := repository.NewInboxTagRepository(c.db.Pool)
|
||||
categories := repository.NewTagCategoryStore(c.db.Pool)
|
||||
key := config.TypeSafeAPIKey()
|
||||
var endpoint string
|
||||
if key != "" {
|
||||
if endpoint, err = config.TypeSafeEndpoint(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// The asker is nil-safe on a dry run, but constructing it is what proves a
|
||||
// key is present, so it is built either way.
|
||||
svc := inboxtag.NewService(
|
||||
inboxtag.NewClient(config.TypeSafeAPIKey()),
|
||||
inboxtag.NewClient(key, typesafe.WithEndpoint(endpoint)),
|
||||
repo,
|
||||
categories,
|
||||
categories,
|
||||
|
||||
@@ -90,6 +90,8 @@ func dispatch(ctx context.Context, args []string) error {
|
||||
return runInboxTag(ctx, args[1:])
|
||||
case "keys":
|
||||
return runKeys(ctx, args[1:])
|
||||
case "db":
|
||||
return runDB(ctx, args[1:])
|
||||
}
|
||||
if _, ok := apiFamilies[args[0]]; ok {
|
||||
return runAPIResource(ctx, args[0], args[1:])
|
||||
@@ -129,6 +131,7 @@ var commands = []command{
|
||||
{"org list", "List the workspaces on this instance with their id, owner, and size", composeExec + "org list"},
|
||||
{"org export", "Write a whole workspace to a portable archive file", composeExec + "org export --org you@example.com --out /tmp/workspace.warmbly.zip"},
|
||||
{"org import", "Apply an archive to a workspace on this instance", composeExec + "org import --org you@example.com --file /tmp/workspace.warmbly.zip"},
|
||||
{"org attachments-preflight", "Read one page of private attachment type results from a local archive, offline", "warmblyctl org attachments-preflight --file ./workspace.warmbly.zip --limit 25"},
|
||||
{"fleet join-token", "Issue the token a machine needs to join the fleet. Shown once", composeExec + "fleet join-token"},
|
||||
{"fleet list", "Every worker and consumer: role, version, liveness and usage", composeExec + "fleet list"},
|
||||
{"fleet version", "Show or set the version every node should be running", composeExec + "fleet version v1.4.2"},
|
||||
@@ -138,6 +141,7 @@ var commands = []command{
|
||||
{"fleet rollout start", "Move the fleet to a tag in stages: one canary, then waves", composeExec + "fleet rollout start v1.4.2 --bake 30m"},
|
||||
{"fleet rollout status", "Show a staged rollout's stage, admitted nodes and halt reason", composeExec + "fleet rollout status"},
|
||||
{"fleet env-status", "Whether every live node has applied the current rendered env", composeExec + "fleet env-status"},
|
||||
{"db load", "Show what the database is busy with: connections by service, costliest queries, largest tables", composeExec + "db load"},
|
||||
}
|
||||
|
||||
func usage(w *os.File) {
|
||||
@@ -188,7 +192,7 @@ Anything piped into a container needs exec -T, which is what turns the TTY off.
|
||||
Anything that prompts needs a TTY, so run it without -T.
|
||||
|
||||
Environment:
|
||||
PRIMARY_DB Postgres connection string. Every operator command except hash-password needs it.
|
||||
PRIMARY_DB Postgres connection string. Not needed by hash-password or org attachments-preflight.
|
||||
REDIS Redis URL. setup-link needs it, and reset-password needs it to mint a link.
|
||||
APP_URL Base URL every printed link is built from.
|
||||
WARMBLY_API_KEY API key (wmbly_...) for the API commands.
|
||||
|
||||
@@ -31,6 +31,8 @@ func runOrg(ctx context.Context, args []string) error {
|
||||
return runOrgExport(ctx, args[1:])
|
||||
case "import":
|
||||
return runOrgImport(ctx, args[1:])
|
||||
case "attachments-preflight":
|
||||
return runOrgAttachmentsPreflight(ctx, args[1:])
|
||||
}
|
||||
|
||||
orgUsage(os.Stderr)
|
||||
@@ -38,7 +40,7 @@ func runOrg(ctx context.Context, args []string) error {
|
||||
}
|
||||
|
||||
func orgUsage(w *os.File) {
|
||||
fmt.Fprint(w, "Move a workspace between instances.\n\nUsage:\n warmblyctl org <subcommand> [flags]\n\nSubcommands:\n")
|
||||
fmt.Fprint(w, "Move a workspace between instances or inspect a local archive.\n\nUsage:\n warmblyctl org <subcommand> [flags]\n\nSubcommands:\n")
|
||||
for _, c := range commands {
|
||||
if !strings.HasPrefix(c.name, "org ") {
|
||||
continue
|
||||
|
||||
@@ -18,6 +18,7 @@ var remoteAdminRoutes = []remoteAdminRoute{
|
||||
{"POST", "/admin/testers", []string{"ManageTesters"}, false, "Credential issuance is intentionally not exposed through diagnostic output"},
|
||||
{"POST", "/admin/organizations/:id/sample-data", []string{"ManageTesters"}, false, ""},
|
||||
{"DELETE", "/admin/testers/:id", []string{"ManageTesters"}, false, ""},
|
||||
{"POST", "/admin/testers/:id/password", []string{"ManageTesters"}, true, "Credential issuance is intentionally not exposed through diagnostic output"},
|
||||
{"PUT", "/admin/users/:id/login-code-exempt", []string{"ManageTesters"}, true, ""},
|
||||
{"POST", "/admin/users/:id/ban", []string{"BanUsers"}, false, ""},
|
||||
{"POST", "/admin/users/:id/unban", []string{"BanUsers"}, false, ""},
|
||||
|
||||
@@ -27,3 +27,17 @@ func TestWorkerCapacityTarget(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerCapacityAutoSizesFromMemory(t *testing.T) {
|
||||
t.Setenv("WARMBLY_WORKER_CAPACITY", "auto")
|
||||
if workerCapacityFromMemory(func() int { return 0 }) == nil {
|
||||
t.Fatal("auto did not size the target from memory")
|
||||
}
|
||||
if got := workerCapacityTarget(); got != defaultWorkerCapacityTarget {
|
||||
t.Fatalf("auto's first beat before a memory reading falls back to %v, got %v", defaultWorkerCapacityTarget, got)
|
||||
}
|
||||
t.Setenv("WARMBLY_WORKER_CAPACITY", "500")
|
||||
if workerCapacityFromMemory(func() int { return 0 }) != nil {
|
||||
t.Fatal("a fixed target was replaced by the memory sizing")
|
||||
}
|
||||
}
|
||||
|
||||
+24
-6
@@ -28,6 +28,7 @@ import (
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
"github.com/warmbly/warmbly/internal/observability"
|
||||
"github.com/warmbly/warmbly/internal/pkg/nodeagent"
|
||||
"github.com/warmbly/warmbly/internal/pkg/nodeauth"
|
||||
"github.com/warmbly/warmbly/internal/repository"
|
||||
)
|
||||
|
||||
@@ -131,11 +132,10 @@ func main() {
|
||||
}
|
||||
log.Printf("Codec: %s", codecImpl.Name())
|
||||
|
||||
// Event bus (NATS default; Kafka when EVENTBUS_PROVIDER=kafka). Kafka
|
||||
// bootstrap/SASL is only loaded for the Kafka provider.
|
||||
// Dual readers retain Kafka credentials until its backlog and rollback window close.
|
||||
var kafkaBootstrapServers string
|
||||
var kafkaSaslConfig *kafka.SASLConfig
|
||||
if config.EventBusProvider() == "kafka" {
|
||||
if config.EventBusUsesKafka() {
|
||||
kafkaBootstrapServers, err = cfg.LoadKafkaBootstrapServers(ctx)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
@@ -169,9 +169,15 @@ func main() {
|
||||
log.Println("WARNING: BOX_GOOGLE_CLIENT_ID/SECRET not set; Gmail mailbox token refresh will fail on expiry")
|
||||
}
|
||||
|
||||
agent := newNodeAgent(workerID, bindIP)
|
||||
var workerService *worker.WorkerService
|
||||
agent := newNodeAgent(workerID, bindIP, func() int {
|
||||
if workerService == nil {
|
||||
return 0
|
||||
}
|
||||
return workerService.MailboxCount()
|
||||
})
|
||||
// WorkerService
|
||||
workerService := &worker.WorkerService{
|
||||
workerService = &worker.WorkerService{
|
||||
OnMailboxMissing: agent.RequestReload,
|
||||
ID: workerID.String(),
|
||||
CipherService: cipherService,
|
||||
@@ -243,22 +249,25 @@ func main() {
|
||||
// newNodeAgent builds the shared fleet agent. It replaces the worker's own
|
||||
// heartbeat loop: identity, usage reporting and self-update are node concerns,
|
||||
// identical for every role, so they live in one place.
|
||||
func newNodeAgent(workerID uuid.UUID, bindIP string) *nodeagent.Agent {
|
||||
func newNodeAgent(workerID uuid.UUID, bindIP string, mailboxes func() int) *nodeagent.Agent {
|
||||
reportedIP := os.Getenv("WORKER_PUBLIC_IP")
|
||||
if reportedIP == "" && bindIP != "default route" {
|
||||
reportedIP = bindIP
|
||||
}
|
||||
return nodeagent.New(nodeagent.Config{
|
||||
WarmupSendProtocol: 2,
|
||||
SyncWakeProtocol: 1,
|
||||
NodeID: workerID,
|
||||
Role: models.NodeRoleWorker,
|
||||
Name: os.Getenv("WARMBLY_NODE_NAME"),
|
||||
Region: nodeRegion(),
|
||||
Address: reportedIP,
|
||||
CapacityTarget: workerCapacityTarget(),
|
||||
Capacity: workerCapacityFromMemory(mailboxes),
|
||||
Version: buildVersion(),
|
||||
BaseURL: os.Getenv("ENCRYPTED_KEYS_BACKEND_URL"),
|
||||
Token: config.NodeAPIToken(),
|
||||
Credential: nodeauth.FromEnv().Credential,
|
||||
// Written for the host-side updater installed by `warmbly join`.
|
||||
TargetVersionPath: os.Getenv("WARMBLY_TARGET_VERSION_PATH"),
|
||||
Condition: wsmtp.EgressCondition,
|
||||
@@ -267,6 +276,15 @@ func newNodeAgent(workerID uuid.UUID, bindIP string) *nodeagent.Agent {
|
||||
|
||||
const defaultWorkerCapacityTarget = 100.0
|
||||
|
||||
// workerCapacityFromMemory is set when WARMBLY_WORKER_CAPACITY=auto: the
|
||||
// worker then plans its mailbox target from its own memory on every beat.
|
||||
func workerCapacityFromMemory(mailboxes func() int) func(models.NodeUsage) float64 {
|
||||
if !strings.EqualFold(strings.TrimSpace(os.Getenv("WARMBLY_WORKER_CAPACITY")), "auto") {
|
||||
return nil
|
||||
}
|
||||
return (&nodeagent.MemoryCapacity{Mailboxes: mailboxes}).Target
|
||||
}
|
||||
|
||||
// workerCapacityTarget reads this machine's assigned-mailbox target.
|
||||
func workerCapacityTarget() float64 {
|
||||
raw := strings.TrimSpace(os.Getenv("WARMBLY_WORKER_CAPACITY"))
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
# Hosted static edge
|
||||
|
||||
This optional Worker serves public frontend files from explicitly mapped HTTPS
|
||||
Pages origins. The browser-facing custom domain belongs to the Warmbly zone and
|
||||
uses that zone's certificate and cipher configuration. Pages remains the release
|
||||
artifact store, so existing release uploads continue to update the upstream.
|
||||
Self-hosted deployments do not use this Worker.
|
||||
|
||||
`PAGES_ORIGINS` is a JSON object mapping each exact public hostname to its Pages
|
||||
origin, for example `{"stage.warmbly.com":"https://example.pages.dev"}`. It is
|
||||
operator configuration, never read from the request. The checked-in configuration
|
||||
has an empty map and no domains or routes. Deploying it alone serves no website.
|
||||
|
||||
Only GET, HEAD and OPTIONS reach the static origin. Application authorization and
|
||||
cookies are removed before forwarding. API, forms and realtime traffic keep their
|
||||
existing hosts and paths. Responses retain the Pages security headers, cache
|
||||
policy, assets and status. Redirects back to the selected Pages origin use the
|
||||
visitor's hostname. No request URL, token or body is logged by this Worker.
|
||||
|
||||
## Deployment and rollback
|
||||
|
||||
1. Save current DNS, Pages custom-domain associations, certificate settings and
|
||||
production deployment identifiers privately. Identify the account that owns
|
||||
the zone, its existing Workers plan, and any usage charges before deployment.
|
||||
2. Deploy the reviewed module with a private configuration mapping only a staging
|
||||
hostname to one existing Pages production origin. Attach that hostname as a
|
||||
Worker custom domain. Keep all existing production domains on Pages.
|
||||
3. Independently verify certificate trust, the allowed TLS 1.2 AEAD suites, TLS
|
||||
1.3 and refusal of CBC. Verify the root page, nested SPA routes, JS/CSS assets,
|
||||
redirects, 404 behavior and response security headers against the upstream.
|
||||
4. Prepare the exact production map from authenticated Pages account metadata.
|
||||
Before each cutover, preserve that hostname's DNS and Pages association. Move
|
||||
one hostname at a time to the Worker custom domain and repeat the checks.
|
||||
Keep the Pages projects and deployment history intact.
|
||||
5. If a check fails, restore that hostname's saved Pages association and DNS, then
|
||||
verify it serves the previous content. Do not proceed to another hostname.
|
||||
|
||||
For normal releases use the stable production Pages origin. An immutable
|
||||
deployment URL can pin a staging or rollback comparison. The Worker map is a
|
||||
separate reviewed configuration; no release workflow changes it automatically.
|
||||
|
||||
Validate with `node --test deploy/cloudflare/static-edge.test.mjs` and
|
||||
`pnpm dlx wrangler@4.45.0 deploy --dry-run --config deploy/cloudflare/wrangler.jsonc`.
|
||||
Cloudflare custom-domain and certificate API responses are configuration evidence;
|
||||
independent TLS handshakes are required to establish the effective policy.
|
||||
@@ -0,0 +1,59 @@
|
||||
const failure = (status) => new Response("Service temporarily unavailable.", {
|
||||
status,
|
||||
headers: {
|
||||
"Cache-Control": "no-store",
|
||||
"Content-Type": "text/plain; charset=utf-8",
|
||||
"Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"Strict-Transport-Security": "max-age=31536000; includeSubDomains",
|
||||
},
|
||||
});
|
||||
|
||||
export async function serveStatic(request, origins, fetchOrigin = fetch) {
|
||||
const incoming = new URL(request.url);
|
||||
const target = Object.hasOwn(origins, incoming.hostname) ? origins[incoming.hostname] : undefined;
|
||||
if (!target) return failure(404);
|
||||
if (!["GET", "HEAD", "OPTIONS"].includes(request.method)) {
|
||||
const response = failure(405);
|
||||
response.headers.set("Allow", "GET, HEAD, OPTIONS");
|
||||
return response;
|
||||
}
|
||||
|
||||
const upstream = new URL(target);
|
||||
if (upstream.protocol !== "https:" || !/^[a-z0-9-]+(?:\.[a-z0-9-]+)*\.pages\.dev$/.test(upstream.hostname)
|
||||
|| upstream.port || upstream.username || upstream.password || upstream.pathname !== "/"
|
||||
|| upstream.search || upstream.hash) {
|
||||
return failure(503);
|
||||
}
|
||||
upstream.pathname = incoming.pathname;
|
||||
upstream.search = incoming.search;
|
||||
const headers = new Headers(request.headers);
|
||||
// These origins serve public static files and never receive application credentials.
|
||||
for (const name of ["authorization", "cookie", "proxy-authorization", "host"]) headers.delete(name);
|
||||
const response = await fetchOrigin(new Request(upstream, {
|
||||
method: request.method,
|
||||
headers,
|
||||
redirect: "manual",
|
||||
}));
|
||||
const result = new Response(response.body, response);
|
||||
const location = result.headers.get("Location");
|
||||
if (location) {
|
||||
const redirect = new URL(location, upstream);
|
||||
if (redirect.origin === upstream.origin) {
|
||||
redirect.protocol = incoming.protocol;
|
||||
redirect.host = incoming.host;
|
||||
result.headers.set("Location", redirect.href);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export default {
|
||||
async fetch(request, env) {
|
||||
try {
|
||||
return await serveStatic(request, JSON.parse(env.PAGES_ORIGINS));
|
||||
} catch {
|
||||
return failure(503);
|
||||
}
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,85 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import worker, { serveStatic } from "./static-edge.mjs";
|
||||
|
||||
const origins = { "stage.warmbly.com": "https://example.pages.dev" };
|
||||
const request = (path = "/", options) => new Request("https://stage.warmbly.com" + path, options);
|
||||
|
||||
test("static paths, query strings and headers retain their public response", async () => {
|
||||
const response = await serveStatic(request("/assets/app.js?v=74", {
|
||||
headers: { Authorization: "Bearer fixture", Cookie: "session=fixture", "If-None-Match": "fixture-etag" },
|
||||
}), origins, async (upstream) => {
|
||||
assert.equal(upstream.url, "https://example.pages.dev/assets/app.js?v=74");
|
||||
assert.equal(upstream.redirect, "manual");
|
||||
assert.equal(upstream.headers.get("Authorization"), null);
|
||||
assert.equal(upstream.headers.get("Cookie"), null);
|
||||
assert.equal(upstream.headers.get("If-None-Match"), "fixture-etag");
|
||||
return new Response("asset", { headers: {
|
||||
"Content-Security-Policy": "default-src 'self'", "X-Content-Type-Options": "nosniff",
|
||||
"Cache-Control": "public, max-age=300", ETag: "fixture-etag",
|
||||
} });
|
||||
});
|
||||
assert.equal(await response.text(), "asset");
|
||||
assert.equal(response.headers.get("Content-Security-Policy"), "default-src 'self'");
|
||||
assert.equal(response.headers.get("X-Content-Type-Options"), "nosniff");
|
||||
assert.equal(response.headers.get("ETag"), "fixture-etag");
|
||||
});
|
||||
|
||||
test("an unknown host cannot select an origin", async () => {
|
||||
const r = await serveStatic(new Request("https://unlisted.warmbly.com/?origin=https://attacker.example"), origins,
|
||||
() => assert.fail("unknown host fetched"));
|
||||
assert.equal(r.status, 404);
|
||||
});
|
||||
|
||||
test("write methods are refused before any origin request", async () => {
|
||||
for (const method of ["POST", "PUT", "PATCH", "DELETE"]) {
|
||||
const r = await serveStatic(request("/", { method }), origins, () => assert.fail("write fetched"));
|
||||
assert.equal(r.status, 405);
|
||||
assert.equal(r.headers.get("Allow"), "GET, HEAD, OPTIONS");
|
||||
}
|
||||
});
|
||||
|
||||
test("HEAD and OPTIONS retain their methods", async () => {
|
||||
for (const method of ["HEAD", "OPTIONS"]) {
|
||||
const r = await serveStatic(request("/", { method }), origins, async (upstream) => {
|
||||
assert.equal(upstream.method, method);
|
||||
return new Response(null, { status: 204 });
|
||||
});
|
||||
assert.equal(r.status, 204);
|
||||
}
|
||||
});
|
||||
|
||||
test("configuration admits only HTTPS Pages origins with no credentials or path", async () => {
|
||||
for (const target of ["http://example.pages.dev", "https://example.com", "https://example.pages.dev.attacker.example",
|
||||
"https://user:pass@example.pages.dev", "https://example.pages.dev/path", "https://example.pages.dev?q=1",
|
||||
"https://example.pages.dev#fragment", "https://example.pages.dev:8443"]) {
|
||||
const r = await serveStatic(request(), { "stage.warmbly.com": target }, () => assert.fail("invalid origin fetched"));
|
||||
assert.equal(r.status, 503, target);
|
||||
}
|
||||
});
|
||||
|
||||
test("Pages canonical redirects keep the visitor on the public hostname", async () => {
|
||||
for (const location of ["https://example.pages.dev/docs/?q=1", "/docs/?q=1"]) {
|
||||
const r = await serveStatic(request(), origins, async () => new Response(null, { status: 308, headers: { Location: location } }));
|
||||
assert.equal(r.status, 308);
|
||||
assert.equal(r.headers.get("Location"), "https://stage.warmbly.com/docs/?q=1");
|
||||
}
|
||||
});
|
||||
|
||||
test("external redirects and missing pages preserve the origin response", async () => {
|
||||
const redirect = await serveStatic(request(), origins, async () => new Response(null, { status: 302, headers: { Location: "https://warmbly.com/terms/" } }));
|
||||
assert.equal(redirect.headers.get("Location"), "https://warmbly.com/terms/");
|
||||
const missing = await serveStatic(request("/missing"), origins, async () => new Response("not found", { status: 404 }));
|
||||
assert.equal(missing.status, 404);
|
||||
assert.equal(await missing.text(), "not found");
|
||||
});
|
||||
|
||||
test("configuration and network failures return one generic response", async (t) => {
|
||||
t.mock.method(globalThis, "fetch", async () => { throw Error("private origin exception"); });
|
||||
for (const value of [undefined, "not json", "null", JSON.stringify(origins)]) {
|
||||
const r = await worker.fetch(request(), { PAGES_ORIGINS: value });
|
||||
assert.equal(r.status, 503);
|
||||
assert.equal(await r.text(), "Service temporarily unavailable.");
|
||||
assert.equal(r.headers.get("Cache-Control"), "no-store");
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"name": "warmbly-static-edge",
|
||||
"main": "static-edge.mjs",
|
||||
"compatibility_date": "2026-11-03",
|
||||
"workers_dev": false,
|
||||
"preview_urls": false,
|
||||
"limits": { "cpu_ms": 10 },
|
||||
"vars": {
|
||||
"PAGES_ORIGINS": "{}"
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user