↑↓ to navigate Enter to open "…" all these words ANDOR to combine

Data & persistence · No. 43

Managed file storage: uploads you don't have to trust

A user uploads a profile photo. It is attacker-controlled bytes with GPS coordinates baked into the metadata and, if you are unlucky, a payload hiding behind a valid image header. Here is how MMCA.Common and the app that consumes it turn that upload into something you never have to trust.


An avatar upload looks like the most harmless feature in the app. A user picks a photo, you store it, you render it back in an <img> tag. What could go wrong?

Three things, and all of them are quiet.

The file is attacker-controlled bytes. The client says it is a JPEG; the client says a lot of things. The EXIF block on a phone photo carries the exact GPS coordinates where it was taken, which is PII you did not ask for and are now storing and re-serving to anyone who loads the profile. And a "valid" image can be a polyglot: bytes that a browser renders as a picture and something else on your box treats as a script or an archive. You did not write a photo-sharing site. You wrote a place for a 256-pixel avatar, and you inherited an untrusted-file-handling problem you never signed up for.

The reflex is to reach for the Azure SDK, write the blob straight from the controller, and move on. That solves storage and nothing else: the metadata still ships, the bytes are still trusted, and the next consumer who needs blob storage copies your controller code and inherits the same holes.

Why it matters

An avatar is user-generated content on an anonymous-visible surface. That combination is exactly where file-upload bugs turn into incidents. The two that bite hardest are not exotic:

  • Metadata leakage. EXIF GPS coordinates are personal data. If you store the original file, you are storing where your users live and work, and re-serving it on every profile view. Under GDPR that is data you are now the controller of, silently.
  • Content-type confusion. A Content-Type: image/jpeg header is a claim, not a fact. Accepting files by their declared type (or worse, their file extension) is how a "JPEG" that is really an HTML or SVG payload ends up served from your domain.

The threat model for an uploaded image is the same shape as the threat model for a password hash: assume the input is hostile, and make the stored form incapable of hurting you. You are not trying to keep the file secret. You are trying to guarantee that what you persist is a fresh encode of decoded pixels, never the bytes the user sent.

The MMCA answer: a storage boundary, and a re-encode that keeps only pixels

Without a blob abstraction, anything file-shaped gets written directly against the Azure SDK inside a module, unusable by the next consumer and untestable. ADR-045 splits the job along the line between what every app needs and what only an image-handling app needs. The framework ships the storage port and a dependency-free magic-byte validator; the re-encode is the application's own processor. The port carries more than avatars: ADR-045's avatar-only scope statement is superseded by ADR-123 (045-managed-file-storage-and-avatars.md:11, :146-148), which publishes speaker session materials through the same IFileStorageService.

IFileStorageService (IFileStorageService.cs:15) is the storage boundary: UploadAsync takes a blob name, a stream, and a content type and returns the public Uri as a Result<Uri> (:26). A second overload adds a FileUploadOptions carrying the Content-Disposition and Cache-Control headers to store with the blob (:41), and it is abstract, so every implementation provides it and honors those headers. DeleteAsync (:47) is idempotent: unknown blob names succeed rather than throw (:43). Callers pass only a blob name scoped within a container; the implementation owns the container, and the container itself is provisioned by infrastructure, never created by the app.

The default implementation is deliberately inert. NullFileStorageService (NullFileStorageService.cs:14) reports IsConfigured => false (:17), fails both upload overloads with a clear FileStorage.NotConfigured error (:34), and lets deletes succeed (there is nothing to delete). A host that never wires storage does not crash mysteriously; its upload endpoints degrade with an honest message. A host that wants real storage calls a vendor adapter: AddAzureBlobFileStorage(configuration) from MMCA.Common.Azure (AzureServiceCollectionExtensions.cs:44) swaps in AzureBlobFileStorageService (AzureBlobFileStorageService.cs:20) when the FileStorage section is complete, and MMCA.Common.Aws and MMCA.Common.Gcp offer S3 and Google Cloud Storage adapters over the same port (NullFileStorageService.cs:10-12). The core references no cloud SDK; storage is one adapter call, the same shape every vendor capability takes under ADR-134 (cloud-neutral vendor adapters). Storage deliberately has no startup tripwire: a FileStorage section is routinely shared configuration that a host storing no files sees too, so a host that lost its adapter call is caught by the Null default instead, which fails every upload with FileStorage.NotConfigured (CloudAdapterTripwire.cs:24-28).

