From 12435f9e1b9676e7b50581666c9f96a5d4cb0d3e Mon Sep 17 00:00:00 2001 From: Yoshiya Hinosawa Date: Fri, 7 Feb 2025 17:16:39 +0900 Subject: [PATCH] test permissions --- .../polyfills/internal_binding/cares_wrap.ts | 14 ++++++--- tests/unit_node/http_test.ts | 30 ++++++++++++++++++- 2 files changed, 39 insertions(+), 5 deletions(-) diff --git a/ext/node/polyfills/internal_binding/cares_wrap.ts b/ext/node/polyfills/internal_binding/cares_wrap.ts index 809a77e8dc77e4..708f7ff4bb9baf 100644 --- a/ext/node/polyfills/internal_binding/cares_wrap.ts +++ b/ext/node/polyfills/internal_binding/cares_wrap.ts @@ -78,14 +78,20 @@ export function getaddrinfo( // REF: https://nodejs.org/api/dns.html#dns_supported_getaddrinfo_flags (async () => { + let error = 0; try { addresses.push(...await op_getaddrinfo(hostname, req.port || undefined)); - } catch { - // pass + if (addresses.length === 0) { + error = codeMap.get("EAI_NODATA")!; + } + } catch (e) { + if (e instanceof Deno.errors.NotCapable) { + error = codeMap.get("EPERM")!; + } else { + error = codeMap.get("EAI_NODATA")!; + } } - const error = addresses.length ? 0 : codeMap.get("EAI_NODATA")!; - // TODO(cmorten): needs work // REF: https://github.com/nodejs/node/blob/master/src/cares_wrap.cc#L1444 if (!verbatim) { diff --git a/tests/unit_node/http_test.ts b/tests/unit_node/http_test.ts index 1994bcd10753ee..2458839073ab65 100644 --- a/tests/unit_node/http_test.ts +++ b/tests/unit_node/http_test.ts @@ -15,7 +15,7 @@ import net, { Socket } from "node:net"; import fs from "node:fs"; import { text } from "node:stream/consumers"; -import { assert, assertEquals, fail } from "@std/assert"; +import { assert, assertEquals, assertStringIncludes, fail } from "@std/assert"; import { assertSpyCalls, spy } from "@std/testing/mock"; import { fromFileUrl, relative } from "@std/path"; import { retry } from "@std/async/retry"; @@ -1916,3 +1916,31 @@ Deno.test("[node/http] supports proxy http request", async () => { await promise; await server.finished; }); + +Deno.test("[node/http] `request` requires net permission to host and port", { + permissions: { net: ["localhost:4545"] }, +}, async () => { + const { promise, resolve } = Promise.withResolvers(); + http.request("http://localhost:4545/echo.ts", async (res) => { + assertEquals(res.statusCode, 200); + assertStringIncludes(await text(res), "function echo("); + resolve(); + }).end(); + await promise; +}); + +Deno.test( + "[node/http] `request` errors with EPERM error when permission is not granted", + { permissions: { net: ["localhost:4321"] } }, // wrong permission + async () => { + const { promise, resolve } = Promise.withResolvers(); + http.request("http://localhost:4545/echo.ts", async (res) => {}) + .on("error", (e) => { + assertEquals(e.message, "getaddrinfo EPERM localhost"); + // deno-lint-ignore no-explicit-any + assertEquals((e as any).code, "EPERM"); + resolve(); + }).end(); + await promise; + }, +);