diff --git a/apps/cli-docs/src/fragments/commands/local.md b/apps/cli-docs/src/fragments/commands/local.md index e575e0440..a19137298 100644 --- a/apps/cli-docs/src/fragments/commands/local.md +++ b/apps/cli-docs/src/fragments/commands/local.md @@ -14,7 +14,9 @@ If nothing is listening on the port, a server is started in the background and s The Local daemon behind `--session` is the exception: it only takes session traffic. When it holds port 8969, a plain `local run` captures on a free port and says so. An SDK that hard-codes 8969 won't reach that port, so make sure it reads `SENTRY_SPOTLIGHT`. Add `--session ` to capture into the daemon instead. With an explicit `--port` that the daemon holds, the command stops with an error. -The same goes for a port held by another process that isn't a Local or Spotlight server, such as `python -m http.server 8969`: a plain `local run` captures on a free port and says so, and with an explicit `--port`, or with `local serve`, the command stops with an error that names the port. +The same goes for a port held by another process that isn't a Local or Spotlight server, such as `python -m http.server 8969` or a listener that doesn't answer HTTP: a plain `local run` captures on a free port and says so, and with an explicit `--port`, or with `local serve`, the command stops with an error that names the port. + +A `local serve` from Sentry CLI 0.35 to 0.40 doesn't identify itself as a Local server, so newer versions treat it as another process. Upgrade it to attach to it. With no command, `local run` picks one from the project, in this order: diff --git a/packages/cli/src/commands/local/run.ts b/packages/cli/src/commands/local/run.ts index 2b392b766..4d66aa439 100644 --- a/packages/cli/src/commands/local/run.ts +++ b/packages/cli/src/commands/local/run.ts @@ -305,7 +305,7 @@ async function startBackgroundServer({ * daemon drops traffic that isn't for a session without a word, so the * notice says to use SENTRY_SPOTLIGHT. * - * @param reason - Why the default port is taken, e.g. "is in use" + * @param reason - Why the default port is taken, e.g. "is held by another process" */ function freePortNotice( defaultPort: number, @@ -318,9 +318,10 @@ function freePortNotice( /** * Get a live event tail on `host:port`, whichever way is available. * - * Prefers attaching to whatever already holds the port so we never compete - * with it, and falls back to attaching if the bind loses a race. `run` wraps - * the user's dev command, so a busy port must never be fatal here. + * Prefers attaching to a receiver that already holds the port so we never + * compete with it, and probes again if the bind loses a race. Anything else on + * the port fails with a port-in-use error, unless `freePortIfHeld` lets this + * run capture on a free port instead. */ async function openEventTail({ port, @@ -333,42 +334,52 @@ async function openEventTail({ }: EventTailOptions): Promise { const url = formatLocalServerUrl(host, port); - let running = false; - // Why this run captures on a free port instead of `port`, if it does. - let heldNotice: ((boundPort: number) => string) | undefined; - try { - running = await isServerRunning(url); - } catch (err) { - if (!(freePortIfHeld && err instanceof ValidationError)) throw err; - if (err.field === PORT_HELD_BY_DAEMON_FIELD) { - // The daemon's receiver only takes session traffic, and it stays up - // while it retains sessions, so a plain run gets its own receiver. - heldNotice = (bound) => - `${freePortNotice(port, bound, "is held by the Local daemon")} Add --session to capture into the daemon instead.`; - } else if (err.field === PORT_IN_USE_FIELD) { - // A server that is not a receiver would drop every event. - heldNotice = (bound) => - freePortNotice(port, bound, "is held by another process"); - } else { + /** + * Whether a receiver to attach to holds `port`, or, when `freePortIfHeld` + * lets this run move off a held port, why it captures on a free one instead. + */ + const probe = async (): Promise<{ + running: boolean; + heldNotice?: (boundPort: number) => string; + }> => { + try { + return { running: await isServerRunning(url) }; + } catch (err) { + if (!(freePortIfHeld && err instanceof ValidationError)) throw err; + if (err.field === PORT_HELD_BY_DAEMON_FIELD) { + // The daemon's receiver only takes session traffic, and it stays up + // while it retains sessions, so a plain run gets its own receiver. + return { + running: false, + heldNotice: (bound) => + `${freePortNotice(port, bound, "is held by the Local daemon")} Add --session to capture into the daemon instead.`, + }; + } + if (err.field === PORT_IN_USE_FIELD) { + // A server that is not a receiver would drop every event. + return { + running: false, + heldNotice: (bound) => + freePortNotice(port, bound, "is held by another process"), + }; + } throw err; } - } + }; - if (running) { + const attach = async (): Promise => { await configureExistingRetention(url, maxEnvelopes); - logger.info(`Connected to existing server at ${bold(url)}`); return attachToExistingServer({ activeFilters, showAttributes, url, useJson, }); - } + }; - if (!heldNotice) { - logger.info("No server detected, starting one in the background..."); - } - try { + const start = async ( + heldNotice: ((boundPort: number) => string) | undefined, + ): Promise => { const bg = await startBackgroundServer({ maxEnvelopes, port: heldNotice ? 0 : port, @@ -382,19 +393,31 @@ async function openEventTail({ } logger.info(`Background server listening on ${bold(bg.url)}`); return bg; + }; + + const first = await probe(); + if (first.running) { + logger.info(`Connected to existing server at ${bold(url)}`); + return await attach(); + } + if (!first.heldNotice) { + logger.info("No server detected, starting one in the background..."); + } + try { + return await start(first.heldNotice); } catch (err) { if (!(err instanceof ValidationError && err.field === PORT_IN_USE_FIELD)) { throw err; } - await configureExistingRetention(url, maxEnvelopes); - // Something grabbed the port between the probe and the bind. - logger.warn(`Port ${port} is in use; attaching to it instead`); - return attachToExistingServer({ - activeFilters, - showAttributes, - url, - useJson, - }); + // Something grabbed the port between the probe and the bind. Attach only + // if it is a receiver; anything else would drop every event. + const second = await probe(); + if (second.running) { + logger.warn(`Port ${port} is in use; attaching to it instead`); + return await attach(); + } + if (!second.heldNotice) throw err; + return await start(second.heldNotice); } } @@ -1020,7 +1043,9 @@ async function listenForVerify( ); } const bound = await tryListen(app, 0, host, { retries: 0 }); - logger.info(freePortNotice(DEFAULT_PORT, bound.port, "is in use")); + logger.info( + freePortNotice(DEFAULT_PORT, bound.port, "is held by another process"), + ); return { ...bound, fellBack: true }; } } @@ -1205,7 +1230,9 @@ async function* runWithVerify( if (fellBack) { // An SDK that ignores SENTRY_SPOTLIGHT still sends to the busy default // port, so it reaches whatever holds that port instead of this receiver. - logger.warn(freePortNotice(DEFAULT_PORT, boundPort, "is in use")); + logger.warn( + freePortNotice(DEFAULT_PORT, boundPort, "is held by another process"), + ); } throw new VerifyFailedError( `Verification timed out after ${verifyTimeout}s — no events received from the SDK`, diff --git a/packages/cli/src/commands/local/server.ts b/packages/cli/src/commands/local/server.ts index 6987c9a38..f38a1d296 100644 --- a/packages/cli/src/commands/local/server.ts +++ b/packages/cli/src/commands/local/server.ts @@ -27,6 +27,7 @@ import { isLoopbackHost } from "./loopback.js"; */ import type { Server } from "node:http"; +import { connect } from "node:net"; import { basename } from "node:path"; import { setTimeout as sleep } from "node:timers/promises"; import { serve } from "@hono/node-server"; @@ -697,27 +698,46 @@ export function tryListen( } /** - * Ask `${url}/health` who holds the port: `none` for a transport failure - * (connection refused, timeout), `daemon` for a Sentry Local daemon, - * `receiver` for a Local or Spotlight receiver, which sends the - * {@link SERVER_IDENTIFIER} header even on an error status, and `foreign` for - * any other HTTP server. + * Ask `${url}/health` who holds the port: + * - `none`: the connection was refused, so nothing listens there, or the + * address cannot be reached at all, which the bind then reports itself. + * - `daemon`: a Sentry Local daemon. + * - `receiver`: a Local or Spotlight receiver, which sends the + * {@link SERVER_IDENTIFIER} header even on an error status. + * - `foreign`: any other HTTP server, including one whose `/health` + * redirects, since the probe does not follow redirects. + * - `unresponsive`: something accepted the connection but gave no HTTP + * answer in time: a silent or slow listener, a non-HTTP or TLS server. + * + * Port 0 asks the OS for a free port, so nothing holds it and it is not + * probed. When fetch fails some other way, such as a port that fetch refuses + * to dial ("bad port"), a plain TCP connect decides whether anything listens. */ export async function probeLocalHealth( url: string, timeoutMs: number, -): Promise<"none" | "daemon" | "receiver" | "foreign"> { +): Promise<"none" | "daemon" | "receiver" | "foreign" | "unresponsive"> { + const { hostname, port } = new URL(url); + if (port === "0") return "none"; let res: Response; try { res = await fetch(`${url}/health`, { + redirect: "manual", signal: AbortSignal.timeout(timeoutMs), }); } catch (err) { - logger.debug( - `No existing server at ${url}`, - err instanceof Error ? err.message : String(err), - ); - return "none"; + const message = err instanceof Error ? err.message : String(err); + const timedOut = err instanceof Error && err.name === "TimeoutError"; + if ( + NO_HOLDER_CODES.has(fetchCauseCode(err)) || + (!timedOut && + !(await acceptsTcpConnection(hostname, Number(port || 80), timeoutMs))) + ) { + logger.debug(`No existing server at ${url}`, message); + return "none"; + } + logger.debug(`Server at ${url} gave no HTTP answer to /health`, message); + return "unresponsive"; } await res.body?.cancel(); if (res.headers.get("X-Sentry-Local-Mode") === "daemon") return "daemon"; @@ -742,9 +762,9 @@ export async function probeLocalHealth( * 2xx: Spotlight's own sidecar can answer `/health` with a 5xx while still * holding the port and ingesting envelopes, and attaching to it is right. * - * Only a transport-level failure (connection refused, timeout) counts as - * "no server". Any other HTTP server, such as `python -m http.server`, throws - * a port-in-use error: attaching to it would lose every event. + * Only a refused connection counts as "no server". Any other holder, such as + * `python -m http.server` or a listener that never answers `/health`, throws a + * port-in-use error: attaching to it would lose every event. */ export async function isServerRunning(url: string): Promise { const holder = await probeLocalHealth(url, 2000); @@ -754,7 +774,7 @@ export async function isServerRunning(url: string): Promise { PORT_HELD_BY_DAEMON_FIELD, ); } - if (holder === "foreign") { + if (holder === "foreign" || holder === "unresponsive") { throw portInUseError(Number(new URL(url).port || 80)); } return holder === "receiver"; @@ -864,12 +884,55 @@ function isAbortError(err: unknown): boolean { ); } +/** + * Connect failures that mean nothing can hold the port: it was refused, the + * host does not resolve, or the address is unreachable or not local. The + * bind gives the accurate error for a bad --host, not "port in use". + */ +const NO_HOLDER_CODES = new Set([ + "ECONNREFUSED", + "ENOTFOUND", + "EAI_AGAIN", + "EHOSTUNREACH", + "ENETUNREACH", + "EADDRNOTAVAIL", +]); + +/** Whether anything accepts a TCP connection at `hostname`:`port`. */ +function acceptsTcpConnection( + hostname: string, + port: number, + timeoutMs: number, +): Promise { + return new Promise((resolve) => { + const socket = connect({ + host: hostname.replace(/^\[(.*)\]$/, "$1"), + port, + timeout: timeoutMs, + }); + const done = (accepted: boolean) => { + socket.destroy(); + resolve(accepted); + }; + socket.once("connect", () => done(true)); + socket.once("error", () => done(false)); + socket.once("timeout", () => done(false)); + }); +} + +/** The `code` of a failed `fetch`'s cause, such as `ECONNREFUSED`. */ +function fetchCauseCode(err: unknown): string | undefined { + const cause = err instanceof Error ? err.cause : undefined; + return cause instanceof Error && + "code" in cause && + typeof cause.code === "string" + ? cause.code + : undefined; +} + /** Whether a failed `fetch` found nothing listening at the address. */ export function isConnectionRefused(err: unknown): boolean { - const cause = err instanceof Error ? err.cause : undefined; - return ( - cause instanceof Error && "code" in cause && cause.code === "ECONNREFUSED" - ); + return fetchCauseCode(err) === "ECONNREFUSED"; } /** Sleep with abort support, suppressing abort errors. */ diff --git a/packages/cli/test/commands/local/run.test.ts b/packages/cli/test/commands/local/run.test.ts index 8cb22c15e..21fbed239 100644 --- a/packages/cli/test/commands/local/run.test.ts +++ b/packages/cli/test/commands/local/run.test.ts @@ -51,7 +51,7 @@ import { wranglerSetupHint, } from "../../../src/lib/wrangler.js"; import { TEST_TMP_DIR } from "../../constants.js"; -import { useTestConfigDir } from "../../helpers.js"; +import { refuseLocalHealthProbes, useTestConfigDir } from "../../helpers.js"; import type { Writer } from "../../../src/types/index.js"; /** @@ -114,6 +114,8 @@ type RunFunc = ( let tmpDir: string; +refuseLocalHealthProbes(); + beforeEach(async () => { tmpDir = await mkdtemp(join(TEST_TMP_DIR, "run-test-")); }); @@ -1151,6 +1153,56 @@ setInterval(() => {}, 1000); expect(output).not.toContain("Could not attach to the event stream"); }); + test("attaches to a Spotlight sidecar whose /health answers with a 5xx", async () => { + // Spotlight's sidecar sets X-Powered-By in middleware, so even an + // unhealthy /health identifies it as a receiver to attach to. + const buffer = createLocalRetentionBuffer(10).buffer; + const sidecar = new Hono(); + sidecar.get("/health", (c) => { + c.header("X-Powered-By", serverModule.SERVER_IDENTIFIER); + return c.text("Internal Server Error", 500); + }); + sidecar.route("/", buildApp(buffer)); + const { server, port } = await tryListen(sidecar, 0, "127.0.0.1"); + const savedFetch = globalThis.fetch; + const realFetch = (globalThis as { __originalFetch?: typeof fetch }) + .__originalFetch; + if (realFetch) { + globalThis.fetch = realFetch; + } + const writes: string[] = []; + const spy = vi + .spyOn(process.stderr, "write") + .mockImplementation((chunk: string | Uint8Array) => { + writes.push(chunk.toString()); + return true; + }); + + try { + await fetch(`http://127.0.0.1:${port}/stream`, { + method: "POST", + headers: { "Content-Type": SENTRY_CONTENT_TYPE }, + body: '{"sdk":{"name":"sentry.javascript.node"}}\n{"type":"log","item_count":1,"content_type":"application/vnd.sentry.items.log+json"}\n{"items":[{"timestamp":1750000000,"level":"info","body":"Hello from the sidecar!","attributes":{}}]}', + }); + const func = (await runCommand.loader()) as unknown as RunFunc; + await func.call( + makeContext(), + { port, host: "127.0.0.1", verify: false, timeout: 0 }, + "sleep", + "1", + ); + } finally { + spy.mockRestore(); + globalThis.fetch = savedFetch; + await shutdownServer(server); + } + + const output = writes.join(""); + expect(output).toContain("Connected to existing server"); + expect(output).toContain("Hello from the sidecar!"); + expect(output).not.toContain("Could not attach to the event stream"); + }); + test("writes normalized NDJSON to stdout when following an existing server", async () => { // A one-command agent workflow uses `local run --format json`, including // when another process already owns the local receiver. @@ -1451,7 +1503,7 @@ describe("sentry local run --verify receiver", () => { ); expect(context.process.exitCode).toBe(EXIT.VERIFY_FAILED); const port = new URL(spawnCapture.env?.["SENTRY_SPOTLIGHT"] ?? "").port; - const notice = `Port ${DEFAULT_PORT} is in use, so this run listens on port ${port} instead. SDKs that hard-code ${DEFAULT_PORT} won't reach it; make sure they read SENTRY_SPOTLIGHT.`; + const notice = `Port ${DEFAULT_PORT} is held by another process, so this run listens on port ${port} instead. SDKs that hard-code ${DEFAULT_PORT} won't reach it; make sure they read SENTRY_SPOTLIGHT.`; // Once when it binds, and again when nothing arrived. expect(info).toHaveBeenCalledWith(notice); expect(warn).toHaveBeenCalledWith(notice); @@ -1631,6 +1683,59 @@ describe("sentry local run messages", () => { } }); + test("plain run probes again when another process takes the port before the bind", async () => { + // Nothing answered the first probe, but by the bind something that is not + // a receiver holds the port; attaching to it would lose every event. + const realIsServerRunning = serverModule.isServerRunning; + let defaultPortProbes = 0; + const probe = vi + .spyOn(serverModule, "isServerRunning") + .mockImplementation((url) => { + if (new URL(url).port !== String(DEFAULT_PORT)) { + return realIsServerRunning(url); + } + defaultPortProbes += 1; + return defaultPortProbes === 1 + ? Promise.resolve(false) + : Promise.reject(serverModule.portInUseError(DEFAULT_PORT)); + }); + const busy = makeDefaultPortBusy(); + const info = vi.spyOn(logger, "info").mockImplementation(() => {}); + const warn = vi.spyOn(logger, "warn").mockImplementation(() => {}); + const context = makeParsedRunContext(); + try { + await run( + app, + [ + "local", + "run", + "--host", + "127.0.0.1", + "--", + process.execPath, + "-e", + "", + ], + context, + ); + expect(context.process.exitCode ?? 0).toBe(0); + expect(defaultPortProbes).toBe(2); + const receiver = new URL(spawnCapture.env?.["SENTRY_SPOTLIGHT"] ?? ""); + expect(Number(receiver.port)).not.toBe(DEFAULT_PORT); + expect(info).toHaveBeenCalledWith( + `Port ${DEFAULT_PORT} is held by another process, so this run listens on port ${receiver.port} instead. SDKs that hard-code ${DEFAULT_PORT} won't reach it; make sure they read SENTRY_SPOTLIGHT.`, + ); + expect(warn).not.toHaveBeenCalledWith( + expect.stringContaining("attaching to it instead"), + ); + } finally { + info.mockRestore(); + warn.mockRestore(); + busy.mockRestore(); + probe.mockRestore(); + } + }, 30_000); + test("plain run still fails when the daemon holds an explicit --port", async () => { const daemonPort = makeDaemonHoldPort(45_678); spawnCapture.env = undefined; diff --git a/packages/cli/test/commands/local/server.test.ts b/packages/cli/test/commands/local/server.test.ts index c64ccaadc..142a3ee3c 100644 --- a/packages/cli/test/commands/local/server.test.ts +++ b/packages/cli/test/commands/local/server.test.ts @@ -10,6 +10,12 @@ import { createLocalRetentionBuffer } from "../../../src/commands/local/retentio import { logger } from "../../../src/lib/logger.js"; import { gzipSync } from "node:zlib"; import { Hono } from "hono"; +import { + createServer as createNetServer, + type Server as NetServer, + type Socket, +} from "node:net"; +import { createServer as createTlsServer } from "node:tls"; import { afterEach, beforeEach, @@ -38,7 +44,7 @@ import { ValidationError, } from "../../../src/lib/errors.js"; import { SENTRY_CONTENT_TYPE } from "../../../src/lib/formatters/local.js"; -import { at } from "../../helpers.js"; +import { at, refuseLocalHealthProbes } from "../../helpers.js"; vi.mock("../../../src/lib/browser.js", () => ({ openBrowser: vi.fn().mockResolvedValue(true), @@ -282,6 +288,8 @@ test("keeps reading after a retained reset notification until Close", async () = } }); +refuseLocalHealthProbes(); + describe("parsePort", () => { test("parses valid port numbers", () => { expect(parsePort("8969")).toBe(8969); @@ -1195,6 +1203,107 @@ describe("isServerRunning", () => { } }); + /** Expect `isServerRunning` to reject `port` as held by another process. */ + async function expectHeldByAnotherProcess(port: number): Promise { + const savedFetch = globalThis.fetch; + const realFetch = (globalThis as { __originalFetch?: typeof fetch }) + .__originalFetch; + if (realFetch) { + globalThis.fetch = realFetch; + } + try { + await expect( + isServerRunning(`http://127.0.0.1:${port}`), + ).rejects.toMatchObject({ + name: "ValidationError", + field: PORT_IN_USE_FIELD, + message: expect.stringContaining( + `Port ${port} is already in use by another process`, + ), + }); + } finally { + globalThis.fetch = savedFetch; + } + } + + /** Listen on a free loopback port with a raw TCP or TLS server. */ + async function listenRaw( + server: NetServer, + ): Promise<{ server: NetServer; port: number }> { + await new Promise((done) => server.listen(0, "127.0.0.1", done)); + const address = server.address(); + if (!address || typeof address === "string") { + throw new Error("Expected a TCP address"); + } + return { server, port: address.port }; + } + + function closeRaw(server: NetServer, sockets: Set): Promise { + for (const socket of sockets) socket.destroy(); + return new Promise((done) => server.close(() => done())); + } + + test("rejects a port whose listener never answers /health", async () => { + // A silent listener, or one slower than the probe: binding the port + // would fail, and attaching would lose every event. + const sockets = new Set(); + const { server, port } = await listenRaw( + createNetServer((socket) => sockets.add(socket)), + ); + try { + await expectHeldByAnotherProcess(port); + } finally { + await closeRaw(server, sockets); + } + }, 10_000); + + test("rejects a port whose listener does not speak HTTP", async () => { + const sockets = new Set(); + const { server, port } = await listenRaw( + createNetServer((socket) => { + sockets.add(socket); + socket.write("SSH-2.0-OpenSSH_9.6\r\n"); + }), + ); + try { + await expectHeldByAnotherProcess(port); + } finally { + await closeRaw(server, sockets); + } + }); + + test("rejects a port whose listener speaks TLS", async () => { + const sockets = new Set(); + const tls = createTlsServer({}); + tls.on("connection", (socket: Socket) => sockets.add(socket)); + tls.on("tlsClientError", () => {}); + const { server, port } = await listenRaw(tls); + try { + await expectHeldByAnotherProcess(port); + } finally { + await closeRaw(server, sockets); + } + }); + + test("rejects a port whose /health redirects to a receiver", async () => { + const receiver = await tryListen( + buildApp(createLocalRetentionBuffer(10).buffer), + 0, + "127.0.0.1", + ); + const redirect = new Hono(); + redirect.get("/health", (c) => + c.redirect(`http://127.0.0.1:${receiver.port}/health`, 302), + ); + const { server, port } = await tryListen(redirect, 0, "127.0.0.1"); + try { + await expectHeldByAnotherProcess(port); + } finally { + await new Promise((done) => server.close(() => done())); + await new Promise((done) => receiver.server.close(() => done())); + } + }); + test("rejects a port that a Sentry Local daemon holds", async () => { vi.stubGlobal( "fetch", @@ -1216,13 +1325,131 @@ describe("isServerRunning", () => { }); test("returns false when no server is running", async () => { - // isServerRunning uses global fetch which is mocked in tests. - // Verify the function handles connection errors gracefully. - const result = await isServerRunning("http://127.0.0.1:19999"); - expect(result).toBe(false); + vi.stubGlobal("fetch", rejectLikeNodeFetch("ECONNREFUSED")); + try { + await expect(isServerRunning("http://127.0.0.1:19999")).resolves.toBe( + false, + ); + } finally { + vi.unstubAllGlobals(); + } + }); + + test("returns false when both localhost addresses refuse", async () => { + // Dual-stack `localhost`: Node wraps both refusals in an AggregateError + // and copies ECONNREFUSED onto it. + const refused = Object.assign( + new AggregateError( + [ + Object.assign(new Error("connect ECONNREFUSED ::1:8969"), { + code: "ECONNREFUSED", + }), + Object.assign(new Error("connect ECONNREFUSED 127.0.0.1:8969"), { + code: "ECONNREFUSED", + }), + ], + "", + ), + { code: "ECONNREFUSED" }, + ); + vi.stubGlobal( + "fetch", + vi.fn(async () => { + throw new TypeError("fetch failed", { cause: refused }); + }), + ); + try { + await expect(isServerRunning("http://localhost:8969")).resolves.toBe( + false, + ); + } finally { + vi.unstubAllGlobals(); + } + }); + + test.each([ + "ENOTFOUND", + "EAI_AGAIN", + "EHOSTUNREACH", + "ENETUNREACH", + "EADDRNOTAVAIL", + ])( + "returns false for an address it cannot reach (%s), so the bind reports it", + async (code) => { + // A bad --host is not a busy port; the bind's own error says what's wrong. + vi.stubGlobal("fetch", rejectLikeNodeFetch(code)); + try { + await expect(isServerRunning("http://typo.invalid:8969")).resolves.toBe( + false, + ); + } finally { + vi.unstubAllGlobals(); + } + }, + ); + + test("returns false for an OS-assigned port without probing it", async () => { + // --port 0 asks the OS for a free port, so there is nothing to attach to. + // On macOS, fetching port 0 fails with EADDRNOTAVAIL, not a refusal. + const fetchSpy = vi.fn(async () => new Response("OK")); + vi.stubGlobal("fetch", fetchSpy); + try { + await expect(isServerRunning("http://127.0.0.1:0")).resolves.toBe(false); + expect(fetchSpy).not.toHaveBeenCalled(); + } finally { + vi.unstubAllGlobals(); + } + }); + + test("returns false for a free port that fetch refuses to dial", async () => { + // Node's fetch blocks some ports (6000, 10080, ...) with "bad port" before + // it connects, so the failure says nothing about the port. + const probe = createNetServer(); + await new Promise((done) => probe.listen(0, "127.0.0.1", done)); + const port = (probe.address() as { port: number }).port; + await new Promise((done) => probe.close(() => done())); + vi.stubGlobal("fetch", rejectLikeBlockedPort()); + try { + await expect(isServerRunning(`http://127.0.0.1:${port}`)).resolves.toBe( + false, + ); + } finally { + vi.unstubAllGlobals(); + } + }); + + test("rejects a held port that fetch refuses to dial", async () => { + const holder = createNetServer((socket) => socket.resume()); + await new Promise((done) => holder.listen(0, "127.0.0.1", done)); + const port = (holder.address() as { port: number }).port; + vi.stubGlobal("fetch", rejectLikeBlockedPort()); + try { + await expect( + isServerRunning(`http://127.0.0.1:${port}`), + ).rejects.toMatchObject({ field: PORT_IN_USE_FIELD }); + } finally { + vi.unstubAllGlobals(); + await new Promise((done) => holder.close(() => done())); + } }); }); +/** A fetch that fails the way Node's does for a port it blocks, like 6000. */ +function rejectLikeBlockedPort() { + return vi.fn(async () => { + throw new TypeError("fetch failed", { cause: new Error("bad port") }); + }); +} + +/** A fetch that fails the way Node's does when the connection fails with `code`. */ +function rejectLikeNodeFetch(code: string) { + return vi.fn(async () => { + throw new TypeError("fetch failed", { + cause: Object.assign(new Error(`connect ${code}`), { code }), + }); + }); +} + describe("oversized envelopes", () => { /** One byte over the encoded ingest limit; SDKs ignore the 413 and drop it. */ const OVERSIZED_BODY = "x".repeat(MAX_BODY_BYTES + 1); diff --git a/packages/cli/test/e2e/local.test.ts b/packages/cli/test/e2e/local.test.ts index 5e88ec9c6..0dec5f5b4 100644 --- a/packages/cli/test/e2e/local.test.ts +++ b/packages/cli/test/e2e/local.test.ts @@ -66,6 +66,25 @@ async function availablePort(): Promise { return address.port; } +/** + * Ports Node's fetch refuses to dial ("bad port"), though a server can bind + * them. Returns one that is free here, or undefined if all are taken. + */ +async function freeFetchBlockedPort(): Promise { + for (const port of [6000, 6665, 6666, 6667, 6668, 6669, 6697, 10080]) { + const server = createServer(); + const bound = await new Promise((resolve) => { + server.once("error", () => resolve(false)); + server.listen(port, "127.0.0.1", () => resolve(true)); + }); + if (bound) { + await new Promise((resolve) => server.close(() => resolve())); + return port; + } + } + return undefined; +} + async function createSession( label: string, port: number, @@ -1169,6 +1188,64 @@ setTimeout(() => {}, 20000);`, }); describe("Local foreground commands", () => { + /** `local run` on 127.0.0.1:`port` with a child that prints a marker. */ + async function runMarkerApp(port: number) { + return await runCli( + [ + "local", + "run", + "--host", + "127.0.0.1", + "--port", + String(port), + "--", + process.execPath, + "-e", + 'console.log("child-ran")', + ], + { + env: { + SENTRY_CONFIG_DIR: getConfigDir(), + SENTRY_CLI_NO_TELEMETRY: "1", + SENTRY_AUTH_TOKEN: "", + SENTRY_TOKEN: "", + }, + }, + ); + } + + test("run --port 0 binds an OS-assigned port and runs the app", async () => { + const result = await runMarkerApp(0); + expect(result.exitCode, result.stderr).toBe(0); + expect(result.stdout).toContain("child-ran"); + }, 30000); + + test("run binds a free port that fetch refuses to dial", async () => { + const port = await freeFetchBlockedPort(); + if (port === undefined) return; + const result = await runMarkerApp(port); + expect(result.exitCode, result.stderr).toBe(0); + expect(result.stdout).toContain("child-ran"); + }, 30000); + + test("run rejects a held port that fetch refuses to dial", async () => { + const port = await freeFetchBlockedPort(); + if (port === undefined) return; + const holder = createSilentServer(); + await new Promise((resolve, reject) => { + holder.once("error", reject); + holder.listen(port, "127.0.0.1", resolve); + }); + try { + const result = await runMarkerApp(port); + expect(result.exitCode).not.toBe(0); + expect(result.stdout).not.toContain("child-ran"); + expect(result.stderr).toContain(`Port ${port} is already in use`); + } finally { + await new Promise((resolve) => holder.close(() => resolve())); + } + }, 30000); + test.each(["bin", "node_modules/.bin"])( "runs a batch-file command from %s on PATH with its arguments intact", async (binPath) => { diff --git a/packages/cli/test/helpers.ts b/packages/cli/test/helpers.ts index 1b2417aa5..29eabdedd 100644 --- a/packages/cli/test/helpers.ts +++ b/packages/cli/test/helpers.ts @@ -229,6 +229,35 @@ export function mintSntrysToken(payload: Record): string { return `sntrys_${b64}_test-secret-tail`; } +const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "localhost", "[::1]"]); + +/** + * Make loopback `/health` probes fail the way Node's fetch does when nothing + * listens there, so Sentry Local's port probe sees a free port. Every other + * fetch still reaches the preload mock, which rejects unmocked calls loudly. + */ +export function refuseLocalHealthProbes(): void { + let saved: typeof fetch; + beforeEach(() => { + saved = globalThis.fetch; + const fallback = saved; + globalThis.fetch = async (input: FetchInput, init?: RequestInit) => { + const url = new URL(extractFetchUrl(input)); + if (url.pathname === "/health" && LOOPBACK_HOSTNAMES.has(url.hostname)) { + throw new TypeError("fetch failed", { + cause: Object.assign(new Error(`connect ECONNREFUSED ${url.host}`), { + code: "ECONNREFUSED", + }), + }); + } + return await fallback(input, init); + }; + }); + afterEach(() => { + globalThis.fetch = saved; + }); +} + /** * Extract the URL string from a fetch input (`string | URL | Request`). * Used by tests that intercept `globalThis.fetch` and assert on the