That registration is defensive on purpose. An incomplete section is a no-op that leaves the Null default in place (AzureServiceCollectionExtensions.cs:52-55, :59-62), so hosts register it unconditionally. Production sets ServiceUri and authenticates with DefaultAzureCredential (:67); local development can use a ConnectionString against Azurite instead (:68, AzureBlobFileStorageSettings.cs:16-19). One detail earns its comment in the source: an empty-string ServiceUri binds to a relative Uri, so the guard only accepts an absolute one (AzureServiceCollectionExtensions.cs:57-58).

But storage is the boring half. The security boundary is the image processor, and the framework deliberately does not ship one: its own registration comment says image normalization is the application's concern, because decoding needs a native image library that every consumer of the package would otherwise carry (DependencyInjection.cs:380-384).

The re-encode is the boundary

In MMCA.ADC the processor belongs to the Identity module. IImageProcessor (MMCA.ADC.Identity.Application/Users/IImageProcessor.cs:11) has one method, NormalizeToSquareJpegAsync (:18), and its implementation SkiaSharpImageProcessor (MMCA.ADC.Identity.Infrastructure/Services/Users/SkiaSharpImageProcessor.cs:16) does something that looks like image resizing and is actually a security control. It buffers the upload under a byte ceiling, admits only four formats, reads the header and refuses anything too big to decode, decodes only the first frame, applies the EXIF orientation while it center-crops to an exact square, and encodes a fresh JPEG from that pixel buffer alone:

// SkiaSharpImageProcessor.NormalizeToSquareJpegAsync (MMCA.ADC Identity.Infrastructure).
// Excerpt: argument guards, cancellation checks and message arguments elided; trailing
// comments on the call lines added for this article.
using var data = await ReadBoundedAsync(content, cancellationToken).ConfigureAwait(false);
if (data is null)
{
    return TooLarge(...);   // more than MaxEncodedBytes buffered
}

using var codec = OpenAllowedCodec(data);   // magic bytes first, then the codec Skia picked
if (codec is null)
{
    return Undecodable();
}

// Header only: SKCodec.Create parses the format's header and allocates no frame, so a
// declared-oversize image is refused before the allocation it was built to provoke.
var width = codec.Info.Width;
var height = codec.Info.Height;
if (TooLargeToDecode(width, height))
{
    return TooLarge(...);
}

using var decoded = Decode(codec, width, height);   // frame 0 only, into exactly width x height
if (decoded is null)
{
    return Undecodable();
}

using var square = RenderCoverSquare(decoded, codec.EncodedOrigin, size);   // orient, then cover-crop
using var pixmap = square.PeekPixels();

// Encoded from the fresh pixel buffer alone: it carries no color space and no metadata, so
// nothing from the original file can be written back out.
using var jpeg = pixmap.Encode(new SKJpegEncoderOptions(JpegQuality, SKJpegEncoderDownsample.Downsample420, SKJpegEncoderAlphaOption.Ignore));
return jpeg is null ? Undecodable() : Result.Success(jpeg.ToArray());

The point is what does not survive. A full decode-then-re-encode means the original bytes never reach the output. The square the encoder reads is a new bitmap allocated with no color space (SkiaSharpImageProcessor.cs:237), drawn from the decoded pixels and encoded at quality 85 (:46, :105), so EXIF (GPS included), XMP, IPTC and the ICC profile are all left behind (:11-14, :103-104). A polyglot payload is gone because the bytes that carried it were never re-emitted: the output is a new JPEG the encoder wrote from a bitmap. One operation kills both classes of problem, and it does so by construction rather than by a blocklist you have to keep updating.

