BlueGit

timfa filemanager

Files

filemanager / tests / admin.routes.test.js

admin.routes.test.js

Add debug uptime timer
timfa Tim Falken · pushed by timfa · 5 months ago
0ed9d51b History
admin.routes.test.js 23.7 KiB Download Raw
1'use strict';
2
3/**
4 * Unit tests for server/routes/admin.js — user CRUD and config management.
5 */
6
7const express = require('express');
8const http = require('http');
9const { once } = require('events');
10const crypto = require('crypto');
11const fs = require('fs');
12const os = require('os');
13const path = require('path');
14
15let mockVideoStreamSnapshot = {
16 streamRootDir: '/tmp/filemanager-video-streams',
17 activeSessionCount: 0,
18 activeLeaseCount: 0,
19 activeStreams: [],
20 orphanedOutputDirs: [],
21};
22
23let mockSubtitleSnapshot = {
24 eventCache: { entries: 0, bytes: 0, maxItems: 3, maxBytes: 0 },
25 frameCache: { entries: 0, bytes: 0, maxItems: 50, maxBytes: 0 },
26 byFile: {},
27};
28
29let mockRestartSchedulerSnapshot = {
30 running: true,
31 startedAt: Date.now(),
32 lastTickAt: Date.now(),
33 nextDueAt: Date.now() + 3600000,
34 pendingSinceAt: null,
35 lastShutdownAt: null,
36 lastDecision: 'waiting-next-window',
37 lastError: null,
38 underSystemd: true,
39 config: { enabled: false, cadence: 'daily', time: '04:00' },
40 intervalMs: 60000,
41};
42
43// ── child_process mock — controlled per test ──────────────────────────────────
44let mockExecFileImpl = null;
45jest.mock('child_process', () =>
46{
47 const real = jest.requireActual('child_process');
48 return {
49 ...real,
50 execFile: jest.fn((...args) =>
51 {
52 const cb = args[args.length - 1];
53 if (typeof mockExecFileImpl === 'function')
54 {
55 mockExecFileImpl(...args);
56 return;
57 }
58 // Default: simulate git not available.
59 cb(new Error('git not found'));
60 }),
61 };
62});
63
64// ── in-memory DB mock ───────────────────────────────────────────────────────
65jest.mock('../server/db', () =>
66{
67 const { Database } = require('node-sqlite3-wasm');
68 let db;
69 function getDb ()
70 {
71 if (!db)
72 {
73 db = new Database(':memory:');
74 db.exec(`
75 CREATE TABLE IF NOT EXISTS users (
76 id INTEGER PRIMARY KEY AUTOINCREMENT,
77 username TEXT UNIQUE NOT NULL,
78 password_hash TEXT NOT NULL,
79 is_admin INTEGER NOT NULL DEFAULT 0,
80 permissions TEXT NOT NULL DEFAULT '{}'
81 );
82 CREATE TABLE IF NOT EXISTS file_meta (
83 file_path TEXT PRIMARY KEY,
84 uploader TEXT NOT NULL DEFAULT '',
85 downloaders TEXT NOT NULL DEFAULT '[]'
86 );
87 CREATE TABLE IF NOT EXISTS auth_sessions (
88 session_id TEXT PRIMARY KEY,
89 username TEXT NOT NULL,
90 ip TEXT NOT NULL,
91 region TEXT NOT NULL,
92 fp_hash TEXT NOT NULL,
93 created_at INTEGER NOT NULL,
94 last_seen_at INTEGER NOT NULL,
95 revoked_at INTEGER
96 );
97 CREATE TABLE IF NOT EXISTS share_tokens (
98 token TEXT PRIMARY KEY,
99 file_path TEXT NOT NULL,
100 is_dir INTEGER NOT NULL DEFAULT 0,
101 created_by TEXT NOT NULL,
102 created_at INTEGER NOT NULL,
103 expires_at INTEGER NOT NULL
104 );
105 `);
106 }
107 return db;
108 }
109 return { getDb, initDb: getDb };
110});
111
112jest.mock('../server/video-stream', () => ({
113 getVideoStreamDebugSnapshot: () => mockVideoStreamSnapshot,
114}));
115
116jest.mock('../server/image-subtitles', () => ({
117 getImageSubtitleDebugSnapshot: () => mockSubtitleSnapshot,
118}));
119
120jest.mock('../server/restart-scheduler', () => ({
121 getRestartSchedulerSnapshot: () => mockRestartSchedulerSnapshot,
122}));
123
124// ── config mock ─────────────────────────────────────────────────────────────
125const mockConfig = {
126 port: 3000,
127 paths: ['/mnt/data', '/mnt/docs'],
128 userPath: null,
129 scheduledRestart: { enabled: false, cadence: 'daily', time: '04:00' },
130};
131jest.mock('../server/config', () => ({
132 loadConfig: () => ({ ...mockConfig }),
133 saveConfig: (c) => Object.assign(mockConfig, c),
134 getEffectivePaths: (p) => p,
135 getAllowedRoot: () => null,
136}));
137
138// ── auth mock — bypass JWT verification ─────────────────────────────────────
139let mockUser = { id: 1, username: 'admin', isAdmin: true, permissions: {} };
140jest.mock('../server/auth', () => ({
141 requireAuth: (req, res, next) => { req.user = mockUser; next(); },
142 requireAdmin: (req, res, next) =>
143 {
144 if (!req.user.isAdmin) return res.status(403).json({ error: 'Admin required.' });
145 next();
146 },
147 createToken: () => 'mock-token',
148 getClientIp: () => '127.0.0.1',
149 getRegion: () => 'US:CA',
150}));
151
152const adminRoutes = require('../server/routes/admin');
153const { getDb } = require('../server/db');
154const bcrypt = require('bcrypt');
155
156jest.setTimeout(30000);
157
158// ── seed a default admin before anything runs ────────────────────────────────
159beforeAll(() =>
160{
161 const db = getDb();
162 const hash = bcrypt.hashSync('admin1234', 4); // low rounds for speed
163 db.prepare('INSERT OR IGNORE INTO users (username, password_hash, is_admin, permissions) VALUES (?,?,1,?)')
164 .run(['admin', hash, '{}']);
165});
166
167// ── build minimal app ────────────────────────────────────────────────────────
168let server;
169let baseUrl;
170let shutdownForRestartMock;
171
172beforeAll(async () =>
173{
174 const app = express();
175 shutdownForRestartMock = jest.fn();
176 app.set('shutdownForRestart', shutdownForRestartMock);
177 app.use(express.json());
178 app.use('/api/admin', adminRoutes);
179 app.use((err, req, res, next) =>
180 {
181 res.status(err.status || 500).json({ error: err.message || 'Internal error' });
182 });
183 server = http.createServer(app);
184 server.listen(0);
185 await once(server, 'listening');
186 baseUrl = `http://127.0.0.1:${server.address().port}`;
187});
188
189afterAll(() => server.close());
190
191// ── helpers ──────────────────────────────────────────────────────────────────
192function req (method, path, body)
193{
194 const payload = body ? JSON.stringify(body) : undefined;
195 return new Promise((resolve, reject) =>
196 {
197 const r = http.request(baseUrl + path, {
198 method,
199 headers: {
200 'Content-Type': 'application/json',
201 ...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}),
202 },
203 }, res =>
204 {
205 let data = '';
206 res.on('data', d => data += d);
207 res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) }));
208 });
209 r.on('error', reject);
210 if (payload) r.write(payload);
211 r.end();
212 });
213}
214
215// ── tests ─────────────────────────────────────────────────────────────────────
216
217describe('GET /api/admin/users', () =>
218{
219 test('returns the list of users', async () =>
220 {
221 const { status, body } = await req('GET', '/api/admin/users');
222 expect(status).toBe(200);
223 expect(Array.isArray(body.users)).toBe(true);
224 expect(body.users[0]).toMatchObject({ username: 'admin', isAdmin: true });
225 });
226});
227
228describe('POST /api/admin/users', () =>
229{
230 test('creates a new user', async () =>
231 {
232 const { status, body } = await req('POST', '/api/admin/users', {
233 username: 'bob', password: 'bobpass1', isAdmin: false, permissions: {},
234 });
235 expect(status).toBe(201);
236 expect(body.ok).toBe(true);
237 });
238
239 test('rejects duplicate username', async () =>
240 {
241 const { status } = await req('POST', '/api/admin/users', {
242 username: 'bob', password: 'bobpass2', isAdmin: false, permissions: {},
243 });
244 expect(status).toBe(409);
245 });
246
247 test('rejects duplicate username with different case', async () =>
248 {
249 const { status } = await req('POST', '/api/admin/users', {
250 username: 'BoB', password: 'bobpass3', isAdmin: false, permissions: {},
251 });
252 expect(status).toBe(409);
253 });
254
255 test('rejects short password', async () =>
256 {
257 const { status } = await req('POST', '/api/admin/users', {
258 username: 'carol', password: 'short', isAdmin: false, permissions: {},
259 });
260 expect(status).toBe(400);
261 });
262
263 test('normalizes permissions so write implies read on create', async () =>
264 {
265 const { status } = await req('POST', '/api/admin/users', {
266 username: 'dora',
267 password: 'dora-pass1',
268 isAdmin: false,
269 permissions: { data: { read: false, write: true } },
270 });
271 expect(status).toBe(201);
272
273 const { body } = await req('GET', '/api/admin/users');
274 const dora = body.users.find(u => u.username === 'dora');
275 expect(dora.permissions).toMatchObject({ data: { read: true, write: true } });
276 });
277});
278
279describe('PATCH /api/admin/users/:id', () =>
280{
281 let bobId;
282
283 beforeAll(async () =>
284 {
285 const { body } = await req('GET', '/api/admin/users');
286 bobId = body.users.find(u => u.username === 'bob').id;
287 });
288
289 test('updates permissions', async () =>
290 {
291 const { status, body } = await req('PATCH', `/api/admin/users/${bobId}`, {
292 permissions: { data: { read: true, write: false } },
293 });
294 expect(status).toBe(200);
295 expect(body.ok).toBe(true);
296 });
297
298 test('returns 404 for unknown user', async () =>
299 {
300 const { status } = await req('PATCH', '/api/admin/users/99999', { isAdmin: false });
301 expect(status).toBe(404);
302 });
303
304 test('normalizes permissions so write implies read on update', async () =>
305 {
306 const { status } = await req('PATCH', `/api/admin/users/${bobId}`, {
307 permissions: { data: { read: false, write: true } },
308 });
309 expect(status).toBe(200);
310
311 const { body } = await req('GET', '/api/admin/users');
312 const bob = body.users.find(u => u.id === bobId);
313 expect(bob.permissions).toMatchObject({ data: { read: true, write: true } });
314 });
315
316 test('rejects removing own admin privileges', async () =>
317 {
318 const { status, body } = await req('PATCH', `/api/admin/users/${mockUser.id}`, {
319 isAdmin: false,
320 });
321 expect(status).toBe(400);
322 expect(body.error).toMatch(/own admin privileges/i);
323
324 const usersRes = await req('GET', '/api/admin/users');
325 const me = usersRes.body.users.find(u => String(u.id) === String(mockUser.id));
326 expect(me).toBeTruthy();
327 expect(me.isAdmin).toBe(true);
328 });
329});
330
331describe('DELETE /api/admin/users/:id', () =>
332{
333 let bobId;
334
335 beforeAll(async () =>
336 {
337 const { body } = await req('GET', '/api/admin/users');
338 bobId = body.users.find(u => u.username === 'bob').id;
339 });
340
341 test('cannot delete own account', async () =>
342 {
343 // mock user id is 1 (admin); bob is a different id — but we test self-delete guard
344 const adminId = mockUser.id;
345 const { status } = await req('DELETE', `/api/admin/users/${adminId}`);
346 expect(status).toBe(400);
347 });
348
349 test('deletes another user', async () =>
350 {
351 const { status, body } = await req('DELETE', `/api/admin/users/${bobId}`);
352 expect(status).toBe(200);
353 expect(body.ok).toBe(true);
354 });
355
356 test('cannot delete the last admin', async () =>
357 {
358 // Only 'admin' left; try to delete them (switch mockUser to be different)
359 const { body: users } = await req('GET', '/api/admin/users');
360 const adminUser = users.users.find(u => u.username === 'admin');
361 const { status } = await req('DELETE', `/api/admin/users/${adminUser.id}`);
362 // Our mockUser.id === 1 === adminUser.id, so it should fail with "cannot delete own account"
363 expect([400]).toContain(status);
364 });
365
366 test('deletes an empty personal user folder when deleting that user account', async () =>
367 {
368 const userFolderRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-admin-userfolders-'));
369 mockConfig.userPath = userFolderRoot;
370
371 const db = getDb();
372 const hash = bcrypt.hashSync('freshpass1', 4);
373 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
374 .run(['emptyfolderuser', hash, 0, '{}']);
375
376 const created = db.prepare('SELECT id FROM users WHERE username = ?').get(['emptyfolderuser']);
377 const folderPath = path.join(userFolderRoot, 'emptyfolderuser');
378 fs.mkdirSync(folderPath, { recursive: true });
379
380 try
381 {
382 const { status, body } = await req('DELETE', `/api/admin/users/${created.id}`);
383 expect(status).toBe(200);
384 expect(body.ok).toBe(true);
385 expect(fs.existsSync(folderPath)).toBe(false);
386 } finally
387 {
388 mockConfig.userPath = null;
389 fs.rmSync(userFolderRoot, { recursive: true, force: true });
390 }
391 });
392
393 test('keeps non-empty personal user folder when deleting that user account', async () =>
394 {
395 const userFolderRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-admin-userfolders-'));
396 mockConfig.userPath = userFolderRoot;
397
398 const db = getDb();
399 const hash = bcrypt.hashSync('freshpass2', 4);
400 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
401 .run(['nonemptyuser', hash, 0, '{}']);
402
403 const created = db.prepare('SELECT id FROM users WHERE username = ?').get(['nonemptyuser']);
404 const folderPath = path.join(userFolderRoot, 'nonemptyuser');
405 fs.mkdirSync(folderPath, { recursive: true });
406 fs.writeFileSync(path.join(folderPath, 'keep.txt'), 'keep');
407
408 try
409 {
410 const { status, body } = await req('DELETE', `/api/admin/users/${created.id}`);
411 expect(status).toBe(200);
412 expect(body.ok).toBe(true);
413 expect(fs.existsSync(folderPath)).toBe(true);
414 } finally
415 {
416 mockConfig.userPath = null;
417 fs.rmSync(userFolderRoot, { recursive: true, force: true });
418 }
419 });
420});
421
422describe('GET /api/admin/orphan-userfolders', () =>
423{
424 test('returns only non-empty orphaned folders and deletes empty orphan folders', async () =>
425 {
426 const userFolderRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-admin-userfolders-'));
427 mockConfig.userPath = userFolderRoot;
428
429 const linkedFolder = path.join(userFolderRoot, 'linkeduser');
430 const orphanFolder = path.join(userFolderRoot, 'ghostuser');
431 const emptyOrphanFolder = path.join(userFolderRoot, 'emptyghost');
432
433 fs.mkdirSync(linkedFolder, { recursive: true });
434 fs.mkdirSync(orphanFolder, { recursive: true });
435 fs.mkdirSync(emptyOrphanFolder, { recursive: true });
436 fs.writeFileSync(path.join(orphanFolder, 'file.txt'), 'hello');
437
438 const db = getDb();
439 const hash = bcrypt.hashSync('linked-pass1', 4);
440 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
441 .run(['linkeduser', hash, 0, '{}']);
442
443 try
444 {
445 const { status, body } = await req('GET', '/api/admin/orphan-userfolders');
446 expect(status).toBe(200);
447 expect(Array.isArray(body.folders)).toBe(true);
448 expect(body.folders).toEqual([
449 {
450 folderName: 'ghostuser',
451 path: orphanFolder,
452 itemCount: 1,
453 },
454 ]);
455 expect(fs.existsSync(emptyOrphanFolder)).toBe(false);
456 } finally
457 {
458 mockConfig.userPath = null;
459 fs.rmSync(userFolderRoot, { recursive: true, force: true });
460 }
461 });
462});
463
464describe('GET /api/admin/config', () =>
465{
466 test('returns port and paths', async () =>
467 {
468 const { status, body } = await req('GET', '/api/admin/config');
469 expect(status).toBe(200);
470 expect(body.port).toBe(3000);
471 expect(Array.isArray(body.paths)).toBe(true);
472 expect(body.scheduledRestart).toEqual(expect.objectContaining({
473 enabled: expect.any(Boolean),
474 cadence: expect.any(String),
475 time: expect.any(String),
476 }));
477 });
478});
479
480describe('GET /api/admin/debug/stream-stats', () =>
481{
482 test('includes active streams and cached-only video files with zero viewers', async () =>
483 {
484 const now = Date.now();
485 mockVideoStreamSnapshot = {
486 streamRootDir: '/tmp/filemanager-video-streams',
487 activeSessionCount: 1,
488 activeLeaseCount: 2,
489 activeStreams: [
490 {
491 sessionId: 'lease-live',
492 sourcePath: '/videos/live.mkv',
493 outputDir: '/tmp/filemanager-video-streams/live',
494 viewers: 2,
495 output: {
496 totalFiles: 12,
497 totalBytes: 12000000,
498 segmentFiles: 10,
499 segmentBytes: 11000000,
500 },
501 },
502 ],
503 orphanedOutputDirs: [],
504 };
505
506 mockSubtitleSnapshot = {
507 eventCache: { entries: 2, bytes: 4096, maxItems: 3, maxBytes: 52428800 },
508 frameCache: { entries: 4, bytes: 8192, maxItems: 50, maxBytes: 50331648 },
509 byFile: {
510 '/videos/live.mkv': {
511 filePath: '/videos/live.mkv',
512 eventEntries: 1,
513 eventBytes: 2048,
514 eventCount: 30,
515 eventImageBytes: 1500,
516 frameEntries: 2,
517 frameBytes: 4096,
518 },
519 '/videos/cached-only.mkv': {
520 filePath: '/videos/cached-only.mkv',
521 eventEntries: 1,
522 eventBytes: 2048,
523 eventCount: 20,
524 eventImageBytes: 1300,
525 frameEntries: 2,
526 frameBytes: 4096,
527 },
528 },
529 };
530
531 const db = getDb();
532 db.prepare(`INSERT OR REPLACE INTO auth_sessions (
533 session_id, username, ip, region, fp_hash, created_at, last_seen_at, revoked_at
534 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`)
535 .run(['sess-debug', 'admin', '127.0.0.1', 'EU', 'fp', now - 1000, now - 1000, null]);
536
537 const { status, body } = await req('GET', '/api/admin/debug/stream-stats');
538 expect(status).toBe(200);
539 expect(Array.isArray(body.videoFiles)).toBe(true);
540 expect(body.maintenance).toEqual(expect.objectContaining({
541 uptimeMs: expect.any(Number),
542 startedAt: expect.any(Number),
543 rows: expect.objectContaining({
544 authSessionsTotal: expect.any(Number),
545 shareTokensTotal: expect.any(Number),
546 }),
547 scheduledRestart: expect.objectContaining({
548 intervalMs: expect.any(Number),
549 }),
550 }));
551
552 const live = body.videoFiles.find((row) => row.filePath === '/videos/live.mkv');
553 expect(live).toBeTruthy();
554 expect(live.viewers).toBe(2);
555
556 const cachedOnly = body.videoFiles.find((row) => row.filePath === '/videos/cached-only.mkv');
557 expect(cachedOnly).toBeTruthy();
558 expect(cachedOnly.viewers).toBe(0);
559 expect(cachedOnly.subtitleCache.eventEntries).toBe(1);
560 expect(body.subtitleDebugLog).toEqual(expect.objectContaining({
561 path: expect.stringContaining('filemanager-subtitle-debug-logs'),
562 files: expect.any(Number),
563 bytes: expect.any(Number),
564 }));
565 });
566});
567
568describe('PUT /api/admin/config', () =>
569{
570 test('saves new paths', async () =>
571 {
572 const { status, body } = await req('PUT', '/api/admin/config', {
573 paths: ['/mnt/newpath'],
574 });
575 expect(status).toBe(200);
576 expect(body.ok).toBe(true);
577 });
578
579 test('rejects non-array paths', async () =>
580 {
581 const { status } = await req('PUT', '/api/admin/config', { paths: 'notanarray' });
582 expect(status).toBe(400);
583 });
584
585 test('rejects invalid port', async () =>
586 {
587 const { status } = await req('PUT', '/api/admin/config', { paths: [], port: 99999 });
588 expect(status).toBe(400);
589 });
590
591 test('saves scheduled restart config when running under systemd', async () =>
592 {
593 const origInvocationId = process.env.INVOCATION_ID;
594 process.env.INVOCATION_ID = 'test-invocation';
595
596 try
597 {
598 const { status, body } = await req('PUT', '/api/admin/config', {
599 paths: ['/mnt/data'],
600 scheduledRestart: {
601 enabled: true,
602 cadence: 'weekly',
603 time: '03:45',
604 },
605 });
606 expect(status).toBe(200);
607 expect(body.ok).toBe(true);
608
609 const readback = await req('GET', '/api/admin/config');
610 expect(readback.body.scheduledRestart).toEqual({
611 enabled: true,
612 cadence: 'weekly',
613 time: '03:45',
614 });
615 } finally
616 {
617 if (origInvocationId === undefined) delete process.env.INVOCATION_ID;
618 else process.env.INVOCATION_ID = origInvocationId;
619 }
620 });
621
622 test('rejects scheduled restart config when not running under systemd', async () =>
623 {
624 const origInvocationId = process.env.INVOCATION_ID;
625 delete process.env.INVOCATION_ID;
626
627 try
628 {
629 const { status } = await req('PUT', '/api/admin/config', {
630 paths: ['/mnt/data'],
631 scheduledRestart: {
632 enabled: true,
633 cadence: 'daily',
634 time: '02:15',
635 },
636 });
637 expect(status).toBe(400);
638 } finally
639 {
640 if (origInvocationId === undefined) delete process.env.INVOCATION_ID;
641 else process.env.INVOCATION_ID = origInvocationId;
642 }
643 });
644});
645
646describe('POST /api/admin/shutdown', () =>
647{
648 test('responds ok and invokes shutdown callback', async () =>
649 {
650 shutdownForRestartMock.mockClear();
651 const { status, body } = await req('POST', '/api/admin/shutdown');
652 expect(status).toBe(200);
653 expect(body.ok).toBe(true);
654
655 // Shutdown invocation is deferred via setImmediate().
656 await new Promise(resolve => setImmediate(resolve));
657 expect(shutdownForRestartMock).toHaveBeenCalledTimes(1);
658 });
659});
660
661describe('GET /api/admin/update-status', () =>
662{
663 const origInvocationId = process.env.INVOCATION_ID;
664
665 afterEach(() =>
666 {
667 mockExecFileImpl = null;
668 if (origInvocationId === undefined)
669 delete process.env.INVOCATION_ID;
670 else
671 process.env.INVOCATION_ID = origInvocationId;
672 });
673
674 test('returns underSystemd=false when INVOCATION_ID is not set', async () =>
675 {
676 delete process.env.INVOCATION_ID;
677 const { status, body } = await req('GET', '/api/admin/update-status');
678 expect(status).toBe(200);
679 expect(body.underSystemd).toBe(false);
680 expect(body.commitsAhead).toEqual([]);
681 });
682
683 test('returns underSystemd=true and commitsAhead when INVOCATION_ID is set and git reports commits', async () =>
684 {
685 process.env.INVOCATION_ID = 'test-invocation-id';
686 // git fetch succeeds, then git log returns two commits.
687 let callCount = 0;
688 let logArgs = null;
689 mockExecFileImpl = (_cmd, _args, _opts, cb) =>
690 {
691 callCount++;
692 if (callCount === 1) cb(null, { stdout: '', stderr: '' }); // git fetch
693 else
694 {
695 logArgs = _args;
696 cb(null, {
697 stdout: 'abc1234567890\x1fFix bug\x1fThis fixes an issue users were hitting.\x1e'
698 + 'def5678901234\x1fAdd feature\x1fUsers can now do the new thing.\x1e',
699 stderr: '',
700 });
701 }
702 };
703 const { status, body } = await req('GET', '/api/admin/update-status');
704 expect(status).toBe(200);
705 expect(body.underSystemd).toBe(true);
706 expect(logArgs).toContain('--no-merges');
707 expect(body.commitsAhead).toEqual([
708 {
709 hash: 'abc1234567890',
710 subject: 'Fix bug',
711 body: 'This fixes an issue users were hitting.',
712 },
713 {
714 hash: 'def5678901234',
715 subject: 'Add feature',
716 body: 'Users can now do the new thing.',
717 },
718 ]);
719 });
720
721 test('returns underSystemd=true and empty commitsAhead when git is up to date', async () =>
722 {
723 process.env.INVOCATION_ID = 'test-invocation-id';
724 let callCount = 0;
725 mockExecFileImpl = (_cmd, _args, _opts, cb) =>
726 {
727 callCount++;
728 cb(null, { stdout: '', stderr: '' }); // fetch and log both return empty
729 };
730 const { status, body } = await req('GET', '/api/admin/update-status');
731 expect(status).toBe(200);
732 expect(body.underSystemd).toBe(true);
733 expect(body.commitsAhead).toEqual([]);
734 });
735
736 test('returns underSystemd=true and empty commitsAhead when git fails', async () =>
737 {
738 process.env.INVOCATION_ID = 'test-invocation-id';
739 mockExecFileImpl = (_cmd, _args, _opts, cb) =>
740 {
741 cb(new Error('git: not found'));
742 };
743 const { status, body } = await req('GET', '/api/admin/update-status');
744 expect(status).toBe(200);
745 expect(body.underSystemd).toBe(true);
746 expect(body.commitsAhead).toEqual([]);
747 });
748});