| | | 1 | | using System.Globalization; |
| | | 2 | | using System.Runtime.CompilerServices; |
| | | 3 | | using System.Text.Json; |
| | | 4 | | using System.Text.Json.Serialization; |
| | | 5 | | using Elsa.Workflows; |
| | | 6 | | using FastEndpoints; |
| | | 7 | | using JetBrains.Annotations; |
| | | 8 | | using Microsoft.AspNetCore.Builder; |
| | | 9 | | using Microsoft.AspNetCore.Http; |
| | | 10 | | using Microsoft.AspNetCore.RateLimiting; |
| | | 11 | | using Microsoft.AspNetCore.Routing; |
| | | 12 | | using Microsoft.Extensions.DependencyInjection; |
| | | 13 | | |
| | | 14 | | // ReSharper disable once CheckNamespace |
| | | 15 | | namespace Elsa.Extensions; |
| | | 16 | | |
| | | 17 | | /// <summary> |
| | | 18 | | /// Provides extension methods to add FastEndpoints configured for use with Elsa API endpoints. |
| | | 19 | | /// </summary> |
| | | 20 | | [PublicAPI] |
| | | 21 | | public static class WebApplicationExtensions |
| | | 22 | | { |
| | 0 | 23 | | private static readonly RequestDelegate NotFoundRequestDelegate = context => |
| | 0 | 24 | | { |
| | 0 | 25 | | context.Response.StatusCode = StatusCodes.Status404NotFound; |
| | 0 | 26 | | return Task.CompletedTask; |
| | 0 | 27 | | }; |
| | | 28 | | |
| | | 29 | | /// <summary> |
| | | 30 | | /// Registers the FastEndpoints middleware configured for use with Elsa API endpoints. |
| | | 31 | | /// </summary> |
| | | 32 | | /// <param name="app"></param> |
| | | 33 | | /// <param name="routePrefix">The route prefix to apply to Elsa API endpoints.</param> |
| | | 34 | | /// <example>E.g. "elsa/api" will expose endpoints like this: "/elsa/api/workflow-definitions"</example> |
| | | 35 | | public static IApplicationBuilder UseWorkflowsApi(this IApplicationBuilder app, string routePrefix = "elsa/api") |
| | | 36 | | { |
| | 0 | 37 | | return app.UseFastEndpoints(config => ConfigureWorkflowsApi(config, routePrefix)); |
| | | 38 | | } |
| | | 39 | | |
| | | 40 | | /// <summary> |
| | | 41 | | /// Applies an ASP.NET Core rate limiting policy to requests targeting the Elsa API route prefix. |
| | | 42 | | /// </summary> |
| | | 43 | | /// <param name="app">The application builder.</param> |
| | | 44 | | /// <param name="routePrefix">The route prefix used by Elsa API endpoints.</param> |
| | | 45 | | /// <param name="policyName">The registered ASP.NET Core rate limiting policy name. Leave empty to skip rate limitin |
| | | 46 | | public static IApplicationBuilder UseWorkflowsApiRateLimiting(this IApplicationBuilder app, string routePrefix = "el |
| | | 47 | | { |
| | 3 | 48 | | if (string.IsNullOrWhiteSpace(policyName)) |
| | 3 | 49 | | return app; |
| | | 50 | | |
| | 0 | 51 | | var pathPrefix = NormalizeRoutePrefixPath(routePrefix); |
| | 0 | 52 | | return app.UseRateLimitingPolicyForPath(pathPrefix, policyName, "Elsa API rate limiting endpoint", requireMatche |
| | | 53 | | } |
| | | 54 | | |
| | | 55 | | /// <summary> |
| | | 56 | | /// Maps FastEndpoints endpoint routes configured for use with Elsa API endpoints. |
| | | 57 | | /// </summary> |
| | | 58 | | /// <param name="routes">The <see cref="IEndpointRouteBuilder"/> to register the endpoints with.</param> |
| | | 59 | | /// <param name="routePrefix">The route prefix to apply to Elsa API endpoints.</param> |
| | | 60 | | /// <example>E.g. "elsa/api" will expose endpoints like this: "/elsa/api/workflow-definitions"</example> |
| | | 61 | | public static IEndpointRouteBuilder MapWorkflowsApi(this IEndpointRouteBuilder routes, string routePrefix = "elsa/ap |
| | 6 | 62 | | routes.MapFastEndpoints(config => ConfigureWorkflowsApi(config, routePrefix)); |
| | | 63 | | |
| | | 64 | | /// <summary> |
| | | 65 | | /// Applies an ASP.NET Core rate limiting policy to requests targeting the specified path prefix. |
| | | 66 | | /// </summary> |
| | | 67 | | /// <param name="app">The application builder.</param> |
| | | 68 | | /// <param name="pathPrefix">The path prefix to protect.</param> |
| | | 69 | | /// <param name="policyName">The registered ASP.NET Core rate limiting policy name.</param> |
| | | 70 | | /// <param name="displayName">The endpoint display name used for rate limiting metadata.</param> |
| | | 71 | | /// <remarks> |
| | | 72 | | /// This method only attaches rate limiting metadata. In endpoint-routed pipelines, call this after routing has sele |
| | | 73 | | /// and before the host's single <c>app.UseRateLimiter()</c> middleware. ASP.NET Core validates the configured polic |
| | | 74 | | /// rate limiter middleware handles matching requests. |
| | | 75 | | /// </remarks> |
| | | 76 | | public static IApplicationBuilder UseRateLimitingPolicyForPath(this IApplicationBuilder app, PathString pathPrefix, |
| | 0 | 77 | | app.UseRateLimitingPolicyForPath(pathPrefix, policyName, displayName, true); |
| | | 78 | | |
| | | 79 | | /// <summary> |
| | | 80 | | /// Applies an ASP.NET Core rate limiting policy to requests targeting the specified path prefix. |
| | | 81 | | /// </summary> |
| | | 82 | | /// <param name="app">The application builder.</param> |
| | | 83 | | /// <param name="pathPrefix">The path prefix to protect.</param> |
| | | 84 | | /// <param name="policyName">The registered ASP.NET Core rate limiting policy name.</param> |
| | | 85 | | /// <param name="displayName">The endpoint display name used for rate limiting metadata.</param> |
| | | 86 | | /// <param name="requireMatchedEndpoint">Whether to skip rate limiting when endpoint routing selected no endpoint.</ |
| | | 87 | | public static IApplicationBuilder UseRateLimitingPolicyForPath(this IApplicationBuilder app, PathString pathPrefix, |
| | | 88 | | { |
| | 0 | 89 | | if (!pathPrefix.HasValue || string.IsNullOrWhiteSpace(policyName)) |
| | 0 | 90 | | return app; |
| | | 91 | | |
| | 0 | 92 | | var rateLimitingMetadata = new EnableRateLimitingAttribute(policyName); |
| | 0 | 93 | | var fallbackEndpoint = CreateRateLimitingEndpoint(null, rateLimitingMetadata, displayName); |
| | 0 | 94 | | var endpointCache = new ConditionalWeakTable<Endpoint, Endpoint>(); |
| | | 95 | | |
| | 0 | 96 | | return app.UseWhen( |
| | 0 | 97 | | context => context.Request.Path.StartsWithSegments(pathPrefix, StringComparison.OrdinalIgnoreCase), |
| | 0 | 98 | | branch => |
| | 0 | 99 | | { |
| | 0 | 100 | | branch.Use(async (context, next) => |
| | 0 | 101 | | { |
| | 0 | 102 | | var originalEndpoint = context.GetEndpoint(); |
| | 0 | 103 | | if (requireMatchedEndpoint && originalEndpoint == null) |
| | 0 | 104 | | { |
| | 0 | 105 | | await next(context); |
| | 0 | 106 | | return; |
| | 0 | 107 | | } |
| | 0 | 108 | | |
| | 0 | 109 | | var rateLimitingEndpoint = originalEndpoint == null |
| | 0 | 110 | | ? fallbackEndpoint |
| | 0 | 111 | | : endpointCache.GetValue(originalEndpoint, endpoint => CreateRateLimitingEndpoint(endpoint, rate |
| | 0 | 112 | | |
| | 0 | 113 | | context.SetEndpoint(rateLimitingEndpoint); |
| | 0 | 114 | | |
| | 0 | 115 | | try |
| | 0 | 116 | | { |
| | 0 | 117 | | await next(context); |
| | 0 | 118 | | } |
| | 0 | 119 | | finally |
| | 0 | 120 | | { |
| | 0 | 121 | | if (ReferenceEquals(context.GetEndpoint(), rateLimitingEndpoint)) |
| | 0 | 122 | | context.SetEndpoint(originalEndpoint); |
| | 0 | 123 | | } |
| | 0 | 124 | | }); |
| | 0 | 125 | | }); |
| | | 126 | | } |
| | | 127 | | |
| | | 128 | | private static PathString NormalizeRoutePrefixPath(string routePrefix) |
| | | 129 | | { |
| | 0 | 130 | | var value = routePrefix.Trim().Trim('/'); |
| | | 131 | | |
| | 0 | 132 | | return string.IsNullOrEmpty(value) ? PathString.Empty : new PathString("/" + value); |
| | | 133 | | } |
| | | 134 | | |
| | | 135 | | private static void ConfigureWorkflowsApi(Config config, string routePrefix) |
| | | 136 | | { |
| | 3 | 137 | | config.Endpoints.RoutePrefix = routePrefix; |
| | 3 | 138 | | config.Serializer.RequestDeserializer = DeserializeRequestAsync; |
| | 3 | 139 | | config.Serializer.ResponseSerializer = SerializeRequestAsync; |
| | | 140 | | |
| | 3 | 141 | | config.Binding.ValueParserFor<DateTimeOffset>(s => |
| | 3 | 142 | | new(DateTimeOffset.TryParse(s.ToString(), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out va |
| | 3 | 143 | | } |
| | | 144 | | |
| | | 145 | | private static Endpoint CreateRateLimitingEndpoint(Endpoint? originalEndpoint, EnableRateLimitingAttribute rateLimit |
| | | 146 | | { |
| | 0 | 147 | | var metadata = originalEndpoint == null |
| | 0 | 148 | | ? new EndpointMetadataCollection(rateLimitingMetadata) |
| | 0 | 149 | | : new EndpointMetadataCollection(originalEndpoint.Metadata.Where(x => x is not EnableRateLimitingAttribute a |
| | | 150 | | |
| | 0 | 151 | | if (originalEndpoint is RouteEndpoint routeEndpoint) |
| | 0 | 152 | | return new RouteEndpoint(routeEndpoint.RequestDelegate ?? NotFoundRequestDelegate, routeEndpoint.RoutePatter |
| | | 153 | | |
| | 0 | 154 | | return new Endpoint(originalEndpoint?.RequestDelegate ?? NotFoundRequestDelegate, metadata, originalEndpoint?.Di |
| | | 155 | | } |
| | | 156 | | |
| | | 157 | | private static ValueTask<object?> DeserializeRequestAsync(HttpRequest httpRequest, Type modelType, JsonSerializerCon |
| | | 158 | | { |
| | 5 | 159 | | var serializer = httpRequest.HttpContext.RequestServices.GetRequiredService<IApiSerializer>(); |
| | 5 | 160 | | var options = serializer.GetOptions(); |
| | | 161 | | |
| | 5 | 162 | | return serializerContext == null |
| | 5 | 163 | | ? JsonSerializer.DeserializeAsync(httpRequest.Body, modelType, options, cancellationToken) |
| | 5 | 164 | | : JsonSerializer.DeserializeAsync(httpRequest.Body, modelType, serializerContext, cancellationToken); |
| | | 165 | | } |
| | | 166 | | |
| | | 167 | | private static Task SerializeRequestAsync(HttpResponse httpResponse, object? dto, string contentType, JsonSerializer |
| | | 168 | | { |
| | 5 | 169 | | var serializer = httpResponse.HttpContext.RequestServices.GetRequiredService<IApiSerializer>(); |
| | 5 | 170 | | var options = serializer.GetOptions(); |
| | | 171 | | |
| | 5 | 172 | | httpResponse.ContentType = contentType; |
| | 5 | 173 | | return serializerContext == null |
| | 5 | 174 | | ? JsonSerializer.SerializeAsync(httpResponse.Body, dto, dto?.GetType() ?? typeof(object), options, cancellat |
| | 5 | 175 | | : JsonSerializer.SerializeAsync(httpResponse.Body, dto, dto?.GetType() ?? typeof(object), serializerContext, |
| | | 176 | | } |
| | | 177 | | |
| | | 178 | | } |