fix(webui): preserve reverse proxy authentication

Prevent login loops when the WebUI is protected by HTTP authentication
at a reverse proxy. Apply the fix to settings, uploads, and live streams
while retaining compatibility with existing WebUI clients.

Fixes #523
This commit is contained in:
DrSmoothl committed 2026-10-14 08:13:50 +08:00
1 parent d6dd748beb
commit 5150d83403
13 files changed
+244 -56

No files matched your search

@@ -32,7 +32,7 @@ describe('API client full TRACE export', () => {
expect(fetchMock).toHaveBeenCalledExactlyOnceWith(
'/api/logs/export/trace',
expect.objectContaining({
headers: { Authorization: 'Bearer trace-token' },
headers: new Headers({ 'X-SnowLuma-Token': 'trace-token' }),
}),
);
});
@@ -0,0 +1,124 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { createApiClient } from '../src/lib/api/client';
const sessionToken = 'webui-session-token';
const proxyAuthorization = 'Basic cHJveHk6cGFzc3dvcmQ=';
const proxyHeaderEntries: [string, string][] = [['Authorization', proxyAuthorization]];
const tokenStore = { load: () => sessionToken, save: vi.fn() };
afterEach(() => {
vi.unstubAllGlobals();
vi.clearAllMocks();
});
describe('WebUI authentication behind a Basic-auth proxy', () => {
it.each([
{ kind: 'object', headers: { Authorization: proxyAuthorization } },
{ kind: 'Headers', headers: new Headers({ Authorization: proxyAuthorization }) },
{ kind: 'tuples', headers: proxyHeaderEntries },
])('preserves supplied proxy credentials from $kind', async ({ headers }) => {
const fetchMock = vi.fn(async (_url: string, init?: RequestInit) => {
const sent = new Headers(init?.headers);
if (sent.get('authorization') !== proxyAuthorization) {
return new Response(null, { status: 401 });
}
return new Response(null, {
status: sent.get('x-snowluma-token') === sessionToken ? 204 : 403,
});
});
vi.stubGlobal('fetch', fetchMock);
const onUnauthorized = vi.fn();
const client = createApiClient({ tokenStore, onUnauthorized });
const response = await client.request('/api/auth/state', { headers });
expect(response.status).toBe(204);
expect(onUnauthorized).not.toHaveBeenCalled();
expect(tokenStore.save).not.toHaveBeenCalled();
});
it('leaves browser-managed proxy authentication available on JSON requests', async () => {
const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(Response.json({ list: [] }));
vi.stubGlobal('fetch', fetchMock);
const client = createApiClient({ tokenStore });
await expect(client.qqList()).resolves.toEqual([]);
const headers = new Headers(fetchMock.mock.calls[0]![1]?.headers);
expect(headers.get('x-snowluma-token')).toBe(sessionToken);
expect(headers.has('authorization')).toBe(false);
});
it('authenticates multipart uploads without replacing the browser multipart boundary', async () => {
const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(Response.json({ config: {} }));
vi.stubGlobal('fetch', fetchMock);
const client = createApiClient({ tokenStore });
const file = new File(['image'], 'background.png', { type: 'image/png' });
await client.ui.uploadBackground(file);
const [url, init] = fetchMock.mock.calls[0]!;
const headers = new Headers(init?.headers);
expect(url).toBe('/api/ui/background');
expect(headers.get('x-snowluma-token')).toBe(sessionToken);
expect(headers.has('authorization')).toBe(false);
expect(headers.has('content-type')).toBe(false);
expect(init?.body).toBeInstanceOf(FormData);
expect((init?.body as FormData).get('file')).toBe(file);
});
it('authenticates streamed action requests without overriding proxy authentication', async () => {
const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(
new Response('data: {"type":"done"}\n\n', {
headers: { 'Content-Type': 'text/event-stream' },
}),
);
vi.stubGlobal('fetch', fetchMock);
const client = createApiClient({ tokenStore });
const onFrame = vi.fn();
await client.debug.invokeStream('12345', 'test_action', {}, onFrame);
const [url, init] = fetchMock.mock.calls[0]!;
const headers = new Headers(init?.headers);
expect(url).toBe('/api/debug/invoke-stream');
expect(headers.get('x-snowluma-token')).toBe(sessionToken);
expect(headers.has('authorization')).toBe(false);
expect(headers.get('content-type')).toBe('application/json');
expect(onFrame).toHaveBeenCalledWith({ type: 'done' });
});
it('authenticates XHR uploads without overriding proxy authentication', async () => {
const headers = new Headers();
const send = vi.fn();
class UploadRequest {
upload = {};
responseType = '';
status = 200;
response = { path: '/tmp/uploaded-file', size: 4 };
onload?: () => void;
open = vi.fn();
setRequestHeader(name: string, value: string) {
headers.set(name, value);
}
send(file: File) {
send(file);
this.onload?.();
}
}
vi.stubGlobal('XMLHttpRequest', UploadRequest);
const client = createApiClient({ tokenStore });
const file = new File(['test'], 'test.txt');
await expect(client.debug.upload(file)).resolves.toEqual({
path: '/tmp/uploaded-file',
size: 4,
});
expect(send).toHaveBeenCalledWith(file);
expect(headers.get('x-snowluma-token')).toBe(sessionToken);
expect(headers.has('authorization')).toBe(false);
});
});
@@ -8,7 +8,7 @@ describe('API client SSE authentication', () => {
vi.unstubAllGlobals();
});
it('uses an Authorization header, parses frames, and never puts the token in the URL', async () => {
it('keeps Authorization available for the proxy while authenticating and parsing frames', async () => {
let streamController: ReadableStreamDefaultController<Uint8Array> | undefined;
const stream = new ReadableStream<Uint8Array>({
start(controller) {
@@ -41,7 +41,8 @@ describe('API client SSE authentication', () => {
await expect(received).resolves.toEqual({ kind: 'ready' });
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
expect(url).toBe('/api/state/stream');
expect(new Headers(init.headers).get('authorization')).toBe('Bearer secret-session-token');
expect(new Headers(init.headers).get('x-snowluma-token')).toBe('secret-session-token');
expect(new Headers(init.headers).has('authorization')).toBe(false);
expect(init.signal?.aborted).toBe(true);
});
@@ -41,10 +41,10 @@ describe('password strength API client', () => {
expect.objectContaining({
method: 'POST',
body: JSON.stringify({ password: 'Strong-password' }),
headers: {
Authorization: 'Bearer test-token',
headers: new Headers({
'X-SnowLuma-Token': 'test-token',
'Content-Type': 'application/json',
},
}),
signal: expect.any(AbortSignal),
}),
);
+4 -4
View File
@@ -49,7 +49,7 @@ describe('storage API client', () => {
expect(fetchMock).toHaveBeenCalledWith(
'/api/system/storage',
expect.objectContaining({
headers: { Authorization: 'Bearer test-token' },
headers: new Headers({ 'X-SnowLuma-Token': 'test-token' }),
signal: expect.any(AbortSignal),
}),
);
@@ -82,10 +82,10 @@ describe('storage API client', () => {
expect.objectContaining({
method: 'POST',
body: JSON.stringify({ logRetainDays: 0 }),
headers: {
Authorization: 'Bearer test-token',
headers: new Headers({
'X-SnowLuma-Token': 'test-token',
'Content-Type': 'application/json',
},
}),
signal: expect.any(AbortSignal),
}),
);