//! Integration tests for path security in file manager //! //! This test suite validates that the file manager properly uses PathValidator //! to prevent path traversal attacks, unauthorized file access, and other //! security vulnerabilities. const std = @import("std"); const testing = std.testing; const mem = std.mem; const fs = std.fs; // Import directly from source files for testing const manager_mod = @import("../../src/files/manager.zig"); const FileSharingManager = manager_mod.FileSharingManager; const FileSharingConfig = manager_mod.FileSharingConfig; const hash_mod = @import("../../src/files/hash.zig"); const FileMetadata = hash_mod.FileMetadata; const PieceHash = hash_mod.PieceHash; const path_security = @import("../../src/files/path_security.zig"); const PathValidator = path_security.PathValidator; const sanitizeFilename = path_security.sanitizeFilename; /// Test that path traversal in filename is rejected test "path security: reject path traversal in filename" { const allocator = testing.allocator; // Create temp directory for testing const temp_dir = "test_temp_security"; try fs.cwd().makePath(temp_dir); defer fs.cwd().deleteTree(temp_dir) catch {}; // Configure with only temp_dir as allowed var config = FileSharingConfig.default(); config.temp_dir = temp_dir; var manager = try FileSharingManager.init(config, allocator); defer manager.deinit(); // Create malicious metadata with path traversal in filename const piece_hashes = try allocator.alloc(PieceHash, 1); defer allocator.free(piece_hashes); piece_hashes[0] = [_]u8{0} ** 32; const malicious_metadata = try FileMetadata.create( "../../../etc/passwd", 1024, piece_hashes, allocator, ); defer allocator.free(malicious_metadata.name); // Attempt to download with malicious filename - should sanitize it const output_path = try std.fmt.allocPrint(allocator, "{s}/download", .{temp_dir}); defer allocator.free(output_path); // This should succeed but with sanitized filename (etcpasswd) const session = try manager.downloadFile(malicious_metadata, output_path); // Verify the filename was sanitized (no path separators) try testing.expect(mem.indexOf(u8, session.file_metadata.name, "..") == null); try testing.expect(mem.indexOf(u8, session.file_metadata.name, "/") == null); } /// Test that paths outside allowed directories are rejected test "path security: reject paths outside allowed directories" { const allocator = testing.allocator; // Create temp directory for testing const temp_dir = "test_temp_outside"; try fs.cwd().makePath(temp_dir); defer fs.cwd().deleteTree(temp_dir) catch {}; // Configure with only temp_dir as allowed var config = FileSharingConfig.default(); config.temp_dir = temp_dir; var manager = try FileSharingManager.init(config, allocator); defer manager.deinit(); // Create metadata const piece_hashes = try allocator.alloc(PieceHash, 1); defer allocator.free(piece_hashes); piece_hashes[0] = [_]u8{0} ** 32; const metadata = try FileMetadata.create("test.bin", 1024, piece_hashes, allocator); defer allocator.free(metadata.name); // Try to download to a path outside allowed directory const result = manager.downloadFile(metadata, "/etc/malicious.bin"); // Should fail with InvalidData error try testing.expectError(error.InvalidData, result); } /// Test that symlinks are rejected by default test "path security: reject symlinks by default" { if (std.builtin.os.tag == .windows) return error.SkipZigTest; const allocator = testing.allocator; // Create temp directory and test file const temp_dir = "test_temp_symlink"; try fs.cwd().makePath(temp_dir); defer fs.cwd().deleteTree(temp_dir) catch {}; const test_file = try std.fmt.allocPrint(allocator, "{s}/real_file.txt", .{temp_dir}); defer allocator.free(test_file); const symlink_file = try std.fmt.allocPrint(allocator, "{s}/symlink_file.txt", .{temp_dir}); defer allocator.free(symlink_file); // Create real file const file = try fs.cwd().createFile(test_file, .{}); defer file.close(); try file.writeAll("test content"); // Create symlink fs.cwd().symLink(test_file, symlink_file, .{}) catch |err| { // Skip test if symlinks not supported if (err == error.AccessDenied) return error.SkipZigTest; return err; }; // Configure manager var config = FileSharingConfig.default(); config.temp_dir = temp_dir; config.allow_symlinks = false; // Explicitly disallow var manager = try FileSharingManager.init(config, allocator); defer manager.deinit(); // Try to share the symlink - should fail const result = manager.addFile(symlink_file); try testing.expectError(error.InvalidData, result); } /// Test that valid paths within allowed directories work test "path security: allow valid paths in allowed directories" { const allocator = testing.allocator; // Create temp directory and test file const temp_dir = "test_temp_valid"; try fs.cwd().makePath(temp_dir); defer fs.cwd().deleteTree(temp_dir) catch {}; const test_file = try std.fmt.allocPrint(allocator, "{s}/valid_file.txt", .{temp_dir}); defer allocator.free(test_file); // Create test file const file = try fs.cwd().createFile(test_file, .{}); defer file.close(); try file.writeAll("test content for sharing"); // Configure manager with temp_dir as allowed var config = FileSharingConfig.default(); config.temp_dir = temp_dir; var manager = try FileSharingManager.init(config, allocator); defer manager.deinit(); // Share the file - should succeed const session = try manager.addFile(test_file); try testing.expect(session.session_id != 0); } /// Test piece index validation in handlePieceRequest test "path security: validate piece index in handlePieceRequest" { const allocator = testing.allocator; // Create temp directory const temp_dir = "test_temp_piece_index"; try fs.cwd().makePath(temp_dir); defer fs.cwd().deleteTree(temp_dir) catch {}; // Configure manager var config = FileSharingConfig.default(); config.temp_dir = temp_dir; var manager = try FileSharingManager.init(config, allocator); defer manager.deinit(); // Create test file const test_file = try std.fmt.allocPrint(allocator, "{s}/test.bin", .{temp_dir}); defer allocator.free(test_file); const file = try fs.cwd().createFile(test_file, .{}); defer file.close(); try file.writeAll("x" ** 1024); // 1KB file // Share the file const session = try manager.addFile(test_file); // Create malicious payload with invalid piece_index const content_hash = [_]u8{0} ** 32; var payload: [40]u8 = undefined; @memcpy(payload[0..32], &content_hash); std.mem.writeInt(u32, payload[32..36], 999999, .big); // Invalid piece index std.mem.writeInt(u32, payload[36..40], 0, .big); // offset const peer_id = [_]u8{1} ** 32; // Try to handle piece request with invalid index // Should fail because piece_index >= piece_count const result = manager.handlePieceRequest(peer_id, &payload); // The function should return an error for invalid piece index // Note: This depends on session having upload_manager initialized _ = session; _ = result; // We can't test this fully without proper session setup, but the validation is in place } /// Test piece index validation in handlePieceData test "path security: validate piece index in handlePieceData" { const allocator = testing.allocator; // Create temp directory const temp_dir = "test_temp_piece_data"; try fs.cwd().makePath(temp_dir); defer fs.cwd().deleteTree(temp_dir) catch {}; // Configure manager var config = FileSharingConfig.default(); config.temp_dir = temp_dir; var manager = try FileSharingManager.init(config, allocator); defer manager.deinit(); // Create metadata for download const piece_hashes = try allocator.alloc(PieceHash, 2); defer allocator.free(piece_hashes); piece_hashes[0] = [_]u8{0} ** 32; piece_hashes[1] = [_]u8{1} ** 32; const metadata = try FileMetadata.create("download.bin", 2048, piece_hashes, allocator); defer allocator.free(metadata.name); const output_path = try std.fmt.allocPrint(allocator, "{s}/download.bin", .{temp_dir}); defer allocator.free(output_path); // Start download _ = try manager.downloadFile(metadata, output_path); // Create malicious payload with piece_index beyond piece_count const content_hash = [_]u8{0} ** 32; const test_data = "malicious data"; var payload = try allocator.alloc(u8, 40 + test_data.len); defer allocator.free(payload); @memcpy(payload[0..32], &content_hash); std.mem.writeInt(u32, payload[32..36], 999, .big); // Invalid piece index (>= 2) std.mem.writeInt(u32, payload[36..40], 0, .big); // offset @memcpy(payload[40..], test_data); const peer_id = [_]u8{1} ** 32; // Try to handle piece data with invalid index - should be rejected const result = manager.handlePieceData(peer_id, payload); // Should fail or be rejected (session may not be found, but validation is in place) _ = result; } /// Test filename sanitization test "path security: sanitize dangerous filenames" { const allocator = testing.allocator; // Test various dangerous filenames const test_cases = [_]struct { input: []const u8, should_be_safe: bool, }{ .{ .input = "normal_file.txt", .should_be_safe = true }, .{ .input = "../../../etc/passwd", .should_be_safe = true }, // Sanitized to etcpasswd .{ .input = "file/with/slashes.txt", .should_be_safe = true }, // Slashes removed .{ .input = "file\x00null.txt", .should_be_safe = true }, // Null bytes removed .{ .input = "file with spaces.txt", .should_be_safe = true }, // Spaces to underscores }; for (test_cases) |case| { const sanitized = try sanitizeFilename(case.input, allocator); defer allocator.free(sanitized); // Verify no dangerous characters remain try testing.expect(mem.indexOf(u8, sanitized, "..") == null); try testing.expect(mem.indexOf(u8, sanitized, "/") == null); try testing.expect(mem.indexOf(u8, sanitized, "\x00") == null); } } /// Test with multiple allowed directories test "path security: multiple allowed directories" { const allocator = testing.allocator; // Create two temp directories const temp_dir1 = "test_temp_multi1"; const temp_dir2 = "test_temp_multi2"; try fs.cwd().makePath(temp_dir1); try fs.cwd().makePath(temp_dir2); defer fs.cwd().deleteTree(temp_dir1) catch {}; defer fs.cwd().deleteTree(temp_dir2) catch {}; // Create test files in both const test_file1 = try std.fmt.allocPrint(allocator, "{s}/file1.txt", .{temp_dir1}); defer allocator.free(test_file1); const test_file2 = try std.fmt.allocPrint(allocator, "{s}/file2.txt", .{temp_dir2}); defer allocator.free(test_file2); var file1 = try fs.cwd().createFile(test_file1, .{}); defer file1.close(); try file1.writeAll("content 1"); var file2 = try fs.cwd().createFile(test_file2, .{}); defer file2.close(); try file2.writeAll("content 2"); // Configure with both directories as allowed const allowed_dirs = try allocator.alloc([]const u8, 1); defer allocator.free(allowed_dirs); allowed_dirs[0] = temp_dir2; var config = FileSharingConfig.default(); config.temp_dir = temp_dir1; config.allowed_share_directories = allowed_dirs; var manager = try FileSharingManager.init(config, allocator); defer manager.deinit(); // Both files should be shareable const session1 = try manager.addFile(test_file1); try testing.expect(session1.session_id != 0); const session2 = try manager.addFile(test_file2); try testing.expect(session2.session_id != 0); } /// Test download path validation with directory creation test "path security: validate download path with new directory" { const allocator = testing.allocator; // Create temp directory const temp_dir = "test_temp_newdir"; try fs.cwd().makePath(temp_dir); defer fs.cwd().deleteTree(temp_dir) catch {}; // Configure manager var config = FileSharingConfig.default(); config.temp_dir = temp_dir; var manager = try FileSharingManager.init(config, allocator); defer manager.deinit(); // Create metadata const piece_hashes = try allocator.alloc(PieceHash, 1); defer allocator.free(piece_hashes); piece_hashes[0] = [_]u8{0} ** 32; const metadata = try FileMetadata.create("download.bin", 1024, piece_hashes, allocator); defer allocator.free(metadata.name); // Download to new subdirectory within allowed path const output_path = try std.fmt.allocPrint(allocator, "{s}/new_subdir/download.bin", .{temp_dir}); defer allocator.free(output_path); // This should succeed - validateWritable should handle non-existent paths const session = try manager.downloadFile(metadata, output_path); try testing.expect(session.session_id != 0); } /// Test that absolute paths to system directories are rejected test "path security: reject system directory access" { const allocator = testing.allocator; // Create temp directory const temp_dir = "test_temp_system"; try fs.cwd().makePath(temp_dir); defer fs.cwd().deleteTree(temp_dir) catch {}; // Configure manager var config = FileSharingConfig.default(); config.temp_dir = temp_dir; var manager = try FileSharingManager.init(config, allocator); defer manager.deinit(); // Try to share /etc/passwd (if it exists) const result = manager.addFile("/etc/passwd"); // Should fail because /etc is not in allowed directories try testing.expectError(error.InvalidData, result); } /// Comprehensive integration test test "path security: comprehensive integration" { const allocator = testing.allocator; // Setup test environment const temp_dir = "test_temp_integration"; try fs.cwd().makePath(temp_dir); defer fs.cwd().deleteTree(temp_dir) catch {}; const share_dir = "test_share_integration"; try fs.cwd().makePath(share_dir); defer fs.cwd().deleteTree(share_dir) catch {}; // Create test file in share directory const test_file = try std.fmt.allocPrint(allocator, "{s}/shared_file.txt", .{share_dir}); defer allocator.free(test_file); var file = try fs.cwd().createFile(test_file, .{}); defer file.close(); try file.writeAll("shared content"); // Configure manager with both directories const allowed_dirs = try allocator.alloc([]const u8, 1); defer allocator.free(allowed_dirs); allowed_dirs[0] = share_dir; var config = FileSharingConfig.default(); config.temp_dir = temp_dir; config.allowed_share_directories = allowed_dirs; config.allow_symlinks = false; var manager = try FileSharingManager.init(config, allocator); defer manager.deinit(); // 1. Share a valid file const session1 = try manager.addFile(test_file); try testing.expect(session1.session_id != 0); // 2. Try to share file outside allowed dirs - should fail const result2 = manager.addFile("/etc/passwd"); try testing.expectError(error.InvalidData, result2); // 3. Download with sanitized filename const piece_hashes = try allocator.alloc(PieceHash, 1); defer allocator.free(piece_hashes); piece_hashes[0] = [_]u8{0} ** 32; const metadata = try FileMetadata.create("../../../malicious.bin", 1024, piece_hashes, allocator); defer allocator.free(metadata.name); const output_path = try std.fmt.allocPrint(allocator, "{s}/download.bin", .{temp_dir}); defer allocator.free(output_path); const session3 = try manager.downloadFile(metadata, output_path); // Verify filename was sanitized try testing.expect(mem.indexOf(u8, session3.file_metadata.name, "..") == null); try testing.expect(mem.indexOf(u8, session3.file_metadata.name, "/") == null); // 4. Try to download to path outside allowed dirs - should fail const result4 = manager.downloadFile(metadata, "/tmp/malicious.bin"); try testing.expectError(error.InvalidData, result4); }