diff --git a/server/src/app.ts b/server/src/app.ts index 9c7dbb1..668a32a 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -20,6 +20,7 @@ import { UpstreamError, absoluteUpstream, expandTemplate, + failureReason, fetchUpstreamSession, hasStalwartRegistry, forgetUpstreamSession, @@ -242,7 +243,7 @@ const requireSession: MiddlewareHandler = async (c, next) => { } catch (err) { // Couldn't ask the server. The token may still have a few minutes; if // not, the call itself will say so. - console.warn("[ihasmail] token refresh failed:", (err as Error).message); + console.warn("[ihasmail] token refresh failed:", failureReason(err)); } if (!session) { deleteCookie(c, config.cookieName, { path: cookiePath }); @@ -563,7 +564,7 @@ export function createApp(basePath = config.basePath): Hono { setCookie(c, OAUTH_STATE_COOKIE, state, { httpOnly: true, sameSite: "Lax", secure: isSecureRequest(c), path: `${basePath}/api/auth`, maxAge: 600 }); return c.redirect(location, 302); } catch (err) { - console.warn("[ihasmail] could not start sign-in:", (err as Error).message); + console.warn("[ihasmail] could not start sign-in:", failureReason(err)); return c.redirect(`${basePath}/?signin_error=unavailable`, 302); } }); @@ -584,7 +585,7 @@ export function createApp(basePath = config.basePath): Hono { result = await finishSignIn({ state, boundState, code }); } catch (err) { if (err instanceof SignInError) return fail(err.code); - console.warn("[ihasmail] sign-in exchange failed:", (err as Error).message); + console.warn("[ihasmail] sign-in exchange failed:", failureReason(err)); return fail("unavailable"); } const authorization = `Bearer ${result.tokens.access}`; @@ -614,7 +615,7 @@ export function createApp(basePath = config.basePath): Hono { if (mailAccount) pushPrepare(session.username, mailAccount, pushCredential(session)); return c.redirect(`${basePath}/`, 302); } catch (err) { - console.warn("[ihasmail] sign-in failed after the exchange:", (err as Error).message); + console.warn("[ihasmail] sign-in failed after the exchange:", failureReason(err)); return fail("unavailable"); } }); diff --git a/server/src/failurereason.test.ts b/server/src/failurereason.test.ts new file mode 100644 index 0000000..c7b2fbd --- /dev/null +++ b/server/src/failurereason.test.ts @@ -0,0 +1,42 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createServer } from "node:net"; +import { failureReason } from "./upstream.js"; + +/** + * A sign-in that can't reach the mail server used to log only "fetch failed", + * with nothing in the proxy's or the server's logs to explain it. The reason + * Node had (refused, unknown host, untrusted certificate) was on `cause`. + */ + +test("a refused connection says so", async () => { + // A port that was just free, so nothing is listening on it. + const port = await new Promise((resolve) => { + const s = createServer().listen(0, "127.0.0.1", () => { + const { port } = s.address() as { port: number }; + s.close(() => resolve(port)); + }); + }); + const err = await fetch(`http://127.0.0.1:${port}/`).then(() => null, (e: unknown) => e); + assert.ok(err); + assert.match(failureReason(err), /^fetch failed \(.*ECONNREFUSED/); +}); + +test("the code is added when the cause's message lacks it", () => { + const cause = Object.assign(new Error("unable to verify the first certificate"), { code: "UNABLE_TO_VERIFY_LEAF_SIGNATURE" }); + assert.equal( + failureReason(new TypeError("fetch failed", { cause })), + "fetch failed (UNABLE_TO_VERIFY_LEAF_SIGNATURE: unable to verify the first certificate)", + ); +}); + +test("several failed addresses report the first", () => { + const first = Object.assign(new Error("connect ECONNREFUSED ::1:443"), { code: "ECONNREFUSED" }); + const cause = new AggregateError([first, new Error("connect ECONNREFUSED 127.0.0.1:443")]); + assert.equal(failureReason(new TypeError("fetch failed", { cause })), "fetch failed (connect ECONNREFUSED ::1:443)"); +}); + +test("an error without a cause is unchanged", () => { + assert.equal(failureReason(new Error("OAuth metadata request failed (502)")), "OAuth metadata request failed (502)"); + assert.equal(failureReason("odd"), "odd"); +}); diff --git a/server/src/upstream.ts b/server/src/upstream.ts index e798535..668ad76 100644 --- a/server/src/upstream.ts +++ b/server/src/upstream.ts @@ -31,6 +31,27 @@ export class UpstreamError extends Error { } } +/** + * An error for the log, with the reason Node keeps underneath it. + * + * When fetch can't reach the server at all -- DNS, a refused connection, a + * certificate Node doesn't trust -- its message is only "fetch failed" and + * the reason is on `cause`. Without it, an operator whose proxy never saw the + * request has nothing to go on. + */ +export function failureReason(err: unknown): string { + if (!(err instanceof Error)) return String(err); + let cause = err.cause; + // Several addresses tried, all failed: the first says enough. + if (cause instanceof AggregateError && !cause.message && cause.errors[0] instanceof Error) { + cause = cause.errors[0]; + } + if (!(cause instanceof Error)) return err.message; + const code = (cause as Error & { code?: unknown }).code; + const detail = typeof code === "string" && !cause.message.includes(code) ? `${code}: ${cause.message}` : cause.message; + return detail ? `${err.message} (${detail})` : err.message; +} + const sessionCache = new Map(); const SESSION_CACHE_MS = 5 * 60_000;