Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,16 +41,21 @@ In order to use the antimalware scanning capabilities, ensure you have a ByteGua
### Basic validation

```csharp
// Without antimalware scanner
var configuration = new FileValidatorConfiguration
{
SupportedFileTypes = [FileExtensions.Pdf, FileExtensions.Jpg, FileExtensions.Png],
FileSizeLimit = ByteSize.MegaBytes(25),
ThrowExceptionOnInvalidFile = false,
AntimalwareScanner = new SpecificAntimalwareScanner(scannerOptions)
ThrowExceptionOnInvalidFile = false
};

var fileValidator = new FileValidator(configuration);
var isValid = fileValidator.IsValidFile("example.pdf", fileStream);

// With antimalware
var antimalwareScanner = AntimalwareScannerImplementation();
var fileValidator = new FileValidator(configuration, antimalwareScanner);
var isValid = fileValidator.IsValidFile("example.pdf", fileStream);
```

### Using the fluent builder
Expand All @@ -60,7 +65,6 @@ var configuration = new FileValidatorConfigurationBuilder()
.AllowFileTypes(FileExtensions.Pdf, FileExtensions.Jpg, FileExtensions.Png)
.SetFileSizeLimit(ByteSize.MegaBytes(25))
.SetThrowExceptionOnInvalidFile(false)
.AddAntimalwareScanner(new SpecificAntimalwareScanner(scannerOptions))
.Build();