The byte ceiling and the header check in front of the decode are not size niceties. The upload is buffered before decoding, and the read stops past MaxEncodedBytes, 32 MiB (:43, :116-142), so the stream length cannot choose the allocation even if a caller forgets its own cap (:37-42). The avatar contract's 2 MB cap bounds the compressed bytes, which a decompression bomb satisfies happily: a 2 MB PNG can declare 40000x40000 and cost roughly 6 GB of frame buffer the moment it is decoded (:23-24). So the processor bounds the decoded frame instead, with MaxDecodedPixels at 50,000,000 (:27) and MaxDecodedDimension at 20,000 (:35); the edge ceiling sits beside the area one because a 1 x 200000 strip is inside the area limit and still pathological for the resampler (:30-32). TooLargeToDecode (:323-328) applies both, and refuses a non-positive dimension, to the header SKCodec.Create parsed without allocating a frame (:81-90). The decode then writes into a buffer of exactly those checked dimensions (:199), so no format can understate its header and decode into more memory than was checked (:83-84). Past either ceiling the upload is Error.Validation("Image.TooLarge", ...) (:330-334): a clean 400 rather than the OutOfMemoryException the upload was built to provoke.

The frame count is bounded as well as the frame size. Decode asks the codec for frame 0 only (new SKCodecOptions(0), :202): the output is a single JPEG, and decoding every frame of an animated GIF or WebP is how a small upload becomes hundreds of megabytes of pixel buffers (:185-187). Anything short of a complete decode, a truncated scan included, is refused rather than stored half blank (:192-195, :201-206).

The set of formats is bounded too, and checked twice. Skia also decodes BMP, ICO, WBMP, HEIF, AVIF and RAW, and SKCodec.Create dispatches on the leading bytes, so OpenAllowedCodec (:156-182) runs the magic-byte check before Skia sees the content (:145-149, :158): the framework's ImageContentSniffer plus a GIF signature (:301-308). It then requires the decoder Skia actually picked to be JPEG, PNG, WebP or GIF (:169, :313-314). No decoder outside those four ever parses an upload. That matters because a library's attack surface is every decoder it can reach, not only the formats you meant to accept.

Undecodable content is a validation failure too, not an exception: a disallowed signature, a header Skia cannot parse, an incomplete decode or a failed encode all return Error.Validation("Image.Undecodable", ...) (:336-340), so a garbage upload is a clean 400, not a 500. The Identity module registers the processor unconditionally, as a stateless singleton, in AddModuleIdentityInfrastructure (MMCA.ADC.Identity.Infrastructure/DependencyInjection.cs:23-25). Unlike storage there is no Null image processor, because there is no safe way to skip the re-encode.

Ahead of the processor sits the framework's ImageContentSniffer (ImageContentSniffer.cs:9), a static, dependency-free magic-byte check. IsAllowedImage (:14) accepts a payload only when its leading bytes match a JPEG, PNG, or WebP signature: the JPEG SOI prefix FF D8 FF (:21), the 8-byte PNG signature (:27), or a RIFF container declaring the WEBP form type (:34-35). The accepted formats are decided by the actual bytes, never the client-declared content type or the file extension. ADC's avatar validator and handler both gate on it (SetUserAvatarCommandValidator.cs:35, SetUserAvatarHandler.cs:63), and MMCA.Store's product image validator uses it the same way (UploadProductImageCommandValidator.cs:71) without decoding anything. It narrows the input; the re-encode neutralizes what gets through. Defense in depth, cheaply.

The avatar contract

Storage and the sniffer are framework legs; the re-encode is the app's. The avatar itself is a contract (BR-116a) each consumer applies: one avatar per user; accept jpeg/png/webp up to 2 MB; the server re-encodes to a 256x256 JPEG (SetUserAvatarHandler.cs:37) through its own image processor, treating client-declared content types as advisory only. The blob name is {userId}-{random8}.jpg in the public-read avatars container, so the URL path reads avatars/{userId}-{random8}.jpg. Replacing, removing or erasing an avatar, and a failed save that leaves a freshly uploaded blob with no row pointing at it, schedules a durable DeleteAvatarBlobInternalCommand (ADR-114) rather than deleting the blob inline. The URL lives on the user entity as [Pii]: nulled on anonymize with the blob delete scheduled in the same transaction, and included in the GDPR data export (045-managed-file-storage-and-avatars.md:100-108). That last part is why this article carries a §30 (data privacy) tie alongside the §8 (data access) and §11 (security) ones: the avatar is treated as personal data from the moment it lands to the moment it is erased.

