| 1 | 'use strict'; |
| 2 | |
| 3 | /** |
| 4 | * Unit tests for server/routes/admin.js — user CRUD and config management. |
| 5 | */ |
| 6 | |
| 7 | const express = require('express'); |
| 8 | const http = require('http'); |
| 9 | const { once } = require('events'); |
| 10 | const crypto = require('crypto'); |
| 11 | |
| 12 | // ── in-memory DB mock ─────────────────────────────────────────────────────── |
| 13 | jest.mock('../server/db', () => |
| 14 | { |
| 15 | const { Database } = require('node-sqlite3-wasm'); |
| 16 | let db; |
| 17 | function getDb () |
| 18 | { |
| 19 | if (!db) |
| 20 | { |
| 21 | db = new Database(':memory:'); |
| 22 | db.exec(` |
| 23 | CREATE TABLE IF NOT EXISTS users ( |
| 24 | id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 25 | username TEXT UNIQUE NOT NULL, |
| 26 | password_hash TEXT NOT NULL, |
| 27 | is_admin INTEGER NOT NULL DEFAULT 0, |
| 28 | permissions TEXT NOT NULL DEFAULT '{}' |
| 29 | ); |
| 30 | CREATE TABLE IF NOT EXISTS file_meta ( |
| 31 | file_path TEXT PRIMARY KEY, |
| 32 | uploader TEXT NOT NULL DEFAULT '', |
| 33 | downloaders TEXT NOT NULL DEFAULT '[]' |
| 34 | ); |
| 35 | `); |
| 36 | } |
| 37 | return db; |
| 38 | } |
| 39 | return { getDb, initDb: getDb }; |
| 40 | }); |
| 41 | |
| 42 | // ── config mock ───────────────────────────────────────────────────────────── |
| 43 | const mockConfig = { port: 3000, paths: ['/mnt/data', '/mnt/docs'] }; |
| 44 | jest.mock('../server/config', () => ({ |
| 45 | loadConfig: () => ({ ...mockConfig }), |
| 46 | saveConfig: (c) => Object.assign(mockConfig, c), |
| 47 | getEffectivePaths: (p) => p, |
| 48 | getAllowedRoot: () => null, |
| 49 | })); |
| 50 | |
| 51 | // ── auth mock — bypass JWT verification ───────────────────────────────────── |
| 52 | let mockUser = { id: 1, username: 'admin', isAdmin: true, permissions: {} }; |
| 53 | jest.mock('../server/auth', () => ({ |
| 54 | requireAuth: (req, res, next) => { req.user = mockUser; next(); }, |
| 55 | requireAdmin: (req, res, next) => |
| 56 | { |
| 57 | if (!req.user.isAdmin) return res.status(403).json({ error: 'Admin required.' }); |
| 58 | next(); |
| 59 | }, |
| 60 | createToken: () => 'mock-token', |
| 61 | getClientIp: () => '127.0.0.1', |
| 62 | getRegion: () => 'US:CA', |
| 63 | })); |
| 64 | |
| 65 | const adminRoutes = require('../server/routes/admin'); |
| 66 | const { getDb } = require('../server/db'); |
| 67 | const bcrypt = require('bcrypt'); |
| 68 | |
| 69 | jest.setTimeout(30000); |
| 70 | |
| 71 | // ── seed a default admin before anything runs ──────────────────────────────── |
| 72 | beforeAll(() => |
| 73 | { |
| 74 | const db = getDb(); |
| 75 | const hash = bcrypt.hashSync('admin1234', 4); // low rounds for speed |
| 76 | db.prepare('INSERT OR IGNORE INTO users (username, password_hash, is_admin, permissions) VALUES (?,?,1,?)') |
| 77 | .run(['admin', hash, '{}']); |
| 78 | }); |
| 79 | |
| 80 | // ── build minimal app ──────────────────────────────────────────────────────── |
| 81 | let server; |
| 82 | let baseUrl; |
| 83 | let shutdownForRestartMock; |
| 84 | |
| 85 | beforeAll(async () => |
| 86 | { |
| 87 | const app = express(); |
| 88 | shutdownForRestartMock = jest.fn(); |
| 89 | app.set('shutdownForRestart', shutdownForRestartMock); |
| 90 | app.use(express.json()); |
| 91 | app.use('/api/admin', adminRoutes); |
| 92 | app.use((err, req, res, next) => |
| 93 | { |
| 94 | res.status(err.status || 500).json({ error: err.message || 'Internal error' }); |
| 95 | }); |
| 96 | server = http.createServer(app); |
| 97 | server.listen(0); |
| 98 | await once(server, 'listening'); |
| 99 | baseUrl = `http://127.0.0.1:${server.address().port}`; |
| 100 | }); |
| 101 | |
| 102 | afterAll(() => server.close()); |
| 103 | |
| 104 | // ── helpers ────────────────────────────────────────────────────────────────── |
| 105 | function req (method, path, body) |
| 106 | { |
| 107 | const payload = body ? JSON.stringify(body) : undefined; |
| 108 | return new Promise((resolve, reject) => |
| 109 | { |
| 110 | const r = http.request(baseUrl + path, { |
| 111 | method, |
| 112 | headers: { |
| 113 | 'Content-Type': 'application/json', |
| 114 | ...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}), |
| 115 | }, |
| 116 | }, res => |
| 117 | { |
| 118 | let data = ''; |
| 119 | res.on('data', d => data += d); |
| 120 | res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) })); |
| 121 | }); |
| 122 | r.on('error', reject); |
| 123 | if (payload) r.write(payload); |
| 124 | r.end(); |
| 125 | }); |
| 126 | } |
| 127 | |
| 128 | // ── tests ───────────────────────────────────────────────────────────────────── |
| 129 | |
| 130 | describe('GET /api/admin/users', () => |
| 131 | { |
| 132 | test('returns the list of users', async () => |
| 133 | { |
| 134 | const { status, body } = await req('GET', '/api/admin/users'); |
| 135 | expect(status).toBe(200); |
| 136 | expect(Array.isArray(body.users)).toBe(true); |
| 137 | expect(body.users[0]).toMatchObject({ username: 'admin', isAdmin: true }); |
| 138 | }); |
| 139 | }); |
| 140 | |
| 141 | describe('POST /api/admin/users', () => |
| 142 | { |
| 143 | test('creates a new user', async () => |
| 144 | { |
| 145 | const { status, body } = await req('POST', '/api/admin/users', { |
| 146 | username: 'bob', password: 'bobpass1', isAdmin: false, permissions: {}, |
| 147 | }); |
| 148 | expect(status).toBe(201); |
| 149 | expect(body.ok).toBe(true); |
| 150 | }); |
| 151 | |
| 152 | test('rejects duplicate username', async () => |
| 153 | { |
| 154 | const { status } = await req('POST', '/api/admin/users', { |
| 155 | username: 'bob', password: 'bobpass2', isAdmin: false, permissions: {}, |
| 156 | }); |
| 157 | expect(status).toBe(409); |
| 158 | }); |
| 159 | |
| 160 | test('rejects duplicate username with different case', async () => |
| 161 | { |
| 162 | const { status } = await req('POST', '/api/admin/users', { |
| 163 | username: 'BoB', password: 'bobpass3', isAdmin: false, permissions: {}, |
| 164 | }); |
| 165 | expect(status).toBe(409); |
| 166 | }); |
| 167 | |
| 168 | test('rejects short password', async () => |
| 169 | { |
| 170 | const { status } = await req('POST', '/api/admin/users', { |
| 171 | username: 'carol', password: 'short', isAdmin: false, permissions: {}, |
| 172 | }); |
| 173 | expect(status).toBe(400); |
| 174 | }); |
| 175 | }); |
| 176 | |
| 177 | describe('PATCH /api/admin/users/:id', () => |
| 178 | { |
| 179 | let bobId; |
| 180 | |
| 181 | beforeAll(async () => |
| 182 | { |
| 183 | const { body } = await req('GET', '/api/admin/users'); |
| 184 | bobId = body.users.find(u => u.username === 'bob').id; |
| 185 | }); |
| 186 | |
| 187 | test('updates permissions', async () => |
| 188 | { |
| 189 | const { status, body } = await req('PATCH', `/api/admin/users/${bobId}`, { |
| 190 | permissions: { data: { read: true, write: false } }, |
| 191 | }); |
| 192 | expect(status).toBe(200); |
| 193 | expect(body.ok).toBe(true); |
| 194 | }); |
| 195 | |
| 196 | test('returns 404 for unknown user', async () => |
| 197 | { |
| 198 | const { status } = await req('PATCH', '/api/admin/users/99999', { isAdmin: false }); |
| 199 | expect(status).toBe(404); |
| 200 | }); |
| 201 | }); |
| 202 | |
| 203 | describe('DELETE /api/admin/users/:id', () => |
| 204 | { |
| 205 | let bobId; |
| 206 | |
| 207 | beforeAll(async () => |
| 208 | { |
| 209 | const { body } = await req('GET', '/api/admin/users'); |
| 210 | bobId = body.users.find(u => u.username === 'bob').id; |
| 211 | }); |
| 212 | |
| 213 | test('cannot delete own account', async () => |
| 214 | { |
| 215 | // mock user id is 1 (admin); bob is a different id — but we test self-delete guard |
| 216 | const adminId = mockUser.id; |
| 217 | const { status } = await req('DELETE', `/api/admin/users/${adminId}`); |
| 218 | expect(status).toBe(400); |
| 219 | }); |
| 220 | |
| 221 | test('deletes another user', async () => |
| 222 | { |
| 223 | const { status, body } = await req('DELETE', `/api/admin/users/${bobId}`); |
| 224 | expect(status).toBe(200); |
| 225 | expect(body.ok).toBe(true); |
| 226 | }); |
| 227 | |
| 228 | test('cannot delete the last admin', async () => |
| 229 | { |
| 230 | // Only 'admin' left; try to delete them (switch mockUser to be different) |
| 231 | const { body: users } = await req('GET', '/api/admin/users'); |
| 232 | const adminUser = users.users.find(u => u.username === 'admin'); |
| 233 | const { status } = await req('DELETE', `/api/admin/users/${adminUser.id}`); |
| 234 | // Our mockUser.id === 1 === adminUser.id, so it should fail with "cannot delete own account" |
| 235 | expect([400]).toContain(status); |
| 236 | }); |
| 237 | }); |
| 238 | |
| 239 | describe('GET /api/admin/config', () => |
| 240 | { |
| 241 | test('returns port and paths', async () => |
| 242 | { |
| 243 | const { status, body } = await req('GET', '/api/admin/config'); |
| 244 | expect(status).toBe(200); |
| 245 | expect(body.port).toBe(3000); |
| 246 | expect(Array.isArray(body.paths)).toBe(true); |
| 247 | }); |
| 248 | }); |
| 249 | |
| 250 | describe('PUT /api/admin/config', () => |
| 251 | { |
| 252 | test('saves new paths', async () => |
| 253 | { |
| 254 | const { status, body } = await req('PUT', '/api/admin/config', { |
| 255 | paths: ['/mnt/newpath'], |
| 256 | }); |
| 257 | expect(status).toBe(200); |
| 258 | expect(body.ok).toBe(true); |
| 259 | }); |
| 260 | |
| 261 | test('rejects non-array paths', async () => |
| 262 | { |
| 263 | const { status } = await req('PUT', '/api/admin/config', { paths: 'notanarray' }); |
| 264 | expect(status).toBe(400); |
| 265 | }); |
| 266 | |
| 267 | test('rejects invalid port', async () => |
| 268 | { |
| 269 | const { status } = await req('PUT', '/api/admin/config', { paths: [], port: 99999 }); |
| 270 | expect(status).toBe(400); |
| 271 | }); |
| 272 | }); |
| 273 | |
| 274 | describe('POST /api/admin/shutdown', () => |
| 275 | { |
| 276 | test('responds ok and invokes shutdown callback', async () => |
| 277 | { |
| 278 | shutdownForRestartMock.mockClear(); |
| 279 | const { status, body } = await req('POST', '/api/admin/shutdown'); |
| 280 | expect(status).toBe(200); |
| 281 | expect(body.ok).toBe(true); |
| 282 | |
| 283 | // Shutdown invocation is deferred via setImmediate(). |
| 284 | await new Promise(resolve => setImmediate(resolve)); |
| 285 | expect(shutdownForRestartMock).toHaveBeenCalledTimes(1); |
| 286 | }); |
| 287 | }); |