|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | + |
| 4 | +using System.Diagnostics.CodeAnalysis; |
| 5 | + |
| 6 | +namespace Aspire.Dashboard.Utils; |
| 7 | + |
| 8 | +/// <summary> |
| 9 | +/// Helpers for validating redirect URLs. |
| 10 | +/// </summary> |
| 11 | +internal static class UrlValidationHelper |
| 12 | +{ |
| 13 | + /// <summary> |
| 14 | + /// Checks whether a URL is safe to use as a redirect target. |
| 15 | + /// The URL must be a valid URI and a local path (not absolute or protocol-relative). |
| 16 | + /// </summary> |
| 17 | + internal static bool IsSafeRedirectUrl([NotNullWhen(true)] string? url) |
| 18 | + { |
| 19 | + return Uri.TryCreate(url, UriKind.Relative, out _) && IsLocalUrl(url); |
| 20 | + } |
| 21 | + |
| 22 | + // Copied from ASP.NET Core's IsLocalUrl implementation: |
| 23 | + // https://github.com/dotnet/aspnetcore/blob/7cbda0e023075490b4365a0754ca410ce6eff59a/src/Shared/ResultsHelpers/SharedUrlHelper.cs#L33 |
| 24 | + internal static bool IsLocalUrl([NotNullWhen(true)] string? url) |
| 25 | + { |
| 26 | + if (string.IsNullOrEmpty(url)) |
| 27 | + { |
| 28 | + return false; |
| 29 | + } |
| 30 | + |
| 31 | + // Allows "/" or "/foo" but not "//" or "/\". |
| 32 | + if (url[0] == '/') |
| 33 | + { |
| 34 | + // url is exactly "/" |
| 35 | + if (url.Length == 1) |
| 36 | + { |
| 37 | + return true; |
| 38 | + } |
| 39 | + |
| 40 | + // url doesn't start with "//" or "/\" |
| 41 | + if (url[1] != '/' && url[1] != '\\') |
| 42 | + { |
| 43 | + return !HasControlCharacter(url.AsSpan(1)); |
| 44 | + } |
| 45 | + |
| 46 | + return false; |
| 47 | + } |
| 48 | + |
| 49 | + // Allows "~/" or "~/foo" but not "~//" or "~/\". |
| 50 | + if (url[0] == '~' && url.Length > 1 && url[1] == '/') |
| 51 | + { |
| 52 | + // url is exactly "~/" |
| 53 | + if (url.Length == 2) |
| 54 | + { |
| 55 | + return true; |
| 56 | + } |
| 57 | + |
| 58 | + // url doesn't start with "~//" or "~/\" |
| 59 | + if (url[2] != '/' && url[2] != '\\') |
| 60 | + { |
| 61 | + return !HasControlCharacter(url.AsSpan(2)); |
| 62 | + } |
| 63 | + |
| 64 | + return false; |
| 65 | + } |
| 66 | + |
| 67 | + return false; |
| 68 | + |
| 69 | + static bool HasControlCharacter(ReadOnlySpan<char> readOnlySpan) |
| 70 | + { |
| 71 | + // URLs may not contain ASCII control characters. |
| 72 | + for (var i = 0; i < readOnlySpan.Length; i++) |
| 73 | + { |
| 74 | + if (char.IsControl(readOnlySpan[i])) |
| 75 | + { |
| 76 | + return true; |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + return false; |
| 81 | + } |
| 82 | + } |
| 83 | +} |
0 commit comments