feat(webui): add SNOWLUMA_WEBUI_TRUST_PROXY for reverse-proxy deploys
The previous commit tightened login rate-limiting to key off the real
TCP socket peer, which fixed the X-Forwarded-For bypass but had the
known caveat of collapsing every client into a single global bucket
when the WebUI runs behind nginx / Caddy / a SaaS CDN.
Give operators an explicit, audited way to opt back into per-client
keying without re-introducing the spoof:
* `SNOWLUMA_WEBUI_TRUST_PROXY` env var. Modes:
- unset / empty → keep socket peer (safe default, unchanged)
- "loopback" → trust X-Real-IP / X-Forwarded-For when the
immediate socket peer is 127.0.0.1 / ::1
(nginx + WebUI on the same host)
- "1" / "true" / → trust headers from any peer (only safe behind
"all" a SaaS proxy that strips client-set headers)
- comma-separated → trust headers only when the socket peer
IP list matches one of these (proxy on another box)
* When trusting headers we prefer X-Real-IP (single value the proxy
overwrites unconditionally) and fall back to the first hop of XFF.
We deliberately do NOT walk the full XFF chain — without a fully
trusted proxy chain the leftmost value is still spoofable; a
single-tier proxy is the only setup this app realistically sees.
* Boot log prints "login rate-limit keyed by: …" so operators can
verify the mode took effect, plus an extra WARN for "all" reminding
them it's only safe with header-stripping in front.
Logic lives in webui/client-ip.ts as a pure pickClientIp() that takes
a socket-IP resolver, so the trust-proxy matrix can be exercised
without standing up a server — see webui-client-ip.test.ts for the
11 new unit tests covering parse + dispatch + loopback / list / all /
none modes.
Smoke-tested with SNOWLUMA_WEBUI_TRUST_PROXY=loopback:
- 5× failed login w/ X-Forwarded-For: 1.1.1.1 → 401
- 6th attempt same XFF → 429 (locked, per-XFF)
- 6th attempt X-Forwarded-For: 2.2.2.2 → 401 (fresh bucket)
- X-Real-IP overrides XFF when both present
This commit is contained in:
1 parent
d66f0b2c6b
commit
ffe0c57abf
3 files changed
+209
-13
No files matched your search
@@ -0,0 +1,106 @@
|
|||||||
|
// Resolve the request's "real" client IP for per-IP rate limiting.
|
||||||
|
//
|
||||||
|
// Threat model:
|
||||||
|
// - By default we ONLY trust the TCP socket peer. `X-Forwarded-For` and
|
||||||
|
// `X-Real-IP` are client-controllable, so honoring them lets any
|
||||||
|
// client rotate the header to escape the 5-attempts/15-min login
|
||||||
|
// lockout.
|
||||||
|
// - Operators who actually run behind a reverse proxy (nginx, Caddy,
|
||||||
|
// a SaaS CDN) need a way to opt back into the real client IP. The
|
||||||
|
// `SNOWLUMA_WEBUI_TRUST_PROXY` env var lets them say "when the
|
||||||
|
// immediate TCP peer is THIS, treat the headers as authoritative".
|
||||||
|
//
|
||||||
|
// Supported values for SNOWLUMA_WEBUI_TRUST_PROXY:
|
||||||
|
// - unset / empty — default; ignore headers, use socket peer
|
||||||
|
// - "loopback" — trust headers when the socket peer is 127.0.0.1
|
||||||
|
// or ::1 (typical for nginx/Caddy on the same host)
|
||||||
|
// - "1" / "true" / — trust headers from any peer (only safe behind a
|
||||||
|
// "all" trusted SaaS CDN that strips client-set headers)
|
||||||
|
// - comma-separated — trust headers when the socket peer matches one
|
||||||
|
// IP list of these IPs (reverse proxy on another machine)
|
||||||
|
//
|
||||||
|
// When trusted, we prefer X-Real-IP (a single value the reverse proxy
|
||||||
|
// overwrites unconditionally) and fall back to the first hop of
|
||||||
|
// X-Forwarded-For. We never parse the FULL XFF chain — if the proxy
|
||||||
|
// chain isn't fully trusted, the leftmost value can still be spoofed
|
||||||
|
// by the original client, and a single-tier proxy is the only setup
|
||||||
|
// this app realistically sees.
|
||||||
|
|
||||||
|
import type { Context } from 'hono';
|
||||||
|
import { getConnInfo } from '@hono/node-server/conninfo';
|
||||||
|
|
||||||
|
export type TrustProxyMode =
|
||||||
|
| { kind: 'none' }
|
||||||
|
| { kind: 'loopback' }
|
||||||
|
| { kind: 'all' }
|
||||||
|
| { kind: 'ip-list'; ips: Set<string> };
|
||||||
|
|
||||||
|
export function parseTrustProxy(raw: string | undefined): TrustProxyMode {
|
||||||
|
const value = raw?.trim().toLowerCase() ?? '';
|
||||||
|
if (!value) return { kind: 'none' };
|
||||||
|
if (value === '1' || value === 'true' || value === 'all') return { kind: 'all' };
|
||||||
|
if (value === 'loopback') return { kind: 'loopback' };
|
||||||
|
const ips = new Set(
|
||||||
|
value.split(',').map((s) => s.trim()).filter(Boolean),
|
||||||
|
);
|
||||||
|
if (ips.size === 0) return { kind: 'none' };
|
||||||
|
return { kind: 'ip-list', ips };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function describeTrustProxy(mode: TrustProxyMode): string {
|
||||||
|
switch (mode.kind) {
|
||||||
|
case 'none': return 'socket peer (default)';
|
||||||
|
case 'all': return 'X-Real-IP / X-Forwarded-For from any peer';
|
||||||
|
case 'loopback': return 'X-Real-IP / X-Forwarded-For when socket peer is loopback';
|
||||||
|
case 'ip-list': return `X-Real-IP / X-Forwarded-For when socket peer is in [${[...mode.ips].join(',')}]`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function isLoopback(ip: string): boolean {
|
||||||
|
return ip === '127.0.0.1' || ip === '::1' || ip === '::ffff:127.0.0.1';
|
||||||
|
}
|
||||||
|
|
||||||
|
function shouldTrustHeaders(mode: TrustProxyMode, socketIp: string): boolean {
|
||||||
|
switch (mode.kind) {
|
||||||
|
case 'none': return false;
|
||||||
|
case 'all': return true;
|
||||||
|
case 'loopback': return isLoopback(socketIp);
|
||||||
|
case 'ip-list': return mode.ips.has(socketIp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pick the right "client IP" for rate-limit keying.
|
||||||
|
*
|
||||||
|
* Exposed as a pure function over a small dependency surface so the
|
||||||
|
* unit tests can fabricate request shapes without spinning up a server.
|
||||||
|
*/
|
||||||
|
export function pickClientIp(
|
||||||
|
c: Pick<Context, 'req'>,
|
||||||
|
mode: TrustProxyMode,
|
||||||
|
getSocketIp: () => string,
|
||||||
|
): string {
|
||||||
|
const socketIp = (() => {
|
||||||
|
try { return getSocketIp() || '127.0.0.1'; }
|
||||||
|
catch { return '127.0.0.1'; }
|
||||||
|
})();
|
||||||
|
|
||||||
|
if (!shouldTrustHeaders(mode, socketIp)) return socketIp;
|
||||||
|
|
||||||
|
const realIp = c.req.header('x-real-ip')?.trim();
|
||||||
|
if (realIp) return realIp;
|
||||||
|
const xff = c.req.header('x-forwarded-for');
|
||||||
|
if (xff) {
|
||||||
|
const first = xff.split(',')[0].trim();
|
||||||
|
if (first) return first;
|
||||||
|
}
|
||||||
|
return socketIp;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Convenience binding for the live server: read socket via getConnInfo. */
|
||||||
|
export function makeClientIpResolver(mode: TrustProxyMode): (c: Context) => string {
|
||||||
|
return (c) => pickClientIp(c, mode, () => {
|
||||||
|
try { return getConnInfo(c).remote.address ?? '127.0.0.1'; }
|
||||||
|
catch { return '127.0.0.1'; }
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import { serve } from '@hono/node-server';
|
import { serve } from '@hono/node-server';
|
||||||
import { getConnInfo } from '@hono/node-server/conninfo';
|
|
||||||
import { serveStatic } from '@hono/node-server/serve-static';
|
import { serveStatic } from '@hono/node-server/serve-static';
|
||||||
import { Hono, type Context } from 'hono';
|
import { Hono, type Context } from 'hono';
|
||||||
|
import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip';
|
||||||
import { createLogger, getRecentLogs, subscribeLogs } from '../utils/logger';
|
import { createLogger, getRecentLogs, subscribeLogs } from '../utils/logger';
|
||||||
import { randomBytes } from 'crypto';
|
import { randomBytes } from 'crypto';
|
||||||
import type { OneBotManager } from '../onebot/manager';
|
import type { OneBotManager } from '../onebot/manager';
|
||||||
@@ -66,19 +66,13 @@ function purgeExpiredTokens() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resolve the client IP from the underlying TCP socket via the official
|
* Resolve the client IP for per-IP rate limiting. Default is the TCP
|
||||||
* @hono/node-server conninfo helper. We deliberately do NOT trust
|
* socket peer (cannot be spoofed by the client). Operators behind a
|
||||||
* `X-Forwarded-For` — the WebUI listens on a local port with no required
|
* reverse proxy must opt in via the `SNOWLUMA_WEBUI_TRUST_PROXY` env
|
||||||
* reverse proxy, so accepting that header would let any client rotate it
|
* var; see `./client-ip.ts` for the accepted values.
|
||||||
* to bypass the per-IP login lockout.
|
|
||||||
*/
|
*/
|
||||||
function getClientIp(c: Context): string {
|
const trustProxyMode = parseTrustProxy(process.env.SNOWLUMA_WEBUI_TRUST_PROXY);
|
||||||
try {
|
const getClientIp = makeClientIpResolver(trustProxyMode);
|
||||||
return getConnInfo(c).remote.address ?? '127.0.0.1';
|
|
||||||
} catch {
|
|
||||||
return '127.0.0.1';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function fetchQqAvatar(uin: string): Promise<{ body: Uint8Array; contentType: string }> {
|
async function fetchQqAvatar(uin: string): Promise<{ body: Uint8Array; contentType: string }> {
|
||||||
const response = await fetch(`https://q1.qlogo.cn/g?b=qq&nk=${encodeURIComponent(uin)}&s=100`, {
|
const response = await fetch(`https://q1.qlogo.cn/g?b=qq&nk=${encodeURIComponent(uin)}&s=100`, {
|
||||||
@@ -109,6 +103,10 @@ export async function initWebUI(
|
|||||||
} else if (auth.mustChangePassword()) {
|
} else if (auth.mustChangePassword()) {
|
||||||
log.warn('password change is still required');
|
log.warn('password change is still required');
|
||||||
}
|
}
|
||||||
|
log.info('login rate-limit keyed by: %s', describeTrustProxy(trustProxyMode));
|
||||||
|
if (trustProxyMode.kind === 'all') {
|
||||||
|
log.warn('SNOWLUMA_WEBUI_TRUST_PROXY=1 — only safe behind a reverse proxy that strips client-set X-Real-IP / X-Forwarded-For');
|
||||||
|
}
|
||||||
|
|
||||||
const app = new Hono();
|
const app = new Hono();
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,92 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import {
|
||||||
|
describeTrustProxy,
|
||||||
|
parseTrustProxy,
|
||||||
|
pickClientIp,
|
||||||
|
type TrustProxyMode,
|
||||||
|
} from '../src/webui/client-ip';
|
||||||
|
|
||||||
|
function mockCtx(headers: Record<string, string> = {}) {
|
||||||
|
return {
|
||||||
|
req: {
|
||||||
|
header: (name: string) => headers[name.toLowerCase()],
|
||||||
|
},
|
||||||
|
} as unknown as Parameters<typeof pickClientIp>[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('parseTrustProxy', () => {
|
||||||
|
it('treats empty / unset as none (safe default)', () => {
|
||||||
|
expect(parseTrustProxy(undefined)).toEqual({ kind: 'none' });
|
||||||
|
expect(parseTrustProxy('')).toEqual({ kind: 'none' });
|
||||||
|
expect(parseTrustProxy(' ')).toEqual({ kind: 'none' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('recognises "1" / "true" / "all" as full trust', () => {
|
||||||
|
expect(parseTrustProxy('1')).toEqual({ kind: 'all' });
|
||||||
|
expect(parseTrustProxy('true')).toEqual({ kind: 'all' });
|
||||||
|
expect(parseTrustProxy('ALL')).toEqual({ kind: 'all' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('recognises "loopback" case-insensitively', () => {
|
||||||
|
expect(parseTrustProxy('Loopback')).toEqual({ kind: 'loopback' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parses a comma-separated IP list', () => {
|
||||||
|
const mode = parseTrustProxy('10.0.0.1, 192.168.1.5, ');
|
||||||
|
expect(mode.kind).toBe('ip-list');
|
||||||
|
if (mode.kind !== 'ip-list') throw new Error('unreachable');
|
||||||
|
expect([...mode.ips].sort()).toEqual(['10.0.0.1', '192.168.1.5']);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('pickClientIp', () => {
|
||||||
|
const xff = { 'x-forwarded-for': '203.0.113.7, 10.0.0.1' };
|
||||||
|
const realIp = { 'x-real-ip': '203.0.113.42' };
|
||||||
|
const both = { ...xff, ...realIp };
|
||||||
|
|
||||||
|
it('returns socket peer and IGNORES headers when trust=none (default)', () => {
|
||||||
|
const mode: TrustProxyMode = { kind: 'none' };
|
||||||
|
expect(pickClientIp(mockCtx(both), mode, () => '198.51.100.9')).toBe('198.51.100.9');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('honors X-Real-IP first, then XFF first hop, when trust=all', () => {
|
||||||
|
const mode: TrustProxyMode = { kind: 'all' };
|
||||||
|
expect(pickClientIp(mockCtx(both), mode, () => '10.0.0.1')).toBe('203.0.113.42');
|
||||||
|
expect(pickClientIp(mockCtx(xff), mode, () => '10.0.0.1')).toBe('203.0.113.7');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('falls back to socket peer when trust=all but no headers present', () => {
|
||||||
|
const mode: TrustProxyMode = { kind: 'all' };
|
||||||
|
expect(pickClientIp(mockCtx({}), mode, () => '10.0.0.1')).toBe('10.0.0.1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('trust=loopback honors headers only when socket is loopback', () => {
|
||||||
|
const mode: TrustProxyMode = { kind: 'loopback' };
|
||||||
|
expect(pickClientIp(mockCtx(both), mode, () => '127.0.0.1')).toBe('203.0.113.42');
|
||||||
|
expect(pickClientIp(mockCtx(both), mode, () => '::1')).toBe('203.0.113.42');
|
||||||
|
expect(pickClientIp(mockCtx(both), mode, () => '::ffff:127.0.0.1')).toBe('203.0.113.42');
|
||||||
|
// Non-loopback peer → headers ignored, socket wins.
|
||||||
|
expect(pickClientIp(mockCtx(both), mode, () => '10.0.0.1')).toBe('10.0.0.1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('trust=ip-list honors headers only when socket is in the list', () => {
|
||||||
|
const mode: TrustProxyMode = { kind: 'ip-list', ips: new Set(['10.0.0.1', '10.0.0.2']) };
|
||||||
|
expect(pickClientIp(mockCtx(both), mode, () => '10.0.0.2')).toBe('203.0.113.42');
|
||||||
|
expect(pickClientIp(mockCtx(both), mode, () => '10.0.0.9')).toBe('10.0.0.9');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('survives a socket resolver that throws', () => {
|
||||||
|
const mode: TrustProxyMode = { kind: 'none' };
|
||||||
|
expect(pickClientIp(mockCtx({}), mode, () => { throw new Error('boom'); })).toBe('127.0.0.1');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('describeTrustProxy', () => {
|
||||||
|
it('renders each mode in a recognisable form for the boot log', () => {
|
||||||
|
expect(describeTrustProxy({ kind: 'none' })).toContain('socket peer');
|
||||||
|
expect(describeTrustProxy({ kind: 'all' })).toContain('any peer');
|
||||||
|
expect(describeTrustProxy({ kind: 'loopback' })).toContain('loopback');
|
||||||
|
expect(describeTrustProxy({ kind: 'ip-list', ips: new Set(['10.0.0.1']) }))
|
||||||
|
.toContain('10.0.0.1');
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user