One capability, two client affordances

On the client, the pick-a-photo gesture differs by host, and ADR-045 reuses the capability pattern from ADR-042. IMediaPickerService (IMediaPickerService.cs:9) exposes native photo pick and camera capture with the permission flow encapsulated; a cancelled or denied picker returns null rather than throwing. Web heads keep the Null default (NullMediaPickerService.cs:7, IsSupported => false) and render a plain InputFile instead. The comment in the port says it plainly: this is an affordance switch, not a degraded path (IMediaPickerService.cs:6-7). The same upload endpoint serves a phone's native picker and a browser's file input; only the gesture in front of it changes.

Trade-offs, honestly

ADR-045 owns most of its rough edges in its Consequences section, the build files record the rest, and they are real design choices rather than oversights.

  • The avatars container is public-read by design. Avatar URLs render in <img> tags on anonymous-visible surfaces without SAS-token plumbing on every request. The cost is that anyone with the URL can fetch the image. The random 8-character blob suffix prevents enumeration (you cannot walk from one avatar to the next), and the trade-off is accepted and documented in the consumer's privacy policy. This is a deliberate acceptance, not a gap.
  • CDN and browser caches can serve a stale avatar briefly. After a replace or a delete, a cache may hold the old URL for a moment. Because the random suffix means a new upload never reuses the old URL, staleness is bounded by cache TTLs and self-heals; there is no cache-busting dance to get right.
  • Avatar blob deletion is eventual, not synchronous. A replaced or deleted avatar has its blob deleted at least once, through the internal-command processor and within its retry budget (045-managed-file-storage-and-avatars.md:115-117). Only erasure schedules inside its own transaction; replace and remove schedule after the save commits, so a host death in between, or a failed schedule, leaves an orphaned blob that is only logged for manual removal (:195-200, SetUserAvatarHandler.cs:162-165).
  • DefaultAzureCredential needs a data-plane role, not a secret. In production the storage account requires a Storage Blob Data Contributor grant for the app identity. That is a bicep-level infrastructure grant, which is the correct place for it, but it does mean the app will not authenticate until the role assignment exists. It is not a connection string you can paste in.
  • An app that normalizes images owns its processor and a native image library. The framework ships no decoder, so a consumer that accepts images writes (or copies) its own processor, and it takes on the library behind it. ADC uses SkiaSharp 4.157.0 under MIT, three packages bumped together (MMCA.ADC/Directory.Packages.props:80-87), whose native libraries come to roughly 490 MB across platforms (:80-84). Containing them is a build-file discipline rather than a default: the Identity Infrastructure project references SkiaSharp with ExcludeAssets="native", so the natives never flow to the projects that reference it (MMCA.ADC.Identity.Infrastructure.csproj:7-10); only the Identity service host (MMCA.ADC.Identity.Service.csproj:21-28) and the processor's own tests (MMCA.ADC.Identity.Infrastructure.Tests.csproj:12-14) reference the native packages. The host keeps them without PrivateAssets, because that would drop them from its own ReadyToRun publish and the image would fail on the first upload (MMCA.ADC.Identity.Service.csproj:23-26), so a project that references the host, such as the service startup tests, excludes the natives on its own side (MMCA.ADC.Services.Tests.csproj:49-53). The payoff is on the other side of the line: every app that never decodes an image carries no image library at all, and MMCA.Common accepts no NuGet advisories today (MMCA.Common/Directory.Build.props:65-69).

