java-topology/defects/esbuild/unit/EsbuildTest.java
russell@unturf.com da26ffd2cf wave16c: esbuild/deno CWE-407 scan results
esbuild-0001: serve_other.go hosts []string scan → map[string]struct{} (57x, MEDIUM)
deno: CLEAN (uses HashSet/HashMap throughout, no Vec.contains() in loops)

1 test: 1/1 PASS
2026-03-30 07:39:57 -04:00

62 lines
2.2 KiB
Java
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import java.util.*;
/**
* CWE-407 unit test for esbuild serve_other.go defect.
*
* esbuild-0001: pkg/api/serve_other.go ServeHTTP() host allowlist
* for _, allowed := range h.hosts { // O(H) scan per HTTP request
* if req.Host == allowed { ok = true; break }
* }
* Fix: map[string]struct{} → O(1) probe per request
*/
public class EsbuildTest {
static boolean checkHostSlice(String[] hosts, String reqHost) {
for (String allowed : hosts) { // O(H) — defect
if (allowed.equals(reqHost)) return true;
}
return false;
}
static boolean checkHostMap(Set<String> hostsMap, String reqHost) {
return hostsMap.contains(reqHost); // O(1) — fix
}
static void testEsbuild0001() throws Exception {
int H = 1000; // configured hosts
String[] hosts = new String[H];
for (int i = 0; i < H; i++) hosts[i] = "server-" + i + ".example.com";
Set<String> hostsMap = new HashSet<>(Arrays.asList(hosts));
// hit middle of list — worst case for linear scan is end
String reqHost = "server-999.example.com";
// correctness
assert checkHostSlice(hosts, reqHost) == checkHostMap(hostsMap, reqHost);
assert !checkHostSlice(hosts, "evil.com") && !checkHostMap(hostsMap, "evil.com");
// performance: simulate R HTTP requests
int R = 100_000;
long t0 = System.nanoTime();
int s1 = 0;
for (int r = 0; r < R; r++) if (checkHostSlice(hosts, reqHost)) s1++;
long tSlice = System.nanoTime() - t0;
t0 = System.nanoTime();
int s2 = 0;
for (int r = 0; r < R; r++) if (checkHostMap(hostsMap, reqHost)) s2++;
long tMap = System.nanoTime() - t0;
assert s1 == s2;
double ratio = (double) tSlice / tMap;
System.out.printf("esbuild-0001: slice=%.3fs map=%.3fs ratio=%.1f×%n",
tSlice / 1e9, tMap / 1e9, ratio);
assert ratio > 10 : "Expected >10× speedup, got " + ratio;
System.out.println("PASS esbuild-0001");
}
public static void main(String[] args) throws Exception {
testEsbuild0001();
System.out.println("ALL PASS");
}
}