Full Toolkit for Next-Level Domain Analysis
Log DNSSEC and WHOIS summary failures with their cause 🪵🔐 (#136)
Felix Wotschofsky1a4f4a93ad5b
diff --git a/app/api/domain-summary/route.ts b/app/api/domain-summary/route.tsindex d38cb0e..87f9334 100644--- a/app/api/domain-summary/route.ts+++ b/app/api/domain-summary/route.ts@@ -35,6 +35,9 @@ export const GET = withEvlog(async (request: Request) => {}),]);+ // Tells a failed WHOIS apart from a registry without a DNSSEC field: both read "Unavailable".+ log.set({ whois });+return NextResponse.json({ whois, sale } satisfies DomainSummaryResponse, {headers: {// Retry a failed lookup soon instead of hiding a listing.diff --git a/app/lookup/[domain]/dnssec/page.tsx b/app/lookup/[domain]/dnssec/page.tsxindex 7ae6e64..f5e1528 100644--- a/app/lookup/[domain]/dnssec/page.tsx+++ b/app/lookup/[domain]/dnssec/page.tsx@@ -1,3 +1,4 @@+import { log } from 'evlog';import type { Metadata } from 'next';import { notFound } from 'next/navigation';import type { FC } from 'react';@@ -7,10 +8,12 @@ import {DsChainNameNotFoundError,type DsChainVerdict,type DsChainZone,- resolveDsChain,+ resolveDsChainWithin,} from '@/lib/dnssec/ds-chain';import { AuthoritativeResolver } from '@/lib/resolvers/authoritative';import { recordLookupAfter } from '@/lib/search';+import { UserFacingError } from '@/lib/user-facing-error';+import { serializeError } from '@/lib/utils';type DnssecResultsPageProps = {params: Promise<{ domain: string }>;@@ -67,19 +70,33 @@ const isBroken = (status: DsChainVerdict): boolean =>const shortFingerprint = (hex: string): string =>hex.length > 24 ? `${hex.slice(0, 16)}…${hex.slice(-8)}` : hex;+// Under the 15s function limit: a platform timeout logs nothing about which queries hung.+const DEADLINE_MS = 12_000;+const DnssecResultsPage: FC<DnssecResultsPageProps> = async ({ params }) => {const { domain } = await params;const resolver = new AuthoritativeResolver({ dnssecOk: true });let chain;+try {- chain = await resolveDsChain(domain, (name, type) =>- resolver.resolveAnswers(name, type),+ chain = await resolveDsChainWithin(+ domain,+ (name, type) => resolver.resolveAnswers(name, type),+ DEADLINE_MS,);} catch (error) {if (error instanceof DsChainNameNotFoundError) {await recordLookupAfter(domain, 'dnssec', false);notFound();}++ // onRequestError logs the rethrown error too, but without its cause.+ log[error instanceof UserFacingError ? 'warn' : 'error']({+ message: 'dnssec_lookup_failed',+ domain,+ error: serializeError(error),+ });+throw error;}diff --git a/lib/dnssec/ds-chain.test.ts b/lib/dnssec/ds-chain.test.tsindex ed70f55..15029aa 100644--- a/lib/dnssec/ds-chain.test.ts+++ b/lib/dnssec/ds-chain.test.ts@@ -8,6 +8,7 @@ import {DsChainNameNotFoundError,type DsChainQuery,resolveDsChain,+ resolveDsChainWithin,} from './ds-chain';import { genKey, signDnskeyRrset } from './test-helpers';import { ROOT_DNSKEY_RRSIG, ROOT_DNSKEYS, ROOT_NOW } from './test-vectors';@@ -438,4 +439,25 @@ describe('resolveDsChain', () => {expect(chain.verdict).toBe('bad-signature');expect(chain.zones[1].keySignature?.outcome).toBe('invalid');});++ it('names the queries still in flight when the deadline passes', async () => {+ vi.useFakeTimers();++ try {+ const settled = resolveDsChainWithin(+ 'com',+ () => new Promise(() => {}),+ 1000,+ ).catch((error: unknown) => error);+ await vi.advanceTimersByTimeAsync(1000);+ const error = await settled;++ expect(error).toBeInstanceOf(UserFacingError);+ expect((error as Error).cause).toMatchObject({+ message: 'Still waiting after 1000ms for: . DNSKEY',+ });+ } finally {+ vi.useRealTimers();+ }+ });});diff --git a/lib/dnssec/ds-chain.ts b/lib/dnssec/ds-chain.tsindex e9c4d2b..17b592d 100644--- a/lib/dnssec/ds-chain.ts+++ b/lib/dnssec/ds-chain.ts@@ -227,3 +227,52 @@ export const resolveDsChain = async (...(breakAt ? { breakAt } : {}),};};++// Rejects with a retryable error at deadlineMs, naming the queries still in flight.+// ponytail: the abandoned walk runs on until the resolver's own budgets expire; thread an+// AbortSignal through DsChainQuery if that background load shows up.+export const resolveDsChainWithin = async (+ domain: string,+ query: DsChainQuery,+ deadlineMs: number,+): Promise<DsChain> => {+ const pending = new Set<string>();+ let timer: NodeJS.Timeout | undefined;++ const trackedQuery: DsChainQuery = async (name, type) => {+ const key = `${name} ${type}`;+ pending.add(key);++ try {+ return await query(name, type);+ } finally {+ pending.delete(key);+ }+ };++ const deadline = new Promise<never>((_, reject) => {+ timer = setTimeout(() => {+ const cause = new Error(+ `Still waiting after ${deadlineMs}ms for: ${[...pending].join(', ')}`,+ );++ reject(+ new UserFacingError(+ {+ title: 'DNSSEC lookup timed out',+ description:+ 'The nameservers along the DNSSEC chain took too long to answer. Please try again shortly.',+ retryable: true,+ },+ { cause },+ ),+ );+ }, deadlineMs);+ });++ try {+ return await Promise.race([resolveDsChain(domain, trackedQuery), deadline]);+ } finally {+ clearTimeout(timer);+ }+};diff --git a/lib/resolvers/authoritative.ts b/lib/resolvers/authoritative.tsindex 92671af..94ec796 100644--- a/lib/resolvers/authoritative.ts+++ b/lib/resolvers/authoritative.ts@@ -12,7 +12,7 @@ import dnsPacket, {} from 'dns-packet';import { log } from 'evlog';-import { retry } from '@/lib/utils';+import { retry, serializeError } from '@/lib/utils';import {UserFacingError,@@ -1231,21 +1231,14 @@ export class AuthoritativeResolver extends DnsResolver {}const { reason } = result;const expected = reason instanceof UserFacingError;- const err = reason instanceof Error ? reason : new Error(String(reason));- // Not rethrown, so onRequestError never sees it. evlog JSON-stringifies- // events in production, which drops an Error's own fields: copy them.- // Expected failures (e.g. a refused PTR) only warn, so error alerts- // stay reserved for bugs.+ // Not rethrown, so onRequestError never sees it. Expected failures+ // (e.g. a refused PTR) only warn, so error alerts stay reserved for+ // bugs.log[expected ? 'warn' : 'error']({message: 'record_type_lookup_failed',domain,recordType: types[index],- error: {- name: err.name,- message: err.message,- stack: err.stack,- cause: (err.cause as Error | undefined)?.message,- },+ error: serializeError(reason),});const error = expected ? reason.payload : FALLBACK_LOOKUP_ERROR;response[types[index]] = { records: [], trace: [], error };diff --git a/lib/utils.ts b/lib/utils.tsindex a96dd86..7ac09e0 100644--- a/lib/utils.ts+++ b/lib/utils.ts@@ -15,6 +15,18 @@ export const cn = (...inputs: ClassValue[]) => twMerge(clsx(inputs));export const deduplicate = <T>(array: T[]): T[] => Array.from(new Set(array));+// evlog JSON-stringifies events in production, which drops an Error's own fields, cause included.+export const serializeError = (error: unknown) => {+ const err = error instanceof Error ? error : new Error(String(error));++ return {+ name: err.name,+ message: err.message,+ stack: err.stack,+ cause: (err.cause as Error | undefined)?.message,+ };+};+// From https://stackoverflow.com/a/30471209/12475254// onError sees every failed attempt, the last one included. It runs inside the// existing catch, so observing attempts doesn't delay when the result settles.diff --git a/lib/whois.ts b/lib/whois.tsindex 08ab3a9..854d716 100644--- a/lib/whois.ts+++ b/lib/whois.ts@@ -1,7 +1,8 @@+import { log } from 'evlog';import { firstResult as getFirstResult, whoisDomain } from 'whoiser';import { UserFacingError } from './user-facing-error';-import { getBaseDomain, isValidDomain } from './utils';+import { getBaseDomain, isValidDomain, serializeError } from './utils';export const formatDate = (date: Date) => date.toISOString().split('T')[0];@@ -101,9 +102,10 @@ export const getWhoisSummary = async (const firstResult = getFirstResult(results);+ if (!firstResult) throw new Error(`No WHOIS result for ${domain}`);// whoiser resolves socket errors and timeouts as { error } per server.- if (!firstResult || 'error' in firstResult) {- throw new Error('No valid result found for domain ' + domain);+ if ('error' in firstResult) {+ throw new Error(`WHOIS query for ${domain} failed: ${firstResult.error}`);}const rawValue = firstResult['__raw'];@@ -133,7 +135,14 @@ export const getWhoisSummary = async (createdAt: createdAt && formatDate(createdAt),dnssec: firstResult['DNSSEC']?.toString() || null,};- } catch {+ } catch (error) {+ // Swallowed into "Unavailable" tiles, so nothing else logs it.+ log.warn({+ message: 'whois_summary_failed',+ domain: baseDomain,+ error: serializeError(error),+ });+return {registered: true,unknown: true,