|
| 1 | +namespace ServiceControl.AcceptanceTesting.OpenIdConnect; |
| 2 | + |
| 3 | +using System; |
| 4 | +using System.Collections.Generic; |
| 5 | +using System.Linq; |
| 6 | +using System.Net; |
| 7 | +using System.Net.Http; |
| 8 | +using System.Threading; |
| 9 | +using System.Threading.Tasks; |
| 10 | +using Microsoft.AspNetCore.Authorization; |
| 11 | +using Microsoft.AspNetCore.Http; |
| 12 | +using Microsoft.AspNetCore.Routing; |
| 13 | +using Microsoft.AspNetCore.Routing.Patterns; |
| 14 | + |
| 15 | +/// <summary> |
| 16 | +/// Finds every route of a running instance that is not marked <c>[AllowAnonymous]</c>, and sends each |
| 17 | +/// one a request without a token. This covers every endpoint, so a new or changed authorization |
| 18 | +/// policy cannot let anonymous callers in without a test failing. |
| 19 | +/// </summary> |
| 20 | +public static class ProtectedRoutes |
| 21 | +{ |
| 22 | + /// <summary> |
| 23 | + /// Sends a request without a token to every protected route, and returns each route that did not |
| 24 | + /// answer 401, as "METHOD /path → status". |
| 25 | + /// </summary> |
| 26 | + public static async Task<IReadOnlyList<string>> FindRoutesNotRejectingAnonymousRequests( |
| 27 | + HttpClient client, |
| 28 | + EndpointDataSource endpointDataSource, |
| 29 | + CancellationToken cancellationToken = default) |
| 30 | + { |
| 31 | + var routes = endpointDataSource.Endpoints |
| 32 | + .OfType<RouteEndpoint>() |
| 33 | + .Where(endpoint => endpoint.Metadata.GetMetadata<IAllowAnonymous>() is null) |
| 34 | + .SelectMany(endpoint => (endpoint.Metadata.GetMetadata<HttpMethodMetadata>()?.HttpMethods ?? [HttpMethods.Get]) |
| 35 | + .Select(method => (Method: method, Path: BuildPath(endpoint.RoutePattern)))) |
| 36 | + .Distinct() |
| 37 | + .ToList(); |
| 38 | + |
| 39 | + if (routes.Count == 0) |
| 40 | + { |
| 41 | + throw new InvalidOperationException("No protected routes found. The endpoint data source is empty or every route allows anonymous access."); |
| 42 | + } |
| 43 | + |
| 44 | + var notRejected = new List<string>(); |
| 45 | + |
| 46 | + foreach (var (method, path) in routes) |
| 47 | + { |
| 48 | + using var response = await OpenIdConnectAssertions.SendRequestWithoutAuth(client, new HttpMethod(method), path, cancellationToken); |
| 49 | + |
| 50 | + if (response.StatusCode != HttpStatusCode.Unauthorized) |
| 51 | + { |
| 52 | + notRejected.Add($"{method} {path} → {(int)response.StatusCode}"); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + return notRejected; |
| 57 | + } |
| 58 | + |
| 59 | + // Fills each route parameter with a value that satisfies its constraint, so the request matches the |
| 60 | + // route and reaches the authorization middleware instead of failing with 404. |
| 61 | + static string BuildPath(RoutePattern pattern) |
| 62 | + { |
| 63 | + var segments = pattern.PathSegments.Select(segment => string.Concat(segment.Parts.Select(part => part switch |
| 64 | + { |
| 65 | + RoutePatternLiteralPart literal => literal.Content, |
| 66 | + RoutePatternSeparatorPart separator => separator.Content, |
| 67 | + RoutePatternParameterPart parameter => SampleValue(parameter), |
| 68 | + _ => throw new NotSupportedException($"Unsupported route pattern part: {part.GetType().Name}") |
| 69 | + }))); |
| 70 | + |
| 71 | + return "/" + string.Join('/', segments); |
| 72 | + } |
| 73 | + |
| 74 | + static string SampleValue(RoutePatternParameterPart parameter) |
| 75 | + { |
| 76 | + var constraints = parameter.ParameterPolicies.Select(policy => policy.Content ?? string.Empty).ToArray(); |
| 77 | + |
| 78 | + if (constraints.Contains("guid", StringComparer.OrdinalIgnoreCase)) |
| 79 | + { |
| 80 | + return Guid.Empty.ToString(); |
| 81 | + } |
| 82 | + |
| 83 | + if (constraints.Any(constraint => constraint is "int" or "long")) |
| 84 | + { |
| 85 | + return "1"; |
| 86 | + } |
| 87 | + |
| 88 | + if (constraints.Contains("bool", StringComparer.OrdinalIgnoreCase)) |
| 89 | + { |
| 90 | + return bool.TrueString; |
| 91 | + } |
| 92 | + |
| 93 | + return "x"; |
| 94 | + } |
| 95 | +} |
0 commit comments