168 lines
6.5 KiB
TypeScript
168 lines
6.5 KiB
TypeScript
import { MemoryAdapter, type SharedStore } from "@hivegrid/shared-store";
|
|
import { getPseudonymousAuthBucketKey, type AuthThrottleAction } from "~/services/auth/auth-rate-limit-key.server";
|
|
import { getSharedStore } from "~/shared-store.server";
|
|
import { createScopedLogger } from "~/utils/logger.server";
|
|
|
|
type AuthRateLimitOptions = {
|
|
request: Request;
|
|
action: AuthThrottleAction;
|
|
identifier?: string | null;
|
|
limit: number;
|
|
windowMs: number;
|
|
/** Optional hard cap shared by all trusted clients for one identifier. Null
|
|
* keeps the per-client and client/identifier pair buckets while disabling
|
|
* the globally poisonable identifier bucket for unauthenticated input. */
|
|
identifierLimit?: number | null;
|
|
/** Optional hard cap for one trusted client across identifier churn. */
|
|
clientLimit?: number;
|
|
};
|
|
|
|
type AuthRateLimitResult = { allowed: true } | { allowed: false; retryAfterSeconds: number };
|
|
|
|
const authRateLimitLogger = createScopedLogger("auth-rate-limit");
|
|
const MAX_WINDOW_MS = 24 * 60 * 60 * 1000;
|
|
const MAX_LIMIT = 10_000;
|
|
const PER_CLIENT_LIMIT_FACTOR = 10;
|
|
const PER_IDENTIFIER_LIMIT_FACTOR = 3;
|
|
|
|
const AUTH_RATE_LIMIT_SCRIPT = `
|
|
local window = tonumber(ARGV[1])
|
|
local clientMax = tonumber(ARGV[2])
|
|
local identifierMax = tonumber(ARGV[3])
|
|
local pairMax = tonumber(ARGV[4])
|
|
local hasIdentifier = ARGV[5] == '1'
|
|
|
|
local function reserve(key)
|
|
local current = redis.call('INCR', key)
|
|
if current == 1 then
|
|
redis.call('EXPIRE', key, window)
|
|
end
|
|
local ttl = redis.call('TTL', key)
|
|
if ttl <= 0 then ttl = window end
|
|
return current, ttl
|
|
end
|
|
|
|
local clientCurrent, clientTtl = reserve(KEYS[1])
|
|
if clientCurrent > clientMax then
|
|
return { 0, clientTtl, 1 }
|
|
end
|
|
|
|
if hasIdentifier then
|
|
local identifierCurrent, identifierTtl = reserve(KEYS[2])
|
|
if identifierCurrent > identifierMax then
|
|
return { 0, identifierTtl, 2 }
|
|
end
|
|
end
|
|
|
|
local pairCurrent, pairTtl = reserve(KEYS[3])
|
|
if pairCurrent > pairMax then
|
|
return { 0, pairTtl, 3 }
|
|
end
|
|
|
|
return { 1, pairTtl, 0 }
|
|
`;
|
|
|
|
MemoryAdapter.registerScript(AUTH_RATE_LIMIT_SCRIPT, async (adapter, keys, args) => {
|
|
const windowSeconds = Number.parseInt(args[0] ?? "0", 10);
|
|
const clientMax = Number.parseInt(args[1] ?? "0", 10);
|
|
const identifierMax = Number.parseInt(args[2] ?? "0", 10);
|
|
const pairMax = Number.parseInt(args[3] ?? "0", 10);
|
|
const hasIdentifier = args[4] === "1";
|
|
|
|
const reserve = async (key: string) => {
|
|
const current = await adapter.incr(key);
|
|
if (current === 1) await adapter.expire(key, windowSeconds);
|
|
return current;
|
|
};
|
|
|
|
const clientCurrent = await reserve(keys[0]);
|
|
if (clientCurrent > clientMax) return [0, windowSeconds, 1];
|
|
if (hasIdentifier) {
|
|
const identifierCurrent = await reserve(keys[1]);
|
|
if (identifierCurrent > identifierMax) return [0, windowSeconds, 2];
|
|
}
|
|
const pairCurrent = await reserve(keys[2]);
|
|
if (pairCurrent > pairMax) return [0, windowSeconds, 3];
|
|
return [1, windowSeconds, 0];
|
|
});
|
|
|
|
let storeFactory: () => SharedStore = () => getSharedStore();
|
|
|
|
function normalizeWindowSeconds(windowMs: number): number {
|
|
if (!Number.isSafeInteger(windowMs) || windowMs <= 0 || windowMs > MAX_WINDOW_MS) {
|
|
throw new Error("Auth rate-limit window is outside the supported range.");
|
|
}
|
|
return Math.ceil(windowMs / 1000);
|
|
}
|
|
|
|
function validateLimit(limit: number): void {
|
|
if (!Number.isSafeInteger(limit) || limit <= 0 || limit > MAX_LIMIT) {
|
|
throw new Error("Auth rate-limit maximum is outside the supported range.");
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Returns a stable, pseudonymous bucket key. The HMAC keeps enumerable email
|
|
* addresses and client IPs out of Redis keys and diagnostic snapshots.
|
|
*/
|
|
export function getAuthRateLimitKey({ request, action, identifier }: Omit<AuthRateLimitOptions, "limit" | "windowMs">) {
|
|
return getPseudonymousAuthBucketKey({ request, action, identifier });
|
|
}
|
|
|
|
/**
|
|
* Atomically reserves an auth attempt in the shared store. Store and
|
|
* configuration failures deny the request: losing the distributed throttle
|
|
* must never silently turn into an unlimited authentication endpoint.
|
|
*/
|
|
export async function checkAuthRateLimit(options: AuthRateLimitOptions): Promise<AuthRateLimitResult> {
|
|
const safeRetryAfterSeconds = Math.max(1, Math.ceil(Math.min(Math.max(options.windowMs || 0, 1000), MAX_WINDOW_MS) / 1000));
|
|
|
|
try {
|
|
validateLimit(options.limit);
|
|
if (options.identifierLimit !== undefined && options.identifierLimit !== null) validateLimit(options.identifierLimit);
|
|
if (options.clientLimit !== undefined) validateLimit(options.clientLimit);
|
|
const windowSeconds = normalizeWindowSeconds(options.windowMs);
|
|
const store = storeFactory();
|
|
const normalizedIdentifier = options.identifier?.trim().toLowerCase() ?? "";
|
|
const keyPrefix = `rl:auth:v1:${options.action}:${options.limit}:${windowSeconds}`;
|
|
const clientKey = getPseudonymousAuthBucketKey({ ...options, scope: "client" });
|
|
const identifierKey = getPseudonymousAuthBucketKey({ ...options, scope: "identifier" });
|
|
const pairKey = getPseudonymousAuthBucketKey({ ...options, scope: "pair" });
|
|
const clientLimit = options.clientLimit ?? Math.min(MAX_LIMIT, options.limit * PER_CLIENT_LIMIT_FACTOR);
|
|
const identifierLimit = options.identifierLimit ?? Math.min(MAX_LIMIT, options.limit * PER_IDENTIFIER_LIMIT_FACTOR);
|
|
const reserveIdentifierBucket = normalizedIdentifier.length > 0 && options.identifierLimit !== null;
|
|
const result = (await store.eval(
|
|
AUTH_RATE_LIMIT_SCRIPT,
|
|
[`${keyPrefix}:client:${clientKey}`, `${keyPrefix}:identifier:${identifierKey}`, `${keyPrefix}:pair:${pairKey}`],
|
|
[String(windowSeconds), String(clientLimit), String(identifierLimit), String(options.limit), reserveIdentifierBucket ? "1" : "0"]
|
|
)) as [number | string, number | string, number | string] | undefined;
|
|
const allowed = Number(result?.[0]) === 1;
|
|
const ttl = Number(result?.[1]);
|
|
if (!allowed) {
|
|
return {
|
|
allowed: false,
|
|
retryAfterSeconds: Number.isFinite(ttl) && ttl > 0 ? Math.ceil(ttl) : windowSeconds,
|
|
};
|
|
}
|
|
return { allowed: true };
|
|
} catch (error) {
|
|
authRateLimitLogger.error(
|
|
{
|
|
event: "auth.rate_limit.store_unavailable",
|
|
action: options.action,
|
|
errorName: error instanceof Error ? error.name : "UnknownError",
|
|
},
|
|
"Auth rate-limit reservation failed; request denied"
|
|
);
|
|
return { allowed: false, retryAfterSeconds: safeRetryAfterSeconds };
|
|
}
|
|
}
|
|
|
|
export function __setAuthRateLimitStoreForTests(store: SharedStore): void {
|
|
storeFactory = () => store;
|
|
}
|
|
|
|
export function __resetAuthRateLimitStoreForTests(): void {
|
|
storeFactory = () => getSharedStore();
|
|
}
|