BlueGit

timfa filemanager

Files

filemanager / tests / admin.routes.test.js

admin.routes.test.js

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