Files
plugins/packages/gcp-ai/test/network.mjs
T
yetone 017f05cbb9 gcp-ai tests: the network guard lets another package's loopback fetch through
gcp-ai's test/network.mjs (from #307) replaced globalThis.fetch with one
that refuses every call. bun test runs every package in one process, so
the guard outlived gcp-ai's files: with #384 merged on top, all eight
Search1API tests that fetch their own 127.0.0.1 fixture failed with
"Unexpected network fetch in test: http://127.0.0.1:…/search" in the
repo-wide run, and passed alone. fetch now refuses only a non-loopback
host, as the socket, http and dns hooks beside it already did. The real
fetch stays inside the module, never on globalThis.

Run (sandbox HOME under TMPDIR, HTTPS_PROXY at a dead port):
- bun test packages/gcp-ai: 40 pass, 1 skip, 0 fail.
- A script importing the guard: a Bun.serve loopback fetch answers "ok";
  https://example.com is refused and the process exits 1.
- bun test (whole repo) with this file over #384's merge: 2647 pass,
  1 skip, 0 fail. Without it: 2638 pass, 9 fail (8 Search1API, plus one
  gcp-ai Chrome test that lost its CDP connection, which passed in the
  next run).
- bun scripts/check.mjs: every package ok.
2026-10-25 17:52:37 +08:00

80 lines
3.0 KiB
JavaScript

import dns from "node:dns"
import http from "node:http"
import https from "node:https"
import net from "node:net"
import tls from "node:tls"
import { syncBuiltinESMExports } from "node:module"
// Importable by tests and as --import: the real fetch stays in this module,
// never on globalThis for a test to restore. Record violations too, since
// production fallbacks catch errors.
const unexpected = []
function refuse(kind, target) {
const message = `Unexpected network ${kind} in test: ${target}`
unexpected.push(message)
throw new Error(message)
}
const local = (host) => {
const value = String(host ?? "localhost").replace(/^\[|\]$/g, "").toLowerCase()
return value === "localhost" || value === "::1" || /^127(?:\.\d{1,3}){3}$/.test(value)
}
// bun test runs every package's files in one process, so this outlives
// gcp-ai's tests: another package's fetch to its own loopback server goes on.
const realFetch = globalThis.fetch
globalThis.fetch = (input, init) => {
const target = input?.url ?? input
let host
try { host = new URL(String(target)).hostname } catch {}
if (host === undefined || !local(host)) refuse("fetch", target)
return realFetch(input, init)
}
function check(kind, host) {
if (!local(host)) refuse(kind, host)
}
function connectionHost(args) {
const first = args[0]
if (typeof first === "object") {
if (first.path) return undefined // Unix pipe, including Chrome's CDP transport.
return first.host ?? first.hostname
}
if (typeof first === "string" && !/^\d+$/.test(first)) return undefined // Unix socket.
return typeof args[1] === "string" ? args[1] : undefined
}
for (const [owner, key] of [[net, "connect"], [net, "createConnection"], [net.Socket.prototype, "connect"], [tls, "connect"]]) {
const original = owner[key]
owner[key] = function (...args) {
// Node may forward already-normalized connect arguments as one array.
check(key, connectionHost(Array.isArray(args[0]) ? args[0] : args))
return original.apply(this, args)
}
}
for (const owner of [http, https]) {
for (const key of ["request", "get"]) {
const original = owner[key]
owner[key] = function (...args) {
const first = args[0]
const url = typeof first === "string" || first instanceof URL ? new URL(first) : undefined
const options = url ? (typeof args[1] === "object" ? args[1] : {}) : first ?? {}
if (!options.socketPath) check(key, options.hostname ?? options.host ?? url?.hostname)
return original.apply(this, args)
}
}
}
for (const owner of [dns, dns.promises]) {
const original = owner.lookup
owner.lookup = function (host, ...args) {
check("dns.lookup", host)
return original.call(this, host, ...args)
}
}
syncBuiltinESMExports()
// Also covers caught errors and fixture subprocesses without importing node:test
// there: its reporter would contaminate gcloud's token output.
process.on("exit", () => {
if (unexpected.length) {
console.error(unexpected.join("\n"))
process.exitCode = 1
}
})