fix(security): harden hook and device token auth

This commit is contained in:
Peter Steinberger
2026-02-13 01:23:26 +01:00
parent 54513f4240
commit 113ebfd6a2
9 changed files with 190 additions and 12 deletions

View File

@@ -1,7 +1,7 @@
import type { IncomingMessage } from "node:http";
import { timingSafeEqual } from "node:crypto";
import type { GatewayAuthConfig, GatewayTailscaleMode } from "../config/config.js";
import { readTailscaleWhoisIdentity, type TailscaleWhoisIdentity } from "../infra/tailscale.js";
import { safeEqualSecret } from "../security/secret-equal.js";
import {
isLoopbackAddress,
isTrustedProxyAddress,
@@ -37,13 +37,6 @@ type TailscaleUser = {
type TailscaleWhoisLookup = (ip: string) => Promise<TailscaleWhoisIdentity | null>;
function safeEqual(a: string, b: string): boolean {
if (a.length !== b.length) {
return false;
}
return timingSafeEqual(Buffer.from(a), Buffer.from(b));
}
function normalizeLogin(login: string): string {
return login.trim().toLowerCase();
}
@@ -253,7 +246,7 @@ export async function authorizeGatewayConnect(params: {
if (!connectAuth?.token) {
return { ok: false, reason: "token_missing" };
}
if (!safeEqual(connectAuth.token, auth.token)) {
if (!safeEqualSecret(connectAuth.token, auth.token)) {
return { ok: false, reason: "token_mismatch" };
}
return { ok: true, method: "token" };
@@ -267,7 +260,7 @@ export async function authorizeGatewayConnect(params: {
if (!password) {
return { ok: false, reason: "password_missing" };
}
if (!safeEqual(password, auth.password)) {
if (!safeEqualSecret(password, auth.password)) {
return { ok: false, reason: "password_mismatch" };
}
return { ok: true, method: "password" };

View File

@@ -18,6 +18,7 @@ import {
handleA2uiHttpRequest,
} from "../canvas-host/a2ui.js";
import { loadConfig } from "../config/config.js";
import { safeEqualSecret } from "../security/secret-equal.js";
import { handleSlackHttpRequest } from "../slack/http/index.js";
import { authorizeGatewayConnect, isLocalDirectRequest, type ResolvedGatewayAuth } from "./auth.js";
import {
@@ -49,6 +50,11 @@ import { handleOpenResponsesHttpRequest } from "./openresponses-http.js";
import { handleToolsInvokeHttpRequest } from "./tools-invoke-http.js";
type SubsystemLogger = ReturnType<typeof createSubsystemLogger>;
type HookAuthFailure = { count: number; windowStartedAtMs: number };
const HOOK_AUTH_FAILURE_LIMIT = 20;
const HOOK_AUTH_FAILURE_WINDOW_MS = 60_000;
const HOOK_AUTH_FAILURE_TRACK_MAX = 2048;
type HookDispatchers = {
dispatchWakeHook: (value: { text: string; mode: "now" | "next-heartbeat" }) => void;
@@ -140,6 +146,39 @@ export function createHooksRequestHandler(
} & HookDispatchers,
): HooksRequestHandler {
const { getHooksConfig, bindHost, port, logHooks, dispatchAgentHook, dispatchWakeHook } = opts;
const hookAuthFailures = new Map<string, HookAuthFailure>();
const resolveHookClientKey = (req: IncomingMessage): string => {
return req.socket?.remoteAddress?.trim() || "unknown";
};
const recordHookAuthFailure = (
clientKey: string,
nowMs: number,
): { throttled: boolean; retryAfterSeconds?: number } => {
if (!hookAuthFailures.has(clientKey) && hookAuthFailures.size >= HOOK_AUTH_FAILURE_TRACK_MAX) {
hookAuthFailures.clear();
}
const current = hookAuthFailures.get(clientKey);
const expired = !current || nowMs - current.windowStartedAtMs >= HOOK_AUTH_FAILURE_WINDOW_MS;
const next: HookAuthFailure = expired
? { count: 1, windowStartedAtMs: nowMs }
: { count: current.count + 1, windowStartedAtMs: current.windowStartedAtMs };
hookAuthFailures.set(clientKey, next);
if (next.count <= HOOK_AUTH_FAILURE_LIMIT) {
return { throttled: false };
}
const retryAfterMs = Math.max(1, next.windowStartedAtMs + HOOK_AUTH_FAILURE_WINDOW_MS - nowMs);
return {
throttled: true,
retryAfterSeconds: Math.ceil(retryAfterMs / 1000),
};
};
const clearHookAuthFailure = (clientKey: string) => {
hookAuthFailures.delete(clientKey);
};
return async (req, res) => {
const hooksConfig = getHooksConfig();
if (!hooksConfig) {
@@ -161,12 +200,24 @@ export function createHooksRequestHandler(
}
const token = extractHookToken(req);
if (!token || token !== hooksConfig.token) {
const clientKey = resolveHookClientKey(req);
if (!safeEqualSecret(token, hooksConfig.token)) {
const throttle = recordHookAuthFailure(clientKey, Date.now());
if (throttle.throttled) {
const retryAfter = throttle.retryAfterSeconds ?? 1;
res.statusCode = 429;
res.setHeader("Retry-After", String(retryAfter));
res.setHeader("Content-Type", "text/plain; charset=utf-8");
res.end("Too Many Requests");
logHooks.warn(`hook auth throttled for ${clientKey}; retry-after=${retryAfter}s`);
return true;
}
res.statusCode = 401;
res.setHeader("Content-Type", "text/plain; charset=utf-8");
res.end("Unauthorized");
return true;
}
clearHookAuthFailure(clientKey);
if (req.method !== "POST") {
res.statusCode = 405;

View File

@@ -318,4 +318,59 @@ describe("gateway server hooks", () => {
await server.close();
}
});
test("throttles repeated hook auth failures and resets after success", async () => {
testState.hooksConfig = { enabled: true, token: "hook-secret" };
const port = await getFreePort();
const server = await startGatewayServer(port);
try {
const firstFail = await fetch(`http://127.0.0.1:${port}/hooks/wake`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer wrong",
},
body: JSON.stringify({ text: "blocked" }),
});
expect(firstFail.status).toBe(401);
let throttled: Response | null = null;
for (let i = 0; i < 20; i++) {
throttled = await fetch(`http://127.0.0.1:${port}/hooks/wake`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer wrong",
},
body: JSON.stringify({ text: "blocked" }),
});
}
expect(throttled?.status).toBe(429);
expect(throttled?.headers.get("retry-after")).toBeTruthy();
const allowed = await fetch(`http://127.0.0.1:${port}/hooks/wake`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer hook-secret",
},
body: JSON.stringify({ text: "auth reset" }),
});
expect(allowed.status).toBe(200);
await waitForSystemEvent();
drainSystemEvents(resolveMainKey());
const failAfterSuccess = await fetch(`http://127.0.0.1:${port}/hooks/wake`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer wrong",
},
body: JSON.stringify({ text: "blocked" }),
});
expect(failAfterSuccess.status).toBe(401);
} finally {
await server.close();
}
});
});