'use strict'; // Public URL behind a reverse proxy: publicUrl in config wins, otherwise // Express "trust proxy" (default loopback) decides the scheme/host. const fs = require('fs'); const path = require('path'); const http = require('http'); const express = require('express'); const { once } = require('events'); const mockConfig = { port: 3000, paths: [], rootAliases: {} }; jest.mock('../server/db', () => { const { Database } = require('node-sqlite3-wasm'); let db; return { getDb: () => { if (!db) db = new Database(':memory:'); return db; }, initDb: () => {}, closeDb: () => {}, }; }); jest.mock('../server/config', () => { const actual = jest.requireActual('../server/config'); return { ...actual, loadConfig: () => mockConfig, saveConfig: () => {} }; }); jest.mock('../server/search-index', () => ({ searchFiles: async () => [], deleteIndexPath: () => {}, deleteIndexUnder: () => {}, rewriteIndexPaths: () => {}, reindexDirectoryTree: async () => {}, })); jest.mock('../server/file-hash-queue', () => ({ enqueueFileHash: () => {} })); jest.mock('../server/thumbnail-cache', () => ({ getCachedThumbnailInfo: async () => null, getFilesWithThumbnailsInDir: async () => [], getFolderIconSourceFile: async () => null, setFolderIconAssignment: () => {}, getThumbnailManifestSourcePathSet: async () => new Set(), needsPreviewImageConversion: () => false, streamPreviewImage: async () => {}, MAX_PREVIEW_IMAGE_BYTES: 1, THUMB_HTTP_MAX_AGE_SEC: 1, })); const { normalizePublicUrl, trustProxySetting } = require('../server/public-url'); const { getDb } = require('../server/db'); const store = require('../server/api/store'); const oauthRoutes = require('../server/api/oauth'); const apiV1Routes = require('../server/api/v1'); describe('normalizePublicUrl', () => { test.each([ ['https://files.example.com', 'https://files.example.com'], ['https://files.example.com/', 'https://files.example.com'], [' https://example.com/files/ ', 'https://example.com/files'], ['http://127.0.0.1:3000', 'http://127.0.0.1:3000'], ])('%s -> %s', (raw, out) => expect(normalizePublicUrl(raw)).toBe(out)); test.each([[''], [null], ['files.example.com'], ['ftp://x'], ['https://u:p@x.com'], ['https://x.com/?a=1'], ['https://x.com/#a']])( 'rejects %p', (raw) => expect(normalizePublicUrl(raw)).toBeNull()); }); describe('trustProxySetting', () => { test('defaults to loopback only', () => { expect(trustProxySetting({})).toBe('loopback'); expect(trustProxySetting({ trustProxy: { weird: 1 } })).toBe('loopback'); }); test('passes through valid Express values', () => { expect(trustProxySetting({ trustProxy: false })).toBe(false); expect(trustProxySetting({ trustProxy: 1 })).toBe(1); expect(trustProxySetting({ trustProxy: '10.0.0.0/8, loopback' })).toBe('10.0.0.0/8, loopback'); expect(trustProxySetting({ trustProxy: ['loopback', '192.168.1.2'] })).toEqual(['loopback', '192.168.1.2']); }); }); describe('URLs in OAuth metadata, redirects and OpenAPI', () => { let server; let base; let app; let client; beforeAll(async () => { getDb().exec("CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, password_hash TEXT NOT NULL, is_admin INTEGER NOT NULL DEFAULT 0, permissions TEXT NOT NULL DEFAULT '{}')"); store.initApiSchema(getDb()); client = store.createClient({ name: 'App', redirectUris: ['https://app.example/cb'], createdBy: 'admin' }); app = express(); app.use(oauthRoutes); app.use('/api/v1', apiV1Routes); server = http.createServer(app).listen(0, '127.0.0.1'); await once(server, 'listening'); base = `http://127.0.0.1:${server.address().port}`; }); afterAll(() => server.close()); beforeEach(() => { delete mockConfig.publicUrl; app.set('trust proxy', trustProxySetting(mockConfig)); }); const proxied = { 'X-Forwarded-Proto': 'https', 'X-Forwarded-Host': 'files.example.com' }; const meta = async (headers) => (await fetch(`${base}/.well-known/oauth-authorization-server`, { headers })).json(); test('without proxy headers the direct URL is used', async () => { expect((await meta({})).issuer).toBe(base); }); test('trusted loopback proxy: X-Forwarded-Proto/Host give https', async () => { const m = await meta(proxied); expect(m.issuer).toBe('https://files.example.com'); expect(m.token_endpoint).toBe('https://files.example.com/oauth/token'); }); test('forwarded headers are ignored when the proxy is not trusted', async () => { app.set('trust proxy', trustProxySetting({ trustProxy: false })); expect((await meta(proxied)).issuer).toBe(base); app.set('trust proxy', trustProxySetting({ trustProxy: '10.1.2.3' })); expect((await meta(proxied)).issuer).toBe(base); }); test('publicUrl wins over everything, including a path prefix', async () => { mockConfig.publicUrl = 'https://example.org/files/'; const m = await meta({ 'X-Forwarded-Proto': 'http', 'X-Forwarded-Host': 'evil.example' }); expect(m.issuer).toBe('https://example.org/files'); expect(m.authorization_endpoint).toBe('https://example.org/files/oauth/authorize'); expect(m.service_documentation).toBe('https://example.org/files/api/v1/openapi.json'); }); test('invalid publicUrl falls back to the request', async () => { mockConfig.publicUrl = 'not a url'; expect((await meta(proxied)).issuer).toBe('https://files.example.com'); }); test('OpenAPI spec uses absolute https links', async () => { const spec = await (await fetch(`${base}/api/v1/openapi.json`, { headers: proxied })).json(); expect(spec.servers).toEqual([{ url: 'https://files.example.com/api/v1' }]); const flow = spec.components.securitySchemes.oauth2.flows.authorizationCode; expect(flow.authorizationUrl).toBe('https://files.example.com/oauth/authorize'); expect(flow.tokenUrl).toBe('https://files.example.com/oauth/token'); const index = await (await fetch(`${base}/api/v1`, { headers: proxied })).json(); expect(index.openapi).toBe('https://files.example.com/api/v1/openapi.json'); }); test('redirect iss and consent form action follow the public URL', async () => { mockConfig.publicUrl = 'https://example.org/files'; const q = new URLSearchParams({ response_type: 'code', client_id: client.clientId, redirect_uri: 'https://app.example/cb', state: 's' }); const r = await fetch(`${base}/oauth/authorize?${q}`, { redirect: 'manual' }); expect(new URL(r.headers.get('location')).searchParams.get('iss')).toBe('https://example.org/files'); q.set('code_challenge', 'a'.repeat(43)); q.set('code_challenge_method', 'S256'); const page = await (await fetch(`${base}/oauth/authorize?${q}`)).text(); expect(page).toContain('action="/files/oauth/authorize"'); expect(page).toContain('https://example.org/files/apps.html'); }); }); describe('Main UI links to the connected apps page', () => { test('user menu has a Connected apps link to /apps.html', () => { const html = fs.readFileSync(path.join(__dirname, '../public/index.html'), 'utf8'); const m = html.match(/]*>/); expect(m).toBeTruthy(); expect(m[0]).toContain('href="/apps.html"'); expect(m[0]).toContain('role="menuitem"'); const menu = html.slice(html.indexOf('aria-label="User actions"'), html.indexOf('id="btn-logout"')); expect(menu).toContain('btn-connected-apps'); }); });