Skip to content
Closed
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 55 additions & 51 deletions src/js/node/dns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,40 @@ function validateOrderOption(options) {
}
}

// Node's resolveMap: an rrtype is valid exactly when a resolve* method exists for it, case-sensitively.
const resolveMethodNames = {
__proto__: null,
A: "resolve4",
AAAA: "resolve6",
ANY: "resolveAny",
CAA: "resolveCaa",
CNAME: "resolveCname",
MX: "resolveMx",
NAPTR: "resolveNaptr",
NS: "resolveNs",
PTR: "resolvePtr",
SOA: "resolveSoa",
SRV: "resolveSrv",
TXT: "resolveTxt",
};
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

// Bound at module load: reassigning resolve4 later does not change resolve(), as in Node.
function createResolveMap(methods) {
const map = { __proto__: null };
for (const rrtype in resolveMethodNames) {
map[rrtype] = methods[resolveMethodNames[rrtype]];
}
return map;
}

function getResolveMethod(map, rrtype) {
const method = map[rrtype];
if (method === undefined) {
throw $ERR_INVALID_ARG_VALUE("rrtype", rrtype, "is invalid");
}
return method;
}

// Validates and returns the callback wrapped by guardCallback.
// Callers must use the return value, not the argument.
function validateResolve(hostname, callback) {
Expand Down Expand Up @@ -410,26 +444,7 @@ var InternalResolver = class Resolver {
throw $ERR_INVALID_ARG_TYPE("rrtype", "string", rrtype);
}

callback = validateResolve(hostname, callback);

Resolver.#getResolver(this)
.resolve(hostname, rrtype)
.then(
results => {
switch (rrtype?.toLowerCase()) {
case "a":

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@robobun how we are compensating for this 3 output differences?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Each case lands on the same output the removed block produced:

  • A and AAAA: resolve4(hostname, callback) and resolve6(hostname, callback) call the native resolve(hostname, "A" | "AAAA") and, with no options, return addresses.map(mapResolveX). That is the old results.map(mapResolveX) branch.
  • The other ten types: the native resolve(hostname, rrtype) arm and the native resolveX method both end in do_resolve_cares::<T> with the same T (src/runtime/dns_jsc/dns.rs:5003-5030 and the resolve_record_fn! list at 5305-5360, for example struct_ares_mx_reply for MX, NsHostent for NS). Same c-ares query, same record objects. That is the old pass-through branch.
  • Errors: every resolveX rejects through withTranslatedError, the same handler the old block used, and the callback goes through validateResolve (guardCallback) in each method as before.

The QTYPE dispatch tests in node-dns-rrtype.test.js pin the query each rrtype sends. The one intentional difference: resolve(hostname, "NS" | "SOA") now accepts an empty hostname, because resolveNs("") and resolveSoa("") allow it (allow_empty = true) and Node does too. That is listed in the PR notes.

case "aaaa":
callback(null, results.map(mapResolveX));
break;
default:
callback(null, results);
break;
}
},
error => {
callback(withTranslatedError(error));
},
);
getResolveMethod(resolveMap, rrtype).$call(this, hostname, callback);
}

