diff --git a/CHANGELOG.md b/CHANGELOG.md index ae16923f..da355a97 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes to this project will be documented in this file. - Redirects can be set to *Exact match*, so a redirect from `/a` no longer also applies to `/a/b`. `/a/` and `/a?b=c` still match, as the query string isn't part of it. It's available on the Redirects tab, and in imported and exported CSV and XML files. Files without it still import, as a redirect that isn't exact. An import or an automatic redirect for an old url that's already saved replaces the row, so it clears the setting unless it sets it too, as it does with the wildcard setting and the redirect type. - Each regex redirect can have its own redirect type. Rules saved earlier keep following `DefaultRedirectType` until you edit them, which saves the type shown on the form. +- Patterns on the *Ignored* tab, such as `/api/*` or `*.php`, stop every url matching them from being logged as a suggestion, and remove the suggestions already logged for them. A pattern only stops suggestions, so a redirect or regex redirect that applies to a url keeps working. It's the same idea as `IgnoreSuggestionsUrlRegexPattern`, but editors can do it without a deploy. ### Security @@ -25,6 +26,8 @@ Check these when upgrading, as they change how existing rules and integrations b - URLs under an entry in the Deleted list now return `410`. Before, `/gone/`, `/gone?a=1` and `/gone/child` were redirected, often to the home page. - A request with no matching redirect keeps the status the application gave it. Before, a response that hadn't started yet was forced to `404`. `RequestHandler.SetStatusCodeAndShow404` is now only called for deleted URLs, so a subclass overriding it no longer runs for unmatched requests. - `HttpContextExtensions.SetStatusCode` no longer clears the response, so a custom page keeps its headers when its status changes to `410`. +- An ignored url with a `*` in it, which used to only ignore that literal url, is now a pattern. `/*`, `https://example.com/*` and others with nothing but wildcards and slashes in the path aren't, as they would stop all suggestions. Neither is one with an encoded `%2A` instead of a `*`. +- `ISuggestionRepository` has a new `DeleteMatching` method, which does nothing unless a class implementing it adds it, so suggestions stay in the list when adding a pattern. `IgnoredModel` takes an `ISuggestionService`. - CSV export: an imported file that was exported with escaped values keeps the `'` prefix and the `%3B` as part of the value. - Automatic redirects are no longer created for urls with an extension in `IgnoredResourceExtensions`, as requests for those urls aren't redirected. Rows created earlier stay until you delete them. Check this if you override `RequestHandler.IsResourceFile` to redirect such files, or have pages with a url like `/docs/node.js` with no trailing slash and children below them, as those children used to be redirected through that row. `RedirectBuilder` takes an `IOptions`. - A regex rule anchored at a `/`, such as `^/en/(.*)`, now matches against the path and query. It used to never match, as rules see the whole url, so one that has been sitting unused starts redirecting. Check your rules for this before upgrading. All other rules still only see the whole url. diff --git a/README.md b/README.md index 8d47daf2..139bd0da 100644 --- a/README.md +++ b/README.md @@ -182,6 +182,12 @@ services.AddNotFoundHandler(o => When a URL matches the specified regex pattern, suggestions will be skipped. +Editors can do the same without a deploy, by adding a pattern with `*` as the wildcard on the *Ignored* tab, such as `/api/*`, `*.php` or `https://example.com/api/*`. A `*` also matches slashes and the query string. Adding one removes the suggestions already logged for those URLs, as far as they're stored in the same form. A pattern naming a host doesn't remove suggestions logged without one, and an encoded suggestion such as `/a%20b` doesn't match the pattern `/a b*`. They stay in the list until you delete them, but aren't logged again. + +A pattern starting with `http` is compared to the whole URL, and any other pattern to the path and query, so `*.com*` doesn't match on the host. The scheme has to match too, so use `http*://example.com/api/*` for both. `*` is the only wildcard, so a `?` is just a `?`. + +A pattern only stops suggestions. A redirect or a regex redirect that applies to a URL keeps working. `/*` and `https://example.com/*` aren't treated as patterns, as they would match everything: set `Logging` to `LoggerMode.Off` for that. + ## Restricting access to the Admin UI diff --git a/src/Geta.NotFoundHandler.Admin/Areas/GetaNotFoundHandlerAdmin/Pages/Ignored.cshtml b/src/Geta.NotFoundHandler.Admin/Areas/GetaNotFoundHandlerAdmin/Pages/Ignored.cshtml index 5d3cc122..d14d2471 100644 --- a/src/Geta.NotFoundHandler.Admin/Areas/GetaNotFoundHandlerAdmin/Pages/Ignored.cshtml +++ b/src/Geta.NotFoundHandler.Admin/Areas/GetaNotFoundHandlerAdmin/Pages/Ignored.cshtml @@ -18,6 +18,21 @@ + + + + +
Use * to ignore every url matching it. Redirects that apply to those urls keep working.
+ + +
+ +
+ + @foreach (var item in Model.Items) { diff --git a/src/Geta.NotFoundHandler.Admin/Areas/GetaNotFoundHandlerAdmin/Pages/Ignored.cshtml.cs b/src/Geta.NotFoundHandler.Admin/Areas/GetaNotFoundHandlerAdmin/Pages/Ignored.cshtml.cs index 0758a4e9..9c072cc8 100644 --- a/src/Geta.NotFoundHandler.Admin/Areas/GetaNotFoundHandlerAdmin/Pages/Ignored.cshtml.cs +++ b/src/Geta.NotFoundHandler.Admin/Areas/GetaNotFoundHandlerAdmin/Pages/Ignored.cshtml.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Linq; using Geta.NotFoundHandler.Admin.Areas.GetaNotFoundHandlerAdmin.Pages.Base; @@ -5,6 +6,7 @@ using Geta.NotFoundHandler.Admin.Areas.GetaNotFoundHandlerAdmin.Pages.Models; using Geta.NotFoundHandler.Admin.Pages.Geta.NotFoundHandler.Admin.Models; using Geta.NotFoundHandler.Core.Redirects; +using Geta.NotFoundHandler.Core.Suggestions; using Geta.NotFoundHandler.Infrastructure; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; @@ -17,16 +19,21 @@ namespace Geta.NotFoundHandler.Admin.Pages.Geta.NotFoundHandler.Admin; public class IgnoredModel : AbstractSortablePageModel { private readonly IRedirectsService _redirectsService; + private readonly ISuggestionService _suggestionService; - public IgnoredModel(IRedirectsService redirectsService) + public IgnoredModel(IRedirectsService redirectsService, ISuggestionService suggestionService) { _redirectsService = redirectsService; + _suggestionService = suggestionService; } public string Message { get; set; } public IPagedList Items { get; set; } = Enumerable.Empty().ToPagedList(); + [BindProperty] + public IgnorePatternModel NewPattern { get; set; } + [BindProperty(SupportsGet = true)] public Paging Paging { get; set; } @@ -37,6 +44,38 @@ public void OnGet(string sortColumn, SortDirection? sortDirection) Load(); } + public IActionResult OnPostCreate() + { + var pattern = NewPattern?.Pattern?.Trim(); + + if (ModelState.IsValid && !IsValidPattern(pattern)) + { + ModelState.AddModelError( + $"{nameof(NewPattern)}.{nameof(IgnorePatternModel.Pattern)}", + "Enter a url starting with /, * or http://, with a * in it and more than wildcards and slashes in the path, such as /api/* or *.php."); + } + + // Note: Saving replaces a row with the same old url, which would silently remove a redirect. + if (ModelState.IsValid && IsSavedAsAnotherState(pattern)) + { + ModelState.AddModelError( + $"{nameof(NewPattern)}.{nameof(IgnorePatternModel.Pattern)}", + $"{pattern} is already saved as a redirect or a deleted url. Remove it there first."); + } + + if (!ModelState.IsValid) + { + Load(); + return Page(); + } + + _suggestionService.IgnoreSuggestion(pattern); + + Confirmation = $"Ignoring suggestions for {pattern}."; + + return RedirectToPage(); + } + public IActionResult OnPostUnignore(string oldUrl) { _redirectsService.DeleteByOldUrl(oldUrl); @@ -46,6 +85,24 @@ public IActionResult OnPostUnignore(string oldUrl) return RedirectToPage(); } + private static bool IsValidPattern(string pattern) + { + // Note: Requests are matched by path or whole url, so anything else would never match. + var hasValidStart = pattern.StartsWith('/') + || pattern.StartsWith('*') + || IgnorePattern.IsAbsolute(pattern); + + return hasValidStart && IgnorePattern.IsPattern(pattern); + } + + private bool IsSavedAsAnotherState(string pattern) + { + return _redirectsService + .GetAll() + .Any(x => x.State != (int)RedirectState.Ignored + && string.Equals(x.OldUrl, pattern, StringComparison.OrdinalIgnoreCase)); + } + private void Load() { var items = FindRedirects().ToPagedList(Paging.PageNumber, Paging.PageSize); diff --git a/src/Geta.NotFoundHandler.Admin/Areas/GetaNotFoundHandlerAdmin/Pages/Models/IgnorePatternModel.cs b/src/Geta.NotFoundHandler.Admin/Areas/GetaNotFoundHandlerAdmin/Pages/Models/IgnorePatternModel.cs new file mode 100644 index 00000000..5b1b0964 --- /dev/null +++ b/src/Geta.NotFoundHandler.Admin/Areas/GetaNotFoundHandlerAdmin/Pages/Models/IgnorePatternModel.cs @@ -0,0 +1,11 @@ +using System.ComponentModel.DataAnnotations; + +namespace Geta.NotFoundHandler.Admin.Pages.Geta.NotFoundHandler.Admin.Models +{ + public class IgnorePatternModel + { + [Required] + [StringLength(2000)] + public string Pattern { get; set; } + } +} diff --git a/src/Geta.NotFoundHandler/Core/Redirects/CustomRedirectCollection.cs b/src/Geta.NotFoundHandler/Core/Redirects/CustomRedirectCollection.cs index 8684099a..fc425fa2 100644 --- a/src/Geta.NotFoundHandler/Core/Redirects/CustomRedirectCollection.cs +++ b/src/Geta.NotFoundHandler/Core/Redirects/CustomRedirectCollection.cs @@ -30,6 +30,11 @@ public class CustomRedirectCollection : IEnumerable /// private KeyValuePair[] _redirectsZACache; + /// + /// Cache of the ignored urls that are patterns + /// + private KeyValuePair[] _ignorePatternsCache; + public CustomRedirectCollection() { } @@ -75,11 +80,14 @@ public CustomRedirect Find(Uri urlNotFound) foundRedirect = FindInProviders(url); } - return foundRedirect; + // Note: Last, so a pattern only stops suggestions, and never a redirect that applies to the url. + return foundRedirect ?? FindIgnorePattern(urlNotFound); } public void Add(CustomRedirect customRedirect) { + _ignorePatternsCache = null; + var oldUrl = HttpUtility.UrlDecode(customRedirect.OldUrl); if (_quickLookupTable.ContainsKey(oldUrl)) { @@ -421,6 +429,40 @@ ReadOnlySpan RemoveQueryString(ReadOnlySpan u) return isSameUrl || isPartOfOldUrl; } + private CustomRedirect FindIgnorePattern(Uri urlNotFound) + { + // working with local copy to avoid multi-threading issues + var patterns = _ignorePatternsCache; + if (patterns == null) + { + // Note: The key is url decoded. A row with an encoded %2A is a literal url, so the saved value has to have the *. + patterns = _quickLookupTable + .Where(x => x.Value.State == (int)RedirectState.Ignored + && IgnorePattern.IsPattern(x.Value.OldUrl) + && IgnorePattern.IsPattern(x.Key)) + .ToArray(); + _ignorePatternsCache = patterns; + } + + if (patterns.Length == 0) + { + return null; + } + + var absoluteUrl = HttpUtility.UrlDecode(urlNotFound.AbsoluteUri); + var localUrl = HttpUtility.UrlDecode(urlNotFound.PathAndQuery); + + foreach (var pattern in patterns) + { + if (IgnorePattern.IsMatch(pattern.Key, IgnorePattern.IsAbsolute(pattern.Key) ? absoluteUrl : localUrl)) + { + return pattern.Value; + } + } + + return null; + } + private CustomRedirect FindInProviders(string oldUrl) { return _providers diff --git a/src/Geta.NotFoundHandler/Core/Redirects/IgnorePattern.cs b/src/Geta.NotFoundHandler/Core/Redirects/IgnorePattern.cs new file mode 100644 index 00000000..c2c7f0e7 --- /dev/null +++ b/src/Geta.NotFoundHandler/Core/Redirects/IgnorePattern.cs @@ -0,0 +1,68 @@ +// Copyright (c) Geta Digital. All rights reserved. +// Licensed under Apache-2.0. See the LICENSE file in the project root for more information + +using System; +using System.IO.Enumeration; + +namespace Geta.NotFoundHandler.Core.Redirects; + +/// +/// An ignored url with a * in it, such as /api/*, which ignores every url matching it. +/// +public static class IgnorePattern +{ + /// + /// Whether an ignored url is a pattern. Something other than wildcards and slashes is required after the + /// host, as bots request /* literally, so a row like that, or https://example.com/* with LogWithHostname + /// on, can be saved already, and it would stop all suggestions. + /// + public static bool IsPattern(string url) + { + return !string.IsNullOrEmpty(url) + && url.Contains('*') + && GetPathToCheck(url).IndexOfAnyExcept('*', '/') >= 0; + } + + /// + /// Whether a pattern is compared to the whole url, such as https://example.com/api/*. Any other pattern is + /// compared to the path and query, so the scheme and host can't make *.com* match every request. + /// + public static bool IsAbsolute(string pattern) + { + return pattern.StartsWith("http", StringComparison.OrdinalIgnoreCase); + } + + public static bool IsMatch(string pattern, string url) + { + return FileSystemName.MatchesSimpleExpression(HideMatcherSyntax(pattern), HideMatcherSyntax(url)); + } + + /// + /// * is the only wildcard. To the matcher ? is one too, which would make /?* match everything, and \ escapes, + /// while a ? in a url starts the query string, and both are literal when deleting suggestions. A ? can't be + /// escaped for the matcher, even with a \, so both are swapped for private use characters on either side. + /// + private static string HideMatcherSyntax(string value) + { + return value.Replace('?', '\uE000').Replace('\\', '\uE001'); + } + + private static ReadOnlySpan GetPathToCheck(string url) + { + if (!IsAbsolute(url)) + { + return url; + } + + var schemeEnd = url.IndexOf("://", StringComparison.Ordinal); + if (schemeEnd < 0) + { + return ReadOnlySpan.Empty; + } + + var hostStart = schemeEnd + "://".Length; + var pathStart = url.IndexOf('/', hostStart); + + return pathStart < 0 ? ReadOnlySpan.Empty : url.AsSpan(pathStart); + } +} diff --git a/src/Geta.NotFoundHandler/Core/Suggestions/DefaultSuggestionService.cs b/src/Geta.NotFoundHandler/Core/Suggestions/DefaultSuggestionService.cs index 6fdb7dba..fe4b3682 100644 --- a/src/Geta.NotFoundHandler/Core/Suggestions/DefaultSuggestionService.cs +++ b/src/Geta.NotFoundHandler/Core/Suggestions/DefaultSuggestionService.cs @@ -43,6 +43,11 @@ public void IgnoreSuggestion(string oldUrl) { SaveIgnoredRedirect(oldUrl); DeleteSuggestionsFor(oldUrl); + + if (IgnorePattern.IsPattern(oldUrl)) + { + _suggestionRepository.DeleteMatching(oldUrl); + } } public void DeleteAll() diff --git a/src/Geta.NotFoundHandler/Data/ISuggestionRepository.cs b/src/Geta.NotFoundHandler/Data/ISuggestionRepository.cs index 4fd6bf8a..a1ed5594 100644 --- a/src/Geta.NotFoundHandler/Data/ISuggestionRepository.cs +++ b/src/Geta.NotFoundHandler/Data/ISuggestionRepository.cs @@ -10,6 +10,14 @@ public interface ISuggestionRepository void DeleteAll(); void Delete(int maxErrors, int minimumDaysOld); void DeleteForRequest(string oldUrl); + + /// + /// Deletes the suggestions for the urls matching a pattern with * as the wildcard, such as /api/*. + /// + void DeleteMatching(string pattern) + { + } + void Save(string oldUrl, string referer, DateTime requestedOn); } } diff --git a/src/Geta.NotFoundHandler/Data/SqlSuggestionRepository.cs b/src/Geta.NotFoundHandler/Data/SqlSuggestionRepository.cs index 120bebef..0c9e7bed 100644 --- a/src/Geta.NotFoundHandler/Data/SqlSuggestionRepository.cs +++ b/src/Geta.NotFoundHandler/Data/SqlSuggestionRepository.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Data; using System.Linq; +using Geta.NotFoundHandler.Core.Redirects; using Geta.NotFoundHandler.Core.Suggestions; using X.PagedList; @@ -112,6 +113,33 @@ public void DeleteForRequest(string oldUrl) _dataExecutor.ExecuteNonQuery(sqlCommand, oldUrlParam); } + public void DeleteMatching(string pattern) + { + // Note: Suggestions include the host with LogWithHostname on, while /api/* has to match them on the path, + // and shouldn't match on the host, the same as when a request is matched. + var comparedUrl = IgnorePattern.IsAbsolute(pattern) + ? "[OldUrl]" + : "CASE WHEN [OldUrl] LIKE 'http%://%' THEN SUBSTRING([OldUrl], CHARINDEX('/', [OldUrl], CHARINDEX('://', [OldUrl]) + 3), 2000) ELSE [OldUrl] END"; + + var sqlCommand = $@"DELETE FROM {SuggestionsTable} + WHERE {comparedUrl} LIKE @pattern ESCAPE '\'"; + + var patternParam = _dataExecutor.CreateParameter("pattern", DbType.String, 4000); + patternParam.Value = ToLikePattern(pattern); + + _dataExecutor.ExecuteNonQuery(sqlCommand, patternParam); + } + + private static string ToLikePattern(string pattern) + { + return pattern + .Replace(@"\", @"\\") + .Replace("%", @"\%") + .Replace("_", @"\_") + .Replace("[", @"\[") + .Replace('*', '%'); + } + public void Save(string oldUrl, string referer, DateTime requestedOn) { var sqlCommand = @$"INSERT INTO {SuggestionsTable} diff --git a/tests/Geta.NotFoundHandler.Tests/IgnorePatternTests.cs b/tests/Geta.NotFoundHandler.Tests/IgnorePatternTests.cs new file mode 100644 index 00000000..e6c959e5 --- /dev/null +++ b/tests/Geta.NotFoundHandler.Tests/IgnorePatternTests.cs @@ -0,0 +1,235 @@ +// Copyright (c) Geta Digital. All rights reserved. +// Licensed under Apache-2.0. See the LICENSE file in the project root for more information + +using System; +using FakeItEasy; +using Geta.NotFoundHandler.Core; +using Geta.NotFoundHandler.Core.Redirects; +using Geta.NotFoundHandler.Core.Suggestions; +using Geta.NotFoundHandler.Data; +using Geta.NotFoundHandler.Infrastructure.Configuration; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using Xunit; + +namespace Geta.NotFoundHandler.Tests +{ + /// + /// https://github.com/Geta/geta-notfoundhandler/issues/197 + /// + public class IgnorePatternTests + { + private readonly NotFoundHandlerOptions _options = new(); + private readonly INotFoundHandler _provider = A.Fake(); + private readonly IRequestLogger _requestLogger = A.Fake(); + private readonly CustomRedirectCollection _redirects; + private readonly RequestHandler _sut; + + public IgnorePatternTests() + { + A.CallTo(() => _provider.RewriteUrl(A._)).Returns(RewriteResult.Empty); + A.CallTo(() => _requestLogger.ShouldLogRequest(A._)).Returns(true); + + _redirects = new CustomRedirectCollection(new[] { _provider }); + var redirectHandler = new CustomRedirectHandler(); + redirectHandler.Set(_redirects); + + _sut = new RequestHandler(redirectHandler, + _requestLogger, + Options.Create(_options), + NullLogger.Instance, + new RedirectLoopGuard(Options.Create(_options))); + } + + [Theory] + [InlineData("/api/*", "/api/")] + [InlineData("/api/*", "/api/users")] + [InlineData("/api/*", "/api/users/1")] + [InlineData("/api/*", "/api/users?id=1")] + [InlineData("/api/*", "/API/Users")] + [InlineData("/API/*", "/api/users")] + [InlineData("/a b/*", "/a%20b/c")] + [InlineData("*.php", "/wp/login.php")] + [InlineData("/*/admin", "/en/admin")] + [InlineData("/*/admin", "/en/no/admin")] + [InlineData("/search?q=*", "/search?q=a")] + [InlineData("/?*", "/?a=1")] + [InlineData("/*?*", "/a?b=1")] + [InlineData("*?x=1", "/a?x=1")] + [InlineData(@"/a\b/*", "/a%5Cb/c")] + [InlineData("https://example.com/api/*", "/api/users")] + [InlineData("HTTPS://EXAMPLE.COM/api/*", "/api/users")] + public void A_url_matching_a_pattern_is_not_logged(string pattern, string url) + { + _redirects.Add(new CustomRedirect(pattern, RedirectState.Ignored)); + + Request(url); + + AssertNotLogged(); + } + + [Theory] + [InlineData("/api/*", "/api")] + [InlineData("/api/*", "/apis/users")] + [InlineData("/api/*", "/en/api/users")] + [InlineData("*.php", "/wp/login.phpx")] + [InlineData("/*/admin", "/admin")] + [InlineData("https://example.com/api/*", "/other/users")] + [InlineData("https://other.com/api/*", "/api/users")] + [InlineData("*.com*", "/a")] + [InlineData("*.*", "/a")] + [InlineData("*example*", "/a")] + [InlineData("*s*", "/a")] + [InlineData("/a?b=*", "/axb=1")] + [InlineData("/?*", "/a")] + [InlineData(@"/a\*", "/a")] + [InlineData(@"/a\b/*", "/ab/c")] + [InlineData("/a%2A", "/ab")] + public void A_url_not_matching_a_pattern_is_logged(string pattern, string url) + { + _redirects.Add(new CustomRedirect(pattern, RedirectState.Ignored)); + + Request(url); + + AssertLogged(); + } + + [Theory] + [InlineData("*")] + [InlineData("/*")] + [InlineData("/**")] + [InlineData("/*/*")] + [InlineData("http*")] + [InlineData("https*")] + [InlineData("https://*")] + [InlineData("https://*/*")] + [InlineData("https://example.com*")] + [InlineData("https://example.com/*")] + [InlineData("HTTPS://EXAMPLE.COM/*")] + [InlineData("http*://example.com/*")] + public void Something_matching_everything_is_not_a_pattern(string url) + { + _redirects.Add(new CustomRedirect(url, RedirectState.Ignored)); + + Request("/a/b"); + + AssertLogged(); + } + + [Fact] + public void An_ignored_url_without_a_wildcard_still_only_stops_itself_being_logged() + { + _redirects.Add(new CustomRedirect("/api", RedirectState.Ignored)); + + Request("/api"); + AssertNotLogged(); + + Request("/api/users"); + AssertLogged(); + } + + [Fact] + public void A_saved_redirect_with_a_wildcard_is_not_a_pattern() + { + _redirects.Add(new CustomRedirect("/api/*", "/new")); + + Request("/api/users"); + + AssertLogged(); + } + + [Fact] + public void A_redirect_for_a_url_matching_a_pattern_still_applies() + { + _redirects.Add(new CustomRedirect("/api/*", RedirectState.Ignored)); + _redirects.Add(new CustomRedirect("/api/old", "/api/new")); + + Assert.Equal("/api/new", Request("/api/old")); + Assert.Equal("/api/new/child", Request("/api/old/child")); + } + + [Fact] + public void A_shorter_redirect_still_applies_to_a_url_matching_a_pattern() + { + _redirects.Add(new CustomRedirect("/a/b/*", RedirectState.Ignored)); + _redirects.Add(new CustomRedirect("/a", "/new")); + + Assert.Equal("/new/b/c", Request("/a/b/c")); + } + + [Fact] + public void A_regex_redirect_still_applies_to_a_url_matching_a_pattern() + { + _redirects.Add(new CustomRedirect("/api/*", RedirectState.Ignored)); + A.CallTo(() => _provider.RewriteUrl(A._)).Returns(new RewriteResult("/new", RedirectType.Temporary)); + + Assert.Equal("/new", Request("/api/users")); + } + + [Fact] + public void A_pattern_replacing_another_row_is_picked_up() + { + _redirects.Add(new CustomRedirect("/a/*", "/new")); + Request("/a/b"); + AssertLogged(); + + _redirects.Add(new CustomRedirect("/a/*", RedirectState.Ignored)); + Request("/a/c"); + + AssertNotLogged(); + } + + [Fact] + public void Ignoring_a_pattern_deletes_the_suggestions_matching_it() + { + var repository = A.Fake(); + var sut = CreateSuggestionService(repository); + + sut.IgnoreSuggestion("/api/*"); + + A.CallTo(() => repository.DeleteMatching("/api/*")).MustHaveHappenedOnceExactly(); + } + + [Theory] + [InlineData("/old")] + [InlineData("/*")] + [InlineData("https://example.com/*")] + public void Ignoring_a_url_only_deletes_the_suggestions_for_that_url(string url) + { + var repository = A.Fake(); + var sut = CreateSuggestionService(repository); + + sut.IgnoreSuggestion(url); + + A.CallTo(() => repository.DeleteForRequest(url)).MustHaveHappenedOnceExactly(); + A.CallTo(() => repository.DeleteMatching(A._)).MustNotHaveHappened(); + } + + private DefaultSuggestionService CreateSuggestionService(ISuggestionRepository repository) + { + return new DefaultSuggestionService(A.Fake(), + A.Fake(), + repository, + Options.Create(_options)); + } + + private string Request(string url) + { + Fake.ClearRecordedCalls(_requestLogger); + + return _sut.HandleRequest(null, new Uri(new Uri("https://example.com"), url), out var redirect) + ? redirect.NewUrl + : null; + } + + private void AssertLogged() + { + A.CallTo(() => _requestLogger.LogRequest(A._, A._)).MustHaveHappenedOnceExactly(); + } + + private void AssertNotLogged() + { + A.CallTo(() => _requestLogger.LogRequest(A._, A._)).MustNotHaveHappened(); + } + } +}