// Copyright (c) 2026 Gordon Bolton. MIT License. import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import fs from 'fs'; import loadSecrets from '../../../server/utils/loadSecrets'; describe('loadSecrets utility', () => { let originalEnv; let exitSpy; beforeEach(() => { originalEnv = { ...process.env }; exitSpy = vi.spyOn(process, 'exit').mockImplementation(() => {}); vi.spyOn(fs, 'readFileSync'); }); afterEach(() => { process.env = originalEnv; vi.restoreAllMocks(); }); it('does nothing if no _FILE env variables are set', () => { // Ensure mappings are not in env delete process.env.COOKIE_SECRET_FILE; delete process.env.COOKIE_SECRET; loadSecrets(); expect(fs.readFileSync).not.toHaveBeenCalled(); expect(process.env.COOKIE_SECRET).toBeUndefined(); expect(exitSpy).not.toHaveBeenCalled(); }); it('loads secrets successfully from a valid file', () => { process.env.COOKIE_SECRET_FILE = '/path/to/cookie_secret'; delete process.env.COOKIE_SECRET; vi.mocked(fs.readFileSync).mockReturnValue(' super_secret_value \n'); loadSecrets(); expect(fs.readFileSync).toHaveBeenCalledWith('/path/to/cookie_secret', 'utf8'); expect(process.env.COOKIE_SECRET).toBe('super_secret_value'); expect(exitSpy).not.toHaveBeenCalled(); }); it('logs a warning if both standard env and _FILE env are set', () => { process.env.COOKIE_SECRET_FILE = '/path/to/cookie_secret'; process.env.COOKIE_SECRET = 'existing_value'; vi.mocked(fs.readFileSync).mockReturnValue('new_value'); const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); loadSecrets(); expect(warnSpy).toHaveBeenCalledWith( expect.stringContaining('Both COOKIE_SECRET and COOKIE_SECRET_FILE are set') ); expect(process.env.COOKIE_SECRET).toBe('new_value'); expect(exitSpy).not.toHaveBeenCalled(); }); it('logs a warning and skips loading if file is empty', () => { process.env.COOKIE_SECRET_FILE = '/path/to/cookie_secret'; delete process.env.COOKIE_SECRET; vi.mocked(fs.readFileSync).mockReturnValue(' \n '); const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); loadSecrets(); expect(warnSpy).toHaveBeenCalledWith( expect.stringContaining('COOKIE_SECRET_FILE points to an empty file') ); expect(process.env.COOKIE_SECRET).toBeUndefined(); expect(exitSpy).not.toHaveBeenCalled(); }); it('exits with status 1 if file reading fails', () => { process.env.COOKIE_SECRET_FILE = '/path/to/cookie_secret'; delete process.env.COOKIE_SECRET; vi.mocked(fs.readFileSync).mockImplementation(() => { throw new Error('Permission denied'); }); const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); loadSecrets(); expect(errorSpy).toHaveBeenCalledWith( expect.stringContaining('Failed to read COOKIE_SECRET_FILE') ); expect(exitSpy).toHaveBeenCalledWith(1); }); });