Enhances security checks and mocks fs module in tests

Updates security check patterns to include brackets for improved command injection prevention. Enhances test reliability by mocking Node's fs module to replace custom mock functions, aligning test behavior closer to actual usage scenarios and ensuring consistent outcomes.

No specific issue reference.
This commit is contained in:
AlexKucera committed 2025-11-09 15:26:33 +01:00
1 parent d39ddd189e
commit b0f8755a56
3 files changed
+61 -42

No files matched your search

+1 -1
View File
@@ -221,7 +221,7 @@ export class SecurityUtils {
// Check for command injection attempts // Check for command injection attempts
const dangerousPatterns = [ const dangerousPatterns = [
/[;&|`$<>]/, // Shell metacharacters that can't appear in safe paths /[;&|`$<>{}[\]]/, // Shell metacharacters that can't appear in safe paths
// eslint-disable-next-line no-control-regex -- Intentionally checking for null byte character for security validation // eslint-disable-next-line no-control-regex -- Intentionally checking for null byte character for security validation
/\x00/, // Null bytes /\x00/, // Null bytes
/\n|\r/, // Newlines /\n|\r/, // Newlines
+1 -1
View File
@@ -154,7 +154,7 @@ describe('SecurityUtils', () => {
it('should return appropriate error for reserved names', () => { it('should return appropriate error for reserved names', () => {
const error = SecurityUtils.getPathValidationError('CON'); const error = SecurityUtils.getPathValidationError('CON');
expect(error).toBe('Reserved system names are not allowed as folder names'); expect(error).toBe('Reserved system names are not allowed in paths (found: CON)');
}); });
it('should return generic error for unknown issues', () => { it('should return generic error for unknown issues', () => {
+59 -40
View File
@@ -2,11 +2,35 @@ import { describe, it, expect, beforeEach, vi } from 'vitest';
import { TempDirectoryManager } from '../src/core/TempDirectoryManager'; import { TempDirectoryManager } from '../src/core/TempDirectoryManager';
import type { App } from 'obsidian'; import type { App } from 'obsidian';
// Create mock functions that will be used in vi.mock - using vi.hoisted to ensure they're available
const { mockFsAccess, mockFsMkdir, mockFsReaddir, mockFsStat, mockFsUnlink } = vi.hoisted(() => ({
mockFsAccess: vi.fn(),
mockFsMkdir: vi.fn(),
mockFsReaddir: vi.fn(),
mockFsStat: vi.fn(),
mockFsUnlink: vi.fn(),
}));
// Mock the fs module
vi.mock('fs', () => ({
default: {},
promises: {
access: mockFsAccess,
mkdir: mockFsMkdir,
readdir: mockFsReaddir,
stat: mockFsStat,
unlink: mockFsUnlink,
},
}));
describe('TempDirectoryManager', () => { describe('TempDirectoryManager', () => {
let mockApp: App; let mockApp: App;
let mockVaultAdapter: any; let mockVaultAdapter: any;
beforeEach(() => { beforeEach(() => {
// Reset all mocks before each test
vi.clearAllMocks();
// Reset mocks before each test // Reset mocks before each test
mockVaultAdapter = { mockVaultAdapter = {
exists: vi.fn(), exists: vi.fn(),
@@ -114,8 +138,9 @@ describe('TempDirectoryManager', () => {
describe('ensureTempDir', () => { describe('ensureTempDir', () => {
it('should create directory if it does not exist', async () => { it('should create directory if it does not exist', async () => {
mockVaultAdapter.exists.mockResolvedValue(false); // fs.access rejects when directory doesn't exist
mockVaultAdapter.mkdir.mockResolvedValue(undefined); mockFsAccess.mockRejectedValue(new Error('ENOENT'));
mockFsMkdir.mockResolvedValue(undefined);
const manager = new TempDirectoryManager({ const manager = new TempDirectoryManager({
vaultPath: '/vault', vaultPath: '/vault',
@@ -126,13 +151,14 @@ describe('TempDirectoryManager', () => {
const result = await manager.ensureTempDir('images'); const result = await manager.ensureTempDir('images');
expect(mockVaultAdapter.exists).toHaveBeenCalledOnce(); expect(mockFsAccess).toHaveBeenCalledOnce();
expect(mockVaultAdapter.mkdir).toHaveBeenCalledOnce(); expect(mockFsMkdir).toHaveBeenCalledOnce();
expect(result).toContain('temp-images'); expect(result).toContain('temp-images');
}); });
it('should not create directory if it already exists', async () => { it('should not create directory if it already exists', async () => {
mockVaultAdapter.exists.mockResolvedValue(true); // fs.access resolves when directory exists
mockFsAccess.mockResolvedValue(undefined);
const manager = new TempDirectoryManager({ const manager = new TempDirectoryManager({
vaultPath: '/vault', vaultPath: '/vault',
@@ -143,14 +169,14 @@ describe('TempDirectoryManager', () => {
const result = await manager.ensureTempDir('images'); const result = await manager.ensureTempDir('images');
expect(mockVaultAdapter.exists).toHaveBeenCalledOnce(); expect(mockFsAccess).toHaveBeenCalledOnce();
expect(mockVaultAdapter.mkdir).not.toHaveBeenCalled(); expect(mockFsMkdir).not.toHaveBeenCalled();
expect(result).toContain('temp-images'); expect(result).toContain('temp-images');
}); });
it('should handle both images and pandoc directories', async () => { it('should handle both images and pandoc directories', async () => {
mockVaultAdapter.exists.mockResolvedValue(false); mockFsAccess.mockRejectedValue(new Error('ENOENT'));
mockVaultAdapter.mkdir.mockResolvedValue(undefined); mockFsMkdir.mockResolvedValue(undefined);
const manager = new TempDirectoryManager({ const manager = new TempDirectoryManager({
vaultPath: '/vault', vaultPath: '/vault',
@@ -164,18 +190,16 @@ describe('TempDirectoryManager', () => {
expect(imagesDir).toContain('temp-images'); expect(imagesDir).toContain('temp-images');
expect(pandocDir).toContain('temp-pandoc'); expect(pandocDir).toContain('temp-pandoc');
expect(mockVaultAdapter.mkdir).toHaveBeenCalledTimes(2); expect(mockFsMkdir).toHaveBeenCalledTimes(2);
}); });
}); });
describe('cleanupTempDir', () => { describe('cleanupTempDir', () => {
it('should remove all files from temp directory', async () => { it('should remove all files from temp directory', async () => {
mockVaultAdapter.exists.mockResolvedValue(true); mockFsAccess.mockResolvedValue(undefined);
mockVaultAdapter.list.mockResolvedValue({ mockFsReaddir.mockResolvedValue(['file1.png', 'file2.png', 'file3.typ']);
files: ['file1.png', 'file2.png', 'file3.typ'], mockFsStat.mockResolvedValue({ isFile: () => true } as any);
folders: [], mockFsUnlink.mockResolvedValue(undefined);
});
mockVaultAdapter.remove.mockResolvedValue(undefined);
const manager = new TempDirectoryManager({ const manager = new TempDirectoryManager({
vaultPath: '/vault', vaultPath: '/vault',
@@ -187,11 +211,11 @@ describe('TempDirectoryManager', () => {
const result = await manager.cleanupTempDir('images'); const result = await manager.cleanupTempDir('images');
expect(result).toBe(true); expect(result).toBe(true);
expect(mockVaultAdapter.remove).toHaveBeenCalledTimes(3); expect(mockFsUnlink).toHaveBeenCalledTimes(3);
}); });
it('should return true if directory does not exist', async () => { it('should return true if directory does not exist', async () => {
mockVaultAdapter.exists.mockResolvedValue(false); mockFsAccess.mockRejectedValue(new Error('ENOENT'));
const manager = new TempDirectoryManager({ const manager = new TempDirectoryManager({
vaultPath: '/vault', vaultPath: '/vault',
@@ -203,11 +227,12 @@ describe('TempDirectoryManager', () => {
const result = await manager.cleanupTempDir('images'); const result = await manager.cleanupTempDir('images');
expect(result).toBe(true); expect(result).toBe(true);
expect(mockVaultAdapter.remove).not.toHaveBeenCalled(); expect(mockFsUnlink).not.toHaveBeenCalled();
}); });
it('should return false and log warning on error', async () => { it('should return false and log warning on error', async () => {
mockVaultAdapter.exists.mockRejectedValue(new Error('Access denied')); mockFsAccess.mockResolvedValue(undefined);
mockFsReaddir.mockRejectedValue(new Error('Access denied'));
const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
const manager = new TempDirectoryManager({ const manager = new TempDirectoryManager({
@@ -226,12 +251,10 @@ describe('TempDirectoryManager', () => {
}); });
it('should handle errors during file removal', async () => { it('should handle errors during file removal', async () => {
mockVaultAdapter.exists.mockResolvedValue(true); mockFsAccess.mockResolvedValue(undefined);
mockVaultAdapter.list.mockResolvedValue({ mockFsReaddir.mockResolvedValue(['file1.png']);
files: ['file1.png'], mockFsStat.mockResolvedValue({ isFile: () => true } as any);
folders: [], mockFsUnlink.mockRejectedValue(new Error('Cannot delete'));
});
mockVaultAdapter.remove.mockRejectedValue(new Error('Cannot delete'));
const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
const manager = new TempDirectoryManager({ const manager = new TempDirectoryManager({
@@ -252,12 +275,10 @@ describe('TempDirectoryManager', () => {
describe('cleanupAllTempDirs', () => { describe('cleanupAllTempDirs', () => {
it('should clean up both temp directories', async () => { it('should clean up both temp directories', async () => {
mockVaultAdapter.exists.mockResolvedValue(true); mockFsAccess.mockResolvedValue(undefined);
mockVaultAdapter.list.mockResolvedValue({ mockFsReaddir.mockResolvedValue(['file1.png']);
files: ['file1.png'], mockFsStat.mockResolvedValue({ isFile: () => true } as any);
folders: [], mockFsUnlink.mockResolvedValue(undefined);
});
mockVaultAdapter.remove.mockResolvedValue(undefined);
const manager = new TempDirectoryManager({ const manager = new TempDirectoryManager({
vaultPath: '/vault', vaultPath: '/vault',
@@ -269,22 +290,20 @@ describe('TempDirectoryManager', () => {
const result = await manager.cleanupAllTempDirs(); const result = await manager.cleanupAllTempDirs();
expect(result).toEqual({ images: true, pandoc: true }); expect(result).toEqual({ images: true, pandoc: true });
expect(mockVaultAdapter.list).toHaveBeenCalledTimes(2); expect(mockFsReaddir).toHaveBeenCalledTimes(2);
}); });
it('should return status for each directory independently', async () => { it('should return status for each directory independently', async () => {
let callCount = 0; let callCount = 0;
mockVaultAdapter.exists.mockImplementation(() => { mockFsAccess.mockImplementation(() => {
callCount++; callCount++;
// First call (images) succeeds, second call (pandoc) fails // First call (images) succeeds, second call (pandoc) fails
if (callCount === 1) return Promise.resolve(true); if (callCount === 1) return Promise.resolve(undefined);
return Promise.reject(new Error('Access denied')); return Promise.reject(new Error('Access denied'));
}); });
mockVaultAdapter.list.mockResolvedValue({ mockFsReaddir.mockResolvedValue(['file1.png']);
files: ['file1.png'], mockFsStat.mockResolvedValue({ isFile: () => true } as any);
folders: [], mockFsUnlink.mockResolvedValue(undefined);
});
mockVaultAdapter.remove.mockResolvedValue(undefined);
vi.spyOn(console, 'warn').mockImplementation(() => {}); vi.spyOn(console, 'warn').mockImplementation(() => {});
const manager = new TempDirectoryManager({ const manager = new TempDirectoryManager({