cast/test/coolify.test.ts

64 lines
2.3 KiB
TypeScript
Raw Normal View History

feat: cast — the Coolify executor, extracted from the infra state repo Public tool, private state. cast holds no hostnames, no bindings, no secrets: it joins a product repo's .infra/ manifest with a state directory you point it at, and makes Coolify match. Extracted from heavy-duty/infra, which was half tool and half state — the inconsistency that made it impossible to say whether "infra" named a CLI or a runbook. rig builds the boxes; cast fills them; infra is what they are filled with. Two changes were required to make it genuinely stateless and publishable: - The implicit cwd contract (environments.yaml / secrets/ / .coolify.env resolved against the working directory, silently reading the wrong file from the wrong place) is now an explicit --state <dir> / $CAST_STATE. - BANNED_IN_PROD — a hardcoded list of one product's ALLOW_* flags, the only product knowledge in the executor — becomes the generic, operator- owned environments.<env>.forbidden_var_patterns. The guard now lives in private state, so a product-side change cannot lower its own guard, and it is a pattern rather than a list, so it catches unforeseen siblings. Age identities resolve as $CAST_AGE_KEY_FILE_<ENV> then ~/.config/cast/age-<env>.key — which is the entire attended-vs-unattended apply mechanism, with no environment names known to the tool. Instance identity (org names, the GitHub App name, founder domains) is out of the fixtures and out of register-github-app.sh, which took APP_NAME and ORG as arguments rather than baking them in. 69 tests green; bin/cast + curl installer mirror rig's shape. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 12:25:44 +00:00
import { describe, expect, it, vi } from "vitest";
import { CoolifyClient } from "../src/coolify.js";
function mockFetch(routes: Record<string, unknown>) {
return vi.fn(async (url: string | URL, init?: RequestInit) => {
const key = `${init?.method ?? "GET"} ${new URL(String(url)).pathname}`;
if (!(key in routes)) return new Response("not found", { status: 404 });
return new Response(JSON.stringify(routes[key]), { status: 200 });
}) as unknown as typeof fetch;
}
describe("CoolifyClient", () => {
it("sends bearer auth and resolves servers by name", async () => {
const fetchImpl = mockFetch({
"GET /api/v1/servers": [{ uuid: "srv-1", name: "prod-box" }],
});
const c = new CoolifyClient("https://coolify.test", "tok", fetchImpl);
expect(await c.serverUuid("prod-box")).toBe("srv-1");
const call = (fetchImpl as unknown as ReturnType<typeof vi.fn>).mock
.calls[0];
expect((call[1].headers as Record<string, string>).Authorization).toBe(
"Bearer tok",
);
});
it("throws a named error when a resolver misses", async () => {
const c = new CoolifyClient(
"https://coolify.test",
"tok",
mockFetch({ "GET /api/v1/servers": [] }),
);
await expect(c.serverUuid("nope")).rejects.toThrow(
/not found in Coolify: server nope/,
);
});
it("surfaces API errors with method, path and status", async () => {
const c = new CoolifyClient("https://coolify.test", "tok", mockFetch({}));
await expect(c.get("/projects")).rejects.toThrow(/GET \/projects → 404/);
});
feat: assert the token's team before touching Coolify (fail-closed) Coolify API tokens are team-scoped, and a wrong-team token does not error: the API resolves what it cannot see to `null` (getResourceByUuid walks resource → environment → project → team_id and returns null on a mismatch). To cast, `null` is indistinguishable from "this resource does not exist yet" — an invitation to create it. So an apply with a token minted under the wrong team would not fail loudly; it would provision a duplicate set of resources into the wrong team, against whatever server that team owns. Silent, mutating, discovered late. That makes this a correctness bug, not hardening. - environments.yaml carries a required `team:` per environment (id, name, or both). Required is the point: an environment with no declared team is one cast cannot verify it is pointed at. - Every command that reaches a live Coolify (apply, diff, server add, smoke) resolves GET /teams/current — the only endpoint that answers "what team does this token act as?" — and aborts on mismatch before its first READ, not merely its first write: a wrong-team diff reports "everything is absent", which is the very lie an apply would then act on. - server add and smoke take --env for this reason. A server belongs to exactly one team forever (no pivot, no is_system_wide escape hatch), and smoke writes env vars onto a live app. - New read-only `cast team` prints the token's team, so the binding can be filled in without a chicken-and-egg. With --env it also checks the binding: the dry run for "would apply refuse?". Team id 0 is a first-class value, not a falsy absent — it is the Root Team that a single-admin instance keeps everything in (app/Models/User.php). Also records the #4 investigation in docs/semantics.md: GithubApp `is_system_wide` IS the supported way to serve every team — list_github_apps scopes to `team_id = token's team OR is_system_wide`, and POST /github-apps accepts the flag — so per-team App duplication is unnecessary. Corollary: resolving a GitHub App by name is NOT a proxy for being in the right team, which is the second reason the assert has to be explicit. Closes #9 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-12 20:55:04 +00:00
it("reads the token's team from /teams/current", async () => {
const c = new CoolifyClient(
"https://coolify.test",
"tok",
mockFetch({
"GET /api/v1/teams/current": {
id: 1,
name: "heavy-duty",
personal_team: false,
},
}),
);
await expect(c.currentTeam()).resolves.toEqual({
id: 1,
name: "heavy-duty",
});
});
feat: cast — the Coolify executor, extracted from the infra state repo Public tool, private state. cast holds no hostnames, no bindings, no secrets: it joins a product repo's .infra/ manifest with a state directory you point it at, and makes Coolify match. Extracted from heavy-duty/infra, which was half tool and half state — the inconsistency that made it impossible to say whether "infra" named a CLI or a runbook. rig builds the boxes; cast fills them; infra is what they are filled with. Two changes were required to make it genuinely stateless and publishable: - The implicit cwd contract (environments.yaml / secrets/ / .coolify.env resolved against the working directory, silently reading the wrong file from the wrong place) is now an explicit --state <dir> / $CAST_STATE. - BANNED_IN_PROD — a hardcoded list of one product's ALLOW_* flags, the only product knowledge in the executor — becomes the generic, operator- owned environments.<env>.forbidden_var_patterns. The guard now lives in private state, so a product-side change cannot lower its own guard, and it is a pattern rather than a list, so it catches unforeseen siblings. Age identities resolve as $CAST_AGE_KEY_FILE_<ENV> then ~/.config/cast/age-<env>.key — which is the entire attended-vs-unattended apply mechanism, with no environment names known to the tool. Instance identity (org names, the GitHub App name, founder domains) is out of the fixtures and out of register-github-app.sh, which took APP_NAME and ORG as arguments rather than baking them in. 69 tests green; bin/cast + curl installer mirror rig's shape. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 12:25:44 +00:00
it("reads version as plain text, not JSON", async () => {
const fetchImpl = vi.fn(
async () => new Response("4.1.2", { status: 200 }),
) as unknown as typeof fetch;
const c = new CoolifyClient("https://coolify.test", "tok", fetchImpl);
await expect(c.version()).resolves.toBe("4.1.2");
});
});