shoc-backend/SeaHaven.Services/Implementation/WorkOrderMediaService.cs
Arthur Bassi 899da0eb4f fix(work-orders): enforce media auth and base scope on mutations
Require an authenticated ClaimsPrincipal at service entry and filter
tracked work orders with board base scope so deleted/template rows
surface as NotFound without disclosure.
2026-08-04 11:08:18 -03:00

302 lines
12 KiB
C#

using System.Security.Claims;
using Data.SeaHavenIndustries;
using Data.SeaHavenIndustries.Enums;
using SeaHaven.DataServices.Interfaces;
using SeaHaven.Services.DTOs;
using SeaHaven.Services.Exceptions;
using SeaHaven.Services.Helpers;
using SeaHaven.Services.Interfaces;
namespace SeaHaven.Services.Implementation
{
public class WorkOrderMediaService : IWorkOrderMediaService
{
private readonly IWorkOrderMediaDataService _mediaData;
private readonly IWorkOrderDetailDataService _detailData;
private readonly IWorkOrderAuditService _auditService;
public WorkOrderMediaService(
IWorkOrderMediaDataService mediaData,
IWorkOrderDetailDataService detailData,
IWorkOrderAuditService auditService)
{
_mediaData = mediaData;
_detailData = detailData;
_auditService = auditService;
}
public async Task<IReadOnlyList<WorkOrderMediaFileDto>?> GetMediaAsync(
int workOrderId,
CancellationToken cancellationToken = default)
{
if (!await _detailData.ExistsAsync(workOrderId))
return null;
var workOrder = await _detailData.GetWorkOrderForMediaAsync(workOrderId);
if (workOrder == null)
return null;
var attachments = await _detailData.GetAttachmentsAsync(workOrderId);
return WorkOrderMediaProjection.ProjectAll(workOrder, attachments);
}
public async Task EnsureCanMutateMediaAsync(
int workOrderId,
ClaimsPrincipal user,
string? actorId,
CancellationToken cancellationToken = default)
{
EnsureAuthenticatedCaller(user, actorId);
await GetMutableWorkOrderAsync(workOrderId, cancellationToken);
}
public async Task<WorkOrderMediaFileDto> AddMediaAsync(
int workOrderId,
WorkOrderMediaCategory? category,
string fileUrl,
ClaimsPrincipal user,
string? actorId,
CancellationToken cancellationToken = default)
{
EnsureAuthenticatedCaller(user, actorId);
var resolvedCategory = category ?? WorkOrderMediaCategory.Extra;
var workOrder = await GetMutableWorkOrderAsync(workOrderId, cancellationToken);
if (resolvedCategory == WorkOrderMediaCategory.Completion)
{
throw new WorkOrderBoardValidationException(
"UseCompletionDocEndpoint",
"Completion documents must be uploaded via POST /api/workorders/{id}/completion-doc.");
}
if (resolvedCategory == WorkOrderMediaCategory.Before)
{
var oldBefore = workOrder.BeforPhotoAttachment;
workOrder.BeforPhotoAttachment = fileUrl;
await _auditService.StageFieldChangedAsync(
workOrderId, "BeforPhotoAttachment", oldBefore, fileUrl, actorId);
await _mediaData.SaveAsync(cancellationToken);
return new WorkOrderMediaFileDto
{
Id = -1,
Category = resolvedCategory,
Url = fileUrl,
IsLegacy = true
};
}
if (resolvedCategory == WorkOrderMediaCategory.After)
{
var oldAfter = workOrder.AfterPhotoAttachment;
workOrder.AfterPhotoAttachment = fileUrl;
await _auditService.StageFieldChangedAsync(
workOrderId, "AfterPhotoAttachment", oldAfter, fileUrl, actorId);
await _mediaData.SaveAsync(cancellationToken);
return new WorkOrderMediaFileDto
{
Id = -2,
Category = resolvedCategory,
Url = fileUrl,
IsLegacy = true
};
}
var attachment = new WorkOrderAttachments
{
WorkorderId = workOrderId,
Attachments = fileUrl,
Category = category.HasValue ? resolvedCategory : null,
CreatedDate = DateTime.UtcNow,
createdby = actorId
};
_mediaData.TrackAttachment(attachment);
await _auditService.StageFieldChangedAsync(
workOrderId,
"MediaCategory",
null,
FormatMediaAuditValue(null, (attachment.Category ?? WorkOrderMediaCategory.Extra).ToString()),
actorId);
await _mediaData.SaveAsync(cancellationToken);
return new WorkOrderMediaFileDto
{
Id = attachment.Id,
Category = attachment.Category ?? WorkOrderMediaCategory.Extra,
Url = fileUrl,
UploadedAt = attachment.CreatedDate?.ToUniversalTime().ToString("o"),
IsLegacy = false
};
}
public async Task<WorkOrderMediaFileDto> UpdateMediaCategoryAsync(
int workOrderId,
int mediaId,
WorkOrderMediaCategory category,
string? workOrderVersion,
ClaimsPrincipal user,
string? actorId,
CancellationToken cancellationToken = default)
{
EnsureAuthenticatedCaller(user, actorId);
if (mediaId <= 0)
throw new WorkOrderBoardValidationException("InvalidMedia", "Legacy media cannot be categorized via this endpoint.");
if (category == WorkOrderMediaCategory.Completion)
{
throw new WorkOrderBoardValidationException(
"UseCompletionDocEndpoint",
"Completion documents must be uploaded via POST /api/workorders/{id}/completion-doc.");
}
var workOrder = await GetMutableWorkOrderAsync(workOrderId, cancellationToken);
ApplyExpectedVersion(workOrder, workOrderVersion);
var attachment = await _mediaData.GetTrackedAttachmentAsync(mediaId, workOrderId, cancellationToken);
if (attachment == null)
throw new WorkOrderBoardValidationException("NotFound", "Media not found.");
var priorCategory = (attachment.Category ?? WorkOrderMediaCategory.Extra).ToString();
if (category == WorkOrderMediaCategory.Before || category == WorkOrderMediaCategory.After)
{
var url = attachment.Attachments ?? "";
if (category == WorkOrderMediaCategory.Before)
workOrder.BeforPhotoAttachment = url;
else
workOrder.AfterPhotoAttachment = url;
attachment.IsDeleted = true;
attachment.DeletionTime = DateTime.UtcNow;
attachment.DeleterUserId = actorId;
await _auditService.StageFieldChangedAsync(
workOrderId,
"MediaCategory",
FormatMediaAuditValue(mediaId, priorCategory),
FormatMediaAuditValue(mediaId, category.ToString()),
actorId);
await _mediaData.SaveAsync(cancellationToken);
return new WorkOrderMediaFileDto
{
Id = category == WorkOrderMediaCategory.Before ? -1 : -2,
Category = category,
Url = url,
IsLegacy = true
};
}
attachment.Category = category;
_mediaData.MarkWorkOrderModified(workOrder);
await _auditService.StageFieldChangedAsync(
workOrderId,
"MediaCategory",
FormatMediaAuditValue(mediaId, priorCategory),
FormatMediaAuditValue(mediaId, category.ToString()),
actorId);
await _mediaData.SaveAsync(cancellationToken);
return new WorkOrderMediaFileDto
{
Id = attachment.Id,
Category = attachment.Category ?? WorkOrderMediaCategory.Extra,
Url = attachment.Attachments ?? "",
UploadedAt = attachment.CreatedDate?.ToUniversalTime().ToString("o"),
IsLegacy = false
};
}
public async Task DeleteMediaAsync(
int workOrderId,
int mediaId,
string? workOrderVersion,
ClaimsPrincipal user,
string? actorId,
CancellationToken cancellationToken = default)
{
EnsureAuthenticatedCaller(user, actorId);
if (mediaId <= 0)
throw new WorkOrderBoardValidationException("InvalidMedia", "Legacy media cannot be deleted via this endpoint.");
var workOrder = await GetMutableWorkOrderAsync(workOrderId, cancellationToken);
ApplyExpectedVersion(workOrder, workOrderVersion);
var attachment = await _mediaData.GetTrackedAttachmentAsync(mediaId, workOrderId, cancellationToken);
if (attachment == null)
throw new WorkOrderBoardValidationException("NotFound", "Media not found.");
var priorCategory = (attachment.Category ?? WorkOrderMediaCategory.Extra).ToString();
attachment.IsDeleted = true;
attachment.DeletionTime = DateTime.UtcNow;
attachment.DeleterUserId = actorId;
_mediaData.MarkWorkOrderModified(workOrder);
await _auditService.StageFieldChangedAsync(
workOrderId,
"MediaCategory",
FormatMediaAuditValue(mediaId, priorCategory),
FormatMediaAuditValue(mediaId, "Deleted"),
actorId);
await _mediaData.SaveAsync(cancellationToken);
}
private async Task<WorkOrder> GetMutableWorkOrderAsync(int workOrderId, CancellationToken cancellationToken)
{
// Base-scoped lookup: deleted/template work orders surface as NotFound (no disclosure).
var workOrder = await _mediaData.GetTrackedWorkOrderAsync(workOrderId, cancellationToken);
if (workOrder == null)
throw new WorkOrderBoardValidationException("NotFound", "Work order not found.");
if (WorkOrderBoardMutationRules.IsReadOnly(workOrder.LifecycleStatus))
throw new WorkOrderBoardValidationException("ReadOnly", "Work order is read-only in its current status.");
return workOrder;
}
private void ApplyExpectedVersion(WorkOrder workOrder, string? workOrderVersion)
{
var expected = ParseRowVersion(workOrderVersion);
if (expected == null)
throw new WorkOrderBoardValidationException("WorkOrderVersionRequired", "workOrderVersion is required.");
if (workOrder.RowVersion == null || !workOrder.RowVersion.AsSpan().SequenceEqual(expected))
throw new WorkOrderBoardValidationException("ConcurrencyConflict", "Work order was modified. Refresh and retry.");
_mediaData.SetExpectedWorkOrderVersion(workOrder, expected);
}
private static void EnsureAuthenticatedCaller(ClaimsPrincipal user, string? actorId)
{
if (user is null
|| !(user.Identity?.IsAuthenticated ?? false)
|| string.IsNullOrWhiteSpace(actorId))
{
throw new WorkOrderBoardValidationException(
"Forbidden",
"You are not allowed to mutate work order media.");
}
}
private static byte[]? ParseRowVersion(string? base64)
{
if (string.IsNullOrWhiteSpace(base64))
return null;
try
{
return Convert.FromBase64String(base64);
}
catch (FormatException)
{
throw new WorkOrderBoardValidationException("InvalidRowVersion", "Invalid workOrderVersion format.");
}
}
private static string FormatMediaAuditValue(int? mediaId, string category)
=> mediaId.HasValue ? $"{mediaId.Value}:{category}" : category;
}
}