fix: fail-closed auth when HEALTH_TOKEN is not set

Reject all requests if HEALTH_TOKEN env var is undefined instead of
allowing unauthenticated access (fail-open → fail-closed).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
le king fu 2026-03-02 13:06:16 -05:00
parent 0e168d5323
commit 69fea95320

View file

@ -5,6 +5,10 @@ const { execSync } = require("node:child_process");
const PORT = parseInt(process.env.PORT || "3001", 10);
const TOKEN = process.env.HEALTH_TOKEN;
if (!TOKEN) {
console.warn("WARNING: HEALTH_TOKEN is not set. All requests will be rejected (fail-closed).");
}
function readProcStat() {
try {
const line = execSync("head -1 /proc/stat", { encoding: "utf-8" }).trim();
@ -84,13 +88,17 @@ const server = http.createServer((req, res) => {
return;
}
if (TOKEN) {
const auth = req.headers["authorization"];
if (auth !== `Bearer ${TOKEN}`) {
res.writeHead(401);
res.end(JSON.stringify({ error: "Unauthorized" }));
return;
}
if (!TOKEN) {
res.writeHead(401);
res.end(JSON.stringify({ error: "HEALTH_TOKEN not configured" }));
return;
}
const auth = req.headers["authorization"];
if (auth !== `Bearer ${TOKEN}`) {
res.writeHead(401);
res.end(JSON.stringify({ error: "Unauthorized" }));
return;
}
const data = getHealth();