diff --git a/apps/api/test/e2e/route-protection.e2e.test.ts b/apps/api/test/e2e/route-protection.e2e.test.ts index c00322877..819e043a6 100644 --- a/apps/api/test/e2e/route-protection.e2e.test.ts +++ b/apps/api/test/e2e/route-protection.e2e.test.ts @@ -6,6 +6,7 @@ import { PassThrough } from "node:stream"; import { readFile, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { normalizeEdgeResponse } from "@repo/core"; import { NginxProvider, OPENRESTY_DEFAULT_PATHS, @@ -203,6 +204,8 @@ describeDockerE2E("password-protected routes through the real edge", () => { `${paths.sitesDir}/_test_upstream.conf`, `server { listen 127.0.0.1:39482; + # Test-only bridge to the loopback management listener. + location = /api/test-rules { proxy_pass http://127.0.0.1:9145/rules; } location / { add_header Cache-Control "public, max-age=3600"; content_by_lua_block { ngx.print(ngx.var.http_cookie or "none") } @@ -352,6 +355,21 @@ describeDockerE2E("password-protected routes through the real edge", () => { } }); + it("protects literal edge responses and prevents them from making private content cacheable", async () => { + const payload = JSON.stringify({ host: "private.test", rules: [{ pathPrefix: "/virtual", spec: { response: normalizeEdgeResponse({ body: "private response", headers: { "Cache-Control": "public, max-age=3600" } }) } }] }); + try { + const applied = await ask("/api/test-rules", { cookie, method: "POST", body: payload, headers: { "Content-Type": "application/json" } }); + expect(applied.status).toBe(200); + expect(JSON.parse(applied.body)).toMatchObject({ ok: true, staticResponses: true }); + expect((await ask("/virtual")).status).toBe(401); + const response = await ask("/virtual", { cookie }); + expect(response).toMatchObject({ status: 200, body: "private response" }); + expect(response.headers["cache-control"]).toBe("private, no-store"); + } finally { + expect((await ask("/api/test-rules?host=private.test", { cookie, method: "DELETE" })).status).toBe(200); + } + }); + it("rejects cross-origin sign-in and unsafe return locations", async () => { const csrf = (await ask("/")).body.match(/name="csrf" value="([^"]+)"/)![1]; for (const origin of ["https://attacker.test", "null"]) { diff --git a/apps/api/test/e2e/routing-rules.e2e.test.ts b/apps/api/test/e2e/routing-rules.e2e.test.ts index d7d7585b8..847467e33 100644 --- a/apps/api/test/e2e/routing-rules.e2e.test.ts +++ b/apps/api/test/e2e/routing-rules.e2e.test.ts @@ -69,13 +69,14 @@ import { type RootChecked, type RouteConfig, } from "@repo/adapters"; -import type { RoutingConfig } from "@repo/core"; +import { normalizeEdgeResponse, type RoutingConfig } from "@repo/core"; import { compileProjectRoutingFields } from "@repo/platform/engine/lib/project-routing-fields"; import { buildDomainFanoutRegistrations } from "@repo/platform/engine/modules/deployments/compose/composite-route"; import type Dockerode from "dockerode"; import { describeDockerE2E, requireDocker } from "../helpers/docker-e2e"; import { freePort } from "../helpers/free-port"; import { EMBEDDED_LUA } from "../../../../packages/adapters/src/infra/lua-embedded"; +import { EDGE_CLIENT_MAX_BODY_SIZE } from "../../../../packages/adapters/src/infra/openresty-lua"; import type { HostRuleEntry } from "@repo/platform/engine/modules/route-rules/route-rule.service"; const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), "../../../.."); @@ -268,16 +269,94 @@ events { worker_connections 128; } http { include ${OPENRESTY_DEFAULT_PATHS.confDir}/mime.types; default_type application/octet-stream; + client_max_body_size ${EDGE_CLIENT_MAX_BODY_SIZE}; access_log off; lua_package_path "/usr/local/openresty/site/lualib/?.lua;;"; ${EDGE_SHARED_DICTS.filter(({ name }) => name === "rules" || name === "rl_counters") .map(({ name, size }) => `lua_shared_dict ${name} ${size};`) .join("\n ")} + # Deterministic hot-path instrumentation, isolated to this fixture worker. + init_worker_by_lua_block { + local counts = { decodes=0, pathDecodes=0, bodyReads=0, bodyBytes=0, hashes=0 } + package.loaded.response_test_costs = counts + local json = require "cjson.safe" + local decode = json.decode + json.decode = function(...) + counts.decodes = counts.decodes + 1 + return decode(...) + end + local unescape = ngx.unescape_uri + ngx.unescape_uri = function(...) + counts.pathDecodes = counts.pathDecodes + 1 + return unescape(...) + end + local dict = ngx.shared.rules + local get = dict.get + dict.get = function(self, key, ...) + local value = get(self, key, ...) + if string.sub(key, 1, 10) == "responses:" then + counts.bodyReads = counts.bodyReads + 1 + counts.bodyBytes = counts.bodyBytes + (value and #value or 0) + end + return value + end + local lib = require "openship.rules_lib" + local digest = lib.response_revision + lib.response_revision = function(...) + counts.hashes = counts.hashes + 1 + return digest(...) + end + } + # Test-only management vhost, on the same loopback-published test port. server { listen 80; server_name management.test; + location = /response-legacy-worker { + content_by_lua_block { + local lib = require "openship.rules_lib" + if ngx.req.get_method() == "POST" then + local previous = {} + for _, key in ipairs({ "static_responses", "valid_responses", "response_revision", "response_for" }) do + previous[key], lib[key] = lib[key], nil + end + package.loaded.response_test_previous = previous + else + for key, value in pairs(package.loaded.response_test_previous or {}) do lib[key] = value end + end + ngx.say("ok") + } + } + location = /response-costs { + content_by_lua_block { + local counts = package.loaded.response_test_costs + if ngx.req.get_method() == "POST" then + for key in pairs(counts) do counts[key] = 0 end + end + ngx.say(require("cjson.safe").encode(counts)) + } + } + location = /response-memory { + content_by_lua_block { + local dict = ngx.shared.rules + if ngx.req.get_method() == "POST" then + local i = 0 + while dict:safe_set("test-fill:" .. i, string.rep("x", 65536)) do i = i + 1 end + ngx.say(i) + else + for _, key in ipairs(dict:get_keys(0)) do + if string.sub(key, 1, 10) == "test-fill:" then dict:delete(key) end + end + ngx.say("cleared") + end + } + } + location = /policy-cache-check { + content_by_lua_block { + ngx.say(ngx.shared.rules:get("rules.test") or "[]") + } + } location = /country-cache-check { content_by_lua_block { ngx.say(assert(loadfile("/tmp/visitor-country.lua"))()) @@ -943,6 +1022,366 @@ http { expect(JSON.parse(response.body)).toMatchObject({ ok: true, host, count: rules.length }); } + it("serves exact literal responses with headers, query strings, Unicode and HEAD", async () => { + const body = '{"message":"مرحبا","literal":"$host; return 500;"}'; + await pushRules("rules.test", [ + { + pathPrefix: "/virtual", + spec: { + response: normalizeEdgeResponse({ + status: 201, + contentType: "application/json", + body, + headers: { "X-Example": "literal-$host" }, + }), + }, + }, + ]); + const result = await ask(port, "/virtual?source=test", "rules.test"); + expect(result).toMatchObject({ status: 201, body }); + expect(result.headers["content-type"]).toBe("application/json"); + expect(result.headers["x-example"]).toBe("literal-$host"); + expect(result.headers["content-length"]).toBe(String(Buffer.byteLength(body))); + const head = await ask(port, "/virtual", "rules.test", { method: "HEAD" }); + expect(head).toMatchObject({ status: 201, body: "" }); + expect(head.headers["content-length"]).toBe(String(Buffer.byteLength(body))); + for (const path of ["/virtual/child", "/virtual-other"]) { + expect((await ask(port, path, "rules.test")).body).not.toBe(body); + } + expect((await ask(port, "/virtual", "other-rules.test")).body).not.toBe(body); + expect((await ask(port, "/virtual", "rules.test", { method: "POST" })).status).not.toBe(201); + }); + + it("keeps responses out of the legacy policy cache during edge upgrades", async () => { + const capability = await ask(port, "/rules/capabilities", "management.test", { + method: "POST", + body: "{}", + }); + expect(JSON.parse(capability.body)).toMatchObject({ ok: true, staticResponses: true }); + const policy = { pathPrefix: null, spec: { access: { methods: ["GET"] } } }; + await pushRules("rules.test", [ + policy, + { pathPrefix: "/virtual", spec: { response: normalizeEdgeResponse({ body: "ready" }) } }, + ]); + const legacy = await ask(port, "/policy-cache-check", "management.test"); + expect(JSON.parse(legacy.body)).toEqual([policy]); + const stored = await ask(port, "/rules?host=rules.test", "management.test"); + expect(JSON.parse(stored.body).rules).toHaveLength(2); + await ask(port, "/rules?host=rules.test", "management.test", { method: "DELETE" }); + expect((await ask(port, "/virtual", "rules.test")).body).not.toBe("ready"); + }); + + it("still publishes policies while a worker has the previous rules library loaded", async () => { + await pushRules("rules.test", [ + { pathPrefix: null, spec: { access: { methods: ["GET"] } } }, + { + pathPrefix: "/virtual", + spec: { response: normalizeEdgeResponse({ body: "new worker response" }) }, + }, + ]); + await ask(port, "/response-legacy-worker", "management.test", { method: "POST" }); + try { + // A new worker may already have published a response into shared memory. + // This worker must still enforce its policies and serve ordinary traffic. + const ordinary = await ask(port, "/virtual", "rules.test"); + expect(ordinary.status).toBe(200); + expect(ordinary.body).not.toBe("new worker response"); + expect((await ask(port, "/virtual", "rules.test", { method: "POST" })).status).toBe(403); + await pushRules("rules.test", [{ pathPrefix: null, spec: { access: { methods: ["GET"] } } }]); + const capability = await ask(port, "/rules/capabilities", "management.test"); + expect(JSON.parse(capability.body).staticResponses).toBe(false); + const response = await ask(port, "/rules", "management.test", { + method: "POST", + body: JSON.stringify({ + host: "rules.test", + rules: [ + { + pathPrefix: "/virtual", + spec: { response: normalizeEdgeResponse({ body: "not yet" }) }, + }, + ], + }), + }); + expect(response.status).toBe(409); + expect((await ask(port, "/virtual", "rules.test", { method: "POST" })).status).toBe(403); + } finally { + await ask(port, "/response-legacy-worker", "management.test", { method: "DELETE" }); + } + }); + + it("retains domain access, bans and rate limits in front of a static response", async () => { + const response = { + pathPrefix: "/virtual", + spec: { response: normalizeEdgeResponse({ body: "answer", methods: [] }) }, + }; + for (const policy of [ + { access: { methods: ["POST"] } }, + { ban: { userAgents: ["blocked-client"] } }, + { hotlink: { allowReferers: ["allowed.test"], allowEmpty: false } }, + ]) { + await pushRules("rules.test", [response, { pathPrefix: null, spec: policy }]); + expect( + (await ask(port, "/virtual", "rules.test", { headers: { "User-Agent": "blocked-client" } })) + .status, + ).toBe(403); + } + await pushRules("rules.test", [ + response, + { pathPrefix: "/virtual", spec: { rateLimit: { rps: 1, burst: 0 } } }, + ]); + const statuses = await Promise.all( + Array.from({ length: 8 }, () => ask(port, "/virtual", "rules.test").then((r) => r.status)), + ); + expect(statuses).toContain(429); + }); + + it("matches prefixes at a path boundary and gives exact responses precedence", async () => { + const rules = [ + { + pathPrefix: "/virtual", + spec: { response: normalizeEdgeResponse({ match: "prefix", body: "prefix" }) }, + }, + { pathPrefix: "/virtual", spec: { response: normalizeEdgeResponse({ body: "exact" }) } }, + ]; + for (const ordered of [rules, [...rules].reverse()]) { + await pushRules("rules.test", ordered); + expect((await ask(port, "/virtual", "rules.test")).body).toBe("exact"); + expect((await ask(port, "/virtual/child", "rules.test")).body).toBe("prefix"); + expect((await ask(port, "/virtual-other", "rules.test")).body).not.toBe("prefix"); + } + await pushRules("rules.test", [ + { + pathPrefix: "/index.html", + spec: { response: normalizeEdgeResponse({ body: "only-index" }) }, + }, + ]); + expect((await ask(port, "/unmatched-spa-path", "rules.test")).body).not.toBe("only-index"); + }); + + it("keeps custom error content and empty responses exact, including bodyless statuses", async () => { + for (const [status, body] of [ + [404, "Custom missing page"], + [503, ""], + [204, ""], + [205, ""], + [304, ""], + ] as const) { + await pushRules("rules.test", [ + { pathPrefix: "/virtual", spec: { response: normalizeEdgeResponse({ status, body }) } }, + ]); + const answer = await ask(port, "/virtual", "rules.test"); + expect(answer).toMatchObject({ status, body }); + if (status === 204 || status === 304) + expect(answer.headers["content-length"]).toBeUndefined(); + } + }); + + it("applies large bodies, updates and removal without a reload", async () => { + const body = "ع".repeat(32000); + await pushRules("rules.test", [ + { pathPrefix: "/virtual", spec: { response: normalizeEdgeResponse({ body }) } }, + ]); + expect((await ask(port, "/virtual", "rules.test")).body).toBe(body); + await pushRules("rules.test", [ + { pathPrefix: "/virtual", spec: { response: normalizeEdgeResponse({ body: "updated" }) } }, + ]); + expect((await ask(port, "/virtual", "rules.test")).body).toBe("updated"); + await pushRules("rules.test", []); + expect((await ask(port, "/virtual", "rules.test")).body).not.toBe("updated"); + }); + + it("rejects unsafe or malformed responses before changing active rules", async () => { + const original = normalizeEdgeResponse({ body: "original response" }); + await pushRules("rules.test", [ + { pathPrefix: null, spec: { access: { methods: ["GET"] } } }, + { pathPrefix: "/virtual", spec: { response: original } }, + ]); + const invalid = [ + { headers: { "X-Test": "ok\r\nInjected: yes" } }, + { headers: { "X-Test": "nul\0value" } }, + { headers: { "Bad Header": "value" } }, + { headers: { "X-Test": "one", "x-test": "two" } }, + ...[ + "Content-Length", + "Transfer-Encoding", + "Content-Encoding", + "Connection", + "X-Accel-Redirect", + ].map((name) => ({ headers: { [name]: "unsafe" } })), + { headers: { "X-Test": "a".repeat(2049) } }, + { headers: Object.fromEntries(Array.from({ length: 33 }, (_, i) => [`X-${i}`, "value"])) }, + { + headers: Object.fromEntries( + Array.from({ length: 5 }, (_, i) => [`X-${i}`, "a".repeat(2048)]), + ), + }, + { body: "ع".repeat(32769) }, + { status: 101 }, + { status: 204 }, + { status: 200.5 }, + { contentType: "text/plain\r\nInjected: yes" }, + { contentType: "bad-type" }, + { methods: "GET" }, + { methods: ["TRACE"] }, + { methods: { GET: true } }, + { match: "regex" }, + ]; + for (const override of invalid) { + const rejected = await ask(port, "/rules", "management.test", { + method: "POST", + body: JSON.stringify({ + host: "rules.test", + rules: [{ pathPrefix: "/virtual", spec: { response: { ...original, ...override } } }], + }), + }); + expect(rejected.status, JSON.stringify(override).slice(0, 100)).toBe(400); + const answer = await ask(port, "/virtual", "rules.test"); + expect(answer.body).toBe(original.body); + expect(answer.headers["injected"]).toBeUndefined(); + expect((await ask(port, "/virtual", "rules.test", { method: "POST" })).status).toBe(403); + } + for (const pathPrefix of [ + "/_openship/hooks/probe", + "/.openship/auth", + "/.well-known/acme-challenge/probe", + "/../virtual", + "/bad//path", + "/bad%2Fpath", + "/" + "x".repeat(512), + ]) { + const rejected = await ask(port, "/rules", "management.test", { + method: "POST", + body: JSON.stringify({ + host: "rules.test", + rules: [{ pathPrefix, spec: { response: original } }], + }), + }); + expect(rejected.status, pathPrefix).toBe(400); + } + }); + + it("bounds route counts and preserves access policies when response storage is full", async () => { + const responses = Array.from({ length: 64 }, (_, i) => ({ + pathPrefix: `/bounded/${i}`, + spec: { response: normalizeEdgeResponse({ body: `response-${i}` }) }, + })); + await pushRules("rules.test", responses); + expect((await ask(port, "/bounded/63", "rules.test")).body).toBe("response-63"); + for (const extra of [responses[0], { ...responses[0], pathPrefix: "/overflow" }]) { + const rejected = await ask(port, "/rules", "management.test", { + method: "POST", + body: JSON.stringify({ host: "rules.test", rules: [...responses, extra] }), + }); + expect(rejected.status).toBe(400); + expect((await ask(port, "/bounded/63", "rules.test")).body).toBe("response-63"); + } + await pushRules("rules.test", [{ pathPrefix: null, spec: { access: { methods: ["GET"] } } }]); + try { + expect( + (await ask(port, "/response-memory", "management.test", { method: "POST" })).status, + ).toBe(200); + const failed = await ask(port, "/rules", "management.test", { + method: "POST", + body: JSON.stringify({ + host: "other-rules.test", + rules: responses.map((entry) => ({ + ...entry, + spec: { response: normalizeEdgeResponse({ body: "x".repeat(65536) }) }, + })), + }), + }); + expect(failed.status, failed.body).toBe(503); + expect((await ask(port, "/virtual", "rules.test", { method: "POST" })).status).toBe(403); + } finally { + await ask(port, "/response-memory", "management.test", { method: "DELETE" }); + } + }); + + it("keeps unconfigured traffic cheap and reuses compiled responses without copying bodies", async () => { + const reset = () => ask(port, "/response-costs", "management.test", { method: "POST" }); + const costs = async () => + JSON.parse((await ask(port, "/response-costs", "management.test")).body); + for (const policies of [[], [{ pathPrefix: null, spec: { access: { methods: ["GET"] } } }]]) { + await pushRules("rules.test", policies); + await ask(port, "/", "rules.test"); // warm existing policy/GeoIP caches + await reset(); + for (let i = 0; i < 16; i++) await ask(port, "/", "rules.test"); + expect(await costs()).toEqual({ + decodes: 0, + pathDecodes: 0, + bodyReads: 0, + bodyBytes: 0, + hashes: 0, + }); + } + const entries = (body: string) => [ + { pathPrefix: "/virtual", spec: { response: normalizeEdgeResponse({ body }) } }, + ]; + const body = "x".repeat(65536); + await pushRules("rules.test", entries(body)); + await reset(); + expect((await ask(port, "/virtual", "rules.test")).body).toBe(body); + expect(await costs()).toMatchObject({ decodes: 1, pathDecodes: 1, bodyReads: 1, hashes: 1 }); + await reset(); + for (let i = 0; i < 16; i++) + expect((await ask(port, `/virtual?request=${i}`, "rules.test")).body).toBe(body); + expect(await costs()).toEqual({ + decodes: 0, + pathDecodes: 16, + bodyReads: 0, + bodyBytes: 0, + hashes: 0, + }); + await pushRules("rules.test", entries("refreshed")); + await reset(); + expect((await ask(port, "/virtual", "rules.test")).body).toBe("refreshed"); + expect(await costs()).toMatchObject({ decodes: 1, bodyReads: 1, hashes: 1 }); + await pushRules("rules.test", []); + await reset(); + expect((await ask(port, "/virtual", "rules.test")).body).not.toBe("refreshed"); + expect(await costs()).toEqual({ + decodes: 0, + pathDecodes: 0, + bodyReads: 0, + bodyBytes: 0, + hashes: 0, + }); + }); + + it("supports an OPTIONS response and leaves platform paths alone under a catch-all", async () => { + await pushRules("rules.test", [ + { + pathPrefix: "/virtual", + spec: { + response: normalizeEdgeResponse({ + status: 204, + methods: ["OPTIONS"], + headers: { "Access-Control-Allow-Origin": "https://client.test" }, + }), + }, + }, + ]); + const options = await ask(port, "/virtual", "rules.test", { method: "OPTIONS" }); + expect(options).toMatchObject({ status: 204, body: "" }); + expect(options.headers["access-control-allow-origin"]).toBe("https://client.test"); + await pushRules("rules.test", [ + { + pathPrefix: null, + spec: { response: normalizeEdgeResponse({ match: "prefix", body: "catch-all" }) }, + }, + ]); + expect((await ask(port, "/ordinary", "rules.test")).body).toBe("catch-all"); + for (const path of [ + "/_openship/hooks/probe", + "/.openship/auth", + "/.well-known/acme-challenge/probe", + "/ignored/../.openship/auth", + "//.openship/auth", + ]) { + expect((await ask(port, path, "rules.test")).body).not.toBe("catch-all"); + } + }); + it.each([ ["JSON null", null], ["omitted", undefined], diff --git a/apps/api/test/lib/edge-mgmt-large-body.test.ts b/apps/api/test/lib/edge-mgmt-large-body.test.ts new file mode 100644 index 000000000..64d0515cb --- /dev/null +++ b/apps/api/test/lib/edge-mgmt-large-body.test.ts @@ -0,0 +1,172 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { exec as shellExec } from "node:child_process"; +import { access, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { createServer, type Server } from "node:http"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { promisify } from "node:util"; +import { LocalExecutor } from "@repo/adapters"; + +const { acquire } = vi.hoisted(() => ({ acquire: vi.fn() })); +vi.mock("@repo/platform/engine/lib/ssh-manager", () => ({ sshManager: { acquire } })); +vi.mock("@repo/platform/engine/lib/ssh-tunnel", () => ({ + tunnelRequest: vi.fn(async () => null), + tunnelStream: vi.fn(), +})); +vi.mock("@repo/adapters", async (original) => ({ + ...(await original()), + resolveOurEdgeContainer: async () => "fixture-edge", +})); + +const { postEdgeMgmt } = await import("@repo/platform/engine/lib/edge-management"); +const exec = promisify(shellExec); +let server: Server | undefined; +let directory: string | undefined; +const files: string[] = []; +let local: LocalExecutor; +beforeEach(() => { + vi.stubEnv("CLOUD_MODE", "false"); + local = new LocalExecutor(); +}); +afterEach(async () => { + await new Promise((resolve) => (server ? server.close(() => resolve()) : resolve())); + server = undefined; + for (const file of files.splice(0)) await rm(file, { force: true }); + if (directory) await rm(directory, { recursive: true, force: true }); + directory = undefined; + await local.dispose(); + vi.unstubAllEnvs(); +}); + +describe("large edge management requests", () => { + it.each([ + { transport: "stdin", bytes: 64000 }, + { transport: "file", bytes: 64000 }, + { transport: "tunnel fallback", bytes: 64000 }, + { transport: "stdin", bytes: 0 }, + { transport: "file", bytes: 0 }, + ])( + "delivers literal JSON via $transport ($bytes padding bytes) and preserves large replies", + async ({ transport, bytes }) => { + directory = await mkdtemp(join(tmpdir(), "openship-response-transport-")); + const marker = join(directory, "must-not-execute"); + const literal = `'; touch ${marker}; $(touch ${marker}) \`touch ${marker}\`\nمرحبا\u0000`; + const payload = { + host: "response.test", + rules: Array.from({ length: 4 }, (_, i) => ({ + pathPrefix: `/response/${i}`, + spec: { response: { body: literal + "x".repeat(bytes) } }, + })), + }; + const reply = { ok: true, count: 4, collected: "مرحبا".repeat(10000) }; + let received = ""; + server = createServer(async (request, response) => { + const chunks: Buffer[] = []; + for await (const chunk of request) chunks.push(Buffer.from(chunk)); + received = Buffer.concat(chunks).toString("utf8"); + response.setHeader("Content-Type", "application/json"); + response.end(JSON.stringify(reply)); + }); + await new Promise((resolve) => server!.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Missing fixture port"); + const stdin = transport !== "file"; + const hostWrite = vi.fn(async (path: string, body: string, options: { mode: number }) => { + files.push(path); + await writeFile(path, body, options); + expect((await stat(path)).mode & 0o777).toBe(0o600); + }); + const hostRemove = vi.fn((path: string) => rm(path, { force: true })); + const toLocal = (command: string, input = false) => { + if (Buffer.byteLength(command) >= 128 * 1024) throw new Error("E2BIG"); + const prefix = `docker exec ${input ? "-i " : ""}'fixture-edge' `; + if (!command.startsWith(prefix)) throw new Error("Unexpected fixture command"); + return command.slice(prefix.length).replace("127.0.0.1:9145", `127.0.0.1:${address.port}`); + }; + acquire.mockResolvedValue({ + ...(transport === "tunnel fallback" ? { forwardPort: vi.fn() } : {}), + ...(stdin + ? { + execWithInput: async (command: string, body: import("node:stream").Readable) => { + const path = command.match(/\/tmp\/openship-edge-request-[\w-]+\.json/)?.[0]; + if (!path) throw new Error("Missing private upload path"); + files.push(path); + const result = await local.execWithInput(toLocal(command, true), body); + expect((await stat(path)).mode & 0o777).toBe(0o600); + return result; + }, + } + : {}), + writeFile: hostWrite, + rm: hostRemove, + exec: async (command: string) => { + // Only Docker isolation is elided: stdin, curl, shell, files and HTTP + // are real. The fixture shares the container's file with the host. + if (command.startsWith("docker cp ")) { + if (stdin) throw new Error("stdin-capable executors must not stage a host copy"); + return ""; + } + return (await exec(toLocal(command))).stdout; + }, + }); + await expect(postEdgeMgmt("fixture-server", "/rules", payload)).resolves.toEqual(reply); + expect(JSON.parse(received)).toEqual(payload); + await expect(access(marker)).rejects.toMatchObject({ code: "ENOENT" }); + expect(files).toHaveLength(1); + await expect(access(files[0]!)).rejects.toMatchObject({ code: "ENOENT" }); + if (stdin) { + expect(hostWrite).not.toHaveBeenCalled(); + expect(hostRemove).not.toHaveBeenCalled(); + } + }, + ); + + it("cleans up a failed stdin upload without publishing or retrying through a host copy", async () => { + const hostWrite = vi.fn(); + const commands: string[] = []; + acquire.mockResolvedValue({ + execWithInput: async (command: string) => { + const path = command.match(/\/tmp\/openship-edge-request-[\w-]+\.json/)?.[0]; + if (!path) throw new Error("Missing upload path"); + files.push(path); + await writeFile(path, "partial", { mode: 0o600 }); + return { code: 1, stdout: "", stderr: "connection interrupted" }; + }, + exec: async (command: string) => { + commands.push(command); + if (command.includes("curl") || command.startsWith("docker cp ")) + throw new Error("Failed upload must not publish"); + return (await exec(command.slice("docker exec 'fixture-edge' ".length))).stdout; + }, + writeFile: hostWrite, + }); + await expect( + postEdgeMgmt("fixture-server", "/rules", { body: "x".repeat(65536) }), + ).resolves.toBeNull(); + expect(hostWrite).not.toHaveBeenCalled(); + expect( + commands.some((command) => command.includes("curl") || command.startsWith("docker cp ")), + ).toBe(false); + expect(files).toHaveLength(1); + await expect(access(files[0]!)).rejects.toMatchObject({ code: "ENOENT" }); + }); + + it("cleans up private request files when copying to the edge fails", async () => { + acquire.mockResolvedValue({ + writeFile: async (path: string, body: string, options: { mode: number }) => { + files.push(path); + await writeFile(path, body, options); + }, + exec: async (command: string) => { + if (command.startsWith("docker cp ")) throw new Error("edge unavailable"); + return ""; + }, + rm: (path: string) => rm(path, { force: true }), + }); + await expect( + postEdgeMgmt("fixture-server", "/rules", { body: "x".repeat(65536) }), + ).resolves.toBeNull(); + expect(files).toHaveLength(1); + await expect(readFile(files[0]!)).rejects.toMatchObject({ code: "ENOENT" }); + }); +}); diff --git a/apps/api/test/lib/post-edge-mgmt.test.ts b/apps/api/test/lib/post-edge-mgmt.test.ts index 9031b4275..8a41c016b 100644 --- a/apps/api/test/lib/post-edge-mgmt.test.ts +++ b/apps/api/test/lib/post-edge-mgmt.test.ts @@ -31,7 +31,6 @@ vi.mock("@repo/platform/engine/lib/ssh-tunnel", () => ({ vi.mock("@repo/platform/engine/lib/ssh-manager", () => ({ sshManager: { retain: vi.fn(), release: vi.fn(), acquire: vi.fn() }, })); -vi.mock("@repo/platform/engine/lib/platform-mode", () => ({ isOblienBackedDeployment: async () => false })); const { findLocal } = vi.hoisted(() => ({ findLocal: vi.fn() })); vi.mock("@repo/db", () => ({ repos: { @@ -39,7 +38,7 @@ vi.mock("@repo/db", () => ({ }, })); -const { postEdgeMgmt } = await import("@repo/platform/engine/lib/project-analytics"); +const { postEdgeMgmt } = await import("@repo/platform/engine/lib/edge-management"); beforeEach(() => { vi.clearAllMocks(); @@ -123,13 +122,13 @@ describe("failure is best-effort by contract", () => { // would abort a routing reconcile over a metrics setting. await expect( postEdgeMgmt(null, "/analytics/config", { hosts: [] }, "org1"), - ).resolves.toBeUndefined(); + ).resolves.toBeNull(); }); it("resolves when the tunnel fails", async () => { tunnelRequest.mockRejectedValue(new Error("tunnel closed")); await expect( postEdgeMgmt("srv1", "/analytics/config", { host: "a.com", paths: true }), - ).resolves.toBeUndefined(); + ).resolves.toBeNull(); }); }); diff --git a/apps/api/test/lib/server-log-stream-framing.test.ts b/apps/api/test/lib/server-log-stream-framing.test.ts index 877b4219b..e641ab402 100644 --- a/apps/api/test/lib/server-log-stream-framing.test.ts +++ b/apps/api/test/lib/server-log-stream-framing.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect } from "vitest"; -import { streamChunkBytes } from "@repo/platform/engine/lib/project-analytics"; +import { streamChunkBytes } from "@repo/platform/engine/lib/edge-management"; /** * The server-logs live tail relays the EDGE's SSE frames. `pipe_stream.lua` emits diff --git a/apps/api/test/modules/analytics/analytics-config-push.test.ts b/apps/api/test/modules/analytics/analytics-config-push.test.ts index bef7892dc..4ec55da96 100644 --- a/apps/api/test/modules/analytics/analytics-config-push.test.ts +++ b/apps/api/test/modules/analytics/analytics-config-push.test.ts @@ -32,10 +32,12 @@ vi.mock("@repo/db", () => ({ })); vi.mock("@repo/platform/engine/lib/project-analytics", () => ({ + resolveProjectTrafficSources: vi.fn(async (id: string) => h.sourcesByProject[id] ?? []), +})); +vi.mock("@repo/platform/engine/lib/edge-management", () => ({ postEdgeMgmt: vi.fn(async (serverId: string | null, path: string, body: unknown) => { h.pushes.push({ serverId, path, body }); }), - resolveProjectTrafficSources: vi.fn(async (id: string) => h.sourcesByProject[id] ?? []), })); const { pushProjectAnalyticsConfig, reconcileAnalyticsConfig } = await import( diff --git a/apps/api/test/modules/analytics/geo-rollup.test.ts b/apps/api/test/modules/analytics/geo-rollup.test.ts index d195752ba..84a37d471 100644 --- a/apps/api/test/modules/analytics/geo-rollup.test.ts +++ b/apps/api/test/modules/analytics/geo-rollup.test.ts @@ -34,6 +34,8 @@ vi.mock("@repo/db", () => ({ vi.mock("@repo/platform/engine/lib/project-analytics", () => ({ resolveProjectTrafficSources: vi.fn(async () => h.sources), +})); +vi.mock("@repo/platform/engine/lib/edge-management", () => ({ fetchMgmt: vi.fn(async (_serverId: string, path: string) => { for (const [prefix, value] of h.mgmt) { if (path.startsWith(prefix)) return value; diff --git a/apps/api/test/modules/analytics/overview-traffic.test.ts b/apps/api/test/modules/analytics/overview-traffic.test.ts index 6efa816cf..e88094fc4 100644 --- a/apps/api/test/modules/analytics/overview-traffic.test.ts +++ b/apps/api/test/modules/analytics/overview-traffic.test.ts @@ -28,6 +28,8 @@ vi.mock("@repo/db", () => ({ repos: { vi.mock("@repo/platform/engine/lib/project-analytics", () => ({ resolveProjectTrafficSources: async (_id: string, options: { domain?: string }) => h.sources.filter((source) => !options.domain || source.domain === options.domain), +})); +vi.mock("@repo/platform/engine/lib/edge-management", () => ({ fetchMgmt: h.readLive, })); vi.mock("@repo/platform/engine/modules/system/analytics-scraper", () => ({ scrapeServerIfStale: h.scrape })); diff --git a/apps/api/test/modules/analytics/scrape-to-db.test.ts b/apps/api/test/modules/analytics/scrape-to-db.test.ts index d8c9fde24..4ac9d46f4 100644 --- a/apps/api/test/modules/analytics/scrape-to-db.test.ts +++ b/apps/api/test/modules/analytics/scrape-to-db.test.ts @@ -87,7 +87,7 @@ vi.mock("@repo/db", () => ({ }, })); -vi.mock("@repo/platform/engine/lib/project-analytics", () => ({ +vi.mock("@repo/platform/engine/lib/edge-management", () => ({ fetchMgmt: vi.fn(async (_serverId: string, path: string) => path.startsWith("/analytics/totals") ? h.totals : null, ), @@ -209,7 +209,7 @@ describe("retained minute history", () => { const now = Math.floor(Date.now() / 60_000); h.lastMinute = lastOffset === null ? null : now + lastOffset; const edge = new Map([[now - 300, 40], [now - 2, 8], [now, 3]]); - const { postMgmtJson } = await import("@repo/platform/engine/lib/project-analytics"); + const { postMgmtJson } = await import("@repo/platform/engine/lib/edge-management"); const collect = async (_server: string, _path: string, body: unknown) => { const request = body as { domains: Array<{ domain: string; from: number; to: number }> }; const { from, to } = request.domains[0]; diff --git a/apps/api/test/modules/deployments/native-sdk-parity.test.ts b/apps/api/test/modules/deployments/native-sdk-parity.test.ts index a247e0c27..6a1cf68ba 100644 --- a/apps/api/test/modules/deployments/native-sdk-parity.test.ts +++ b/apps/api/test/modules/deployments/native-sdk-parity.test.ts @@ -6,7 +6,7 @@ import { join } from "node:path"; import { createShip } from "@repo/sdk/native"; import { OpenshipClient } from "@repo/sdk/client"; import type { VerifiedIdentity } from "@repo/platform"; -import { ENV_MASK, type AppTemplate } from "@repo/core"; +import { ENV_MASK, normalizeEdgeResponse, type AppTemplate } from "@repo/core"; import type { BackupDestination as StoredBackupDestination } from "@repo/db"; import type { ProjectInfo } from "@repo/platform/engine/modules/deployments/prepare.service"; import { alice, storedDeployment } from "../../../../../packages/platform/test/fixtures"; @@ -1910,6 +1910,9 @@ describe("domain and DNS HTTP/native parity", () => { }); describe("project routing HTTP/native parity", () => { + beforeEach(() => { + for (const id of ["project-a", "project-b", "project-sibling"]) h.projects.set(id, { ...h.projects.get(id)!, id }); + }); const remote = () => new OpenshipClient({ baseUrl: "http://openship.test", organizationId: "org-a", fetch: ((url, init) => app.request(url as string, init)) as typeof fetch }); const rule = { id: "rule-a", organizationId: "org-a", projectId: "project-a", domainId: "domain-a", pathPrefix: "/api", spec: { access: { methods: ["GET"] } }, enabled: true, createdAt: "2026-09-12T00:00:00.000Z", updatedAt: "2026-09-12T00:00:00.000Z" }; it("retains the sanitizer, project/domain checks, edge push, and one audit per facade", async () => { @@ -1936,6 +1939,41 @@ describe("project routing HTTP/native parity", () => { expect(h.ruleUpdate).not.toHaveBeenCalled(); for (const args of h.ruleRemove.mock.calls) expect(args).toEqual(["project-sibling", rule.id]); }); + it("validates domain responses in both facades and distinguishes persistence from edge application", async () => { + const local = await native(); + h.ruleCreate.mockImplementation(async data => ({ ...rule, ...data })); + const input = { domainId: "domain-a", pathPrefix: "/status", spec: { response: normalizeEdgeResponse({ body: "ready", headers: { "Cache-Control": "no-store" } }) } }; + for (const projects of [remote().projects, local.projects]) { + h.rulePush.mockResolvedValue(true); + expect(await projects.createRouteRule("project-a", input)).toMatchObject({ domainId: "domain-a", pathPrefix: "/status", edgeApplied: true, spec: { response: { match: "exact", status: 200, body: "ready", headers: { "cache-control": "no-store" } } } }); + h.rulePush.mockResolvedValue(false); + expect(await projects.createRouteRule("project-a", input)).toMatchObject({ edgeApplied: false }); + for (const invalid of [ + { ...input, domainId: null }, + { ...input, domainId: "domain-b" }, + { ...input, pathPrefix: "/_openship/auth" }, + { ...input, spec: { response: { ...input.spec.response, headers: { "X-Test": "ok\r\nInjected: yes" } } } }, + { ...input, spec: { ...input.spec, access: { methods: ["GET"] } } }, + ]) await expect(projects.createRouteRule("project-a", invalid)).rejects.toMatchObject({ statusCode: 400 }); + } + expect(h.ruleCreate).toHaveBeenCalledTimes(4); + }); + it("refuses unsupported edge targets and prevents changing a response to a foreign domain", async () => { + const local = await native(); + const input = { domainId: "domain-a", spec: { response: normalizeEdgeResponse({ body: "ready" }) } }; + for (const projects of [remote().projects, local.projects]) { + h.domains.set("domain-a", { projectId: "project-a", externalIngress: true }); + await expect(projects.createRouteRule("project-a", input)).rejects.toMatchObject({ code: "EDGE_RESPONSE_UNSUPPORTED" }); + h.domains.set("domain-a", { projectId: "project-a" }); + h.projects.set("project-a", { id: "project-a", organizationId: "org-a", workspaceId: "workspace" }); + await expect(projects.createRouteRule("project-a", input)).rejects.toMatchObject({ code: "EDGE_RESPONSE_UNSUPPORTED" }); + h.projects.set("project-a", { id: "project-a", organizationId: "org-a" }); + h.ruleGet.mockResolvedValue({ ...rule, spec: input.spec }); + await expect(projects.updateRouteRule("project-a", { ruleId: rule.id, domainId: "domain-b" })).rejects.toMatchObject({ code: "INVALID_DOMAIN" }); + } + expect(h.ruleCreate).not.toHaveBeenCalled(); + expect(h.ruleUpdate).not.toHaveBeenCalled(); + }); it("connects a primary domain through the same domain operation and retains legacy errors", async () => { h.domainCreate.mockResolvedValue({ domain: domainFixture(), records: { mode: "external", records: [] }, wwwError: "sibling is already owned" }); const local = await native(); diff --git a/apps/api/test/modules/projects/project-overview-logs.test.ts b/apps/api/test/modules/projects/project-overview-logs.test.ts index 05434455e..a716386d1 100644 --- a/apps/api/test/modules/projects/project-overview-logs.test.ts +++ b/apps/api/test/modules/projects/project-overview-logs.test.ts @@ -27,6 +27,8 @@ vi.mock("@repo/platform/engine/lib/ssh-manager", () => ({ sshManager: {} })); vi.mock("@repo/platform/engine/lib/openresty-paths", () => ({ getOpenRestyPaths: vi.fn() })); vi.mock("@repo/platform/engine/lib/project-analytics", () => ({ resolveProjectTrafficSource: h.source, resolveProjectTrafficSources: h.sources, +})); +vi.mock("@repo/platform/engine/lib/edge-management", () => ({ fetchMgmt: h.fetchMgmt, mgmtStream: vi.fn(), probeMgmt: vi.fn(), })); import { getProjectHome } from "@repo/platform/engine/modules/projects/project-home.operations"; diff --git a/apps/api/test/modules/route-rules/route-rule-push.test.ts b/apps/api/test/modules/route-rules/route-rule-push.test.ts index 947253175..0b1ec36ee 100644 --- a/apps/api/test/modules/route-rules/route-rule-push.test.ts +++ b/apps/api/test/modules/route-rules/route-rule-push.test.ts @@ -1,6 +1,6 @@ import { diagnostics as errorDiagnostics } from "@repo/core/diagnostics"; import { describe, expect, it, vi, beforeEach } from "vitest"; -import type { RouteRuleSpec } from "@repo/core"; +import { normalizeEdgeResponse, type RouteRuleSpec } from "@repo/core"; /** * The DB is the source of truth for route rules; the edge only knows what was last @@ -41,8 +41,8 @@ vi.mock("@repo/db", async (importOriginal) => ({ }, })); -vi.mock("@repo/platform/engine/lib/project-analytics", async (importOriginal) => ({ - ...(await importOriginal()), +vi.mock("@repo/platform/engine/lib/edge-management", async (importOriginal) => ({ + ...(await importOriginal()), postEdgeMgmt, })); @@ -88,7 +88,7 @@ function capturedPushes() { beforeEach(() => { vi.clearAllMocks(); - postEdgeMgmt.mockResolvedValue(undefined); + postEdgeMgmt.mockResolvedValue({ ok: true, staticResponses: true }); // pushProjectRules now loads the project too, for the organizationId that resolves a // null serverId to the "This Server" row. The real repo always returns a promise; an // unset mock returns undefined and blows up on `.catch`. @@ -171,6 +171,38 @@ describe("serializeProjectRules", () => { }); describe("pushProjectRules", () => { + it("checks response support before publishing and keeps the response bound to its domain", async () => { + const response = { response: normalizeEdgeResponse({ body: "ready" }) }; + listByProject.mockResolvedValue([rule({ domainId: "d1", pathPrefix: "/health", spec: response })]); + listDomains.mockResolvedValue([domain("d1", "a.com"), domain("d2", "b.com")]); + await expect(pushProjectRules("p1", "srv1")).resolves.toBe(true); + const calls = capturedPushes(); + expect(calls.findIndex(call => call.path === "/rules/capabilities")).toBeLessThan( + calls.findIndex(call => call.path === "/rules" && call.body.host === "a.com")); + expect(calls.find(call => call.body.host === "a.com")?.body.rules).toEqual([{ pathPrefix: "/health", spec: response }]); + expect(calls.find(call => call.body.host === "b.com")?.body.rules).toEqual([]); + }); + + it.each([null, { ok: true }, { ok: true, staticResponses: false }])("does not send a response to an older edge: %j", async (capability) => { + listByProject.mockResolvedValue([rule(), rule({ id: "response", domainId: "d1", spec: { response: normalizeEdgeResponse({ body: "ready" }) } })]); + listDomains.mockResolvedValue([domain("d1", "a.com")]); + postEdgeMgmt.mockImplementation(async (_server, path) => path === "/rules/capabilities" ? capability : { ok: true }); + const warn = vi.spyOn(errorDiagnostics, "warn").mockImplementation(() => {}); + try { + await expect(pushProjectRules("p1", "srv1")).resolves.toBe(false); + expect(capturedPushes().find(call => call.path === "/rules")?.body.rules).toEqual([{ pathPrefix: null, spec: RL }]); + } finally { warn.mockRestore(); } + }); + + it("reports an unacknowledged push as pending", async () => { + listByProject.mockResolvedValue([]); + listDomains.mockResolvedValue([domain("d1", "a.com")]); + postEdgeMgmt.mockResolvedValue(null); + const warn = vi.spyOn(errorDiagnostics, "warn").mockImplementation(() => {}); + try { await expect(pushProjectRules("p1", "srv1")).resolves.toBe(false); } + finally { warn.mockRestore(); } + }); + it("pushes every current host, even the ones with no rules", async () => { // An empty ruleset is how a host is CLEARED. Pushing only hosts that still have // rules is exactly the bug where a deleted rule keeps enforcing. @@ -212,7 +244,7 @@ describe("pushProjectRules", () => { postEdgeMgmt.mockRejectedValueOnce(new Error("tunnel closed")).mockResolvedValue({ ok: true }); const warn = vi.spyOn(errorDiagnostics, "warn").mockImplementation(() => {}); - await expect(pushProjectRules("p1", "srv1")).resolves.toBeUndefined(); + await expect(pushProjectRules("p1", "srv1")).resolves.toBe(false); expect(postEdgeMgmt).toHaveBeenCalledTimes(2); expect(warn).toHaveBeenCalled(); warn.mockRestore(); diff --git a/apps/api/test/modules/route-rules/rules-lua-contract.test.ts b/apps/api/test/modules/route-rules/rules-lua-contract.test.ts index 23c058eb6..4fc4e0ea7 100644 --- a/apps/api/test/modules/route-rules/rules-lua-contract.test.ts +++ b/apps/api/test/modules/route-rules/rules-lua-contract.test.ts @@ -202,7 +202,7 @@ describe("rules_guard.lua keeps the properties its comments promise", () => { it("returns early when the host has no rules (the common case)", () => { const head = guard.slice(0, guard.indexOf("local lib =")); - expect(head).toContain("if not raw then return end"); + expect(head).toContain("if not raw and not response_revision then return end"); }); it("picks the longest matching path prefix", () => { @@ -231,10 +231,8 @@ describe("rules_guard.lua keeps the properties its comments promise", () => { expect(guard).not.toContain("http_x_forwarded_for"); }); - it("never writes a rule value into a response header", () => { - const headerWrites = [...guard.matchAll(/ngx\.header\[[^\]]+\]\s*=\s*(.+)/g)].map((m) => m[1]!); - expect(headerWrites).toEqual(['"1"']); // Retry-After only, a literal - }); + // Literal response headers now have an explicit validator. Header injection + // and access-policy preservation are exercised by routing-rules.e2e.test.ts. it("applies access before ban before hotlink before rate limit", () => { // After resolving the country header, keep the cheaper access/ban checks diff --git a/apps/api/test/modules/system/analytics-scrape-sweep.test.ts b/apps/api/test/modules/system/analytics-scrape-sweep.test.ts index ef0d25e3e..40eb4a913 100644 --- a/apps/api/test/modules/system/analytics-scrape-sweep.test.ts +++ b/apps/api/test/modules/system/analytics-scrape-sweep.test.ts @@ -51,14 +51,14 @@ vi.mock("@repo/platform/engine/lib/system-debug", () => ({ formatDuration: () => "1ms", })); -vi.mock("@repo/platform/engine/lib/project-analytics", () => ({ +vi.mock("@repo/platform/engine/lib/edge-management", () => ({ probeMgmt: vi.fn(async (serverId: string) => { h.scraped.push(serverId); if (h.failing.has(serverId)) throw new Error("ssh refused"); return true; }), fetchMgmt: vi.fn(async () => h.totals), - postMgmt: vi.fn(async () => ({ buckets: [], flushed: 0 })), + postMgmtJson: vi.fn(async () => ({ buckets: [], flushed: 0 })), })); const { runAnalyticsScrapeSweep } = await import("@repo/platform/engine/modules/system/analytics-scraper"); @@ -98,7 +98,7 @@ describe("runAnalyticsScrapeSweep", () => { it("goes one server at a time — a 50-box control plane must not connect to all at once", async () => { let concurrent = 0; let peak = 0; - const { probeMgmt } = await import("@repo/platform/engine/lib/project-analytics"); + const { probeMgmt } = await import("@repo/platform/engine/lib/edge-management"); (probeMgmt as unknown as { mockImplementation: (f: unknown) => void }).mockImplementation( async (serverId: string) => { concurrent += 1; diff --git a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/DomainSettings.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/DomainSettings.tsx index 43691ed49..86b8f4391 100644 --- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/DomainSettings.tsx +++ b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/DomainSettings.tsx @@ -11,6 +11,7 @@ import { useRouter } from "next/navigation"; import { useProjectSettings } from "@/context/ProjectSettingsContext"; import { RoutingConfigCard } from "./RoutingConfigCard"; import { RouteRules } from "./RouteRules"; +import { DomainResponseRoutes } from "@/components/routing/DomainResponseRoutes"; import { RoutingUnsyncedCallout } from "./RoutingUnsyncedCallout"; import { localizeDiagnosisMessage } from "@/lib/i18n/localize-issues"; import { invalidateProjectCaches } from "@/hooks/useProjectEndpoints"; @@ -2008,6 +2009,11 @@ export const DomainSettings = ({ applicationScope = false, serviceScope, onRoute + ) : undefined} protectionControl={} menuActions={menuActions} @@ -3109,6 +3115,7 @@ function DiagnosablePill({ function DomainOverviewCard({ domain, + responseRoutes, protectionControl, menuActions = [], sslActionBusy = false, @@ -3128,6 +3135,7 @@ function DomainOverviewCard({ ingressSettings, }: { domain: DomainSummaryItem; + responseRoutes?: React.ReactNode; protectionControl?: React.ReactNode; /** Secondary actions (edit, renew, …) collapsed into a ⋯ menu. Visit is a * plain icon; Verify is a direct inline button below, not a menu item. */ @@ -3501,6 +3509,7 @@ function DomainOverviewCard({ ) : null} + {responseRoutes} ); } diff --git a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/RouteRules.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/RouteRules.tsx index e10f0b21b..845559b21 100644 --- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/RouteRules.tsx +++ b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/RouteRules.tsx @@ -69,7 +69,7 @@ export function RouteRules() { setLoading(true); try { const res = await projectsApi.listRouteRules(projectData.id); - const list = res?.rules ?? []; + const list = (res?.rules ?? []).filter(rule => !rule.spec.response); setRules(list); if (!autoOpened.current && list.length > 0) { setOpen(true); diff --git a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/domain-routing-retry.test.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/domain-routing-retry.test.tsx index 8045f5187..e23c9279f 100644 --- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/domain-routing-retry.test.tsx +++ b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/domain-routing-retry.test.tsx @@ -41,6 +41,7 @@ vi.mock("@/lib/api", async (original) => { ...actual.projectsApi, getEdgeStatus: mocks.edgeStatus, listRouteProtection: async () => ({ data: [] }), + listRouteRules: async () => ({ rules: [] }), }, domainsApi: { ...actual.domainsApi, list: mocks.listDomains, verifySsl: mocks.verifySsl }, deployApi: { diff --git a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/services/service-domains.test.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/services/service-domains.test.tsx index 28825b05d..b776ee564 100644 --- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/services/service-domains.test.tsx +++ b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/services/service-domains.test.tsx @@ -32,7 +32,7 @@ vi.mock("@/lib/api", async (original) => { return { ...actual, servicesApi: { ...actual.servicesApi, get: mocks.get, update: mocks.update }, - projectsApi: { ...actual.projectsApi, update: mocks.updateProject, connectDomain: mocks.connect, getEdgeStatus: async () => ({ ready: true }), listRouteProtection: async () => ({ data: [] }) }, + projectsApi: { ...actual.projectsApi, update: mocks.updateProject, connectDomain: mocks.connect, getEdgeStatus: async () => ({ ready: true }), listRouteProtection: async () => ({ data: [] }), listRouteRules: async () => ({ rules: [] }) }, deployApi: { ...actual.deployApi, checkPorts: async () => ({ data: [] }), checkOutput: async () => ({ data: [] }) }, domainsApi: { ...actual.domainsApi, remove: mocks.remove, verify: mocks.verify, records: mocks.records, list: mocks.listDomains, dnsChallenge: mocks.dnsChallenge, startDnsChallenge: mocks.startDnsChallenge, dnsPlan: mocks.dnsPlan, diff --git a/apps/dashboard/src/components/routing/DomainResponseRoutes.test.tsx b/apps/dashboard/src/components/routing/DomainResponseRoutes.test.tsx new file mode 100644 index 000000000..e9b7f1f68 --- /dev/null +++ b/apps/dashboard/src/components/routing/DomainResponseRoutes.test.tsx @@ -0,0 +1,193 @@ +// @vitest-environment happy-dom +import { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { normalizeEdgeResponse } from "@repo/core"; +import { DomainResponseRoutes } from "./DomainResponseRoutes"; + +const api = vi.hoisted(() => ({ + listRouteRules: vi.fn(), + createRouteRule: vi.fn(), + updateRouteRule: vi.fn(), + deleteRouteRule: vi.fn(), +})); +vi.mock("@/lib/api", () => ({ + projectsApi: api, + getApiErrorMessage: (error: unknown, fallback: string) => + error instanceof Error ? error.message : fallback, +})); +let root: Root; +let container: HTMLDivElement; +const rule = (overrides = {}) => ({ + id: "response-a", + projectId: "project", + domainId: "domain-a", + pathPrefix: "/x", + enabled: true, + spec: { + response: normalizeEdgeResponse({ body: "original", headers: { "cache-control": "no-store" } }), + }, + ...overrides, +}); +beforeEach(() => { + vi.clearAllMocks(); + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + api.listRouteRules.mockResolvedValue({ rules: [] }); + api.createRouteRule.mockImplementation(async (_project, input) => ({ + rule: rule({ ...input, edgeApplied: true }), + })); + api.updateRouteRule.mockImplementation(async (_project, _id, input) => ({ + rule: rule({ ...input, edgeApplied: true }), + })); + api.deleteRouteRule.mockResolvedValue({ success: true, edgeApplied: true }); + container = document.createElement("div"); + document.body.append(container); + root = createRoot(container); +}); +afterEach(async () => { + await act(async () => root.unmount()); + container.remove(); + vi.unstubAllGlobals(); +}); +async function render() { + await act(async () => + root.render( + , + ), + ); +} +async function click(label: string) { + const button = [...document.querySelectorAll("button")].find( + (element) => + element.getAttribute("aria-label") === label || element.textContent?.trim() === label, + ); + expect(button, label).toBeTruthy(); + await act(async () => button!.click()); +} +async function input(selector: string, value: string) { + const element = document.querySelector(selector)!; + expect(element, selector).toBeTruthy(); + await act(async () => { + Object.getOwnPropertyDescriptor( + element.tagName === "TEXTAREA" ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype, + "value", + )!.set!.call(element, value); + element.dispatchEvent(new Event("input", { bubbles: true })); + }); +} +async function submit() { + await act(async () => { + document + .querySelector("form")! + .dispatchEvent(new Event("submit", { bubbles: true, cancelable: true })); + }); +} + +it("creates a response for this domain, keeps preview HTML inert, and reports edge acknowledgement", async () => { + await render(); + await click("Add route"); + await input('input[placeholder="/health"]', "/status"); + await input("textarea", ""); + await click("Add header"); + await input('input[aria-label="Header name 1"]', "Cache-Control"); + await input('input[aria-label="Header value 1"]', "no-store"); + await click("Response preview"); + expect(document.querySelector("pre")?.textContent).toContain("", + headers: { "cache-control": "no-store" }, + match: "exact", + }), + }, + }), + ); + expect(document.body.textContent).toContain("Saved and applied to the edge."); + expect(document.querySelector('[role="dialog"]')).toBeNull(); +}); + +it("retains a failed draft, avoids double submit and distinguishes saved from applied", async () => { + await render(); + await click("Add route"); + await input('input[placeholder="/health"]', "/x"); + await input("textarea", "keep this content"); + let reject!: (error: Error) => void; + api.createRouteRule.mockImplementationOnce( + () => + new Promise((_, fail) => { + reject = fail; + }), + ); + await submit(); + await submit(); + expect(api.createRouteRule).toHaveBeenCalledTimes(1); + await act(async () => reject(new Error("offline"))); + expect(document.querySelector("textarea")?.value).toBe("keep this content"); + expect(document.body.textContent).toContain("offline"); + api.createRouteRule.mockResolvedValue({ rule: rule({ edgeApplied: false }) }); + await submit(); + expect(document.body.textContent).toContain("Edge application is pending"); + expect(document.body.textContent).not.toContain("Saved and applied"); +}); + +it("rejects duplicate or injected headers before sending a mutation", async () => { + await render(); + await click("Add route"); + await input('input[placeholder="/health"]', "/headers"); + for (const [index, name] of ["X-Test", "x-test"].entries()) { + await click("Add header"); + await input(`input[aria-label="Header name ${index + 1}"]`, name); + } + await submit(); + expect(api.createRouteRule).not.toHaveBeenCalled(); + expect(document.body.textContent).toContain("must be unique"); +}); + +it("edits only the selected domain response and preserves its disabled state", async () => { + api.listRouteRules.mockResolvedValue({ + rules: [ + rule({ enabled: false }), + rule({ id: "other", domainId: "domain-b", pathPrefix: "/other-domain" }), + rule({ id: "policy", spec: { rateLimit: { rps: 5, burst: 0 } } }), + ], + }); + await render(); + expect(container.textContent).not.toContain("/other-domain"); + await click("Edit route /x"); + expect(document.querySelector("textarea")?.value).toBe("original"); + await input("textarea", "changed"); + await submit(); + const patch = api.updateRouteRule.mock.calls[0]![2]; + expect(patch).not.toHaveProperty("enabled"); + expect(patch.spec.response).toMatchObject({ + body: "changed", + headers: { "cache-control": "no-store" }, + }); + expect(api.createRouteRule).not.toHaveBeenCalled(); +}); + +it("keeps failed loading distinct from an empty list and requires confirmation to remove", async () => { + api.listRouteRules.mockRejectedValueOnce(new Error("Cannot reach API")); + await render(); + expect(container.textContent).toContain("Cannot reach API"); + expect( + [...container.querySelectorAll("button")].find((button) => + button.textContent?.includes("Add route"), + )?.disabled, + ).toBe(true); + api.listRouteRules.mockResolvedValue({ rules: [rule()] }); + await click("Retry"); + await click("Remove /x"); + expect(api.deleteRouteRule).not.toHaveBeenCalled(); + await click("Remove"); + expect(api.deleteRouteRule).toHaveBeenCalledWith("project", "response-a"); + expect(container.textContent).not.toContain("/x"); +}); diff --git a/apps/dashboard/src/components/routing/DomainResponseRoutes.tsx b/apps/dashboard/src/components/routing/DomainResponseRoutes.tsx new file mode 100644 index 000000000..cb59ad690 --- /dev/null +++ b/apps/dashboard/src/components/routing/DomainResponseRoutes.tsx @@ -0,0 +1,625 @@ +"use client"; + +import { useCallback, useEffect, useId, useRef, useState } from "react"; +import { Icon } from "@repo/ui/icons"; +import { normalizeEdgeResponse, normalizeResponsePath, EDGE_RESPONSE_MAX_BYTES } from "@repo/core"; +import { useI18n } from "@/components/i18n-provider"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Textarea } from "@/components/ui/textarea"; +import { CustomSelect } from "@/components/ui/CustomSelect"; +import { Modal } from "@/components/ui/Modal"; +import { useDialogFocus } from "@/hooks/useDialogFocus"; +import { projectsApi, getApiErrorMessage, type RouteRuleRow } from "@/lib/api"; + +type Draft = { + id?: string; + path: string; + match: "exact" | "prefix"; + status: string; + contentType: string; + body: string; + methods: string; + headers: Array<{ name: string; value: string }>; +}; +const blank = (): Draft => ({ + path: "", + match: "exact", + status: "200", + contentType: "text/plain; charset=utf-8", + body: "", + methods: "GET, HEAD", + headers: [], +}); +const fromRule = (rule: RouteRuleRow): Draft => ({ + id: rule.id, + path: rule.pathPrefix || "/", + match: rule.spec.response!.match, + status: String(rule.spec.response!.status), + contentType: rule.spec.response!.contentType, + body: rule.spec.response!.body, + methods: rule.spec.response!.methods.join(", "), + headers: Object.entries(rule.spec.response!.headers).map(([name, value]) => ({ name, value })), +}); + +/** The same domain editor is used by single-app, service and project route cards. */ +export function DomainResponseRoutes({ + projectId, + domainId, + hostname, +}: { + projectId: string; + domainId: string; + hostname: string; +}) { + const { t, locale } = useI18n(); + const w = t.projectSettings.responseRoutes; + const labelId = useId(); + const [rules, setRules] = useState([]); + const [loading, setLoading] = useState(true); + const [loadError, setLoadError] = useState(""); + const [error, setError] = useState(""); + const [notice, setNotice] = useState(""); + const [draft, setDraft] = useState(null); + const [open, setOpen] = useState(false); + const [preview, setPreview] = useState(false); + const [busy, setBusy] = useState(false); + const [removeId, setRemoveId] = useState(null); + const mutation = useRef(false); + const alive = useRef(true); + useEffect(() => { + alive.current = true; + return () => { + alive.current = false; + }; + }, []); + const close = () => { + if (!mutation.current) setOpen(false); + }; + const { dialog, onKeyDown } = useDialogFocus(close, open); + const load = useCallback(async () => { + setLoading(true); + setLoadError(""); + try { + const result = await projectsApi.listRouteRules(projectId); + if (alive.current) + setRules(result.rules.filter((rule) => rule.domainId === domainId && rule.spec.response)); + } catch (cause) { + if (alive.current) setLoadError(getApiErrorMessage(cause, w.loadFailed)); + } finally { + if (alive.current) setLoading(false); + } + }, [projectId, domainId, w.loadFailed]); + useEffect(() => { + void load(); + }, [load]); + + const update = (patch: Partial) => + setDraft((current) => current && { ...current, ...patch }); + const edit = (rule?: RouteRuleRow) => { + setDraft((current) => + current && current.id === rule?.id ? current : rule ? fromRule(rule) : blank(), + ); + setError(""); + setPreview(false); + setOpen(true); + }; + const run = async (operation: () => Promise) => { + if (mutation.current) return; + mutation.current = true; + setBusy(true); + setError(""); + setNotice(""); + try { + await operation(); + } catch (cause) { + if (alive.current) setError(getApiErrorMessage(cause, w.saveFailed)); + } finally { + mutation.current = false; + if (alive.current) setBusy(false); + } + }; + const save = () => + run(async () => { + if (!draft) return; + const path = normalizeResponsePath(draft.path); + const headers: Record = {}; + for (const row of draft.headers) { + if (!row.name && !row.value) continue; + const name = row.name.trim().toLowerCase(); + if (Object.hasOwn(headers, name)) throw new Error(w.duplicateHeader); + Object.defineProperty(headers, name, { value: row.value, enumerable: true }); + } + const response = normalizeEdgeResponse({ + match: draft.match, + status: Number(draft.status), + contentType: draft.contentType.trim(), + body: draft.body, + headers, + methods: draft.methods + .split(/[\s,]+/) + .filter(Boolean) + .map((value) => value.toUpperCase()), + }); + const input = { domainId, pathPrefix: path, spec: { response } }; + const result = draft.id + ? await projectsApi.updateRouteRule(projectId, draft.id, input) + : await projectsApi.createRouteRule(projectId, { ...input, enabled: true }); + if (!alive.current) return; + setRules((current) => [...current.filter((rule) => rule.id !== result.rule.id), result.rule]); + setDraft(null); + setOpen(false); + setNotice(result.rule.edgeApplied === true ? w.saved : w.pending); + }); + const toggle = (rule: RouteRuleRow) => + run(async () => { + const result = await projectsApi.updateRouteRule(projectId, rule.id, { + enabled: !rule.enabled, + }); + if (alive.current) { + setRules((current) => current.map((row) => (row.id === rule.id ? result.rule : row))); + setNotice(result.rule.edgeApplied === true ? w.saved : w.pending); + } + }); + const remove = (rule: RouteRuleRow) => + run(async () => { + const result = await projectsApi.deleteRouteRule(projectId, rule.id); + if (!alive.current) return; + setRules((current) => current.filter((row) => row.id !== rule.id)); + setRemoveId(null); + setNotice(result.edgeApplied === true ? w.saved : w.pending); + if (draft?.id === rule.id) setDraft(null); + }); + const contentTypes = [ + { value: "text/plain; charset=utf-8", label: w.plainText }, + { value: "application/json", label: "JSON" }, + { value: "text/html; charset=utf-8", label: "HTML" }, + { value: "application/xml", label: "XML" }, + ]; + const format = + draft && contentTypes.some((type) => type.value === draft.contentType) + ? draft.contentType + : "custom"; + const contentBytes = new TextEncoder().encode(draft?.body ?? "").length; + const fieldClass = "bg-muted/60 ring-1 ring-inset ring-border/50 focus:bg-muted/80"; + const bodyless = draft && [204, 205, 304].includes(Number(draft.status)); + + return ( +
+
+

{w.title}

+ +
+

{w.description}

+ {loading && ( +
+ )} + {loadError && ( +
+

+ {loadError} +

+ +
+ )} + {!open && error && ( +

+ {error} +

+ )} + {notice && ( +

+ {notice} +

+ )} +
+ {rules.map((rule) => { + const path = rule.pathPrefix || "/"; + const response = rule.spec.response!; + return ( +
+
+ + + +
+ {removeId === rule.id && ( +
+

{w.removeHint}

+ + +
+ )} +
+ ); + })} +
+ +
+
{ + event.preventDefault(); + void save(); + }} + className="flex min-h-0 flex-1 flex-col" + > +
+
+ +
+
+

+ {draft?.id ? w.edit : w.add} +

+

+ {hostname} +

+
+ + {w.staticResponse} + + +
+ {draft && ( +
+
+
+
+
+ +
+ {w.match} + update({ match })} + /> +
+
+

+ {draft.match === "exact" ? w.exactHint : w.prefixHint} +

+
+
+ +
+ {w.contentType} + + update({ contentType: value === "custom" ? "" : value }) + } + /> +
+
+ {format === "custom" && ( + + )} +
+
+
+ {[ + { value: false, label: w.body, icon: "code" as const }, + { value: true, label: w.preview, icon: "eye" as const }, + ].map((view) => ( + + ))} +
+ {preview ? ( +
{`HTTP/1.1 ${draft.status}\nContent-Type: ${draft.contentType}\n${draft.headers
+                            .filter((row) => row.name)
+                            .map((row) => `${row.name}: ${row.value}\n`)
+                            .join("")}\n${draft.body}`}
+ ) : ( +