BlueGit

timfa filemanager

Files

filemanager / tests / public-url.test.js

public-url.test.js

public-url.test.js 7.3 KiB Download Raw
1'use strict';
2
3// Public URL behind a reverse proxy: publicUrl in config wins, otherwise
4// Express "trust proxy" (default loopback) decides the scheme/host.
5
6const fs = require('fs');
7const path = require('path');
8const http = require('http');
9const express = require('express');
10const { once } = require('events');
11
12const mockConfig = { port: 3000, paths: [], rootAliases: {} };
13
14jest.mock('../server/db', () =>
15{
16 const { Database } = require('node-sqlite3-wasm');
17 let db;
18 return {
19 getDb: () => { if (!db) db = new Database(':memory:'); return db; },
20 initDb: () => {},
21 closeDb: () => {},
22 };
23});
24jest.mock('../server/config', () =>
25{
26 const actual = jest.requireActual('../server/config');
27 return { ...actual, loadConfig: () => mockConfig, saveConfig: () => {} };
28});
29jest.mock('../server/search-index', () => ({
30 searchFiles: async () => [], deleteIndexPath: () => {}, deleteIndexUnder: () => {}, rewriteIndexPaths: () => {}, reindexDirectoryTree: async () => {},
31}));
32jest.mock('../server/file-hash-queue', () => ({ enqueueFileHash: () => {} }));
33jest.mock('../server/thumbnail-cache', () => ({
34 getCachedThumbnailInfo: async () => null, getFilesWithThumbnailsInDir: async () => [], getFolderIconSourceFile: async () => null,
35 setFolderIconAssignment: () => {}, getThumbnailManifestSourcePathSet: async () => new Set(), needsPreviewImageConversion: () => false,
36 streamPreviewImage: async () => {}, MAX_PREVIEW_IMAGE_BYTES: 1, THUMB_HTTP_MAX_AGE_SEC: 1,
37}));
38
39const { normalizePublicUrl, trustProxySetting } = require('../server/public-url');
40const { getDb } = require('../server/db');
41const store = require('../server/api/store');
42const oauthRoutes = require('../server/api/oauth');
43const apiV1Routes = require('../server/api/v1');
44
45describe('normalizePublicUrl', () =>
46{
47 test.each([
48 ['https://files.example.com', 'https://files.example.com'],
49 ['https://files.example.com/', 'https://files.example.com'],
50 [' https://example.com/files/ ', 'https://example.com/files'],
51 ['http://127.0.0.1:3000', 'http://127.0.0.1:3000'],
52 ])('%s -> %s', (raw, out) => expect(normalizePublicUrl(raw)).toBe(out));
53
54 test.each([[''], [null], ['files.example.com'], ['ftp://x'], ['https://u:p@x.com'], ['https://x.com/?a=1'], ['https://x.com/#a']])(
55 'rejects %p', (raw) => expect(normalizePublicUrl(raw)).toBeNull());
56});
57
58describe('trustProxySetting', () =>
59{
60 test('defaults to loopback only', () =>
61 {
62 expect(trustProxySetting({})).toBe('loopback');
63 expect(trustProxySetting({ trustProxy: { weird: 1 } })).toBe('loopback');
64 });
65 test('passes through valid Express values', () =>
66 {
67 expect(trustProxySetting({ trustProxy: false })).toBe(false);
68 expect(trustProxySetting({ trustProxy: 1 })).toBe(1);
69 expect(trustProxySetting({ trustProxy: '10.0.0.0/8, loopback' })).toBe('10.0.0.0/8, loopback');
70 expect(trustProxySetting({ trustProxy: ['loopback', '192.168.1.2'] })).toEqual(['loopback', '192.168.1.2']);
71 });
72});
73
74describe('URLs in OAuth metadata, redirects and OpenAPI', () =>
75{
76 let server;
77 let base;
78 let app;
79 let client;
80
81 beforeAll(async () =>
82 {
83 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 '{}')");
84 store.initApiSchema(getDb());
85 client = store.createClient({ name: 'App', redirectUris: ['https://app.example/cb'], createdBy: 'admin' });
86 app = express();
87 app.use(oauthRoutes);
88 app.use('/api/v1', apiV1Routes);
89 server = http.createServer(app).listen(0, '127.0.0.1');
90 await once(server, 'listening');
91 base = `http://127.0.0.1:${server.address().port}`;
92 });
93
94 afterAll(() => server.close());
95
96 beforeEach(() =>
97 {
98 delete mockConfig.publicUrl;
99 app.set('trust proxy', trustProxySetting(mockConfig));
100 });
101
102 const proxied = { 'X-Forwarded-Proto': 'https', 'X-Forwarded-Host': 'files.example.com' };
103 const meta = async (headers) => (await fetch(`${base}/.well-known/oauth-authorization-server`, { headers })).json();
104
105 test('without proxy headers the direct URL is used', async () =>
106 {
107 expect((await meta({})).issuer).toBe(base);
108 });
109
110 test('trusted loopback proxy: X-Forwarded-Proto/Host give https', async () =>
111 {
112 const m = await meta(proxied);
113 expect(m.issuer).toBe('https://files.example.com');
114 expect(m.token_endpoint).toBe('https://files.example.com/oauth/token');
115 });
116
117 test('forwarded headers are ignored when the proxy is not trusted', async () =>
118 {
119 app.set('trust proxy', trustProxySetting({ trustProxy: false }));
120 expect((await meta(proxied)).issuer).toBe(base);
121 app.set('trust proxy', trustProxySetting({ trustProxy: '10.1.2.3' }));
122 expect((await meta(proxied)).issuer).toBe(base);
123 });
124
125 test('publicUrl wins over everything, including a path prefix', async () =>
126 {
127 mockConfig.publicUrl = 'https://example.org/files/';
128 const m = await meta({ 'X-Forwarded-Proto': 'http', 'X-Forwarded-Host': 'evil.example' });
129 expect(m.issuer).toBe('https://example.org/files');
130 expect(m.authorization_endpoint).toBe('https://example.org/files/oauth/authorize');
131 expect(m.service_documentation).toBe('https://example.org/files/api/v1/openapi.json');
132 });
133
134 test('invalid publicUrl falls back to the request', async () =>
135 {
136 mockConfig.publicUrl = 'not a url';
137 expect((await meta(proxied)).issuer).toBe('https://files.example.com');
138 });
139
140 test('OpenAPI spec uses absolute https links', async () =>
141 {
142 const spec = await (await fetch(`${base}/api/v1/openapi.json`, { headers: proxied })).json();
143 expect(spec.servers).toEqual([{ url: 'https://files.example.com/api/v1' }]);
144 const flow = spec.components.securitySchemes.oauth2.flows.authorizationCode;
145 expect(flow.authorizationUrl).toBe('https://files.example.com/oauth/authorize');
146 expect(flow.tokenUrl).toBe('https://files.example.com/oauth/token');
147 const index = await (await fetch(`${base}/api/v1`, { headers: proxied })).json();
148 expect(index.openapi).toBe('https://files.example.com/api/v1/openapi.json');
149 });
150
151 test('redirect iss and consent form action follow the public URL', async () =>
152 {
153 mockConfig.publicUrl = 'https://example.org/files';
154 const q = new URLSearchParams({ response_type: 'code', client_id: client.clientId, redirect_uri: 'https://app.example/cb', state: 's' });
155 const r = await fetch(`${base}/oauth/authorize?${q}`, { redirect: 'manual' });
156 expect(new URL(r.headers.get('location')).searchParams.get('iss')).toBe('https://example.org/files');
157
158 q.set('code_challenge', 'a'.repeat(43));
159 q.set('code_challenge_method', 'S256');
160 const page = await (await fetch(`${base}/oauth/authorize?${q}`)).text();
161 expect(page).toContain('action="/files/oauth/authorize"');
162 expect(page).toContain('https://example.org/files/apps.html');
163 });
164});
165
166describe('Main UI links to the connected apps page', () =>
167{
168 test('user menu has a Connected apps link to /apps.html', () =>
169 {
170 const html = fs.readFileSync(path.join(__dirname, '../public/index.html'), 'utf8');
171 const m = html.match(/<a id="btn-connected-apps"[^>]*>/);
172 expect(m).toBeTruthy();
173 expect(m[0]).toContain('href="/apps.html"');
174 expect(m[0]).toContain('role="menuitem"');
175 const menu = html.slice(html.indexOf('aria-label="User actions"'), html.indexOf('id="btn-logout"'));
176 expect(menu).toContain('btn-connected-apps');
177 });
178});