Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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<NotFoundHandlerOptions>`.
- 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.
Expand Down
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,21 @@
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" class="form-control" placeholder="/api/*" aria-label="URL pattern" asp-for="NewPattern.Pattern">
<span asp-validation-for="NewPattern.Pattern" class="text-danger"></span>
<div class="form-text">Use * to ignore every url matching it. Redirects that apply to those urls keep working.</div>
</td>
<td>
<div class="d-grid gap-2">
<button type="submit" class="btn btn-primary"
asp-page-handler="create">
<span data-feather="plus"></span> add
</button>
</div>
</td>
</tr>
@foreach (var item in Model.Items)
{
<tr class="align-middle">
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Geta.NotFoundHandler.Admin.Areas.GetaNotFoundHandlerAdmin.Pages.Base;
using Geta.NotFoundHandler.Admin.Areas.GetaNotFoundHandlerAdmin.Pages.Extensions;
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;
Expand All @@ -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<CustomRedirect> Items { get; set; } = Enumerable.Empty<CustomRedirect>().ToPagedList();

[BindProperty]
public IgnorePatternModel NewPattern { get; set; }

[BindProperty(SupportsGet = true)]
public Paging Paging { get; set; }

Expand All @@ -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);
Expand All @@ -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);
Expand Down
Original file line number Diff line number Diff line change
@@ -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; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ public class CustomRedirectCollection : IEnumerable<CustomRedirect>
/// </summary>
private KeyValuePair<string, CustomRedirect>[] _redirectsZACache;

/// <summary>
/// Cache of the ignored urls that are patterns
/// </summary>
private KeyValuePair<string, CustomRedirect>[] _ignorePatternsCache;

public CustomRedirectCollection()
{
}
Expand Down Expand Up @@ -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))
{
Expand Down Expand Up @@ -421,6 +429,40 @@ ReadOnlySpan<char> RemoveQueryString(ReadOnlySpan<char> 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
Expand Down
68 changes: 68 additions & 0 deletions src/Geta.NotFoundHandler/Core/Redirects/IgnorePattern.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// An ignored url with a * in it, such as /api/*, which ignores every url matching it.
/// </summary>
public static class IgnorePattern
{
/// <summary>
/// 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.
/// </summary>
public static bool IsPattern(string url)
{
return !string.IsNullOrEmpty(url)
&& url.Contains('*')
&& GetPathToCheck(url).IndexOfAnyExcept('*', '/') >= 0;
}

/// <summary>
/// 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.
/// </summary>
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));
}

/// <summary>
/// * 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.
/// </summary>
private static string HideMatcherSyntax(string value)
{
return value.Replace('?', '\uE000').Replace('\\', '\uE001');
}

private static ReadOnlySpan<char> GetPathToCheck(string url)
{
if (!IsAbsolute(url))
{
return url;
}

var schemeEnd = url.IndexOf("://", StringComparison.Ordinal);
if (schemeEnd < 0)
{
return ReadOnlySpan<char>.Empty;
}

var hostStart = schemeEnd + "://".Length;
var pathStart = url.IndexOf('/', hostStart);

return pathStart < 0 ? ReadOnlySpan<char>.Empty : url.AsSpan(pathStart);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ public void IgnoreSuggestion(string oldUrl)
{
SaveIgnoredRedirect(oldUrl);
DeleteSuggestionsFor(oldUrl);

if (IgnorePattern.IsPattern(oldUrl))
{
_suggestionRepository.DeleteMatching(oldUrl);
}
}

public void DeleteAll()
Expand Down
8 changes: 8 additions & 0 deletions src/Geta.NotFoundHandler/Data/ISuggestionRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,14 @@ public interface ISuggestionRepository
void DeleteAll();
void Delete(int maxErrors, int minimumDaysOld);
void DeleteForRequest(string oldUrl);

/// <summary>
/// Deletes the suggestions for the urls matching a pattern with * as the wildcard, such as /api/*.
/// </summary>
void DeleteMatching(string pattern)
{
}

void Save(string oldUrl, string referer, DateTime requestedOn);
}
}
28 changes: 28 additions & 0 deletions src/Geta.NotFoundHandler/Data/SqlSuggestionRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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}
Expand Down
Loading
Loading