resolve4(hostname, options, callback) {
Expand Down Expand Up @@ -602,10 +617,7 @@ var InternalResolver = class Resolver {
if (arguments.length > 2) {
callback = arguments[2];
}
if (typeof callback !== "function") {
throw $ERR_INVALID_ARG_TYPE("callback", "function", callback);
}
callback = guardCallback(callback);
callback = validateResolve(hostname, callback);

Resolver.#getResolver(this)
.resolveCaa(hostname)
Expand All @@ -623,10 +635,7 @@ var InternalResolver = class Resolver {
if (arguments.length > 2) {
callback = arguments[2];
}
if (typeof callback !== "function") {
throw $ERR_INVALID_ARG_TYPE("callback", "function", callback);
}
callback = guardCallback(callback);
callback = validateResolve(hostname, callback);

Resolver.#getResolver(this)
.resolveTxt(hostname)
Expand All @@ -643,10 +652,7 @@ var InternalResolver = class Resolver {
if (arguments.length > 2) {
callback = arguments[2];
}
if (typeof callback !== "function") {
throw $ERR_INVALID_ARG_TYPE("callback", "function", callback);
}
callback = guardCallback(callback);
callback = validateResolve(hostname, callback);

Resolver.#getResolver(this)
.resolveSoa(hostname)
Expand Down Expand Up @@ -691,6 +697,8 @@ var InternalResolver = class Resolver {
}
};

const resolveMap = createResolveMap(InternalResolver.prototype);

function Resolver(options) {
return new InternalResolver(options);
}
Expand Down Expand Up @@ -829,23 +837,18 @@ const promises = {
},

resolve(hostname, rrtype) {
if (typeof hostname !== "string") {
throw $ERR_INVALID_ARG_TYPE("hostname", "string", hostname);
}

if (typeof rrtype === "undefined") {
rrtype = "A";
} else if (typeof rrtype !== "string") {
throw $ERR_INVALID_ARG_TYPE("rrtype", "string", rrtype);
}
const method = getResolveMethod(promisesResolveMap, rrtype);

switch (rrtype?.toLowerCase()) {
case "a":
case "aaaa":
return translateErrorCode(dns.resolve(hostname, rrtype).then(promisifyResolveX(false)));
default:
return translateErrorCode(dns.resolve(hostname, rrtype));
if (typeof hostname !== "string") {
throw $ERR_INVALID_ARG_TYPE("hostname", "string", hostname);
}

return method.$call(this, hostname);
},

resolve4(hostname, options) {
Expand Down Expand Up @@ -913,17 +916,15 @@ const promises = {
if (typeof rrtype === "undefined") {
rrtype = "A";
} else if (typeof rrtype !== "string") {
rrtype = null;
throw $ERR_INVALID_ARG_TYPE("rrtype", "string", rrtype);
}
switch (rrtype?.toLowerCase()) {
case "a":
case "aaaa":
return translateErrorCode(
Resolver.#getResolver(this).resolve(hostname, rrtype).then(promisifyResolveX(false)),
);
default:
return translateErrorCode(Resolver.#getResolver(this).resolve(hostname, rrtype));
const method = getResolveMethod(promisesResolverResolveMap, rrtype);

if (typeof hostname !== "string") {
throw $ERR_INVALID_ARG_TYPE("hostname", "string", hostname);
}

return method.$call(this, hostname);
}

resolve4(hostname, options) {
Expand Down Expand Up @@ -998,6 +999,9 @@ const promises = {
setServers,
};

const promisesResolveMap = createResolveMap(promises);
const promisesResolverResolveMap = createResolveMap(promises.Resolver.prototype);

// Compatibility with util.promisify(dns[method])
for (const [method, pMethod] of [
[lookup, promises.lookup],
Expand Down
127 changes: 127 additions & 0 deletions test/js/node/dns/node-dns-rrtype.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
import { describe, expect, it } from "bun:test";
import * as dgram from "node:dgram";
import * as dns from "node:dns";
import * as dns_promises from "node:dns/promises";
import { once } from "node:events";

// https://github.com/oven-sh/bun/issues/39553
// Node validates rrtype case-sensitively: 'a' is invalid, only 'A' works.
// These tests are in their own file because they do not depend on a working
// resolver: an invalid rrtype throws before any query is issued, the dispatch
// tests at the end talk to a socket on 127.0.0.1, and the module-level
// positive checks discard their query's result.
describe.each([
["dns.resolve", rrtype => dns.resolve("localhost", rrtype, () => {})],
["dns.Resolver#resolve", rrtype => new dns.Resolver().resolve("localhost", rrtype, () => {})],
["dns.promises.resolve", rrtype => dns_promises.resolve("localhost", rrtype)],
["dns.promises.Resolver#resolve", rrtype => new dns_promises.Resolver().resolve("localhost", rrtype)],
])("%s", (_, fn) => {
// "constructor" and "toString" only miss the lookup table because it has a
// null prototype. They guard that clause.
Comment thread
robobun marked this conversation as resolved.
Resolved
it.each(["a", "aaaa", "txt", "Mx", "", "BOGUS", "constructor", "toString"])(
"with rrtype %p throws ERR_INVALID_ARG_VALUE",
rrtype => {
expect(() => fn(rrtype)).toThrow(
expect.objectContaining({
code: "ERR_INVALID_ARG_VALUE",
message: `The argument 'rrtype' is invalid. Received '${rrtype}'`,
}),
);
},
);
});

// Only the module-level entry points, which share the default resolver and so
// cannot be pointed at a local socket. The Resolver surfaces are covered for
// every rrtype by the QTYPE dispatch tests below, with a cancel.
describe.each([
["dns.resolve", rrtype => dns.resolve("localhost", rrtype, () => {})],
["dns.promises.resolve", rrtype => dns_promises.resolve("localhost", rrtype).catch(() => {})],
])("%s", (_, fn) => {
it.each(["A", "AAAA", "ANY", "CAA", "CNAME", "MX", "NAPTR", "NS", "PTR", "SOA", "SRV", "TXT"])(
"with rrtype %p does not throw synchronously",
rrtype => {
// The query itself may fail depending on the environment's resolver.
// Only the synchronous validation is under test here.
fn(rrtype);
},
);
Comment thread
robobun marked this conversation as resolved.
Resolved
});

it("dns.promises.Resolver#resolve with non-string rrtype throws ERR_INVALID_ARG_TYPE", () => {
expect(() => new dns_promises.Resolver().resolve("localhost", 1)).toThrow(
expect.objectContaining({
code: "ERR_INVALID_ARG_TYPE",
message: expect.stringContaining('The "rrtype" argument must be of type string'),
}),
);
});

it.each([
["dns.resolve", () => dns.resolve(1, "a", () => {})],
["dns.Resolver#resolve", () => new dns.Resolver().resolve(1, "a", () => {})],
["dns.promises.resolve", () => dns_promises.resolve(1, "a")],
["dns.promises.Resolver#resolve", () => new dns_promises.Resolver().resolve(1, "a")],
])("%s checks rrtype before hostname, like Node", (_, fn) => {
expect(fn).toThrow(expect.objectContaining({ code: "ERR_INVALID_ARG_VALUE" }));
});

// QTYPE of each record type, from the IANA DNS parameters registry.
const qtypes = {
A: 1,
AAAA: 28,
ANY: 255,
CAA: 257,
CNAME: 5,
MX: 15,
NAPTR: 35,
NS: 2,
PTR: 12,
SOA: 6,
SRV: 33,
TXT: 16,
};

// The fake server never answers. The QTYPE of the query that reaches it shows
// which query resolve(hostname, rrtype) issues. The trailing dot in the name
// keeps c-ares from also trying the host's search domains.
async function querySentBy(startQuery) {
const socket = dgram.createSocket("udp4");
try {
socket.bind(0, "127.0.0.1");
await once(socket, "listening");
const received = once(socket, "message");
const { resolver, settled } = startQuery("127.0.0.1:" + socket.address().port, "rrtype.example.test.");
const [query] = await received;
resolver.cancel();
const { code, syscall } = await settled;
// QNAME ends at the first zero byte after the 12-byte header. QTYPE follows it.
return { qtype: query.readUInt16BE(query.indexOf(0, 12) + 1), code, syscall };
} finally {
socket.close();
}
}

describe.each(Object.entries(qtypes))("resolve(hostname, %p)", (rrtype, qtype) => {
const expected = { qtype, code: "ECANCELLED", syscall: "query" + rrtype[0] + rrtype.slice(1).toLowerCase() };

it.concurrent("dns.Resolver#resolve issues that query", async () => {
const sent = await querySentBy((server, hostname) => {
const resolver = new dns.Resolver({ timeout: 1000, tries: 1 });
resolver.setServers([server]);
const { promise, resolve } = Promise.withResolvers();
resolver.resolve(hostname, rrtype, resolve);
return { resolver, settled: promise };
});
expect(sent).toEqual(expected);
});

it.concurrent("dns.promises.Resolver#resolve issues that query", async () => {
const sent = await querySentBy((server, hostname) => {
const resolver = new dns_promises.Resolver({ timeout: 1000, tries: 1 });
resolver.setServers([server]);
return { resolver, settled: resolver.resolve(hostname, rrtype).catch(err => err) };
});
expect(sent).toEqual(expected);
});
});
2 changes: 1 addition & 1 deletion test/js/node/test/parallel/test-c-ares.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ dns.lookup('::1', common.mustSucceed((result, addressType) => {
const err = {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
// message: `The argument 'rrtype' is invalid. Received '${val}'`,
message: `The argument 'rrtype' is invalid. Received '${val}'`,
};

assert.throws(
Expand Down