var fileValidator = new FileValidator(configuration);
Expand Down Expand Up @@ -96,15 +100,16 @@ public async Task<IActionResult> Upload(IFormFile file)
{
using var stream = file.OpenReadStream();

var antimalwareScanner = AntimalwareScannerImplementation();

var configuration = new FileValidatorConfiguration
{
SupportedFileTypes = [FileExtensions.Pdf, FileExtensions.Docx],
FileSizeLimit = ByteSize.MegaBytes(10),
ThrowExceptionOnInvalidFile = false,
AntimalwareScanner = new SpecificAntimalwareScanner(scannerOptions)
ThrowExceptionOnInvalidFile = false
};

var validator = new FileValidator(configuration);
var validator = new FileValidator(configuration, antimalwareScanner);

if (!validator.IsValidFile(file.FileName, stream))
{
Expand Down Expand Up @@ -170,7 +175,6 @@ The `FileValidatorConfiguration` supports:
| `SupportedFileTypes` | Yes | N/A | A list of allowed file extensions (e.g., `.pdf`, `.jpg`).<br>Use the predefined constants in `FileExtensions` for supported types. |
| `FileSizeLimit` | Yes | N/A | Maximum permitted size of files.<br>Use the static `ByteSize` class provided with this package, to simplify your limit. |
| `ThrowExceptionOnInvalidFile` | No | `true` | Whether to throw an exception on invalid files or return `false`. |
| `AntimalwareScanner` | No | N/A | An antimalware scanner used to scan the given file for potential malware. |

### Exceptions

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,5 @@ public class FileValidatorConfiguration
/// Whether to throw an exception if an unsupported/invalid file is encountered. Defaults to <c>true</c>.
/// </summary>
public bool ThrowExceptionOnInvalidFile { get; set; } = true;

/// <summary>
/// Optional antimalware scanner to use during file validation.
/// </summary>
public IAntimalwareScanner? AntimalwareScanner { get; set; } = null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ public class FileValidatorConfigurationBuilder
private readonly List<string> supportedFileTypes = new List<string>();
private bool throwOnInvalidFiles = true;
private long fileSizeLimit = ByteSize.MegaBytes(25);
private IAntimalwareScanner? antimalwareScanner = null;

/// <summary>
/// Allow specific file types (extensions) to be validated.
Expand Down Expand Up @@ -44,22 +43,6 @@ public FileValidatorConfigurationBuilder SetFileSizeLimit(long inFileSizeLimit)
return this;
}

/// <summary>
/// Add an antimalware scanner.
/// </summary>
/// <param name="scanner">Antimalware scanner to use.</param>
/// <exception cref="ArgumentNullException">Thrown when the provided scanner is null.</exception>
public FileValidatorConfigurationBuilder AddAntimalwareScanner(IAntimalwareScanner scanner)
{
if (scanner == null)
{
throw new ArgumentNullException(nameof(scanner));
}

antimalwareScanner = scanner;
return this;
}

/// <summary>
/// Build configuration.
/// </summary>
Expand All @@ -70,8 +53,7 @@ public FileValidatorConfiguration Build()
{
SupportedFileTypes = supportedFileTypes,
ThrowExceptionOnInvalidFile = throwOnInvalidFiles,
FileSizeLimit = fileSizeLimit,
AntimalwareScanner = antimalwareScanner
FileSizeLimit = fileSizeLimit
};

ConfigurationValidator.ThrowIfInvalid(configuration);
Expand Down
34 changes: 28 additions & 6 deletions src/ByteGuard.FileValidator/FileValidator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using ByteGuard.FileValidator.Exceptions;
using ByteGuard.FileValidator.Models;
using ByteGuard.FileValidator.Validators;
using ByteGuard.FileValidator.Scanners;

namespace ByteGuard.FileValidator
{
Expand Down Expand Up @@ -239,17 +240,38 @@ public class FileValidator
/// </summary>
private readonly FileValidatorConfiguration _configuration;

/// <summary>
/// Antimalware scanner instance.
/// </summary>
private readonly IAntimalwareScanner? _antimalwareScanner;

/// <summary>
/// Instantiate a new instance of the file validator.
/// </summary>
/// <param name="configuration">Configuration including which files should be supported and whether an exception should be thrown when encountering an invalid file.</param>
/// <param name="configuration">Validator configuration.</param>
public FileValidator(FileValidatorConfiguration configuration)
{
ConfigurationValidator.ThrowIfInvalid(configuration);

_configuration = configuration;
}

/// <summary>
/// Instantiate a new instance of the file validator.
/// </summary>
/// <param name="configuration">Validator configuration.</param>
/// <param name="antimalwareScanner">Antimalware scanner to use during file validation.</param>
public FileValidator(FileValidatorConfiguration configuration, IAntimalwareScanner antimalwareScanner)
: this(configuration)
{
if (antimalwareScanner == null)
{
throw new ArgumentNullException(nameof(antimalwareScanner), "Antimalware scanner cannot be null.");
}

_antimalwareScanner = antimalwareScanner;
}

/// <summary>
/// Get all supported file types based on the current configuration.
/// </summary>
Expand Down Expand Up @@ -326,7 +348,7 @@ public bool IsValidFile(string fileName, byte[] content)
}

// Validate antimalware scan if configured.
if (_configuration.AntimalwareScanner != null)
if (_antimalwareScanner != null)
{
var isClean = IsMalwareClean(fileName, content);
if (!isClean)
Expand Down Expand Up @@ -988,7 +1010,7 @@ public bool IsValidOpenDocumentFormat(string filePath)
/// <exception cref="AntimalwareScannerException">Thrown if the configured antimalware scanner encountered an error while scanning the file for malware.</exception>
public bool IsMalwareClean(string fileName, byte[] content)
{
if (_configuration.AntimalwareScanner is null)
if (_antimalwareScanner is null)
{
throw new InvalidOperationException("No antimalware scanner has been configured for the FileValidator.");
}
Expand All @@ -1010,7 +1032,7 @@ public bool IsMalwareClean(string fileName, byte[] content)
/// <exception cref="AntimalwareScannerException">Thrown if the configured antimalware scanner encountered an error while scanning the file for malware.</exception>
public bool IsMalwareClean(string fileName, Stream stream)
{
if (_configuration.AntimalwareScanner is null)
if (_antimalwareScanner is null)
{
throw new InvalidOperationException("No antimalware scanner has been configured for the FileValidator.");
}
Expand All @@ -1020,7 +1042,7 @@ public bool IsMalwareClean(string fileName, Stream stream)
bool isClean;
try
{
isClean = _configuration.AntimalwareScanner.IsClean(stream, fileName);
isClean = _antimalwareScanner.IsClean(stream, fileName);
}
catch (Exception ex)
{
Expand Down Expand Up @@ -1051,7 +1073,7 @@ public bool IsMalwareClean(string fileName, Stream stream)
/// <exception cref="AntimalwareScannerException">Thrown if the configured antimalware scanner encountered an error while scanning the file for malware.</exception>
public bool IsMalwareClean(string filePath)
{
if (_configuration.AntimalwareScanner is null)
if (_antimalwareScanner is null)
{
throw new InvalidOperationException("No antimalware scanner has been configured for the FileValidator.");
}
Expand Down
10 changes: 4 additions & 6 deletions tests/ByteGuard.FileValidator.Tests.Unit/FileValidatorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1073,10 +1073,9 @@ public void IsValidFile_AntimalwareScannerDetectsMalwareAndThrowExceptionOnInval
{
SupportedFileTypes = [".pdf"],
FileSizeLimit = ByteSize.MegaBytes(25),
ThrowExceptionOnInvalidFile = true,
AntimalwareScanner = mockAntimalwareScanner
ThrowExceptionOnInvalidFile = true
};
var fileValidator = new FileValidator(config);
var fileValidator = new FileValidator(config, mockAntimalwareScanner);
var fileBytes = new byte[] { 0x25, 0x50, 0x44, 0x46, 0x2D }; // Valid PDF signature

// Act
Expand All @@ -1097,10 +1096,9 @@ public void IsValidFile_AntimalwareScannerDetectsMalwareAndThrowExceptionOnInval
{
SupportedFileTypes = [".pdf"],
FileSizeLimit = ByteSize.MegaBytes(25),
ThrowExceptionOnInvalidFile = false,
AntimalwareScanner = mockAntimalwareScanner
ThrowExceptionOnInvalidFile = false
};
var fileValidator = new FileValidator(config);
var fileValidator = new FileValidator(config, mockAntimalwareScanner);
var fileBytes = new byte[] { 0x25, 0x50, 0x44, 0x46, 0x2D }; // Valid PDF signature

// Act
Expand Down