Files
ersatztv/ErsatzTV/Controllers/Api/ArtworkUploadController.cs
T
timothyandClaude Opus 4.8 cf834d8b60
Build ErsatzTV Image / Docs update reminder (pull_request) Successful in 5s
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 8m33s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 10m40s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
security(#283): sniff artwork content type from bytes, remove serve-side ?contentType= reflection
S4 stored-XSS + S9 upload-size DoS from the #197 cold API review.

The artwork path trusted client-supplied content types at both ends: upload
validated only the declared multipart Content-Type (never decoded the bytes),
and serving reflected a client `?contentType=` straight into the response
Content-Type on unauthenticated GET sinks (/iptv/logos, /artwork/watermarks).
Chain: upload <script> bytes as image/png -> GET ...?contentType=text/html
serves them as HTML in-origin. nosniff (#279) does not help because the server
explicitly declares text/html.

- Upload: derive the content type from the bytes via SkiaSharp SKCodec
  (header-only, no decode -> no decompression-bomb path); reject non-images 422.
  New ErsatzTV.Core/Images/ImageContentTypes as the single allow-list source.
  Dropped the untrusted declared Content-Type from the UploadArtwork command.
- Serve: removed the ?contentType= reflection structurally -- dropped ContentType
  from GetCachedImagePath and the [FromQuery] binding on GetImage/GetWatermark;
  the handler always sniffs the file, defaulting application/octet-stream.
  ArtworkContentTypeModel.UrlWithContentType is now the bare path; SPA previews
  no longer append the query.
- Defense-in-depth: channel-logo / watermark {path, contentType} DTOs run through
  ArtworkContentTypeModel.Sanitized(), blanking non-allow-listed types on write.
- S9: Kestrel MaxRequestBodySize from ETV_MAXIMUM_UPLOAD_MB rejects oversized
  bodies during read (controller file.Length check kept as friendly-error backstop).

Both serve sinks are IgnoreApi, so no OpenAPI change. Tests: byte-sniff accept/
reject, Sanitized() allow-list, Location no longer carries ?contentType=.
Docs: api-conventions §4a + decisions.md 2026-07-12.

Refs #283 #197 #66

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-12 00:07:55 +02:00

83 lines
3.1 KiB
C#

using System.ComponentModel;
using ErsatzTV.Application.Artworks;
using ErsatzTV.Core;
using ErsatzTV.Core.Api.Artwork;
using ErsatzTV.Core.Domain;
using ErsatzTV.Extensions;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace ErsatzTV.Controllers.Api;
[ApiController]
public class ArtworkUploadController(IMediator mediator) : ControllerBase
{
[HttpPost("/api/artwork/uploads", Name = "UploadArtwork")]
[Consumes("multipart/form-data")]
[Tags("Artwork")]
[EndpointSummary("Upload channel logo or watermark artwork")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(ArtworkUploadResponseModel), StatusCodes.Status201Created)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> Upload(
IFormFile file,
[FromForm] [Description("Artwork target: 'logo' (default) or 'watermark'")] string target,
CancellationToken cancellationToken)
{
if (file is null || file.Length == 0)
{
return BaseError.New("A non-empty image file is required").ToErrorResult();
}
long maxBytes = (long)SystemEnvironment.MaximumUploadMb * 1024 * 1024;
if (file.Length > maxBytes)
{
return BaseError.New($"Image exceeds the maximum allowed size of {SystemEnvironment.MaximumUploadMb} MB")
.ToErrorResult();
}
if (!TryParseTarget(target, out ArtworkKind artworkKind))
{
return BaseError.New($"Unknown upload target '{target}'; expected 'logo' or 'watermark'").ToErrorResult();
}
await using Stream stream = file.OpenReadStream();
Either<BaseError, ArtworkUploadResponseModel> result = await mediator.Send(
new UploadArtwork(stream, artworkKind),
cancellationToken);
return result.ToCreatedResult(
value => LocationFor(artworkKind, value.Path),
value => value);
}
// "logo" (default) and "watermark" are the two channel-artwork surfaces the API exposes today.
private static bool TryParseTarget(string target, out ArtworkKind artworkKind)
{
switch ((target ?? string.Empty).Trim().ToLowerInvariant())
{
case "":
case "logo":
artworkKind = ArtworkKind.Logo;
return true;
case "watermark":
artworkKind = ArtworkKind.Watermark;
return true;
default:
artworkKind = ArtworkKind.Logo;
return false;
}
}
// The serve routes (GetImage / GetWatermark) sniff the content type from the stored file, so the
// Location no longer carries a ?contentType= (issue #283 — that reflection was the XSS sink).
private static string LocationFor(ArtworkKind artworkKind, string path) =>
artworkKind switch
{
// logo paths already carry the servable prefix ("iptv/logos/{file}")
ArtworkKind.Logo => $"/{path}",
_ => $"/artwork/watermarks/{path}"
};
}