Close data leaks: remove anonymous user creation, hide private playlists, validate uploads and clamp gateway ranges

This commit is contained in:
2026-09-24 05:00:21 +02:00
parent c8fe28b07b
commit c8e9c7790e
34 changed files with 374 additions and 553 deletions
@@ -1,7 +0,0 @@
namespace Musify.Api.DataTransferObjects.Users;
public record CreateUserRequest(
long Id,
string Name,
string? FirstName,
string? SecondName);
@@ -19,11 +19,6 @@ public static class PlayListEndpoints
var group = app.MapGroup("/playlists")
.WithTags("PlayLists");
group.MapGet("/", GetPlayLists)
.WithName("GetPlayLists")
.WithSummary("Get Paginated PlayLists.")
.Produces<PaginatedResponse<PlayListApplicationResponse>>();
group.MapGet("/{id}", GetPlayListById)
.WithName("GetPlayListById")
.WithSummary("Get A PlayList By Id.")
@@ -32,7 +27,7 @@ public static class PlayListEndpoints
group.MapGet("/users/{userId}", GetPlayListsByUserId)
.WithName("GetPlayListsByUserId")
.WithSummary("Get Paginated PlayLists For A User.")
.WithSummary("Get Paginated PlayLists For A User. Private PlayLists Are Only Returned To Their Owner.")
.Produces<PaginatedResponse<PlayListApplicationResponse>>();
group.MapGet("/{playlistId}/tracks", GetPlayListTracks)
@@ -105,16 +100,6 @@ public static class PlayListEndpoints
return app;
}
private static async Task<IResult> GetPlayLists(
IMediator mediator,
CancellationToken cancellationToken,
int pageNumber = 1,
int pageSize = 10)
{
var result = await mediator.Send(new GetPlayListsQuery(pageNumber, pageSize), cancellationToken);
return result.ToHttpResult();
}
private static async Task<IResult> GetPlayListById(
IMediator mediator,
CurrentUser currentUser,
@@ -127,25 +112,26 @@ public static class PlayListEndpoints
private static async Task<IResult> GetPlayListsByUserId(
IMediator mediator,
CurrentUser currentUser,
long userId,
CancellationToken cancellationToken,
string? name,
int pageNumber = 1,
int pageSize = 10,
bool onlyPublic = false)
int pageSize = 10)
{
var result = await mediator.Send(new GetPlayListsByUserIdQuery(userId, name, pageNumber, pageSize, onlyPublic), cancellationToken);
var result = await mediator.Send(new GetPlayListsByUserIdQuery(userId, name, pageNumber, pageSize, currentUser.Id), cancellationToken);
return result.ToHttpResult();
}
private static async Task<IResult> GetPlayListTracks(
IMediator mediator,
CurrentUser currentUser,
Guid playlistId,
CancellationToken cancellationToken,
int pageNumber = 1,
int pageSize = 10)
{
var result = await mediator.Send(new GetPlayListTracksQuery(playlistId, pageNumber, pageSize), cancellationToken);
var result = await mediator.Send(new GetPlayListTracksQuery(playlistId, pageNumber, pageSize, currentUser.Id), cancellationToken);
return result.ToHttpResult();
}
@@ -1,8 +1,6 @@
using Mediator;
using Musify.Api.Authentication;
using Musify.Api.DataTransferObjects.Users;
using Musify.Api.Extensions;
using Musify.Api.Filters;
using Musify.Application.Shared;
using Musify.Application.Tracks;
using Musify.Application.Tracks.Responses;
@@ -38,7 +36,10 @@ public static class UserEndpoints
group.MapGet("/{id}/listening-stats", GetListeningStats)
.WithName("GetListeningStats")
.WithSummary("Get A User'S Listening Stats For The Current Week And Streak.")
.Produces<ListeningStatsResponse>();
.RequireAuthorization()
.Produces<ListeningStatsResponse>()
.Produces(StatusCodes.Status401Unauthorized)
.Produces(StatusCodes.Status403Forbidden);
group.MapGet("/{id}/last-listened-track", GetLastTrackListenedByUserId)
.WithName("GetLastTrackListenedByUserId")
@@ -88,14 +89,6 @@ public static class UserEndpoints
.Produces(StatusCodes.Status204NoContent)
.Produces(StatusCodes.Status401Unauthorized);
group.MapPost("/", CreateUser)
.WithName("CreateUser")
.WithSummary("Create A New User.")
.AddEndpointFilter<ValidationFilter<CreateUserRequest>>()
.Produces<UserApplicationResponse>(StatusCodes.Status201Created)
.ProducesValidationProblem()
.Produces(StatusCodes.Status409Conflict);
return app;
}
@@ -128,12 +121,16 @@ public static class UserEndpoints
return await mediator.Send(new GetListeningHistoryQuery(id), cancellationToken);
}
private static async Task<ListeningStatsResponse> GetListeningStats(
private static async Task<IResult> GetListeningStats(
IMediator mediator,
CurrentUser currentUser,
long id,
CancellationToken cancellationToken)
{
return await mediator.Send(new GetListeningStatsQuery(id), cancellationToken);
if (currentUser.RequiredId != id)
return Results.StatusCode(StatusCodes.Status403Forbidden);
return Results.Ok(await mediator.Send(new GetListeningStatsQuery(id), cancellationToken));
}
private static async Task<IResult> GetLastTrackListenedByUserId(
@@ -207,16 +204,4 @@ public static class UserEndpoints
var result = await mediator.Send(new UnfollowUserCommand(currentUser.RequiredId, id), cancellationToken);
return result.ToHttpResult();
}
private static async Task<IResult> CreateUser(
IMediator mediator,
CreateUserRequest request,
CancellationToken cancellationToken)
{
var result = await mediator.Send(
new CreateUserCommand(request.Id, request.Name, request.FirstName, request.SecondName),
cancellationToken);
return result.ToCreatedResult(user => $"/users/{user.Id}");
}
}
@@ -1,20 +1,20 @@
using FluentValidation;
using Musify.Api.DataTransferObjects.Albums;
using Musify.Application.Configuration;
namespace Musify.Api.Validators.Albums;
public sealed class RequestAlbumPictureUploadRequestValidator : AbstractValidator<RequestAlbumPictureUploadRequest>
{
public RequestAlbumPictureUploadRequestValidator()
public RequestAlbumPictureUploadRequestValidator(UploadIntentConfiguration uploadConfiguration)
{
RuleFor(x => x.FileType)
.NotEmpty();
.MustBeFileType(Uploads.PictureFileTypes);
RuleFor(x => x.ContentType)
.NotEmpty();
.MustBeContentType(Uploads.PictureContentTypes);
RuleFor(x => x.ExpectedSizeBytes)
.GreaterThan(0)
.When(x => x.ExpectedSizeBytes.HasValue);
.MustBeValidUploadSize(uploadConfiguration.MaxUploadBytes);
}
}
@@ -1,20 +1,20 @@
using FluentValidation;
using Musify.Api.DataTransferObjects.PlayLists;
using Musify.Application.Configuration;
namespace Musify.Api.Validators.PlayLists;
public sealed class RequestPlayListPictureUploadRequestValidator : AbstractValidator<RequestPlayListPictureUploadRequest>
{
public RequestPlayListPictureUploadRequestValidator()
public RequestPlayListPictureUploadRequestValidator(UploadIntentConfiguration uploadConfiguration)
{
RuleFor(x => x.FileType)
.NotEmpty();
.MustBeFileType(Uploads.PictureFileTypes);
RuleFor(x => x.ContentType)
.NotEmpty();
.MustBeContentType(Uploads.PictureContentTypes);
RuleFor(x => x.ExpectedSizeBytes)
.GreaterThan(0)
.When(x => x.ExpectedSizeBytes.HasValue);
.MustBeValidUploadSize(uploadConfiguration.MaxUploadBytes);
}
}
@@ -1,30 +1,29 @@
using FluentValidation;
using Musify.Api.DataTransferObjects.Tracks;
using Musify.Application.Configuration;
namespace Musify.Api.Validators.Tracks;
public sealed class RequestTrackUploadUrlsRequestValidator : AbstractValidator<RequestTrackUploadUrlsRequest>
{
public RequestTrackUploadUrlsRequestValidator()
public RequestTrackUploadUrlsRequestValidator(UploadIntentConfiguration uploadConfiguration)
{
RuleFor(x => x.PictureFileType)
.NotEmpty();
.MustBeFileType(Uploads.PictureFileTypes);
RuleFor(x => x.PictureContentType)
.NotEmpty();
.MustBeContentType(Uploads.PictureContentTypes);
RuleFor(x => x.AudioFileType)
.NotEmpty();
.MustBeFileType(Uploads.AudioFileTypes);
RuleFor(x => x.AudioContentType)
.NotEmpty();
.MustBeContentType(Uploads.AudioContentTypes);
RuleFor(x => x.ExpectedPictureSizeBytes)
.GreaterThan(0)
.When(x => x.ExpectedPictureSizeBytes.HasValue);
.MustBeValidUploadSize(uploadConfiguration.MaxUploadBytes);
RuleFor(x => x.ExpectedAudioSizeBytes)
.GreaterThan(0)
.When(x => x.ExpectedAudioSizeBytes.HasValue);
.MustBeValidUploadSize(uploadConfiguration.MaxUploadBytes);
}
}
@@ -0,0 +1,42 @@
using FluentValidation;
namespace Musify.Api.Validators;
public static class Uploads
{
public static readonly IReadOnlySet<string> PictureFileTypes =
new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "jpg", "jpeg", "png", "webp" };
public static readonly IReadOnlySet<string> PictureContentTypes =
new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "image/jpeg", "image/png", "image/webp" };
public static readonly IReadOnlySet<string> AudioFileTypes =
new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "mp3", "wav", "flac", "ogg", "m4a", "aac" };
public static readonly IReadOnlySet<string> AudioContentTypes =
new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"audio/mpeg", "audio/mp3", "audio/wav", "audio/x-wav", "audio/wave", "audio/flac", "audio/x-flac",
"audio/ogg", "audio/mp4", "audio/x-m4a", "audio/m4a", "audio/aac"
};
public static IRuleBuilderOptions<T, string> MustBeFileType<T>(
this IRuleBuilder<T, string> rule, IReadOnlySet<string> allowed) =>
rule
.NotEmpty()
.Length(1, 10)
.Matches("^[A-Za-z0-9]+$").WithMessage("'{PropertyName}' must contain only letters and digits.")
.Must(allowed.Contains).WithMessage("'{PropertyName}' must be one of: " + string.Join(", ", allowed) + ".");
public static IRuleBuilderOptions<T, string> MustBeContentType<T>(
this IRuleBuilder<T, string> rule, IReadOnlySet<string> allowed) =>
rule
.NotEmpty()
.Must(allowed.Contains).WithMessage("'{PropertyName}' is not an allowed content type.");
public static IRuleBuilderOptions<T, long?> MustBeValidUploadSize<T>(
this IRuleBuilder<T, long?> rule, long maxUploadBytes) =>
rule
.Must(size => size is null || (size > 0 && size <= maxUploadBytes))
.WithMessage($"'{{PropertyName}}' must be greater than 0 and at most {maxUploadBytes} bytes.");
}
@@ -1,25 +0,0 @@
using FluentValidation;
using Musify.Api.DataTransferObjects.Users;
namespace Musify.Api.Validators.Users;
public sealed class CreateUserRequestValidator : AbstractValidator<CreateUserRequest>
{
public CreateUserRequestValidator()
{
RuleFor(x => x.Id)
.NotEmpty();
RuleFor(x => x.Name)
.NotEmpty()
.MaximumLength(48);
RuleFor(x => x.FirstName)
.MaximumLength(48)
.When(x => !string.IsNullOrWhiteSpace(x.FirstName));
RuleFor(x => x.SecondName)
.MaximumLength(48)
.When(x => !string.IsNullOrWhiteSpace(x.SecondName));
}
}
@@ -61,7 +61,7 @@ public sealed class TicketValidationMiddleware(
if (validation.MaxBytes is { } maxBytes && !TryClampRange(context, maxBytes))
{
logger.LogInformation(
"Rejected media request {ObjectKey}: requested range starts beyond the {MaxBytes}-byte preview limit",
"Rejected media request {ObjectKey}: requested range is a suffix range or starts beyond the {MaxBytes}-byte preview limit",
objectKey, maxBytes);
context.Response.StatusCode = StatusCodes.Status416RangeNotSatisfiable;
context.Response.Headers[HeaderNames.ContentRange] = $"bytes */{maxBytes}";
@@ -81,11 +81,19 @@ public sealed class TicketValidationMiddleware(
return true;
}
if (!RangeHeaderValue.TryParse(rangeHeader.ToString(), out var range) || range.Ranges.Count != 1)
if (!RangeHeaderValue.TryParse(rangeHeader.ToString(), out var range)
|| range.Ranges.Count != 1
|| !string.Equals(range.Unit.ToString(), "bytes", StringComparison.OrdinalIgnoreCase))
{
context.Request.Headers.Range = $"bytes=0-{maxBytes - 1}";
return true;
}
var requested = range.Ranges.Single();
var start = requested.From ?? 0;
if (requested.From is null)
return false;
var start = requested.From.Value;
if (start >= maxBytes)
return false;