Interview question
Implement a bounded PDF upload endpoint
Validates size and signature, writes under a generated storage key, and keeps untrusted files outside the public web root.
TL;DR
Validates size and signature, writes under a generated storage key, and keeps untrusted files outside the public web root.
Request limits, file signatures, storage keys, quarantine, cancellation, ownership, and safe responses.
Practice the problem like a real interview: restate, reason, implement, and test.
Accept one PDF up to 10 MB. Verify the PDF signature, store it under a server-generated key in quarantine, scan it, and persist only safe metadata and ownership.
Uploading invoice.exe renamed to .pdf fails signature validation and never becomes downloadable.
I reject impossible metadata early, inspect the content signature, and generate an opaque storage key. The file stays quarantined until scanning succeeds; the database stores ownership and safe display metadata.
[Authorize]
[HttpPost("documents")]
[RequestSizeLimit(10_500_000)]
public async Task<ActionResult<DocumentResponse>> Upload(
IFormFile file, CancellationToken ct)
{
const long maxBytes = 10_000_000;
if (file.Length is <= 0 or > maxBytes)
return ValidationProblem(new() {
["file"] = ["Choose a non-empty PDF up to 10 MB."]
});
await using var input = file.OpenReadStream();
var signature = new byte[5];
var read = 0;
while (read < signature.Length) {
var count = await input.ReadAsync(signature.AsMemory(read), ct);
if (count == 0) break;
read += count;
}
if (read != signature.Length || !signature.AsSpan().SequenceEqual("%PDF-"u8))
return ValidationProblem(new() { ["file"] = ["The file is not a valid PDF."] });
input.Seek(0, SeekOrigin.Begin);
var storageKey = $"quarantine/{Guid.NewGuid():N}";
var retained = false;
try {
await storage.WriteAsync(storageKey, input, maxBytes, ct);
var scan = await scanner.ScanAsync(storageKey, ct);
if (!scan.IsSafe)
return ValidationProblem(new() {
["file"] = ["The file could not be accepted."]
});
var document = Document.Create(User.RequireUserId(), storageKey,
FileNames.ForDisplay(file.FileName), file.Length, "application/pdf");
db.Documents.Add(document);
await db.SaveChangesAsync(ct);
retained = true;
return CreatedAtAction(nameof(GetDocument), new { id = document.Id },
DocumentResponse.From(document));
} finally {
if (!retained)
await storage.DeleteIfExistsAsync(storageKey, CancellationToken.None);
}
}
Signature checks are only a first filter; malware scanning and storage policy remain separate controls. Large or slow scanning should become an asynchronous quarantine workflow rather than tying up the request.
ContentType.wwwroot.Next in Authorization & Files: Authorized Download