|
| 1 | +import http from "node:http" |
| 2 | +import { createRequire } from "node:module" |
| 3 | +import { fileURLToPath } from "node:url" |
| 4 | +import { randomBytes } from "node:crypto" |
| 5 | +import { mkdtemp, rm } from "node:fs/promises" |
| 6 | +import { tmpdir } from "node:os" |
| 7 | +import path from "node:path" |
| 8 | +import { build, createServer, preview } from "vite" |
| 9 | +import { createFixture, directory } from "./composer-fixture.mjs" |
| 10 | + |
| 11 | +const { chromium, firefox, expect } = createRequire(new URL("../../app/package.json", import.meta.url))( |
| 12 | + "@playwright/test", |
| 13 | +) |
| 14 | +const cleanups = [] |
| 15 | +try { |
| 16 | + const fixture = await createFixture() |
| 17 | + cleanups.push(() => fixture.close()) |
| 18 | + const credential = `Basic ${Buffer.from(`fixture:${randomBytes(24).toString("hex")}`).toString("base64")}` |
| 19 | + const denied = JSON.stringify({ error: "Authentication required" }) |
| 20 | + const upstream = http.createServer((request, response) => { |
| 21 | + const pathname = new URL(request.url, fixture.url).pathname |
| 22 | + if (["/session/ses_a", "/event", "/api/state"].includes(pathname) && request.headers.authorization !== credential) { |
| 23 | + response.writeHead(401, { |
| 24 | + "www-authenticate": 'Basic realm="fixture"', |
| 25 | + "content-type": "application/json", |
| 26 | + "x-fixture": "protected", |
| 27 | + }) |
| 28 | + response.end(denied) |
| 29 | + return |
| 30 | + } |
| 31 | + if (pathname === "/forbidden") { |
| 32 | + response.writeHead(403, { "content-type": "application/json" }) |
| 33 | + response.end(JSON.stringify({ error: "Forbidden" })) |
| 34 | + return |
| 35 | + } |
| 36 | + const proxy = http.request( |
| 37 | + new URL(request.url, fixture.url), |
| 38 | + { method: request.method, headers: request.headers }, |
| 39 | + (result) => { |
| 40 | + response.writeHead(result.statusCode, result.headers) |
| 41 | + result.pipe(response) |
| 42 | + response.on("close", () => result.destroy()) |
| 43 | + }, |
| 44 | + ) |
| 45 | + proxy.on("error", () => { |
| 46 | + if (!response.headersSent) response.writeHead(502) |
| 47 | + response.end() |
| 48 | + }) |
| 49 | + request.pipe(proxy) |
| 50 | + }) |
| 51 | + cleanups.push( |
| 52 | + () => |
| 53 | + new Promise((resolve) => { |
| 54 | + upstream.closeAllConnections() |
| 55 | + upstream.close(() => resolve()) |
| 56 | + }), |
| 57 | + ) |
| 58 | + await new Promise((resolve) => upstream.listen(0, "127.0.0.1", resolve)) |
| 59 | + const upstreamURL = `http://127.0.0.1:${upstream.address().port}` |
| 60 | + process.env.OPENCODE_URL = process.env.ES_DASHBOARD_URL = upstreamURL |
| 61 | + const root = fileURLToPath(new URL("..", import.meta.url)) |
| 62 | + const scratch = await mkdtemp(path.join(tmpdir(), "opencode-auth-proxy-")) |
| 63 | + cleanups.push(() => rm(scratch, { recursive: true, force: true })) |
| 64 | + const dev = await createServer({ root, server: { host: "127.0.0.1", port: 0 } }) |
| 65 | + cleanups.push(() => dev.close()) |
| 66 | + await dev.listen() |
| 67 | + await build({ root, logLevel: "error", build: { outDir: path.join(scratch, "dist") } }) |
| 68 | + const built = await preview({ |
| 69 | + root, |
| 70 | + build: { outDir: path.join(scratch, "dist") }, |
| 71 | + preview: { host: "127.0.0.1", port: 0 }, |
| 72 | + }) |
| 73 | + cleanups.push( |
| 74 | + () => |
| 75 | + new Promise((resolve) => { |
| 76 | + built.httpServer.closeAllConnections() |
| 77 | + built.httpServer.close(() => resolve()) |
| 78 | + }), |
| 79 | + ) |
| 80 | + const origins = [ |
| 81 | + ["dev", `http://127.0.0.1:${dev.httpServer.address().port}`], |
| 82 | + ["preview", `http://127.0.0.1:${built.httpServer.address().port}`], |
| 83 | + ] |
| 84 | + if (process.argv.includes("--serve")) { |
| 85 | + console.log( |
| 86 | + JSON.stringify({ |
| 87 | + preview: `${origins[1][1]}/session/ses_a?directory=${encodeURIComponent(directory)}`, |
| 88 | + scenario: "Synthetic protected upstream; expected HTTP 401 application error", |
| 89 | + }), |
| 90 | + ) |
| 91 | + await new Promise((resolve) => { |
| 92 | + const stop = () => { |
| 93 | + process.off("SIGINT", stop) |
| 94 | + process.off("SIGTERM", stop) |
| 95 | + resolve() |
| 96 | + } |
| 97 | + process.once("SIGINT", stop) |
| 98 | + process.once("SIGTERM", stop) |
| 99 | + }) |
| 100 | + } else { |
| 101 | + const browser = await (process.env.AUTH_BROWSER === "firefox" |
| 102 | + ? firefox.launch({ headless: true }) |
| 103 | + : chromium.launch({ headless: true, channel: "chrome" })) |
| 104 | + cleanups.push(() => browser.close()) |
| 105 | + const baseline = process.env.AUTH_EXPECT_CHALLENGE === "1" |
| 106 | + const direct = await fetch(`${upstreamURL}/session/ses_a`) |
| 107 | + expect(direct.status).toBe(401) |
| 108 | + expect(/^Basic\b/.test(direct.headers.get("www-authenticate") ?? "")).toBe(true) |
| 109 | + await direct.body?.cancel() |
| 110 | + for (const [mode, origin] of origins) { |
| 111 | + for (const pathname of ["/oc/session/ses_a", "/oc/event", "/es/api/state"]) { |
| 112 | + const response = await fetch(`${origin}${pathname}`) |
| 113 | + console.log( |
| 114 | + JSON.stringify({ |
| 115 | + mode, |
| 116 | + path: pathname, |
| 117 | + status: response.status, |
| 118 | + challengePresent: response.headers.has("www-authenticate"), |
| 119 | + }), |
| 120 | + ) |
| 121 | + expect(response.status).toBe(401) |
| 122 | + expect(response.headers.has("www-authenticate")).toBe(baseline) |
| 123 | + expect(response.headers.get("x-fixture")).toBe("protected") |
| 124 | + expect(await response.text()).toBe(denied) |
| 125 | + const authorized = await fetch(`${origin}${pathname}`, { headers: { Authorization: credential } }) |
| 126 | + expect(authorized.status).toBe(200) |
| 127 | + await authorized.body?.cancel() |
| 128 | + } |
| 129 | + const forbidden = await fetch(`${origin}/oc/forbidden`) |
| 130 | + expect(forbidden.status).toBe(403) |
| 131 | + await forbidden.body?.cancel() |
| 132 | + const context = await browser.newContext() |
| 133 | + try { |
| 134 | + if (process.env.AUTH_BROWSER === "firefox") |
| 135 | + await context.route("**/*", (route) => |
| 136 | + new URL(route.request().url()).origin === origin ? route.continue() : route.abort(), |
| 137 | + ) |
| 138 | + const page = await context.newPage() |
| 139 | + const challenges = [] |
| 140 | + const cdp = process.env.AUTH_BROWSER === "firefox" ? undefined : await context.newCDPSession(page) |
| 141 | + if (cdp) { |
| 142 | + cdp.on( |
| 143 | + "Fetch.requestPaused", |
| 144 | + (event) => |
| 145 | + void (new URL(event.request.url).origin === origin |
| 146 | + ? cdp.send("Fetch.continueRequest", { requestId: event.requestId }) |
| 147 | + : cdp.send("Fetch.failRequest", { requestId: event.requestId, errorReason: "BlockedByClient" })), |
| 148 | + ) |
| 149 | + cdp.on("Fetch.authRequired", (event) => { |
| 150 | + challenges.push({ path: new URL(event.request.url).pathname, scheme: event.authChallenge.scheme }) |
| 151 | + void cdp.send("Fetch.continueWithAuth", { |
| 152 | + requestId: event.requestId, |
| 153 | + authChallengeResponse: { response: "CancelAuth" }, |
| 154 | + }) |
| 155 | + }) |
| 156 | + await cdp.send("Fetch.enable", { handleAuthRequests: true }) |
| 157 | + } |
| 158 | + const responses = ["/oc/session/ses_a", "/oc/event", "/es/api/state"].map((pathname) => |
| 159 | + page.waitForResponse( |
| 160 | + (response) => new URL(response.url()).pathname === pathname && response.status() === 401, |
| 161 | + ), |
| 162 | + ) |
| 163 | + await Promise.all([ |
| 164 | + page.goto(`${origin}/session/ses_a?directory=${encodeURIComponent(directory)}`), |
| 165 | + ...responses, |
| 166 | + ]) |
| 167 | + await expect(page.getByRole("alert").filter({ hasText: "HTTP 401" }).first()).toBeVisible({ timeout: 30000 }) |
| 168 | + if (cdp) |
| 169 | + expect([...new Set(challenges.map((challenge) => challenge.path))].sort()).toEqual( |
| 170 | + baseline ? ["/es/api/state", "/oc/event", "/oc/session/ses_a"] : [], |
| 171 | + ) |
| 172 | + console.log( |
| 173 | + JSON.stringify({ |
| 174 | + mode, |
| 175 | + browser: browser.browserType().name(), |
| 176 | + applicationError: 401, |
| 177 | + authenticationChallenges: cdp ? challenges : null, |
| 178 | + }), |
| 179 | + ) |
| 180 | + } finally { |
| 181 | + await context.close() |
| 182 | + } |
| 183 | + } |
| 184 | + } |
| 185 | +} finally { |
| 186 | + const results = await Promise.allSettled(cleanups.map((close) => Promise.resolve().then(close))) |
| 187 | + if (results.some((result) => result.status === "rejected")) throw new Error("Auth proxy fixture cleanup failed") |
| 188 | +} |
0 commit comments