|
| 1 | +using System.Diagnostics; |
| 2 | +using System.Text.Json; |
| 3 | +using Microsoft.AspNetCore.Http; |
| 4 | +using Microsoft.AspNetCore.Mvc; |
| 5 | + |
| 6 | +namespace PythonScriptRunner.Dashboard; |
| 7 | + |
| 8 | +/// <summary>Errors of the API as <c>ProblemDetails</c> (RFC 9457) with the extensions <c>code</c>, <c>errors</c>, <c>current</c> and <c>traceId</c>.</summary> |
| 9 | +internal static class ApiProblems |
| 10 | +{ |
| 11 | + public static ProblemDetails Create(HttpContext context, int status, string code, string title, string? detail = null) |
| 12 | + { |
| 13 | + var problem = new ProblemDetails |
| 14 | + { |
| 15 | + Status = status, |
| 16 | + Title = title, |
| 17 | + Detail = detail, |
| 18 | + Type = $"https://httpstatuses.io/{status}", |
| 19 | + }; |
| 20 | + problem.Extensions["code"] = code; |
| 21 | + problem.Extensions["traceId"] = Activity.Current?.TraceId.ToHexString() ?? context.TraceIdentifier; |
| 22 | + return problem; |
| 23 | + } |
| 24 | + |
| 25 | + public static IResult Result(HttpContext context, int status, string code, string title, string? detail = null, Action<ProblemDetails>? extend = null) |
| 26 | + { |
| 27 | + var problem = Create(context, status, code, title, detail); |
| 28 | + extend?.Invoke(problem); |
| 29 | + return TypedResults.Problem(problem); |
| 30 | + } |
| 31 | + |
| 32 | + public static IResult NotFound(HttpContext context, string detail) => |
| 33 | + Result(context, StatusCodes.Status404NotFound, "NOT_FOUND", "The resource was not found.", detail); |
| 34 | + |
| 35 | + public static Task WriteAsync(HttpContext context, int status, string code, string title, string? detail = null) |
| 36 | + { |
| 37 | + context.Response.StatusCode = status; |
| 38 | + return context.Response.WriteAsJsonAsync(Create(context, status, code, title, detail), options: null, contentType: "application/problem+json"); |
| 39 | + } |
| 40 | + |
| 41 | + /// <summary>Maps a domain exception to its status (spec 007); <c>null</c> for unexpected exceptions.</summary> |
| 42 | + public static IResult? FromException(HttpContext context, Exception exception) => exception switch |
| 43 | + { |
| 44 | + InputValidationException invalid => Result(context, StatusCodes.Status400BadRequest, "INPUT_INVALID", "The inputs do not match the contract.", |
| 45 | + invalid.Message, p => p.Extensions["errors"] = invalid.Errors |
| 46 | + .GroupBy(e => e.Field) |
| 47 | + .ToDictionary(g => g.Key, g => g.Select(e => new { e.Code, e.Message }).ToArray())), |
| 48 | + ConcurrencyConflictException conflict => Result(context, StatusCodes.Status412PreconditionFailed, conflict.Code, "The resource was changed by someone else.", |
| 49 | + conflict.Message, p => p.Extensions["current"] = conflict.Current), |
| 50 | + ScriptSyntaxException syntax => Result(context, StatusCodes.Status422UnprocessableEntity, syntax.Code, "The script does not compile.", |
| 51 | + syntax.Message, p => |
| 52 | + { |
| 53 | + p.Extensions["line"] = syntax.Line; |
| 54 | + p.Extensions["column"] = syntax.Column; |
| 55 | + }), |
| 56 | + DefinitionInvalidException definition => Result(context, |
| 57 | + definition.Code == PsrErrorCodes.ImportInvalid ? StatusCodes.Status400BadRequest : StatusCodes.Status422UnprocessableEntity, |
| 58 | + definition.Code, "The definition is not valid.", definition.Message, p => p.Extensions["report"] = definition.Report), |
| 59 | + VersionReferencedException referenced => Result(context, StatusCodes.Status409Conflict, referenced.Code, "The version is in use.", |
| 60 | + referenced.Message, p => p.Extensions["pipelines"] = referenced.Pipelines), |
| 61 | + PsrDomainException domain => Result(context, StatusOf(domain.Code), domain.Code, Title(domain.Code), domain.Message), |
| 62 | + StageNotFoundException or PipelineNotFoundException or VersionNotFoundException or RunNotFoundException or ArtifactNotFoundException => |
| 63 | + Result(context, StatusCodes.Status404NotFound, "NOT_FOUND", "The resource was not found.", exception.Message), |
| 64 | + VersionNotRunnableException => Result(context, StatusCodes.Status409Conflict, "VERSION_NOT_RUNNABLE", "The version cannot run.", exception.Message), |
| 65 | + PayloadTooLargeException or BadHttpRequestException { StatusCode: StatusCodes.Status413PayloadTooLarge } => |
| 66 | + Result(context, StatusCodes.Status413PayloadTooLarge, "PAYLOAD_TOO_LARGE", "The upload is larger than allowed.", exception.Message), |
| 67 | + BadHttpRequestException bad => Result(context, bad.StatusCode, "BAD_REQUEST", "The request is not valid.", exception.Message), |
| 68 | + ArgumentException or JsonException or InvalidDataException => |
| 69 | + Result(context, StatusCodes.Status400BadRequest, "INVALID_ARGUMENT", "The request is not valid.", exception.Message), |
| 70 | + _ => null, |
| 71 | + }; |
| 72 | + |
| 73 | + private static int StatusOf(string code) => code switch |
| 74 | + { |
| 75 | + PsrErrorCodes.ConcurrencyConflict => StatusCodes.Status412PreconditionFailed, |
| 76 | + PsrErrorCodes.ArtifactExpired => StatusCodes.Status410Gone, |
| 77 | + PsrErrorCodes.ScheduleNotFound => StatusCodes.Status404NotFound, |
| 78 | + PsrErrorCodes.ScriptSyntaxError or PsrErrorCodes.DependencyResolutionFailed or PsrErrorCodes.StageInvalid or PsrErrorCodes.PipelineInvalid |
| 79 | + => StatusCodes.Status422UnprocessableEntity, |
| 80 | + PsrErrorCodes.RetentionExceedsGlobal or PsrErrorCodes.ScheduleFileInput or PsrErrorCodes.InvalidCron or PsrErrorCodes.InvalidTimeZone |
| 81 | + or PsrErrorCodes.ScheduleInvalid or PsrErrorCodes.ImportInvalid or PsrErrorCodes.FileInputNotAllowed => StatusCodes.Status400BadRequest, |
| 82 | + _ => StatusCodes.Status409Conflict, |
| 83 | + }; |
| 84 | + |
| 85 | + private static string Title(string code) => code switch |
| 86 | + { |
| 87 | + PsrErrorCodes.ArtifactExpired => "The file is beyond the retention.", |
| 88 | + PsrErrorCodes.ScheduleNotFound => "The schedule was not found.", |
| 89 | + _ => "The operation is not allowed in the current state.", |
| 90 | + }; |
| 91 | +} |
| 92 | + |
| 93 | +/// <summary> |
| 94 | +/// Endpoint filter of the API: requires <c>X-PSR-Request: 1</c> on mutating requests (CSRF; QA-007-3) and turns domain |
| 95 | +/// exceptions into <c>ProblemDetails</c>. |
| 96 | +/// </summary> |
| 97 | +internal sealed class ApiFilter : IEndpointFilter |
| 98 | +{ |
| 99 | + public const string CsrfHeader = "X-PSR-Request"; |
| 100 | + |
| 101 | + public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next) |
| 102 | + { |
| 103 | + ArgumentNullException.ThrowIfNull(context); |
| 104 | + ArgumentNullException.ThrowIfNull(next); |
| 105 | + var http = context.HttpContext; |
| 106 | + if (!HttpMethods.IsGet(http.Request.Method) && !HttpMethods.IsHead(http.Request.Method) && !HttpMethods.IsOptions(http.Request.Method) |
| 107 | + && http.Request.Headers[CsrfHeader] != "1") |
| 108 | + { |
| 109 | + return ApiProblems.Result(http, StatusCodes.Status400BadRequest, "CSRF_HEADER_MISSING", |
| 110 | + $"Mutating requests must send the header {CsrfHeader}: 1."); |
| 111 | + } |
| 112 | + |
| 113 | + try |
| 114 | + { |
| 115 | + return await next(context).ConfigureAwait(false); |
| 116 | + } |
| 117 | + catch (Exception ex) when (ApiProblems.FromException(http, ex) is { } problem) |
| 118 | + { |
| 119 | + return problem; |
| 120 | + } |
| 121 | + } |
| 122 | +} |
| 123 | + |
| 124 | +/// <summary>An uploaded file or the whole upload exceeds the limits (413 before any run is created).</summary> |
| 125 | +internal sealed class PayloadTooLargeException(string message) : Exception(message); |
| 126 | + |
| 127 | +/// <summary>Optimistic concurrency with <c>ETag</c> = row version (<c>xmin</c>) and <c>If-Match</c>.</summary> |
| 128 | +internal static class ETags |
| 129 | +{ |
| 130 | + public static string Of(uint rowVersion) => $"\"{rowVersion}\""; |
| 131 | + |
| 132 | + public static void Set(HttpContext context, uint rowVersion) => context.Response.Headers.ETag = Of(rowVersion); |
| 133 | + |
| 134 | + /// <summary>The row version sent in <c>If-Match</c>; <c>null</c> when missing or malformed.</summary> |
| 135 | + public static uint? IfMatch(HttpContext context) => |
| 136 | + context.Request.Headers.IfMatch.ToString().Trim().Trim('"') is { Length: > 0 } text && uint.TryParse(text, out var version) ? version : null; |
| 137 | + |
| 138 | + public static IResult Required(HttpContext context) => |
| 139 | + ApiProblems.Result(context, StatusCodes.Status428PreconditionRequired, "IF_MATCH_REQUIRED", "Send the ETag read before in If-Match."); |
| 140 | +} |
0 commit comments