Be precise about status: the framework legs are implemented and shipped in MMCA.Common, and two MMCA.ADC services wire them end to end. The Identity service calls AddAzureBlobFileStorage(configuration) at startup for avatars (MMCA.ADC.Identity.Service/Program.cs:225) and the Conference service calls it for speaker session assets (MMCA.ADC.Conference.Service/Program.cs:301). On the Identity side, SetUserAvatarHandler normalizes through the module's own processor (SetUserAvatarHandler.cs:29, :103) and is the only request-path handler that calls IFileStorageService, for the upload itself (SetUserAvatarHandler.cs:117). Every avatar blob delete is a durable DeleteAvatarBlobInternalCommand scheduled through IInternalCommandScheduler: the replaced blob once the new URL is saved (SetUserAvatarHandler.cs:158-160), the freshly uploaded blob when the save fails and leaves no row pointing at it (:78-88, :187), a removed avatar (RemoveUserAvatarHandler.cs:20,75) and an erased user (DeleteUserHandler.cs:38,90). The deletion runs in DeleteAvatarBlobInternalCommandHandler (DeleteAvatarBlobInternalCommandHandler.cs:17-23), which only names the blob kind for its log lines and inherits the work from Common's DeleteBlobInternalCommandHandlerBase (DeleteBlobInternalCommandHandlerBase.cs:28): the port call (:45), with a NotFound answer completing the row as success (:53-57) so at-least-once execution stays idempotent. The Profile page uploads through IMediaPickerService (Profile.razor.cs:24). Each consumer still provisions its own storage account and wires its own upload endpoints against these ports, so this is a capability the framework provides rather than one that is live in every downstream app by default: MMCA.Store has not adopted the storage port.

Apply this even without MMCA

The pattern ports to any stack and any blob store. The rules are short:

  1. Never trust the declared content type or the file extension. Sniff the leading magic bytes and accept only the formats you actually support. When your image library can decode more than that, sniff before it sees the bytes and check which decoder it picked.
  2. Re-encode every uploaded image; do not store the original. A full decode-then-re-encode is the single move that strips EXIF GPS (PII) and defeats polyglot payloads, because the original bytes never reach the output. Encode from a fresh pixel buffer, so no metadata profile (ICC included) rides along, and check what your encoder writes. Resize to the size you will actually serve while you are at it.
  3. Apply the EXIF orientation before you crop, or portrait phone photos come out sideways once the orientation tag is gone.
  4. Bound the decoded frame, not just the uploaded bytes. Cap the bytes you buffer, read the header, refuse the declared dimensions that would not fit in memory, decode only the one frame you keep, and decode into a buffer of exactly the size you checked.
  5. Put storage behind a port with an inert default. An unconfigured implementation that fails uploads with a clear message beats a host that half-works or crashes at first use.
  6. Keep a native image library where it is used. Reference its natives from the host that decodes and the tests that exercise it, and exclude them everywhere else.
  7. Treat the stored URL as PII. If it points at a user's face, it belongs in your erasure path and your data export, not just your database.
  8. Prefer managed identity over secrets for the store, and let infrastructure provision the container and its access level. The app should never create the bucket it writes to.

The takeaway: an upload is hostile bytes until you have re-encoded it into something that can only be a picture. Storage is the easy half; the re-encode is the boundary that matters.


What we covered: why an avatar upload is an untrusted-file problem in disguise (EXIF GPS as PII, content-type confusion, polyglot payloads); how IFileStorageService gives an upload-by-blob-name boundary with an inert NullFileStorageService default that fails clearly and an AddAzureBlobFileStorage swap to the real Azure implementation; how the real security boundary is the full re-encode in the app's own processor, ADC's SkiaSharpImageProcessor (bounded read, four-format allowlist checked by magic bytes and by codec, header size check, single-frame decode, EXIF orientation, center-crop, a fresh JPEG from pixels only) fronted by the framework's ImageContentSniffer; the avatar contract (256x256 JPEG, 2 MB, random-suffixed public-read blob, URL as [Pii], blob deletes as durable internal commands); and the honest trade-offs (public-read container, cache staleness, eventual blob deletion, a data-plane role grant, and an app-owned processor whose native image library stays out of every other project).

Next in the series: HTTP API versioning, proven not just claimed, one header-based policy adopted by every service and kept honest by a shared fitness contract that runs two live versions.

MMCA.Common is open source. Star the repo, read the 2-minute ADR behind this pattern, or dotnet add package MMCA.Common.Infrastructure and try it.

Tags: .NET, C Sharp, Software Architecture, Security, Cloud