From 588599688f1c4b26421c74afb125de37508e228f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Schwarzer?= Date: Sun, 15 Nov 2026 07:28:45 +0100 Subject: [PATCH 01/16] feat: move to .NET 11 and version 2.0.2-alpha Co-Authored-By: Claude Opus 5.5 --- .github/workflows/generate-docs.yml | 2 +- .github/workflows/unittest-verification.yml | 2 +- src/WebExpress.WebCore.Test/WebExpress.WebCore.Test.csproj | 2 +- src/WebExpress.WebCore/WebExpress.WebCore.csproj | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/generate-docs.yml b/.github/workflows/generate-docs.yml index e3617ef..9e2c06c 100644 --- a/.github/workflows/generate-docs.yml +++ b/.github/workflows/generate-docs.yml @@ -28,7 +28,7 @@ jobs: - name: Setup .NET SDK uses: actions/setup-dotnet@v6 with: - dotnet-version: 10.x + dotnet-version: 11.x - name: Install DocFX run: dotnet tool install -g docfx diff --git a/.github/workflows/unittest-verification.yml b/.github/workflows/unittest-verification.yml index f0f640d..f2e8f8e 100644 --- a/.github/workflows/unittest-verification.yml +++ b/.github/workflows/unittest-verification.yml @@ -20,7 +20,7 @@ jobs: - name: Setup .NET uses: actions/setup-dotnet@v6 with: - dotnet-version: 10.x + dotnet-version: 11.x - name: Restore dependencies run: dotnet restore ./WebExpress.WebCore.slnx diff --git a/src/WebExpress.WebCore.Test/WebExpress.WebCore.Test.csproj b/src/WebExpress.WebCore.Test/WebExpress.WebCore.Test.csproj index 7b6fedc..3f3aaa8 100644 --- a/src/WebExpress.WebCore.Test/WebExpress.WebCore.Test.csproj +++ b/src/WebExpress.WebCore.Test/WebExpress.WebCore.Test.csproj @@ -1,7 +1,7 @@  - net10.0 + net11.0 enable disable diff --git a/src/WebExpress.WebCore/WebExpress.WebCore.csproj b/src/WebExpress.WebCore/WebExpress.WebCore.csproj index da06c28..fdb33a6 100644 --- a/src/WebExpress.WebCore/WebExpress.WebCore.csproj +++ b/src/WebExpress.WebCore/WebExpress.WebCore.csproj @@ -3,8 +3,8 @@ Library WebExpress.WebCore - 2.0.1-alpha - net10.0 + 2.0.2-alpha + net11.0 any https://github.com/webexpress-framework/WebExpress.git webexpress-framework@outlook.com From cf50c7373bd0d1e4bb049ccdcd198dfe037eae87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Schwarzer?= Date: Tue, 17 Nov 2026 19:37:06 +0100 Subject: [PATCH 02/16] fix: give identity validators the claims of the verified token IdentityValidationContext carries the token id, the token expiration and the grant expiration, read in Confirm from the token that was verified. On a refresh the request still carries the previous access cookie, which nobody verified; a validator reading its claims from there could be handed a forged grant end and keep a revoked session alive. Co-Authored-By: Claude Opus 5.5 --- .../Manager/UnitTestIdentityValidation.cs | 56 +++++++++++++++++++ .../WebIdentity/IdentityManager.Validation.cs | 10 +++- .../WebIdentity/IdentityValidationContext.cs | 21 +++++++ 3 files changed, 85 insertions(+), 2 deletions(-) diff --git a/src/WebExpress.WebCore.Test/Manager/UnitTestIdentityValidation.cs b/src/WebExpress.WebCore.Test/Manager/UnitTestIdentityValidation.cs index 83825ca..13c34e8 100644 --- a/src/WebExpress.WebCore.Test/Manager/UnitTestIdentityValidation.cs +++ b/src/WebExpress.WebCore.Test/Manager/UnitTestIdentityValidation.cs @@ -185,6 +185,49 @@ public void RefusedIdentityIsNotRenewed() Assert.Equal("", response.Header.Cookies[IdentityManager.AccessCookieName]?.Value); } + /// + /// Tests that on a renewal the validator learns the claims of the renewed, verified token + /// and not those of the access cookie the request still carries, which nobody verified: + /// a forged cookie must not set the grant, the token id or the deadlines a revocation is + /// measured by. The revoked grant is not renewed afterwards. + /// + [Fact] + public void RenewalValidatesTheRenewedTokenNotTheCookie() + { + // arrange + using var fixture = new AuthenticationFixture(); + var pair = fixture.Manager.Login(MockIdentityFactory.GetIdentity("Alice"), fixture.Request()); + var validator = new DelegateValidator(_ => true); + fixture.Manager.RegisterValidator(validator, fixture.Application); + var forged = Unsigned(new Dictionary + { + ["sub"] = Guid.NewGuid().ToString(), + ["token_use"] = "access", + ["jti"] = "forged", + ["grant"] = "forged", + ["grant_exp"] = DateTimeOffset.UtcNow.AddHours(-1).ToUnixTimeSeconds(), + ["exp"] = DateTimeOffset.UtcNow.AddMinutes(10).ToUnixTimeSeconds() + }); + var cookies = $"Cookie: {IdentityManager.AccessCookieName}={forged}; {IdentityManager.RefreshCookieName}={pair.RefreshToken}\r\n"; + + // act + var renewed = fixture.Manager.Refresh(fixture.Request(cookies, "POST", IdentityManager.RefreshPath)); + var context = validator.Last; + fixture.Manager.RevokeGrant(renewed.AccessToken, fixture.Application); + var renewedAfterRevocation = fixture.Manager.Refresh(renewed.RefreshToken, fixture.Application); + + // validation + var issued = new Microsoft.IdentityModel.JsonWebTokens.JsonWebToken(renewed.AccessToken); + Assert.True(issued.TryGetPayloadValue("grant", out var grant)); + Assert.True(issued.TryGetPayloadValue("grant_exp", out var grantExpires)); + Assert.Equal(grant, context.Grant); + Assert.Equal(issued.Id, context.TokenId); + Assert.Equal(new DateTimeOffset(issued.ValidTo, TimeSpan.Zero), context.ExpiresAt); + Assert.Equal(DateTimeOffset.FromUnixTimeSeconds(grantExpires), context.GrantExpiresAt); + Assert.True(context.GrantExpiresAt > DateTimeOffset.UtcNow); + Assert.Null(renewedAfterRevocation); + } + /// /// Tests that a validator a plugin defines is discovered for the plugin's applications. /// @@ -241,6 +284,19 @@ private static IApplicationContext Application(AuthenticationFixture fixture, Ty return fixture.Hub.ApplicationManager.GetApplications(type).First(); } + /// + /// Builds a token with the given claims and no signature, as an attacker can put into a + /// cookie without knowing the signing key. + /// + /// The claims of the payload. + /// The serialized token. + private static string Unsigned(IDictionary claims) + { + static string Encode(object value) => Microsoft.IdentityModel.Tokens.Base64UrlEncoder.Encode(System.Text.Json.JsonSerializer.Serialize(value)); + + return $"{Encode(new Dictionary { ["alg"] = "none", ["typ"] = "JWT" })}.{Encode(claims)}."; + } + /// /// A token store of one application, to tell its markers from those of the default store. /// diff --git a/src/WebExpress.WebCore/WebIdentity/IdentityManager.Validation.cs b/src/WebExpress.WebCore/WebIdentity/IdentityManager.Validation.cs index 2c3bb02..35b2268 100644 --- a/src/WebExpress.WebCore/WebIdentity/IdentityManager.Validation.cs +++ b/src/WebExpress.WebCore/WebIdentity/IdentityManager.Validation.cs @@ -167,14 +167,20 @@ private IIdentity Confirm(IIdentity identity, string token, IRequest request) // the token was verified before, reading it again only takes the claims apart var jwt = new JsonWebToken(token); + var grant = jwt.TryGetPayloadValue("grant", out var claimedGrant) && !string.IsNullOrEmpty(claimedGrant) ? claimedGrant : null; var context = new IdentityValidationContext { Identity = identity, Request = request, ApplicationContext = request.ApplicationContext, - Grant = jwt.TryGetPayloadValue("grant", out var grant) ? grant : null, + Grant = grant, TokenUse = jwt.TryGetPayloadValue("token_use", out var use) ? use : null, - IssuedAt = new DateTimeOffset(jwt.IssuedAt, TimeSpan.Zero) + TokenId = string.IsNullOrEmpty(jwt.Id) ? null : jwt.Id, + IssuedAt = new DateTimeOffset(jwt.IssuedAt, TimeSpan.Zero), + ExpiresAt = new DateTimeOffset(jwt.ValidTo, TimeSpan.Zero), + GrantExpiresAt = grant is not null && jwt.TryGetPayloadValue("grant_exp", out var grantExpires) + ? DateTimeOffset.FromUnixTimeSeconds(grantExpires) + : null }; foreach (var validator in validators) diff --git a/src/WebExpress.WebCore/WebIdentity/IdentityValidationContext.cs b/src/WebExpress.WebCore/WebIdentity/IdentityValidationContext.cs index 5079e10..4ae0ed7 100644 --- a/src/WebExpress.WebCore/WebIdentity/IdentityValidationContext.cs +++ b/src/WebExpress.WebCore/WebIdentity/IdentityValidationContext.cs @@ -37,9 +37,30 @@ public sealed class IdentityValidationContext /// public string TokenUse { get; init; } + /// + /// Gets the id (jti) of the token, which a validator matches a personal access + /// token by; null when the token carries none. + /// + public string TokenId { get; init; } + /// /// Gets the time the token was issued. /// public DateTimeOffset IssuedAt { get; init; } + + /// + /// Gets the time the token itself stops being accepted. + /// + public DateTimeOffset ExpiresAt { get; init; } + + /// + /// Gets the time the login grant ends however often it is renewed, which is how long a + /// revocation of the grant must last; null for a token without a grant. + /// + /// + /// A validator takes the token's claims from here and never from the request: on a + /// renewal the request still carries the previous access cookie, which nobody verified. + /// + public DateTimeOffset? GrantExpiresAt { get; init; } } } From 6e9e22fe3deaeac2c548c2745541801b2bd74f83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Schwarzer?= Date: Tue, 17 Nov 2026 19:37:07 +0100 Subject: [PATCH 03/16] fix: drain the console on a thread of its own The console writer ran on the thread pool and read from a channel, which resumes a waiting reader through the pool as well. With the pool saturated nothing was written and every Close waited out its five seconds. A blocking collection drained by a dedicated thread needs no pool thread at all. Co-Authored-By: Claude Opus 5.5 --- src/WebExpress.WebCore/WebLog/Log.cs | 47 ++++++++++------------------ 1 file changed, 17 insertions(+), 30 deletions(-) diff --git a/src/WebExpress.WebCore/WebLog/Log.cs b/src/WebExpress.WebCore/WebLog/Log.cs index 3c70cff..f6be99d 100644 --- a/src/WebExpress.WebCore/WebLog/Log.cs +++ b/src/WebExpress.WebCore/WebLog/Log.cs @@ -6,7 +6,6 @@ using System.Runtime.CompilerServices; using System.Text; using System.Threading; -using System.Threading.Channels; using System.Threading.Tasks; using WebExpress.WebCore.WebSetting; @@ -50,19 +49,20 @@ public class Log : ILog // the console is slow and serialized, so a request thread only queues its line; one // background writer drains the queue. Bounded so a console that cannot keep up slows the - // callers down instead of growing memory without limit. - private static readonly Channel _console = Channel.CreateBounded - ( - new BoundedChannelOptions(10_000) { SingleReader = true, FullMode = BoundedChannelFullMode.Wait } - ); + // callers down instead of growing memory without limit. A blocking collection and not a + // channel: its waits are synchronous, while a channel resumes a waiting reader through + // the thread pool - and a saturated pool (a loaded host, a parallel test run) then left + // the queue undrained until every flush ran into its timeout. + private static readonly BlockingCollection _console = new(10_000); private static readonly TimeSpan _consoleDrainTimeout = TimeSpan.FromSeconds(5); private const int _consoleBatchSize = 256; // the background writer and the direct fallback must not interleave their color changes private static readonly Lock _consoleWriteLock = new(); - // started last, so everything the writer touches is initialized before it runs - private static readonly Task _consoleWriter = Task.Run(WriteConsoleAsync); + // started last, so everything the writer touches is initialized before it runs; on a + // thread of its own, so it never waits for the pool it would otherwise share + private static readonly Task _consoleWriter = Task.Factory.StartNew(WriteConsole, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); // the class part of the origin column comes from the caller's file name; resolving it once // per file keeps the string work off the logging path @@ -335,7 +335,7 @@ private void WriteToConsole(LogLevel level, string text) /// True if the item was queued, false if the writer cannot take it. private static bool Enqueue(ConsoleLine line) { - if (_console.Writer.TryWrite(line)) + if (_console.TryAdd(line)) { return true; } @@ -345,18 +345,8 @@ private static bool Enqueue(ConsoleLine line) return false; } - // a canceled write is never queued, so a timed-out entry cannot show up twice - using var timeout = new CancellationTokenSource(_consoleDrainTimeout); - - try - { - _console.Writer.WriteAsync(line, timeout.Token).AsTask().GetAwaiter().GetResult(); - return true; - } - catch (OperationCanceledException) - { - return false; - } + // a timed-out add is never queued, so a dropped entry cannot show up twice + return _console.TryAdd(line, _consoleDrainTimeout); } /// @@ -378,11 +368,7 @@ public static void FlushConsole() try { - if (!_console.Writer.TryWrite(marker)) - { - _console.Writer.WriteAsync(marker, timeout.Token).AsTask().GetAwaiter().GetResult(); - } - + _console.Add(marker, timeout.Token); done.Task.Wait(timeout.Token); } catch (OperationCanceledException) @@ -395,15 +381,16 @@ public static void FlushConsole() /// color are written as a single block, so the color is switched once per block and not /// once per entry. /// - private static async Task WriteConsoleAsync() + private static void WriteConsole() { - var reader = _console.Reader; var batch = new List(_consoleBatchSize); var block = new StringBuilder(); - while (await reader.WaitToReadAsync().ConfigureAwait(false)) + foreach (var first in _console.GetConsumingEnumerable()) { - while (batch.Count < _consoleBatchSize && reader.TryRead(out var line)) + batch.Add(first); + + while (batch.Count < _consoleBatchSize && _console.TryTake(out var line)) { batch.Add(line); } From f0b8c64ed8133f0e94aca3b641ae293b22df7d48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Schwarzer?= Date: Tue, 17 Nov 2026 19:39:27 +0100 Subject: [PATCH 04/16] feat: update xunit.v3 to 4.0.3 and the TRX report extension to 2.5.3 Co-Authored-By: Claude Opus 5.5 --- src/WebExpress.WebCore.Test/WebExpress.WebCore.Test.csproj | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/WebExpress.WebCore.Test/WebExpress.WebCore.Test.csproj b/src/WebExpress.WebCore.Test/WebExpress.WebCore.Test.csproj index 3f3aaa8..b566347 100644 --- a/src/WebExpress.WebCore.Test/WebExpress.WebCore.Test.csproj +++ b/src/WebExpress.WebCore.Test/WebExpress.WebCore.Test.csproj @@ -37,8 +37,8 @@ - - + + From b542213ab8580fbab3511024220551c42070e9d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Schwarzer?= Date: Thu, 19 Nov 2026 21:05:40 +0100 Subject: [PATCH 05/16] fix: keep the slow-console log test independent of other tests' console output Co-Authored-By: Claude Opus 5.5 --- .../WebLog/UnitTestLog.cs | 20 +++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/src/WebExpress.WebCore.Test/WebLog/UnitTestLog.cs b/src/WebExpress.WebCore.Test/WebLog/UnitTestLog.cs index aeed788..ea7edef 100644 --- a/src/WebExpress.WebCore.Test/WebLog/UnitTestLog.cs +++ b/src/WebExpress.WebCore.Test/WebLog/UnitTestLog.cs @@ -252,7 +252,7 @@ public void ErrorDoesNotWaitForConsole(bool fatal) var log = new Log { LogMode = LogMode.Off }; var lines = string.Join(Environment.NewLine, Enumerable.Range(0, 20).Select(x => $"console-line-{x}")); var originalOutput = Console.Out; - using var output = new SlowWriter(TimeSpan.FromMilliseconds(500)); + using var output = new SlowWriter(TimeSpan.FromMilliseconds(500), "console-line-"); var stopwatch = new System.Diagnostics.Stopwatch(); try @@ -285,18 +285,26 @@ public void ErrorDoesNotWaitForConsole(bool fatal) } /// - /// A console whose every write takes a while, as a redirected or captured console does. + /// A console whose writes of the test's own entries take a while, as a redirected or + /// captured console does. The console is shared by the whole process, so entries other + /// tests log meanwhile pass through it as well; they are written at once, or each of their + /// blocks would hold up the test's entry until the flush gives up. /// - /// The time a write takes. - private sealed class SlowWriter(TimeSpan delay) : StringWriter + /// The time a write of the test's entries takes. + /// The text that identifies the test's entries. + private sealed class SlowWriter(TimeSpan delay, string marker) : StringWriter { /// - /// Writes a block of entries after the delay. + /// Writes a block of entries, after the delay if it holds the test's entries. /// /// The block. public override void Write(string value) { - Thread.Sleep(delay); + if (value?.Contains(marker, StringComparison.Ordinal) == true) + { + Thread.Sleep(delay); + } + base.Write(value); } } From 676cdcf717e3f71d41fa487a794cd4ac10785526 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Schwarzer?= Date: Fri, 20 Nov 2026 20:32:40 +0100 Subject: [PATCH 06/16] fix: harden the http server and request handling - read Content-Encoding as a content coding, not a charset: a compressed body no longer fails the context with a 500 - resolve the request target below the request's authority, so "//host/x" cannot replace the host and steer the routing past a proxy's path rule - build the websocket uri from the host header port, not the listener port - parse the query in order, so a repeated key always takes its last value - map unknown methods to NONE and answer them with 501 instead of running the GET handler; accept websockets over HTTP/2 and HTTP/3 extended CONNECT - challenge 401s with Bearer instead of Basic, which made browsers prompt and then shadow the sign-in cookie with typed credentials - refuse an upgrade to an endpoint that is no socket with a 400, write the handshake headers only for an upgradable request and take them back on failure, and send no http status once the connection is switched - read the request body asynchronously in the pipeline, also without a Content-Length; an oversized or malformed body is answered with 413/400 - enforce MaxMessageSize on sockets with close code 1009 and drop the never thrown SocketMessageTooLargeException - match the status page application by whole segments, longest route first - render the 500 page for a failed context as a single document - number requests atomically and log the done line with the same number - keep colons in Basic passwords and unquote a quoted multipart boundary Co-Authored-By: Claude Opus 5.5 --- .../Message/UnitTestGetRequest.cs | 34 ++++ .../Message/UnitTestHttpContextHost.cs | 45 ++++++ .../Message/UnitTestPostRequest.cs | 18 +++ .../Message/UnitTestRequestAuthorization.cs | 36 +++++ .../Message/UnitTestRequestContent.cs | 93 +++++++++-- .../Message/UnitTestResponseSender.cs | 14 ++ .../Server/UnitTestHttpServer.cs | 19 +++ .../Server/UnitTestSocketConnection.cs | 61 +++++++ .../Server/UnitTestWebSocketHandshake.cs | 50 +++++- src/WebExpress.WebCore/HttpServer.cs | 151 +++++++++++++----- .../WebMessage/HttpContext.cs | 60 ++++++- .../WebMessage/HttpExceptionContext.cs | 1 - .../WebMessage/HttpWebSocketContext.cs | 14 +- src/WebExpress.WebCore/WebMessage/Request.cs | 63 ++++++-- .../WebMessage/RequestAuthorization.cs | 4 +- .../WebMessage/RequestBase.cs | 11 +- .../WebMessage/RequestHeaderFields.cs | 11 +- .../RequestHeaderFieldsExtensions.cs | 2 +- .../WebMessage/ResponseHeaderFields.cs | 18 ++- .../WebMessage/ResponseSender.cs | 2 +- .../WebSocket/SocketConnection.cs | 30 +++- .../WebSocket/SocketManager.cs | 118 +++++++++++--- .../SocketMessageTooLargeException.cs | 63 -------- 23 files changed, 732 insertions(+), 186 deletions(-) create mode 100644 src/WebExpress.WebCore.Test/Message/UnitTestRequestAuthorization.cs delete mode 100644 src/WebExpress.WebCore/WebSocket/SocketMessageTooLargeException.cs diff --git a/src/WebExpress.WebCore.Test/Message/UnitTestGetRequest.cs b/src/WebExpress.WebCore.Test/Message/UnitTestGetRequest.cs index d82e7ff..787233e 100644 --- a/src/WebExpress.WebCore.Test/Message/UnitTestGetRequest.cs +++ b/src/WebExpress.WebCore.Test/Message/UnitTestGetRequest.cs @@ -114,5 +114,39 @@ public void ParameterKeepsItsPlainValue() Assert.Equal("C++ 100%", parameter.Value); Assert.Equal("a=C%2B%2B%20100%25", parameter.ToString()); } + + /// + /// Tests that a key repeated in the query always resolves to its last occurrence. The + /// query was parsed in parallel once, so which value won changed from request to request. + /// + [Fact] + public void RepeatedQueryKeyTakesTheLastValue() + { + var query = string.Join("&", Enumerable.Range(0, 200).Select(x => $"page={x}")); + + for (var i = 0; i < 20; i++) + { + var request = UnitTestFixture.CreateRequestMock($"GET /a?{query} HTTP/1.1\r\n\r\n"); + + Assert.Equal("199", request.GetParameter("page")?.Value); + } + } + + /// + /// Tests that a method the framework does not implement is not taken for a GET, which + /// would answer an OPTIONS preflight or a PROPFIND with the resource itself. + /// + /// The request method. + [Theory] + [InlineData("OPTIONS")] + [InlineData("PROPFIND")] + [InlineData("CONNECT")] + [InlineData("TRACE")] + public void UnknownMethodIsNoGet(string method) + { + var request = UnitTestFixture.CreateRequestMock($"{method} /a HTTP/1.1\r\n\r\n"); + + Assert.Equal(WebMessage.RequestMethod.NONE, request.Method); + } } } diff --git a/src/WebExpress.WebCore.Test/Message/UnitTestHttpContextHost.cs b/src/WebExpress.WebCore.Test/Message/UnitTestHttpContextHost.cs index 6f7fe8f..cefbb23 100644 --- a/src/WebExpress.WebCore.Test/Message/UnitTestHttpContextHost.cs +++ b/src/WebExpress.WebCore.Test/Message/UnitTestHttpContextHost.cs @@ -57,5 +57,50 @@ public void HostNameBuildsUri(string host, int port, string expected) // validation Assert.Equal(expected, uri.ToString()); } + + /// + /// Tests that the request target never replaces the authority of the request: a target + /// starting with "//" is a path, not a network-path reference, so the routing cannot be + /// steered to "/admin" while a proxy in front saw "//evil.com/admin". + /// + /// The request target as the client sent it. + /// The expected uri. + [Theory] + [InlineData("/a/b?c=1", "http://localhost:8080/a/b?c=1")] + [InlineData("//evil.com/admin", "http://localhost:8080//evil.com/admin")] + [InlineData("http://other.org/x?y=2", "http://localhost:8080/x?y=2")] + [InlineData("*", "http://localhost:8080/")] + [InlineData("", "http://localhost:8080/")] + [InlineData(null, "http://localhost:8080/")] + public void ResolveTargetKeepsTheAuthority(string target, string expected) + { + // act + var uri = HttpContext.ResolveTarget(new Uri("http://localhost:8080/"), target); + + // validation + Assert.Equal("localhost", uri.Host); + Assert.Equal(8080, uri.Port); + Assert.Equal(expected, uri.ToString()); + } + + /// + /// Tests that a compressed body does not fail the context: Content-Encoding names a + /// compression such as gzip, not a character set, and reading it as one threw before the + /// request existed, so every compressed post was answered with a 500. + /// + /// The value of the Content-Encoding header. + [Theory] + [InlineData("gzip")] + [InlineData("br")] + [InlineData("deflate, gzip")] + public void ContentEncodingIsNoCharset(string contentEncoding) + { + // act + var context = Fixture.UnitTestFixture.CreateHttpContextMock($"POST /a HTTP/1.1\r\nContent-Encoding: {contentEncoding}\r\n\r\n"); + + // validation + Assert.Equal(contentEncoding, context.Request.Header.ContentEncoding); + Assert.Equal("utf-8", context.Encoding.WebName); + } } } diff --git a/src/WebExpress.WebCore.Test/Message/UnitTestPostRequest.cs b/src/WebExpress.WebCore.Test/Message/UnitTestPostRequest.cs index ec9962e..7751fff 100644 --- a/src/WebExpress.WebCore.Test/Message/UnitTestPostRequest.cs +++ b/src/WebExpress.WebCore.Test/Message/UnitTestPostRequest.cs @@ -177,6 +177,24 @@ public void UrlencodedDecodesItsKeys() Assert.Equal("b", GetParameterValue(request, "first name")?.Trim()); } + /// + /// Tests that a quoted multipart boundary - required once it contains characters such + /// as ':' (RFC 2046) - is matched without its quotes, so the fields are not lost. + /// + /// The boundary parameter as the content type carries it. + [Theory] + [InlineData("\"wx:boundary\"")] + [InlineData("wxboundary")] + public void MultipartWithQuotedBoundary(string boundary) + { + var delimiter = boundary.Trim('"'); + var body = $"--{delimiter}\r\nContent-Disposition: form-data; name=\"a\"\r\n\r\n1\r\n--{delimiter}--\r\n"; + + var request = Post($"multipart/form-data; boundary={boundary}", body); + + Assert.Equal("1", GetParameterValue(request, "a")?.Trim()); + } + /// /// Builds a POST request with the given body. /// diff --git a/src/WebExpress.WebCore.Test/Message/UnitTestRequestAuthorization.cs b/src/WebExpress.WebCore.Test/Message/UnitTestRequestAuthorization.cs new file mode 100644 index 0000000..76e3f54 --- /dev/null +++ b/src/WebExpress.WebCore.Test/Message/UnitTestRequestAuthorization.cs @@ -0,0 +1,36 @@ +using WebExpress.WebCore.WebMessage; + +namespace WebExpress.WebCore.Test.Message +{ + /// + /// Unit tests for parsing the Authorization header with . + /// + public class UnitTestRequestAuthorization + { + /// + /// Tests that the user id of Basic credentials ends at the first colon and the password + /// keeps every further one (RFC 7617). + /// + /// The decoded credentials. + /// The expected user id. + /// The expected password. + [Theory] + [InlineData("alice:secret", "alice", "secret")] + [InlineData("alice:pa:ss:word", "alice", "pa:ss:word")] + [InlineData("alice:", "alice", "")] + [InlineData("alice", "alice", null)] + public void BasicSplitsAtTheFirstColon(string credentials, string identification, string password) + { + // arrange + var encoded = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(credentials)); + + // act + var authorization = RequestAuthorization.Parse($"Basic {encoded}"); + + // validation + Assert.Equal("Basic", authorization.Type); + Assert.Equal(identification, authorization.Identification); + Assert.Equal(password, authorization.Password); + } + } +} diff --git a/src/WebExpress.WebCore.Test/Message/UnitTestRequestContent.cs b/src/WebExpress.WebCore.Test/Message/UnitTestRequestContent.cs index 3f189d1..f9b524c 100644 --- a/src/WebExpress.WebCore.Test/Message/UnitTestRequestContent.cs +++ b/src/WebExpress.WebCore.Test/Message/UnitTestRequestContent.cs @@ -9,16 +9,63 @@ namespace WebExpress.WebCore.Test.Message public class UnitTestRequestContent { /// - /// Tests that a missing or non-positive content length yields no content. + /// Tests that a non-positive content length yields no content. /// [Theory] - [InlineData(null)] [InlineData(0L)] [InlineData(-1L)] - public void NoContentLength(long? contentLength) + public async Task NonPositiveContentLength(long contentLength) { // act - var content = Request.GetContent(new MemoryStream([1, 2, 3]), contentLength); + var content = await Request.GetContentAsync(new MemoryStream([1, 2, 3]), contentLength, CancellationToken.None); + + // validation + Assert.Null(content); + } + + /// + /// Tests that a body sent without a content length - chunked over HTTP/1.1, or over + /// HTTP/2 and HTTP/3 without the header - is read to the end of the stream instead of + /// being dropped. + /// + [Fact] + public async Task MissingContentLengthReadsToTheEnd() + { + // arrange + var body = CreateBody(Request.InitialContentBufferSize + 5); + + // act + var content = await Request.GetContentAsync(new FragmentedStream(body, 4096), null, CancellationToken.None); + + // validation + Assert.Equal(body, content); + } + + /// + /// Tests that the body is read asynchronously, so a server that disallows synchronous IO + /// still receives it. + /// + [Fact] + public async Task BodyIsReadWithoutSynchronousIo() + { + // arrange + var body = CreateBody(100); + + // act + var content = await Request.GetContentAsync(new FragmentedStream(body, 7, allowSynchronousIo: false), body.Length, CancellationToken.None); + + // validation + Assert.Equal(body, content); + } + + /// + /// Tests that a request without a body yields no content. + /// + [Fact] + public async Task NoBody() + { + // act + var content = await Request.GetContentAsync(null, null, CancellationToken.None); // validation Assert.Null(content); @@ -32,13 +79,13 @@ public void NoContentLength(long? contentLength) [InlineData(1)] [InlineData(4096)] [InlineData(Request.InitialContentBufferSize)] - public void BodyLargerThanInitialBuffer(int maxReadSize) + public async Task BodyLargerThanInitialBuffer(int maxReadSize) { // arrange var body = CreateBody(Request.InitialContentBufferSize * 3 + 17); // act - var content = Request.GetContent(new FragmentedStream(body, maxReadSize), body.Length); + var content = await Request.GetContentAsync(new FragmentedStream(body, maxReadSize), body.Length, CancellationToken.None); // validation Assert.Equal(body, content); @@ -49,13 +96,13 @@ public void BodyLargerThanInitialBuffer(int maxReadSize) /// those bytes, without the server reserving memory for the announced size. /// [Fact] - public void AnnouncedLengthExceedsBody() + public async Task AnnouncedLengthExceedsBody() { // arrange var body = CreateBody(5); // act - var content = Request.GetContent(new MemoryStream(body), long.MaxValue); + var content = await Request.GetContentAsync(new MemoryStream(body), long.MaxValue, CancellationToken.None); // validation Assert.Equal(body, content); @@ -65,13 +112,13 @@ public void AnnouncedLengthExceedsBody() /// Tests that bytes beyond the announced content length are not read. /// [Fact] - public void BodyExceedsAnnouncedLength() + public async Task BodyExceedsAnnouncedLength() { // arrange var body = CreateBody(100); // act - var content = Request.GetContent(new MemoryStream(body), 40); + var content = await Request.GetContentAsync(new MemoryStream(body), 40, CancellationToken.None); // validation Assert.Equal(body[..40], content); @@ -81,10 +128,10 @@ public void BodyExceedsAnnouncedLength() /// Tests that an announced body that never arrives yields no content. /// [Fact] - public void EmptyBody() + public async Task EmptyBody() { // act - var content = Request.GetContent(new MemoryStream(), 1024); + var content = await Request.GetContentAsync(new MemoryStream(), 1024, CancellationToken.None); // validation Assert.Null(content); @@ -105,14 +152,32 @@ private static byte[] CreateBody(int length) /// /// A stream that returns at most a fixed number of bytes per read, as a network - /// stream does when the client sends its body in several packets. + /// stream does when the client sends its body in several packets. Like Kestrel's request + /// body with AllowSynchronousIO off, it can refuse synchronous reads. /// - private sealed class FragmentedStream(byte[] data, int maxReadSize) : MemoryStream(data) + private sealed class FragmentedStream(byte[] data, int maxReadSize, bool allowSynchronousIo = true) + : MemoryStream(data, 0, data.Length, writable: false, publiclyVisible: true) { public override int Read(byte[] buffer, int offset, int count) { + if (!allowSynchronousIo) + { + throw new InvalidOperationException("Synchronous operations are disallowed."); + } + return base.Read(buffer, offset, Math.Min(count, maxReadSize)); } + + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + // copied by hand: the base implementation of a derived memory stream falls back + // to the synchronous read + var count = (int)Math.Min(Math.Min(buffer.Length, maxReadSize), Length - Position); + GetBuffer().AsSpan((int)Position, count).CopyTo(buffer.Span); + Position += count; + + return ValueTask.FromResult(count); + } } } } diff --git a/src/WebExpress.WebCore.Test/Message/UnitTestResponseSender.cs b/src/WebExpress.WebCore.Test/Message/UnitTestResponseSender.cs index 1f7d3d2..044338e 100644 --- a/src/WebExpress.WebCore.Test/Message/UnitTestResponseSender.cs +++ b/src/WebExpress.WebCore.Test/Message/UnitTestResponseSender.cs @@ -225,6 +225,20 @@ public async Task ConnectionAndUpgradeSuppressedOnHttp2() Assert.False(feature.Headers.ContainsKey("Upgrade")); } + /// + /// Tests that a 401 challenges for a bearer token and never for Basic credentials, which + /// the server does not accept: a browser answers a Basic challenge with a login dialog and + /// then sends the typed credentials with every request in place of the sign-in cookie. + /// + [Fact] + public async Task UnauthorizedChallengesBearerNotBasic() + { + var feature = await Send("HTTP/1.1", new ResponseUnauthorized()); + + Assert.Equal("Bearer", feature.Headers.WWWAuthenticate.ToString()); + Assert.Equal("WWW-Authenticate: Bearer", new ResponseUnauthorized().Header.ToString().Split(Environment.NewLine).Single(x => x.StartsWith("WWW-Authenticate"))); + } + /// /// A minimal backed by an explicit feature collection, used to /// drive the sender without constructing a full request pipeline. diff --git a/src/WebExpress.WebCore.Test/Server/UnitTestHttpServer.cs b/src/WebExpress.WebCore.Test/Server/UnitTestHttpServer.cs index abd4a67..8dd8b3d 100644 --- a/src/WebExpress.WebCore.Test/Server/UnitTestHttpServer.cs +++ b/src/WebExpress.WebCore.Test/Server/UnitTestHttpServer.cs @@ -505,5 +505,24 @@ public async Task ProcessRequestAsync_ProtectedPage_RequiresPolicy(bool authenti // validation Assert.Equal(status, response.StatusCode); } + + /// + /// Tests that a route belongs to an application only by whole segments, so the status + /// page of "/app" is never chosen for "/application/x". + /// + /// The route of the request. + /// The route of the application. + /// Whether the route belongs to the application. + [Theory] + [InlineData("/app", "/app", true)] + [InlineData("/app/x", "/app", true)] + [InlineData("/app/x", "/app/", true)] + [InlineData("/application/x", "/app", false)] + [InlineData("/x", "/", true)] + [InlineData("/x", "", true)] + public void RouteBelongsToApplicationBySegments(string route, string applicationRoute, bool expected) + { + Assert.Equal(expected, HttpServer.IsRouteBelow(route, applicationRoute)); + } } } diff --git a/src/WebExpress.WebCore.Test/Server/UnitTestSocketConnection.cs b/src/WebExpress.WebCore.Test/Server/UnitTestSocketConnection.cs index 68d0f80..db0c12e 100644 --- a/src/WebExpress.WebCore.Test/Server/UnitTestSocketConnection.cs +++ b/src/WebExpress.WebCore.Test/Server/UnitTestSocketConnection.cs @@ -54,6 +54,67 @@ public void SocketWithoutSubProtocolConnects() Assert.NotNull(connection); } + /// + /// A message within the declared maximum size is delivered, while one beyond it closes + /// the connection with the close code for a message too big, before it is handed on. + /// + /// A task that completes after both messages have been verified. + [Fact] + public async Task MessageOverMaxSizeClosesTheConnection() + { + // arrange + var componentHub = UnitTestFixture.CreateAndRegisterComponentHubMock(); + var applicationContext = componentHub.ApplicationManager.GetApplications(typeof(TestApplicationA)).First(); + var socketContext = (SocketContext)componentHub.SocketManager.GetSockets(applicationContext).First(); + socketContext.MaxMessageSize = 16; + var toServer = new System.IO.Pipelines.Pipe(); + var toClient = new System.IO.Pipelines.Pipe(); + using var connection = new SocketConnection(new DuplexStream(toServer.Reader.AsStream(), toClient.Writer.AsStream()), socketContext); + using var client = System.Net.WebSockets.WebSocket.CreateFromStream(new DuplexStream(toClient.Reader.AsStream(), toServer.Writer.AsStream()), + new System.Net.WebSockets.WebSocketCreationOptions { IsServer = false }); + var received = new List(); + var closed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + connection.TextMessageReceived += received.Add; + connection.Disconnected += info => closed.TrySetResult(info); + var cancellation = TestContext.Current.CancellationToken; + + // act + var loop = connection.ReceiveLoopAsync(cancellation); + await client.SendAsync("short"u8.ToArray(), System.Net.WebSockets.WebSocketMessageType.Text, true, cancellation); + await client.SendAsync(new byte[100], System.Net.WebSockets.WebSocketMessageType.Text, true, cancellation); + var answer = await client.ReceiveAsync(new ArraySegment(new byte[256]), cancellation).WaitAsync(TimeSpan.FromSeconds(5), cancellation); + var info = await closed.Task.WaitAsync(TimeSpan.FromSeconds(5), cancellation); + await loop.WaitAsync(TimeSpan.FromSeconds(5), cancellation); + + // validation + Assert.Equal(["short"], received); + Assert.Equal(System.Net.WebSockets.WebSocketMessageType.Close, answer.MessageType); + Assert.Equal(System.Net.WebSockets.WebSocketCloseStatus.MessageTooBig, answer.CloseStatus); + Assert.Equal(System.Net.WebSockets.WebSocketCloseStatus.MessageTooBig, info.Status); + } + + /// + /// Joins a read and a write stream into the one stream a websocket runs on. + /// + private sealed class DuplexStream(Stream read, Stream write) : Stream + { + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => true; + public override long Length => throw new NotSupportedException(); + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + public override void Flush() => write.Flush(); + public override Task FlushAsync(CancellationToken cancellationToken) => write.FlushAsync(cancellationToken); + public override int Read(byte[] buffer, int offset, int count) => read.Read(buffer, offset, count); + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) => read.ReadAsync(buffer, cancellationToken); + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => read.ReadAsync(buffer, offset, count, cancellationToken); + public override void Write(byte[] buffer, int offset, int count) => write.Write(buffer, offset, count); + public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) => write.WriteAsync(buffer, cancellationToken); + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => write.WriteAsync(buffer, offset, count, cancellationToken); + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + } + /// /// A write-only stream whose writes stay pending until the test opens it, and that /// records how many writes overlapped. diff --git a/src/WebExpress.WebCore.Test/Server/UnitTestWebSocketHandshake.cs b/src/WebExpress.WebCore.Test/Server/UnitTestWebSocketHandshake.cs index 99e08ef..a1c19d1 100644 --- a/src/WebExpress.WebCore.Test/Server/UnitTestWebSocketHandshake.cs +++ b/src/WebExpress.WebCore.Test/Server/UnitTestWebSocketHandshake.cs @@ -66,7 +66,8 @@ public void CreateContext_WithPublicHost_PreservesWebSocketRequest( var socketContext = Assert.IsType(result); Assert.IsType(socketContext.Request); Assert.Equal(expectedHost, socketContext.Uri.Host); - Assert.Equal(localPort, socketContext.Uri.Port); + // the public port of the host header, never the listener port behind a port mapping + Assert.Equal(new HostString(host).Port ?? (scheme == "https" ? 443 : 80), socketContext.Uri.Port); Assert.Equal(target, socketContext.Uri.PathAndQuery); Assert.Equal("updates", socketContext.Request.GetParameter("domains")?.Value); Assert.Equal(key, socketContext.WebSocketKey); @@ -208,5 +209,52 @@ public async Task ConnectAsync_ProtectedSocketWithoutIdentity_IsRefused() UnitTestFixture.BindComponentHub(previousHub); } } + + /// + /// Verifies that an upgrade to an endpoint that is no socket is refused as a bad request, + /// without the handshake being attempted: the socket manager would otherwise run against + /// an endpoint without socket metadata and fail with an internal error. + /// + /// A task that completes after the refused handshake has been verified. + [Fact] + public async Task ConnectAsync_ToResourceThatIsNoSocket_IsBadRequest() + { + // arrange + var previousHub = WebEx.ComponentHub; + var server = new HttpServer(UnitTestFixture.CreateHttpServerContextMock()) + { + Settings = new HttpServerSettings { Endpoints = [new() { Uri = "http://127.0.0.1:0/" }] } + }; + var componentHub = UnitTestFixture.CreateAndRegisterComponentHubMock(server.HttpServerContext); + using var client = new ClientWebSocket(); + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + + try + { + var application = componentHub.ApplicationManager.GetApplications(typeof(TestApplicationA)).First(); + componentHub.SitemapManager.Refresh(); + var resource = componentHub.SitemapManager.GetUri(typeof(WWW.Resources.TestResourceA), application); + Assert.True(server.Start()); + var kestrel = (IServer)typeof(HttpServer).GetProperty("Kestrel", BindingFlags.Instance | BindingFlags.NonPublic) + .GetValue(server); + var address = kestrel.Features.Get().Addresses.Single(); + var target = new UriBuilder(address) { Scheme = "ws", Path = new Uri(new Uri("http://localhost/"), resource.ToString()).AbsolutePath }.Uri; + client.Options.CollectHttpResponseDetails = true; + + // act + await Assert.ThrowsAsync(() => client.ConnectAsync(target, timeout.Token)); + + // validation + Assert.Equal(HttpStatusCode.BadRequest, client.HttpStatusCode); + Assert.False(client.HttpResponseHeaders?.ContainsKey("Sec-WebSocket-Accept") ?? false); + } + finally + { + client.Abort(); + server.Stop(); + componentHub.IdentityProviderManager.Dispose(); + UnitTestFixture.BindComponentHub(previousHub); + } + } } } diff --git a/src/WebExpress.WebCore/HttpServer.cs b/src/WebExpress.WebCore/HttpServer.cs index fd73c27..2e1773d 100644 --- a/src/WebExpress.WebCore/HttpServer.cs +++ b/src/WebExpress.WebCore/HttpServer.cs @@ -133,10 +133,13 @@ public class HttpServer : IHost, IHttpApplication /// public static DateTime ExecutionTime { get; } = DateTime.Now; + private long _requestNumber; + /// - /// Gets the request number; + /// Gets the number of the request answered last; each request takes the next one, also + /// while several are answered at once. /// - public long RequestNumber { get; private set; } + public long RequestNumber => Interlocked.Read(ref _requestNumber); /// /// Gets the statistics history. @@ -594,12 +597,15 @@ private IResponse HandleClient(IHttpContext context, SearchResult searchResult) var request = context.Request; var response = default(IResponse); + // taken once, so the done line names this request and not whichever started last + var requestNumber = Interlocked.Increment(ref _requestNumber); + HttpServerContext.Log?.Debug(message: I18N.Translate("webexpress.webcore:httpserver.connected"), args: context.RemoteEndPoint); HttpServerContext.Log?.Info(I18N.Translate ( "webexpress.webcore:httpserver.request", context.RemoteEndPoint, - ++RequestNumber, + requestNumber, $"{request?.Method} {request?.Uri} {request?.Protocol}" )); @@ -704,7 +710,7 @@ private IResponse HandleClient(IHttpContext context, SearchResult searchResult) ( "webexpress.webcore:httpserver.request.done", context?.RemoteEndPoint, - RequestNumber, + requestNumber, stopwatch.ElapsedMilliseconds, response.Status )); @@ -1044,7 +1050,8 @@ private static IResponse CreateStatusPage(string message, IRequest re var applicationContext = string.IsNullOrEmpty(route) ? null : applicationManager?.Applications - .FirstOrDefault(x => route.StartsWith(x.Route.ToString())); + .Where(x => IsRouteBelow(route, x.Route.ToString())) + .MaxBy(x => x.Route.ToString().TrimEnd('/').Length); if (statusPageManager is not null && searchResult is not null) { @@ -1079,6 +1086,27 @@ private static IResponse CreateStatusPage(string message, IRequest re return response; } + /// + /// Determines whether a route lies at or below the route of an application. The routes + /// are compared by whole segments: a plain prefix test takes "/application/x" for a + /// route of the application at "/app". + /// + /// The route of the request. + /// The route of the application. + /// True when the route belongs to the application. + internal static bool IsRouteBelow(string route, string applicationRoute) + { + var root = applicationRoute?.TrimEnd('/') ?? string.Empty; + + if (root.Length == 0) + { + return true; + } + + return route.StartsWith(root, StringComparison.Ordinal) + && (route.Length == root.Length || route[root.Length] == '/'); + } + /// /// Determines whether the request names a file whose type is not html. A browser /// loading a stylesheet, script or image does not surface the status of the answer, @@ -1126,17 +1154,13 @@ public IHttpContext CreateContext(IFeatureCollection contextFeatures) { try { - var requestFeature = contextFeatures.Get(); - - // check if schema or upgrade header indicates websocket - if (IsWebSocketRequest(requestFeature)) + if (IsWebSocketRequest(contextFeatures)) { - // use WebSocketContext for websocket connections return new HttpWebSocketContext(contextFeatures, HttpServerContext); } - // use regular HttpContext for normal HTTP requests - return new HttpContext(contextFeatures, HttpServerContext); + // the body is read once the request is processed, asynchronously + return new HttpContext(contextFeatures, HttpServerContext, readContent: false); } catch (Exception ex) { @@ -1356,13 +1380,9 @@ private async Task ProcessRequestCoreAsync(IHttpContext httpContext, Stopwatch s { var sender = new ResponseSender(SecurityHeaders); - /* - * Applies pending authentication and optional session cookies even when routing bypasses a handler. - * Records statistics before transmission so client latency does not inflate server processing time. - * The context parameter identifies the HTTP exchange and its pending credential changes. - * The response parameter carries the result of routing, authentication, or an application handler. - * Returns a task that completes after the response has been sent. - */ + // cookies are applied here so they reach the client even when routing bypasses a + // handler; statistics are recorded before sending, so client latency does not + // count as server processing time async Task SendAsync(IHttpContext context, IResponse response) { IssueSessionCookie(context?.Request, response); @@ -1379,17 +1399,25 @@ async Task SendAsync(IHttpContext context, IResponse response) { HttpServerContext.Log?.Exception(exceptionContext.Exception); - var message = "404" + - Describe(exceptionContext.Exception) + - ""; - - var response500 = CreateStatusPage(message, httpContext?.Request); + // only the fragment: the status page supplies the document around it + var response500 = CreateStatusPage(Describe(exceptionContext.Exception), httpContext?.Request); await SendAsync(exceptionContext, response500); return; } + if (httpContext is not HttpWebSocketContext && httpContext.Request.Method == RequestMethod.NONE) + { + await SendAsync(httpContext, CreateStatusPage + ( + "The request method is not supported.", + httpContext.Request + )); + + return; + } + // checked before any handler runs, so no application can forget it if (!OriginGuard.IsAllowed(httpContext.Request, httpContext is HttpWebSocketContext)) { @@ -1398,6 +1426,27 @@ async Task SendAsync(IHttpContext context, IResponse response) return; } + if (httpContext.Request is Request bodyRequest) + { + try + { + await bodyRequest.ReadContentAsync(httpContext.Features.Get()?.RequestAborted + ?? CancellationToken.None); + } + catch (Microsoft.AspNetCore.Http.BadHttpRequestException ex) + { + // kestrel rejects a body over MaxRequestBodySize or a malformed chunked one; + // the client is told why instead of seeing an internal error + var rejected = ex.StatusCode == Microsoft.AspNetCore.Http.StatusCodes.Status413PayloadTooLarge + ? CreateStatusPage(EncodeHtml(ex.Message), httpContext.Request) + : CreateStatusPage(EncodeHtml(ex.Message), httpContext.Request); + + await SendAsync(httpContext, rejected); + + return; + } + } + var authenticationResponse = await _authenticationEndpoint.Value.HandleAsync(httpContext.Request); if (authenticationResponse is not null) { @@ -1458,8 +1507,12 @@ async Task SendAsync(IHttpContext context, IResponse response) if (httpContext is HttpWebSocketContext) { - // try to obtain websocket context and optional handler - var socketContext = searchResult.EndpointContext as ISocketContext; + if (searchResult.EndpointContext is not ISocketContext socketContext) + { + await SendAsync(httpContext, new ResponseBadRequest(new StatusMessage("The resource does not accept websocket connections."))); + + return; + } await HandleWebSocketAsync(httpContext, socketContext); @@ -1495,6 +1548,18 @@ public async Task HandleWebSocketAsync(IHttpContext httpContext, ISocketContext return; } + // once the connection is switched it no longer speaks http: a status written then + // only fails, so a failure ends the request and with it the upgraded connection + async Task FailAsync(IResponse response) + { + if (httpContext.Features.Get()?.HasStarted ?? false) + { + return; + } + + await responseSender.SendAsync(httpContext, response); + } + try { BindSocketSession(httpContext); @@ -1506,30 +1571,19 @@ public async Task HandleWebSocketAsync(IHttpContext httpContext, ISocketContext var response = new ResponseUpgradeRequired(new StatusMessage("Invalid WebSocket handshake headers")); response.Header.Upgrade = "websocket"; - await responseSender.SendAsync(httpContext, response); - } - catch (SocketMessageTooLargeException ex) - { - // the client sent a WebSocket message exceeding the configured maximum size -> respond with 413 - var response = new ResponsePayloadTooLarge(new StatusMessage($"WebSocket message exceeds the maximum allowed size of {ex.MaxSize} bytes.")); - await responseSender.SendAsync(httpContext, response); + await FailAsync(response); } catch (SocketException ex) { HttpServerContext.Log?.Exception(ex); - // return 500 when socket error - var response = new ResponseInternalServerError(new StatusMessage("A transport-level socket error occurred during WebSocket communication.")); - await responseSender.SendAsync(httpContext, response); + await FailAsync(new ResponseInternalServerError(new StatusMessage("A transport-level socket error occurred during WebSocket communication."))); } catch (Exception ex) { - // log unhandled exceptions during websocket processing HttpServerContext.Log?.Exception(ex); - // return 500 when handshake did not succeed and no websocket established - var response = new ResponseInternalServerError(new StatusMessage("An unexpected server error occurred during WebSocket processing.")); - await responseSender.SendAsync(httpContext, response); + await FailAsync(new ResponseInternalServerError(new StatusMessage("An unexpected server error occurred during WebSocket processing."))); } } @@ -1545,16 +1599,27 @@ public void DisposeContext(IHttpContext context, Exception exception) /// /// Checks whether the current request is a WebSocket connection. /// - /// The HTTP request feature instance. + /// + /// Over HTTP/2 and HTTP/3 a browser opens a websocket with an extended CONNECT + /// (RFC 8441, RFC 9220), which carries the protocol in a pseudo-header and no Upgrade + /// header at all. + /// + /// The feature collection of the request. /// True if it is a WebSocket connection; otherwise, false. - private static bool IsWebSocketRequest(IHttpRequestFeature requestFeature) + private static bool IsWebSocketRequest(IFeatureCollection contextFeatures) { - // check scheme and "Upgrade" header for websocket protocol + var requestFeature = contextFeatures.Get(); if (requestFeature == null) { return false; } + var extendedConnect = contextFeatures.Get(); + if (extendedConnect?.IsExtendedConnect == true) + { + return string.Equals(extendedConnect.Protocol, "websocket", StringComparison.OrdinalIgnoreCase); + } + var upgradeHeader = requestFeature.Headers.Upgrade; var scheme = requestFeature.Scheme; var isWebSocket = diff --git a/src/WebExpress.WebCore/WebMessage/HttpContext.cs b/src/WebExpress.WebCore/WebMessage/HttpContext.cs index f8c9154..ecaaffc 100644 --- a/src/WebExpress.WebCore/WebMessage/HttpContext.cs +++ b/src/WebExpress.WebCore/WebMessage/HttpContext.cs @@ -3,6 +3,7 @@ using System; using System.Net; using System.Text; +using System.Threading; namespace WebExpress.WebCore.WebMessage { @@ -63,7 +64,27 @@ internal HttpContext() /// /// Initial set of features. /// The context of the Web server. + /// + /// The request body is read here, synchronously. That suits a body already held in + /// memory; the server itself builds its contexts without the body and reads it + /// asynchronously once the request is being processed. + /// public HttpContext(IFeatureCollection contextFeatures, IHttpServerContext httpServerContext) + : this(contextFeatures, httpServerContext, readContent: true) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// Initial set of features. + /// The context of the Web server. + /// + /// True to read the request body right away; false leaves it to + /// , as a context Kestrel creates + /// must not block on a body that is still arriving. + /// + internal HttpContext(IFeatureCollection contextFeatures, IHttpServerContext httpServerContext, bool readContent) { var connectionFeature = contextFeatures.Get(); var requestFeature = contextFeatures.Get(); @@ -75,13 +96,42 @@ public HttpContext(IFeatureCollection contextFeatures, IHttpServerContext httpSe Id = connectionFeature.ConnectionId; LocalEndPoint = new IPEndPoint(connectionFeature.LocalIpAddress, connectionFeature.LocalPort); RemoteEndPoint = new IPEndPoint(connectionFeature.RemoteIpAddress, connectionFeature.RemotePort); + Uri = ResolveTarget(baseUri, requestFeature.RawTarget); + + var request = new Request(contextFeatures, header, httpServerContext); - Encoding = requestFeature.Headers.ContentEncoding.Count != 0 - ? Encoding.GetEncoding(requestFeature.Headers.ContentEncoding) - : Encoding.Default; - Uri = new Uri(baseUri, requestFeature.RawTarget); + if (readContent) + { + request.ReadContentAsync(CancellationToken.None).GetAwaiter().GetResult(); + } + + Request = request; + } + + /// + /// Resolves the request target against the authority the request was addressed to. + /// + /// + /// The target is never resolved as a relative reference: one that starts with "//" + /// ("//evil.com/admin") would then be read as a network-path reference and replace the + /// host, so the routing would see "/admin" while a proxy in front saw a different path. + /// An absolute-form target only contributes its path and query, and anything else + /// (the asterisk of "OPTIONS *") addresses the root. + /// + /// The scheme, host and port of the request. + /// The request target as the client sent it. + /// The uri of the request. + internal static Uri ResolveTarget(Uri baseUri, string rawTarget) + { + var target = rawTarget switch + { + null or "" => "/", + _ when rawTarget.StartsWith('/') => rawTarget, + _ when Uri.TryCreate(rawTarget, UriKind.Absolute, out var absolute) => absolute.PathAndQuery, + _ => "/" + }; - Request = new Request(contextFeatures, header, httpServerContext); + return new Uri(baseUri.GetLeftPart(UriPartial.Authority) + target); } /// diff --git a/src/WebExpress.WebCore/WebMessage/HttpExceptionContext.cs b/src/WebExpress.WebCore/WebMessage/HttpExceptionContext.cs index 178b755..b3617d3 100644 --- a/src/WebExpress.WebCore/WebMessage/HttpExceptionContext.cs +++ b/src/WebExpress.WebCore/WebMessage/HttpExceptionContext.cs @@ -25,7 +25,6 @@ public class HttpExceptionContext : HttpContext public HttpExceptionContext(Exception exception, IFeatureCollection contextFeatures) { var connectionFeature = contextFeatures.Get(); - //var requestFeature = contextFeatures.Get(); Features = contextFeatures; Id = connectionFeature.ConnectionId; diff --git a/src/WebExpress.WebCore/WebMessage/HttpWebSocketContext.cs b/src/WebExpress.WebCore/WebMessage/HttpWebSocketContext.cs index d7e6d9d..f2049f5 100644 --- a/src/WebExpress.WebCore/WebMessage/HttpWebSocketContext.cs +++ b/src/WebExpress.WebCore/WebMessage/HttpWebSocketContext.cs @@ -1,4 +1,5 @@ -using Microsoft.AspNetCore.Http.Features; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; using System; using System.Net; using System.Text; @@ -70,18 +71,17 @@ public HttpWebSocketContext(IFeatureCollection contextFeatures, IHttpServerConte var connectionFeature = contextFeatures.Get(); var requestFeature = contextFeatures.Get(); var header = new RequestHeaderFields(contextFeatures); - var baseUri = new UriBuilder(requestFeature.Scheme, HttpContext.HostNameOf(header.Host), connectionFeature.LocalPort).Uri; + var requestHost = new HostString(header.Host); + + // an omitted host port denotes the scheme default, never the internal listener port + var baseUri = new UriBuilder(requestFeature.Scheme, HttpContext.HostNameOf(header.Host), requestHost.Port ?? -1).Uri; Features = contextFeatures; HttpServerContext = httpServerContext; Id = connectionFeature.ConnectionId; LocalEndPoint = new IPEndPoint(connectionFeature.LocalIpAddress, connectionFeature.LocalPort); RemoteEndPoint = new IPEndPoint(connectionFeature.RemoteIpAddress, connectionFeature.RemotePort); - - Encoding = requestFeature.Headers.ContentEncoding.Count != 0 - ? Encoding.GetEncoding(requestFeature.Headers.ContentEncoding) - : Encoding.Default; - Uri = new Uri(baseUri, requestFeature.RawTarget); + Uri = HttpContext.ResolveTarget(baseUri, requestFeature.RawTarget); // always initialize as websocket-request for this context Request = new RequestWebSocket(contextFeatures, header, httpServerContext); diff --git a/src/WebExpress.WebCore/WebMessage/Request.cs b/src/WebExpress.WebCore/WebMessage/Request.cs index 7daf6ee..097898d 100644 --- a/src/WebExpress.WebCore/WebMessage/Request.cs +++ b/src/WebExpress.WebCore/WebMessage/Request.cs @@ -4,6 +4,8 @@ using System.Linq; using System.Text; using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; using WebExpress.WebCore.WebHtml; using WebExpress.WebCore.WebParameter; @@ -35,13 +37,18 @@ public partial class Request : RequestBase /// internal const int InitialContentBufferSize = 64 * 1024; + private readonly Stream _body; + private readonly long? _contentLength; + private bool _contentRead; + /// /// Gets the content. /// public byte[] Content { get; private set; } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. The body is not read yet; see + /// . /// /// Initial set of features. /// The header. @@ -51,7 +58,31 @@ internal Request(IFeatureCollection contextFeatures, RequestHeaderFields header, { var requestFeature = contextFeatures.Get(); - Content = GetContent(requestFeature.Body, Header.ContentLength); + _body = requestFeature.Body; + _contentLength = requestFeature.Headers.ContentLength; + } + + /// + /// Reads the request body and adds the parameters it carries. + /// + /// + /// Kept apart from the constructor because a context is created synchronously while the + /// body may still be arriving: reading it there blocks a pool thread per upload and fails + /// outright once Kestrel disallows synchronous IO. + /// + /// Signals that the client gave up on the request. + /// A task that completes once the body has been read and parsed. + internal async Task ReadContentAsync(CancellationToken cancellationToken) + { + // a context built with its body already read reaches the pipeline as well; a second + // read would find the stream drained and discard the content + if (_contentRead) + { + return; + } + + _contentRead = true; + Content = await GetContentAsync(_body, _contentLength, cancellationToken).ConfigureAwait(false); ParseRequestParams(); } @@ -59,12 +90,17 @@ internal Request(IFeatureCollection contextFeatures, RequestHeaderFields header, /// /// Returns the content. /// - /// The content of a request. - /// The number of bytes sent in the body or zero. + /// The content of a request, or null when there is none. + /// + /// The number of bytes the client announced, or null when it announced none - a chunked + /// HTTP/1.1 body or an HTTP/2 or HTTP/3 body without content-length, which then runs to + /// the end of the stream. Kestrel's MaxRequestBodySize bounds such a body. + /// + /// Signals that the client gave up on the request. /// The content as a byte array, or null if the body is empty. - internal static byte[] GetContent(Stream body, long? contentLength) + internal static async Task GetContentAsync(Stream body, long? contentLength, CancellationToken cancellationToken) { - if (!contentLength.HasValue || contentLength.Value <= 0) + if (body is null || contentLength <= 0) { return null; } @@ -72,7 +108,7 @@ internal static byte[] GetContent(Stream body, long? contentLength) // the announced length is client-controlled, so it only caps the read; memory is // committed as bytes actually arrive, otherwise a slow client announcing a large // body would pin that much memory per connection before sending anything - var length = (int)Math.Min(contentLength.Value, int.MaxValue); + var length = (int)Math.Min(contentLength ?? int.MaxValue, int.MaxValue); var buffer = new byte[Math.Min(length, InitialContentBufferSize)]; var offset = 0; @@ -83,7 +119,7 @@ internal static byte[] GetContent(Stream body, long? contentLength) Array.Resize(ref buffer, (int)Math.Min((long)buffer.Length * 2, length)); } - var read = body.Read(buffer, offset, buffer.Length - offset); + var read = await body.ReadAsync(buffer.AsMemory(offset, buffer.Length - offset), cancellationToken).ConfigureAwait(false); if (read == 0) { break; @@ -146,10 +182,17 @@ protected virtual void ParseRequestParams() /// private void ParseMultipart(string[] contentTypeParts) { - // extract boundary + // a boundary with characters such as ':' or '=' must be quoted (RFC 2046), and the + // quotes are not part of the delimiter in the body var boundary = contentTypeParts .FirstOrDefault(x => x.StartsWith("boundary=", StringComparison.OrdinalIgnoreCase)) - ?["boundary=".Length..]; + ?["boundary=".Length..] + .Trim(); + + if (boundary is { Length: >= 2 } && boundary[0] == '"' && boundary[^1] == '"') + { + boundary = boundary[1..^1]; + } if (string.IsNullOrWhiteSpace(boundary)) { diff --git a/src/WebExpress.WebCore/WebMessage/RequestAuthorization.cs b/src/WebExpress.WebCore/WebMessage/RequestAuthorization.cs index 75f1f02..415de58 100644 --- a/src/WebExpress.WebCore/WebMessage/RequestAuthorization.cs +++ b/src/WebExpress.WebCore/WebMessage/RequestAuthorization.cs @@ -72,7 +72,9 @@ public static RequestAuthorization Parse(string str) { // decode the base64 string var decoded = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(data)); - var split = decoded.Split(':'); + // only the user id is barred from containing a colon (RFC 7617), the + // password may hold any number of them + var split = decoded.Split(':', 2); if (split.Length > 0) { diff --git a/src/WebExpress.WebCore/WebMessage/RequestBase.cs b/src/WebExpress.WebCore/WebMessage/RequestBase.cs index 76cbaef..01871c9 100644 --- a/src/WebExpress.WebCore/WebMessage/RequestBase.cs +++ b/src/WebExpress.WebCore/WebMessage/RequestBase.cs @@ -5,7 +5,6 @@ using System.Globalization; using System.Linq; using System.Net; -using System.Threading.Tasks; using WebExpress.WebCore.WebApplication; using WebExpress.WebCore.WebEndpoint; using WebExpress.WebCore.WebParameter; @@ -131,7 +130,6 @@ internal RequestBase(IFeatureCollection contextFeatures, RequestHeaderFields hea var connectionFeature = contextFeatures.Get(); var requestFeature = contextFeatures.Get(); var requestIdentifierFeature = contextFeatures.Get(); - //var sessionFeature = contextFeatures.Get(); HttpServerContext = httpServerContext; RequestTraceIdentifier = requestIdentifierFeature.TraceIdentifier; @@ -156,7 +154,9 @@ internal RequestBase(IFeatureCollection contextFeatures, RequestHeaderFields hea "DELETE" => RequestMethod.DELETE, "HEAD" => RequestMethod.HEAD, "PATCH" => RequestMethod.PATCH, - _ => RequestMethod.GET + // a method the framework does not implement must not reach a GET handler, which + // would answer an OPTIONS preflight or a PROPFIND with the resource itself + _ => RequestMethod.NONE }; Header = header; @@ -190,7 +190,8 @@ private void ParseQueryParams(string query) { query = query.TrimStart('?'); - Parallel.ForEach(query.Split('&'), (param) => + // in order, so a repeated key always resolves to its last occurrence + foreach (var param in query.Split('&')) { if (!string.IsNullOrWhiteSpace(param)) { @@ -202,7 +203,7 @@ private void ParseQueryParams(string query) AddParameter(new Parameter(key, value, ParameterScope.Parameter)); } - }); + } } /// diff --git a/src/WebExpress.WebCore/WebMessage/RequestHeaderFields.cs b/src/WebExpress.WebCore/WebMessage/RequestHeaderFields.cs index b15e2e1..9f5fc9a 100644 --- a/src/WebExpress.WebCore/WebMessage/RequestHeaderFields.cs +++ b/src/WebExpress.WebCore/WebMessage/RequestHeaderFields.cs @@ -38,9 +38,14 @@ public class RequestHeaderFields public string ContentLanguage { get; private set; } /// - /// Gets the encoding of the content. + /// Gets the content codings applied to the body (for example "gzip"), as the + /// Content-Encoding header lists them; null when the body is sent as is. /// - public Encoding ContentEncoding { get; private set; } + /// + /// A content coding is a compression, not a character set: the charset of a text body + /// travels as a parameter of the Content-Type header. + /// + public string ContentEncoding { get; private set; } /// /// Gets the user agent. @@ -153,7 +158,7 @@ internal RequestHeaderFields(IFeatureCollection contextFeatures) ContentType = requestFeature.Headers.ContentType; ContentLength = requestFeature.Headers.ContentLength ?? 0; ContentLanguage = requestFeature.Headers.ContentLanguage; - ContentEncoding = requestFeature.Headers.ContentEncoding.Count != 0 ? Encoding.GetEncoding(requestFeature.Headers.ContentEncoding) : Encoding.Default; + ContentEncoding = requestFeature.Headers.ContentEncoding.Count != 0 ? requestFeature.Headers.ContentEncoding.ToString() : null; Accept = requestFeature.Headers.Accept; AcceptEncoding = requestFeature.Headers.AcceptEncoding; AcceptLanguage = requestFeature.Headers.AcceptLanguage.SelectMany(x => x.Split(';', StringSplitOptions.RemoveEmptyEntries)); diff --git a/src/WebExpress.WebCore/WebMessage/RequestHeaderFieldsExtensions.cs b/src/WebExpress.WebCore/WebMessage/RequestHeaderFieldsExtensions.cs index c682099..edf0c6c 100644 --- a/src/WebExpress.WebCore/WebMessage/RequestHeaderFieldsExtensions.cs +++ b/src/WebExpress.WebCore/WebMessage/RequestHeaderFieldsExtensions.cs @@ -32,7 +32,7 @@ void Add(string name, string value) Add("Content-Type", header.ContentType); Add("Content-Length", header.ContentLength > 0 ? header.ContentLength.ToString() : null); Add("Content-Language", header.ContentLanguage); - Add("Content-Encoding", header.ContentEncoding?.WebName); + Add("Content-Encoding", header.ContentEncoding); Add("User-Agent", header.UserAgent); Add("Referer", header.Referer); diff --git a/src/WebExpress.WebCore/WebMessage/ResponseHeaderFields.cs b/src/WebExpress.WebCore/WebMessage/ResponseHeaderFields.cs index 50b04e9..0c90125 100644 --- a/src/WebExpress.WebCore/WebMessage/ResponseHeaderFields.cs +++ b/src/WebExpress.WebCore/WebMessage/ResponseHeaderFields.cs @@ -39,10 +39,22 @@ public class ResponseHeaderFields public string ContentDisposition { get; set; } /// - /// Gets or sets a value indicating whether basic authentication (as per RFC 2617) is required. - /// + /// Gets or sets a value indicating whether the response challenges the client to + /// authenticate with a bearer token (RFC 6750). + /// + /// + /// The challenge is never Basic: the server does not accept Basic credentials, yet a + /// browser answers a Basic challenge with a login dialog and then sends whatever was typed + /// with every request - and an Authorization header takes precedence over the sign-in + /// cookie, so the user stays signed out until the browser is closed. + /// public bool WWWAuthenticate { get; set; } + /// + /// The challenge sent when is set. + /// + internal const string BearerChallenge = "Bearer"; + /// /// Gets or sets the location. /// @@ -140,7 +152,7 @@ public override string ToString() if (WWWAuthenticate) { - sb.AppendLine("WWW-Authenticate: Basic realm=\"Bereich\""); + sb.AppendLine("WWW-Authenticate: " + BearerChallenge); } if (!string.IsNullOrWhiteSpace(Location)) diff --git a/src/WebExpress.WebCore/WebMessage/ResponseSender.cs b/src/WebExpress.WebCore/WebMessage/ResponseSender.cs index 4899367..9fc8be0 100644 --- a/src/WebExpress.WebCore/WebMessage/ResponseSender.cs +++ b/src/WebExpress.WebCore/WebMessage/ResponseSender.cs @@ -102,7 +102,7 @@ public async Task SendAsync(IHttpContext context, IResponse response, bool keepA if (response.Header.WWWAuthenticate) { - responseFeature.Headers.WWWAuthenticate = "Basic realm=\"Bereich\""; + responseFeature.Headers.WWWAuthenticate = ResponseHeaderFields.BearerChallenge; } if (response.Header.Cookies.Count != 0) diff --git a/src/WebExpress.WebCore/WebSocket/SocketConnection.cs b/src/WebExpress.WebCore/WebSocket/SocketConnection.cs index 455ba28..ef17698 100644 --- a/src/WebExpress.WebCore/WebSocket/SocketConnection.cs +++ b/src/WebExpress.WebCore/WebSocket/SocketConnection.cs @@ -17,6 +17,7 @@ internal class SocketConnection : ISocketConnection, IDisposable private readonly CancellationTokenSource _cts = new(); private readonly SemaphoreSlim _sendLock = new(1, 1); private readonly int _bufferSize; + private readonly ulong? _maxMessageSize; private bool _disconnectRaised; private static readonly TimeSpan _shutdownCloseTimeout = TimeSpan.FromSeconds(1); @@ -63,6 +64,7 @@ public SocketConnection(Stream networkStream, ISocketContext socketContext, int ?? throw new ArgumentNullException(nameof(networkStream)); _bufferSize = bufferSize; + _maxMessageSize = socketContext.MaxMessageSize; } /// @@ -170,6 +172,16 @@ internal async Task ReceiveLoopAsync(CancellationToken stopping = default) // accumulate fragments builder.Write(buffer, 0, result.Count); + // checked per fragment, so a message announced as endless cannot grow the + // buffer past the limit before it ends; the http exchange is over by now, so + // the refusal is the close code of RFC 6455 and not a status + if (_maxMessageSize is ulong maxMessageSize && (ulong)builder.Length > maxMessageSize) + { + using var deadline = new CancellationTokenSource(_shutdownCloseTimeout); + await CloseAsync(WebSocketCloseStatus.MessageTooBig, $"message exceeds {maxMessageSize} bytes", deadline.Token); + break; + } + if (result.EndOfMessage) { if (result.MessageType == WebSocketMessageType.Text) @@ -199,7 +211,19 @@ internal async Task ReceiveLoopAsync(CancellationToken stopping = default) /// /// A task that represents the asynchronous close operation. /// - public async Task CloseAsync(string reason = "closed", CancellationToken cancellation = default) + public Task CloseAsync(string reason = "closed", CancellationToken cancellation = default) + { + return CloseAsync(WebSocketCloseStatus.NormalClosure, reason, cancellation); + } + + /// + /// Closes the connection with the given close code. + /// + /// The close code sent to the client. + /// A textual description sent to the client as part of the close frame. + /// A token used to cancel the close operation. + /// A task that represents the asynchronous close operation. + private async Task CloseAsync(WebSocketCloseStatus status, string reason, CancellationToken cancellation) { if (_socket.State == WebSocketState.Open || _socket.State == WebSocketState.CloseReceived) { @@ -210,7 +234,7 @@ public async Task CloseAsync(string reason = "closed", CancellationToken cancell try { - await _socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, reason, cancellation); + await _socket.CloseOutputAsync(status, reason, cancellation); } finally { @@ -224,7 +248,7 @@ public async Task CloseAsync(string reason = "closed", CancellationToken cancell } _cts.Cancel(); - RaiseDisconnected(WebSocketCloseStatus.NormalClosure, reason); + RaiseDisconnected(status, reason); } /// diff --git a/src/WebExpress.WebCore/WebSocket/SocketManager.cs b/src/WebExpress.WebCore/WebSocket/SocketManager.cs index 7de5eab..8e248de 100644 --- a/src/WebExpress.WebCore/WebSocket/SocketManager.cs +++ b/src/WebExpress.WebCore/WebSocket/SocketManager.cs @@ -111,32 +111,13 @@ private SocketManager(IComponentHub componentHub, IHttpServerContext httpServerC /// public async Task HandleConnectionAsync(IHttpContext httpContext, ISocketContext socketContext) { - // WebSocket handshake - var connectionId = Guid.NewGuid(); - var secWebSocketKey = httpContext.Request.Header.SecWebSocketKey; - var secWebSocketAccept = ComputeWebSocketAcceptKey(secWebSocketKey); - - var headerFeatures = httpContext.Features.Get(); - headerFeatures.Headers.Append("Upgrade", "websocket"); - headerFeatures.Headers.Append("Connection", "Upgrade"); - headerFeatures.Headers.Append("Sec-WebSocket-Accept", secWebSocketAccept); - if (!string.IsNullOrWhiteSpace(socketContext.SupportedSubProtocol)) - { - headerFeatures.Headers.Append("Sec-WebSocket-Protocol", socketContext.SupportedSubProtocol); - } + ArgumentNullException.ThrowIfNull(socketContext); - var upgradeFeature = httpContext.Features.Get() - ?? throw new SocketHandshakeException("Upgrade feature not supported. WebSocket handshake aborted."); - - Stream networkStream; - try - { - networkStream = await upgradeFeature.UpgradeAsync(); - } - catch (Exception ex) - { - throw new SocketHandshakeException("WebSocket upgrade failed.", ex); - } + var connectionId = Guid.NewGuid(); + var extendedConnect = httpContext.Features.Get(); + var networkStream = extendedConnect?.IsExtendedConnect == true + ? await AcceptExtendedConnectAsync(httpContext, socketContext, extendedConnect) + : await UpgradeAsync(httpContext, socketContext); // create application socket instance var instance = CreateSocketInstance(connectionId, socketContext, httpContext.Request); @@ -592,6 +573,93 @@ private static string ComputeWebSocketAcceptKey(string key) return Convert.ToBase64String(hash); } + /// + /// Completes the HTTP/1.1 handshake (RFC 6455) and takes over the connection. + /// + /// + /// The handshake headers are only written once the request is known to be upgradable, + /// and taken back when the upgrade fails: the error response sent instead must not + /// carry an accept key for a connection that was never switched. + /// + /// The context of the upgrade request. + /// The endpoint the socket connects to. + /// The stream of the upgraded connection. + private static async Task UpgradeAsync(IHttpContext httpContext, ISocketContext socketContext) + { + var upgradeFeature = httpContext.Features.Get(); + if (upgradeFeature is null || !upgradeFeature.IsUpgradableRequest) + { + throw new SocketHandshakeException("The request cannot be upgraded. WebSocket handshake aborted."); + } + + var secWebSocketKey = httpContext.Request.Header.SecWebSocketKey; + if (string.IsNullOrWhiteSpace(secWebSocketKey)) + { + throw new SocketHandshakeException("The Sec-WebSocket-Key header is missing. WebSocket handshake aborted."); + } + + var headers = httpContext.Features.Get().Headers; + headers.Append("Upgrade", "websocket"); + headers.Append("Connection", "Upgrade"); + headers.Append("Sec-WebSocket-Accept", ComputeWebSocketAcceptKey(secWebSocketKey)); + if (!string.IsNullOrWhiteSpace(socketContext.SupportedSubProtocol)) + { + headers.Append("Sec-WebSocket-Protocol", socketContext.SupportedSubProtocol); + } + + try + { + return await upgradeFeature.UpgradeAsync(); + } + catch (Exception ex) + { + headers.Remove("Upgrade"); + headers.Remove("Connection"); + headers.Remove("Sec-WebSocket-Accept"); + headers.Remove("Sec-WebSocket-Protocol"); + + throw new SocketHandshakeException("WebSocket upgrade failed.", ex); + } + } + + /// + /// Accepts a websocket that a client opens with an HTTP/2 or HTTP/3 extended CONNECT + /// (RFC 8441, RFC 9220). + /// + /// + /// Such a request carries neither an Upgrade header nor a key: the stream of the request + /// itself becomes the socket once a 2xx is sent, and the Upgrade, Connection and accept + /// headers of HTTP/1.1 are forbidden on it. + /// + /// The context of the connect request. + /// The endpoint the socket connects to. + /// The extended connect feature of the request. + /// The stream of the accepted socket. + private static async Task AcceptExtendedConnectAsync(IHttpContext httpContext, ISocketContext socketContext, IHttpExtendedConnectFeature extendedConnect) + { + if (!string.Equals(extendedConnect.Protocol, "websocket", StringComparison.OrdinalIgnoreCase)) + { + throw new SocketHandshakeException("The extended CONNECT does not ask for a websocket. WebSocket handshake aborted."); + } + + var headers = httpContext.Features.Get().Headers; + if (!string.IsNullOrWhiteSpace(socketContext.SupportedSubProtocol)) + { + headers.Append("Sec-WebSocket-Protocol", socketContext.SupportedSubProtocol); + } + + try + { + return await extendedConnect.AcceptAsync(); + } + catch (Exception ex) + { + headers.Remove("Sec-WebSocket-Protocol"); + + throw new SocketHandshakeException("WebSocket connect failed.", ex); + } + } + /// /// Release of unmanaged resources reserved during use. /// diff --git a/src/WebExpress.WebCore/WebSocket/SocketMessageTooLargeException.cs b/src/WebExpress.WebCore/WebSocket/SocketMessageTooLargeException.cs deleted file mode 100644 index 8a56c99..0000000 --- a/src/WebExpress.WebCore/WebSocket/SocketMessageTooLargeException.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System; - -namespace WebExpress.WebCore.WebSocket -{ - /// - /// Represents an error that occurs when an incoming WebSocket message - /// exceeds the maximum allowed message size configured for the endpoint. - /// - public class SocketMessageTooLargeException : Exception - { - /// - /// Gets the total number of bytes received for the message. - /// - public ulong ActualSize { get; } - - /// - /// Gets the maximum allowed message size in bytes. - /// - public ulong MaxSize { get; } - - /// - /// Initializes a new instance of the class - /// with the specified actual and maximum message sizes. - /// - /// The number of bytes received. - /// The maximum allowed message size in bytes. - public SocketMessageTooLargeException(ulong actualSize, ulong maxSize) - : base($"WebSocket message size {actualSize} bytes exceeds the maximum allowed size of {maxSize} bytes.") - { - ActualSize = actualSize; - MaxSize = maxSize; - } - - /// - /// Initializes a new instance of the class - /// with a custom error message and the specified actual and maximum message sizes. - /// - /// The custom exception message. - /// The number of bytes received. - /// The maximum allowed message size in bytes. - public SocketMessageTooLargeException(string message, ulong actualSize, ulong maxSize) - : base(message) - { - ActualSize = actualSize; - MaxSize = maxSize; - } - - /// - /// Initializes a new instance of the class - /// with a custom error message, an inner exception, and the specified size values. - /// - /// The custom exception message. - /// The inner exception. - /// The number of bytes received. - /// The maximum allowed message size in bytes. - public SocketMessageTooLargeException(string message, Exception innerException, ulong actualSize, ulong maxSize) - : base(message, innerException) - { - ActualSize = actualSize; - MaxSize = maxSize; - } - } -} From 6e860e6342a938717a2f3a928501857e51c86b4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Schwarzer?= Date: Tue, 24 Nov 2026 22:17:09 +0100 Subject: [PATCH 07/16] fix: render fragments on their own instance and lock the fragment registry The compiled render delegate captured the fragment instance of the first request (Expression.Constant) and was cached per class, so every later request rendered on that foreign instance: state leaked across requests and users, concurrent requests rendered on one object, and the instance was never released. The delegate now takes the instance as an argument (typed Func, no DynamicInvoke); a [Cache] fragment keeps one instance, created race-free and disposed with its item. FragmentDictionary is now guarded by a lock and returns materialized lists: the package scan writes it while requests read it. RemoveFragments read the removed items lazily after removing them, so RemoveFragment never fired; it now collects them first, and the manager disposes them. GetFragments(app, section, IEnumerable) called itself with the same arguments - an infinite recursion that overflowed the stack. Co-Authored-By: Claude Opus 5.5 --- .../Manager/UnitTestFragmentIsolation.cs | 177 +++++++++++ .../WebFragment/FragmentManager.cs | 27 +- .../WebFragment/Model/FragmentDictionary.cs | 280 +++++++++++------- .../WebFragment/Model/FragmentItem.cs | 82 ++--- 4 files changed, 412 insertions(+), 154 deletions(-) create mode 100644 src/WebExpress.WebCore.Test/Manager/UnitTestFragmentIsolation.cs diff --git a/src/WebExpress.WebCore.Test/Manager/UnitTestFragmentIsolation.cs b/src/WebExpress.WebCore.Test/Manager/UnitTestFragmentIsolation.cs new file mode 100644 index 0000000..b0034d1 --- /dev/null +++ b/src/WebExpress.WebCore.Test/Manager/UnitTestFragmentIsolation.cs @@ -0,0 +1,177 @@ +using WebExpress.WebCore.Test.Fixture; +using WebExpress.WebCore.WebFragment; +using WebExpress.WebCore.WebFragment.Model; +using WebExpress.WebCore.WebHtml; +using WebExpress.WebCore.WebPage; +using WebExpress.WebCore.WebScope; + +namespace WebExpress.WebCore.Test.Manager +{ + /// + /// Tests that fragments are rendered on their own instance and leave the registry completely + /// when their plugin goes. + /// + public class UnitTestFragmentIsolation + { + /// + /// A fragment that renders the number of its instance. It is nested, so the fragment scan, + /// which only takes public top-level classes, does not register it. + /// + public sealed class InstanceFragment : IFragment + { + private static int _next; + private readonly int _number = Interlocked.Increment(ref _next); + + /// + /// Gets the id. + /// + public string Id => string.Empty; + + /// + /// Renders the number of the instance. + /// + /// The render context. + /// The visual tree. + /// The number as text. + public IHtmlNode Render(IRenderContext renderContext, IVisualTree visualTree) + { + return new HtmlText($"instance {_number}"); + } + + /// + /// Releases nothing. + /// + public void Dispose() + { + } + } + + /// + /// Verifies that every render of an uncached fragment runs on a fresh instance. The compiled + /// render call captured the instance of the first request, so every later request rendered + /// on that one - its state leaked to other requests and users. + /// + [Fact] + public void UncachedFragmentRendersOnItsOwnInstance() + { + // arrange + var item = CreateItem(cache: false, out var renderContext); + + // act + var first = (item.Render(renderContext, new VisualTree()) as HtmlText)?.Value; + var second = (item.Render(renderContext, new VisualTree()) as HtmlText)?.Value; + + // validation + Assert.NotNull(first); + Assert.NotEqual(first, second); + } + + /// + /// Verifies that a cached fragment keeps rendering on the one instance it keeps. + /// + [Fact] + public void CachedFragmentRendersOnTheKeptInstance() + { + // arrange + var item = CreateItem(cache: true, out var renderContext); + + // act + var first = (item.Render(renderContext, new VisualTree()) as HtmlText)?.Value; + var second = (item.Render(renderContext, new VisualTree()) as HtmlText)?.Value; + + // validation + Assert.Equal(first, second); + } + + /// + /// Verifies that removing a plugin announces each of its fragments; the removed fragments + /// were read after they had left the registry, so no remove event ever fired. + /// + [Fact] + public void RemovingAPluginAnnouncesItsFragments() + { + // arrange + var componentHub = UnitTestFixture.CreateAndRegisterComponentHubMock(); + var fragmentManager = componentHub.FragmentManager as FragmentManager; + var plugin = componentHub.PluginManager.GetPlugin(typeof(TestPlugin)); + var registered = componentHub.FragmentManager.Fragments.Count(); + var removed = new List(); + fragmentManager.RemoveFragment += (sender, e) => removed.Add(e); + + // act + fragmentManager.Remove(plugin); + + // validation + Assert.True(registered > 0); + Assert.Equal(registered, removed.Count); + Assert.Empty(componentHub.FragmentManager.Fragments); + } + + /// + /// Verifies that removing every application of a plugin empties the registry and announces + /// each fragment once. + /// + [Fact] + public void RemovingApplicationsAnnouncesTheirFragments() + { + // arrange + var componentHub = UnitTestFixture.CreateAndRegisterComponentHubMock(); + var fragmentManager = componentHub.FragmentManager as FragmentManager; + var registered = componentHub.FragmentManager.Fragments.Count(); + var removed = new List(); + fragmentManager.RemoveFragment += (sender, e) => removed.Add(e); + + // act + foreach (var application in componentHub.ApplicationManager.Applications.ToList()) + { + fragmentManager.Remove(application); + } + + // validation + Assert.Equal(registered, removed.Count); + Assert.Empty(componentHub.FragmentManager.Fragments); + } + + /// + /// Verifies that asking for the fragments of several scopes returns instead of recursing + /// into itself until the stack overflowed. + /// + [Fact] + public void FragmentsOfSeveralScopes() + { + // arrange + var componentHub = UnitTestFixture.CreateAndRegisterComponentHubMock(); + var application = componentHub.ApplicationManager.GetApplications(typeof(TestApplicationA)).FirstOrDefault(); + + // act + var fragments = componentHub.FragmentManager.GetFragments(application, typeof(TestSectionA), [typeof(TestScopeA), typeof(IScope)]); + + // validation + Assert.NotEmpty(fragments); + } + + /// + /// Creates a fragment item of the instance fragment, borrowing the context of a registered + /// fragment whose conditions let it render. + /// + /// Whether the item keeps one instance. + /// The render context the fragment renders in. + /// The fragment item. + private static FragmentItem CreateItem(bool cache, out IRenderContext renderContext) + { + var httpServerContext = UnitTestFixture.CreateHttpServerContextMock(); + var componentHub = UnitTestFixture.CreateAndRegisterComponentHubMock(httpServerContext); + var application = componentHub.ApplicationManager.GetApplications(typeof(TestApplicationA)).FirstOrDefault(); + var fragmentContext = componentHub.FragmentManager.GetFragments(application, typeof(TestFragmentA)).First(); + + renderContext = UnitTestFixture.CrerateRenderContextMock(application, [typeof(TestScopeA)]); + + return new FragmentItem(componentHub, httpServerContext) + { + FragmentContext = fragmentContext, + FragmentClass = typeof(InstanceFragment), + Cache = cache + }; + } + } +} diff --git a/src/WebExpress.WebCore/WebFragment/FragmentManager.cs b/src/WebExpress.WebCore/WebFragment/FragmentManager.cs index 76300cf..2ab94c4 100644 --- a/src/WebExpress.WebCore/WebFragment/FragmentManager.cs +++ b/src/WebExpress.WebCore/WebFragment/FragmentManager.cs @@ -250,11 +250,10 @@ internal void Remove(IPluginContext pluginContext) return; } - var fragments = _dictionary.RemoveFragments(pluginContext); - - foreach (var fragment in fragments) + foreach (var fragment in _dictionary.RemoveFragments(pluginContext)) { - OnRemoveFragment(fragment); + fragment.Dispose(); + OnRemoveFragment(fragment.FragmentContext); } } @@ -269,11 +268,10 @@ internal void Remove(IApplicationContext applicationContext) return; } - var fragments = _dictionary.RemoveFragments(applicationContext); - - foreach (var fragment in fragments) + foreach (var fragment in _dictionary.RemoveFragments(applicationContext)) { - OnRemoveFragment(fragment); + fragment.Dispose(); + OnRemoveFragment(fragment.FragmentContext); } } @@ -486,13 +484,12 @@ public IEnumerable GetFragments(IApplicationContext applicatio { var effectiveScopes = (scopes?.Any() == true) ? scopes : [typeof(IScope)]; - foreach (var scope in effectiveScopes) - { - foreach (var item in GetFragments(applicationContext, section, effectiveScopes)) - { - yield return item; - } - } + // each scope is asked through the single-scope overload; the call passed the whole + // list again and recursed into this method until the stack overflowed + return effectiveScopes + .SelectMany(scope => GetFragments(applicationContext, section, scope)) + .Distinct() + .ToList(); } /// diff --git a/src/WebExpress.WebCore/WebFragment/Model/FragmentDictionary.cs b/src/WebExpress.WebCore/WebFragment/Model/FragmentDictionary.cs index e8a7ae1..0423bbd 100644 --- a/src/WebExpress.WebCore/WebFragment/Model/FragmentDictionary.cs +++ b/src/WebExpress.WebCore/WebFragment/Model/FragmentDictionary.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading; using WebExpress.WebCore.WebApplication; using WebExpress.WebCore.WebPlugin; using WebExpress.WebCore.WebScope; @@ -12,19 +13,35 @@ namespace WebExpress.WebCore.WebFragment.Model /// which in turn maps to a dictionary of section types and inner maps of scope types and lists of FragmentItem objects. /// Plugin -> Application -> Section -> Scope -> FragmentItem /// + /// + /// The package scan adds and removes fragments on its own thread while requests render them, + /// and a dictionary written during a read can throw or loop forever. Every member therefore + /// runs under one lock and returns a list taken under it, never a query that would read the + /// dictionary later, outside the lock. + /// internal class FragmentDictionary { private readonly Dictionary>>>> _dict = []; + private readonly Lock _lock = new(); /// /// Gets all fragment contexts from the dictionary. /// - public IEnumerable All => _dict.Values - .SelectMany(x => x.Values) - .SelectMany(x => x.Values) - .SelectMany(x => x.Values) - .SelectMany(x => x) - .Select(x => x.FragmentContext); + public IEnumerable All + { + get + { + lock (_lock) + { + return [.. _dict.Values + .SelectMany(x => x.Values) + .SelectMany(x => x.Values) + .SelectMany(x => x.Values) + .SelectMany(x => x) + .Select(x => x.FragmentContext)]; + } + } + } /// /// Adds a fragment item to the dictionary. @@ -42,81 +59,102 @@ public bool AddFragmentItem(IPluginContext pluginContext, IApplicationContext ap return false; } - if (!_dict.TryGetValue(pluginContext, out var applicationDict)) + lock (_lock) { - applicationDict = []; - _dict[pluginContext] = applicationDict; - } + if (!_dict.TryGetValue(pluginContext, out var applicationDict)) + { + applicationDict = []; + _dict[pluginContext] = applicationDict; + } - if (!applicationDict.TryGetValue(applicationContext, out var sectionDict)) - { - sectionDict = []; - applicationDict[applicationContext] = sectionDict; - } + if (!applicationDict.TryGetValue(applicationContext, out var sectionDict)) + { + sectionDict = []; + applicationDict[applicationContext] = sectionDict; + } - if (!sectionDict.TryGetValue(fragmentItem.Section, out var scopeDict)) - { - scopeDict = []; - sectionDict[fragmentItem.Section] = scopeDict; - } + if (!sectionDict.TryGetValue(fragmentItem.Section, out var scopeDict)) + { + scopeDict = []; + sectionDict[fragmentItem.Section] = scopeDict; + } - if (!scopeDict.TryGetValue(fragmentItem.Scope, out var itemList)) - { - itemList = []; - scopeDict[fragmentItem.Scope] = itemList; - } + if (!scopeDict.TryGetValue(fragmentItem.Scope, out var itemList)) + { + itemList = []; + scopeDict[fragmentItem.Scope] = itemList; + } - if (!itemList.Any(x => x.FragmentClass == fragmentItem.FragmentClass)) - { - itemList.Add(fragmentItem); + if (!itemList.Any(x => x.FragmentClass == fragmentItem.FragmentClass)) + { + itemList.Add(fragmentItem); - return true; - } + return true; + } - return false; + return false; + } } /// - /// Removes fragments from the dictionary. + /// Removes the fragments of a plugin. /// + /// + /// The removed items are collected before they leave the dictionary; a query read after + /// the removal found nothing, so the remove events never fired. + /// /// The plugin context. - /// An IEnumerable of fragment contexts that were removed. - public IEnumerable RemoveFragments(IPluginContext pluginContext) + /// The fragment items that were removed. + public IReadOnlyList RemoveFragments(IPluginContext pluginContext) { - var fragments = GetFragments(pluginContext); - - _dict.Remove(pluginContext); + lock (_lock) + { + if (pluginContext is null || !_dict.Remove(pluginContext, out var applicationDict)) + { + return []; + } - return fragments; + return [.. applicationDict.Values + .SelectMany(x => x.Values) + .SelectMany(x => x.Values) + .SelectMany(x => x)]; + } } /// - /// Removes fragments from the dictionary. + /// Removes the fragments of an application. /// + /// + /// The plugins are listed before any of them is removed; removing an entry while the + /// dictionary was enumerated threw on every removal of an application. + /// /// The application context. - /// An IEnumerable of fragment contexts that were removed. - public IEnumerable RemoveFragments(IApplicationContext applicationContext) + /// The fragment items that were removed. + public IReadOnlyList RemoveFragments(IApplicationContext applicationContext) { - foreach (var pluginKeyValue in _dict) + var removed = new List(); + + lock (_lock) { - if (pluginKeyValue.Value.TryGetValue(applicationContext, out var sectionDict)) + foreach (var (pluginContext, applicationDict) in _dict.ToList()) { - pluginKeyValue.Value.Remove(applicationContext); - - if (pluginKeyValue.Value.Count == 0) + if (!applicationDict.Remove(applicationContext, out var sectionDict)) { - _dict.Remove(pluginKeyValue.Key); + continue; } - foreach (var item in sectionDict.Values - .SelectMany(x => x.Values) - .SelectMany(x => x) - .Select(x => x.FragmentContext)) + if (applicationDict.Count == 0) { - yield return item; + _dict.Remove(pluginContext); } + + removed.AddRange(sectionDict.Values + .SelectMany(x => x.Values) + .SelectMany(x => x)); } } + + return removed; } /// @@ -128,15 +166,21 @@ public IEnumerable RemoveFragments(IApplicationContext applica /// An enumeration of the filtered fragment contexts. public IEnumerable GetFragmentItems(IApplicationContext applicationContext, Type section, IEnumerable scopes) { - return _dict.Values - .SelectMany(x => x) - .Where(x => x.Key == applicationContext) - .SelectMany(x => x.Value) - .Where(x => x.Key == section || section.IsAssignableFrom(x.Key)) - .SelectMany(x => x.Value) - .Where(x => scopes.Any(y => x.Key == y)) - .SelectMany(x => x.Value) - .OrderBy(x => x.Order); + // the caller's sequence is read before the lock is taken, so no foreign code runs under it + var scopeSet = (scopes ?? []).ToHashSet(); + + lock (_lock) + { + return [.. _dict.Values + .SelectMany(x => x) + .Where(x => x.Key == applicationContext) + .SelectMany(x => x.Value) + .Where(x => x.Key == section || section.IsAssignableFrom(x.Key)) + .SelectMany(x => x.Value) + .Where(x => scopeSet.Contains(x.Key)) + .SelectMany(x => x.Value) + .OrderBy(x => x.Order)]; + } } /// @@ -149,16 +193,21 @@ public IEnumerable GetFragmentItems(IApplicationContext applicatio /// An enumeration of the filtered fragment items. public IEnumerable GetFragmentItems(IApplicationContext applicationContext, Type fragment, Type section, IEnumerable scopes) { - return _dict.Values - .SelectMany(x => x) - .Where(x => x.Key == applicationContext) - .SelectMany(x => x.Value) - .Where(x => x.Key == section || section.IsAssignableFrom(x.Key)) - .SelectMany(x => x.Value) - .Where(x => scopes.Any(y => x.Key == y)) - .SelectMany(x => x.Value) - .Where(x => x.FragmentClass == fragment || fragment.IsAssignableFrom(x.FragmentClass)) - .OrderBy(x => x.Order); + var scopeSet = (scopes ?? []).ToHashSet(); + + lock (_lock) + { + return [.. _dict.Values + .SelectMany(x => x) + .Where(x => x.Key == applicationContext) + .SelectMany(x => x.Value) + .Where(x => x.Key == section || section.IsAssignableFrom(x.Key)) + .SelectMany(x => x.Value) + .Where(x => scopeSet.Contains(x.Key)) + .SelectMany(x => x.Value) + .Where(x => x.FragmentClass == fragment || fragment.IsAssignableFrom(x.FragmentClass)) + .OrderBy(x => x.Order)]; + } } /// @@ -168,12 +217,15 @@ public IEnumerable GetFragmentItems(IApplicationContext applicatio /// An IEnumerable of fragment contexts. public IEnumerable GetFragments(IPluginContext pluginContext) { - return _dict.Where(x => x.Key == pluginContext) - .SelectMany(x => x.Value.Values) - .SelectMany(x => x.Values) - .SelectMany(x => x.Values) - .SelectMany(x => x) - .Select(x => x.FragmentContext); + lock (_lock) + { + return [.. _dict.Where(x => x.Key == pluginContext) + .SelectMany(x => x.Value.Values) + .SelectMany(x => x.Values) + .SelectMany(x => x.Values) + .SelectMany(x => x) + .Select(x => x.FragmentContext)]; + } } /// @@ -183,14 +235,17 @@ public IEnumerable GetFragments(IPluginContext pluginContext) /// An enumeration of the filtered fragment contexts. public IEnumerable GetFragments(Type fragmentType) { - return _dict.Values - .SelectMany(x => x) - .SelectMany(x => x.Value) - .SelectMany(x => x.Value) - .SelectMany(x => x.Value) - .Where(x => x.FragmentClass == fragmentType) - .OrderBy(x => x.Order) - .Select(x => x.FragmentContext); + lock (_lock) + { + return [.. _dict.Values + .SelectMany(x => x) + .SelectMany(x => x.Value) + .SelectMany(x => x.Value) + .SelectMany(x => x.Value) + .Where(x => x.FragmentClass == fragmentType) + .OrderBy(x => x.Order) + .Select(x => x.FragmentContext)]; + } } /// @@ -201,15 +256,18 @@ public IEnumerable GetFragments(Type fragmentType) /// An enumeration of the filtered fragment contexts. public IEnumerable GetFragments(IApplicationContext applicationContext, Type fragmentType) { - return _dict.Values - .SelectMany(x => x) - .Where(x => x.Key == applicationContext) - .SelectMany(x => x.Value) - .SelectMany(x => x.Value) - .SelectMany(x => x.Value) - .Where(x => x.FragmentClass == fragmentType) - .OrderBy(x => x.Order) - .Select(x => x.FragmentContext); + lock (_lock) + { + return [.. _dict.Values + .SelectMany(x => x) + .Where(x => x.Key == applicationContext) + .SelectMany(x => x.Value) + .SelectMany(x => x.Value) + .SelectMany(x => x.Value) + .Where(x => x.FragmentClass == fragmentType) + .OrderBy(x => x.Order) + .Select(x => x.FragmentContext)]; + } } /// @@ -223,16 +281,19 @@ public IEnumerable GetFragments(IApplicationContext applicatio { scope ??= typeof(IScope); - return _dict.Values - .SelectMany(x => x) - .Where(x => x.Key == applicationContext) - .SelectMany(x => x.Value) - .Where(x => x.Key == section || section.IsAssignableFrom(x.Key)) - .SelectMany(x => x.Value) - .Where(x => x.Key == scope) - .SelectMany(x => x.Value) - .OrderBy(x => x.Order) - .Select(x => x.FragmentContext); + lock (_lock) + { + return [.. _dict.Values + .SelectMany(x => x) + .Where(x => x.Key == applicationContext) + .SelectMany(x => x.Value) + .Where(x => x.Key == section || section.IsAssignableFrom(x.Key)) + .SelectMany(x => x.Value) + .Where(x => x.Key == scope) + .SelectMany(x => x.Value) + .OrderBy(x => x.Order) + .Select(x => x.FragmentContext)]; + } } /// @@ -242,7 +303,10 @@ public IEnumerable GetFragments(IApplicationContext applicatio /// True if the plugin context exists in the dictionary, otherwise false. public bool Contains(IPluginContext pluginContext) { - return _dict.ContainsKey(pluginContext); + lock (_lock) + { + return pluginContext is not null && _dict.ContainsKey(pluginContext); + } } /// @@ -253,7 +317,11 @@ public bool Contains(IPluginContext pluginContext) /// True if the plugin context and application context exist in the dictionary, otherwise false. public bool Contains(IPluginContext pluginContext, IApplicationContext applicationContext) { - return _dict.TryGetValue(pluginContext, out var appDict) && appDict.ContainsKey(applicationContext); + lock (_lock) + { + return pluginContext is not null && applicationContext is not null + && _dict.TryGetValue(pluginContext, out var appDict) && appDict.ContainsKey(applicationContext); + } } } } diff --git a/src/WebExpress.WebCore/WebFragment/Model/FragmentItem.cs b/src/WebExpress.WebCore/WebFragment/Model/FragmentItem.cs index d099e1f..6276d44 100644 --- a/src/WebExpress.WebCore/WebFragment/Model/FragmentItem.cs +++ b/src/WebExpress.WebCore/WebFragment/Model/FragmentItem.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; +using System.Threading; using WebExpress.WebCore.WebApplication; using WebExpress.WebCore.WebComponent; using WebExpress.WebCore.WebCondition; @@ -21,7 +22,11 @@ internal class FragmentItem : IDisposable private IFragmentBase _instance; private readonly IComponentHub _componentHub; private readonly IHttpServerContext _httpServerContext; - private static readonly ConcurrentDictionary _delegateCache = new(); + // one compiled call per fragment class, shared by all items and requests. It takes the + // instance as its first argument: a delegate that captured the instance of the first + // request rendered every later request on that foreign instance - its state leaked + // across requests and users, and concurrent requests rendered on it at the same time. + private static readonly ConcurrentDictionary> _delegateCache = new(); /// /// Gets or sets the context of the associated plugin. @@ -86,9 +91,12 @@ public FragmentItem(IComponentHub componentHub, IHttpServerContext httpServerCon public TFragment CreateInstance(IPageContext pageContext = null) where TFragment : IFragmentBase { - var instance = _instance; + if (Cache && _instance is not null) + { + return (TFragment)_instance; + } - instance ??= ComponentActivator.CreateInstance + var instance = ComponentActivator.CreateInstance ( FragmentClass, FragmentContext, @@ -100,7 +108,8 @@ public TFragment CreateInstance(IPageContext pageContext = null) if (Cache) { - _instance = instance; + // two requests may create an instance at once; both use the one that is kept + instance = Interlocked.CompareExchange(ref _instance, instance, null) ?? instance; } return (TFragment)instance; @@ -120,44 +129,51 @@ public IHtmlNode Render(TRenderContext renderContex { if (FragmentContext.Check(renderContext?.Request)) { - var instance = CreateInstance(); - - if (!_delegateCache.TryGetValue(FragmentClass, out var del)) - { - // create and compile the expression - var renderContextType = FragmentClass.GetInterface(typeof(IFragment<,>).Name).GetGenericArguments()[0]; - var visualTreeType = FragmentClass.GetInterface(typeof(IFragment<,>).Name).GetGenericArguments()[1]; - var renderContextParam = Expression.Parameter(renderContextType, "renderContext"); - var visualTreeParam = Expression.Parameter(visualTreeType, "visualTree"); - var renderMethod = FragmentClass.GetMethod("Render", [renderContextType, visualTreeType]); - var callProzessMethod = Expression.Call - ( - Expression.Constant(instance), - renderMethod, - renderContextParam, - visualTreeParam - ); - var lambda = Expression.Lambda(callProzessMethod, renderContextParam, visualTreeParam) - .Compile(); - - _delegateCache[FragmentClass] = lambda; - del = lambda; - } - - // execute the cached delegate - var html = del.DynamicInvoke(renderContext, visualTree) as IHtmlNode; - - return html; + var instance = CreateInstance(renderContext?.PageContext); + var render = _delegateCache.GetOrAdd(FragmentClass, CompileRender); + + return render(instance, renderContext, visualTree); } return null; } /// - /// Performs application-specific tasks related to sharing, returning, or resetting unmanaged resources. + /// Compiles the call of the fragment's render method with the instance, the render context + /// and the visual tree as arguments. + /// + /// The fragment class. + /// The compiled call. + private static Func CompileRender(Type fragmentClass) + { + var arguments = fragmentClass.GetInterface(typeof(IFragment<,>).Name).GetGenericArguments(); + var renderMethod = fragmentClass.GetMethod("Render", [arguments[0], arguments[1]]); + var instanceParam = Expression.Parameter(typeof(object), "instance"); + var renderContextParam = Expression.Parameter(typeof(object), "renderContext"); + var visualTreeParam = Expression.Parameter(typeof(object), "visualTree"); + var call = Expression.Call + ( + Expression.Convert(instanceParam, fragmentClass), + renderMethod, + Expression.Convert(renderContextParam, arguments[0]), + Expression.Convert(visualTreeParam, arguments[1]) + ); + + return Expression.Lambda> + ( + Expression.TypeAs(call, typeof(IHtmlNode)), + instanceParam, + renderContextParam, + visualTreeParam + ).Compile(); + } + + /// + /// Releases the instance kept for a cached fragment, so a removed plugin leaves none behind. /// public void Dispose() { + (Interlocked.Exchange(ref _instance, null) as IDisposable)?.Dispose(); } /// From b7d6e76ea7c69ca655dd026c0069d246f19b29be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Schwarzer?= Date: Tue, 24 Nov 2026 22:25:24 +0100 Subject: [PATCH 08/16] fix: lock the component registries and announce what they remove The package scan adds and removes plugins on its own thread while requests read the registries; plain dictionaries written during a read can throw or loop forever. Page, include, theme, application, event, job, task and identity registries now take every access under a lock and hand out copies, so handlers, renders and access checks run outside it. Removal was broken in several places: PageDictionary read the removed pages lazily after removing them (no Dispose, no RemovePage, so endpoint listeners kept dead pages), StatusPageManager dropped a plugin without announcing or disposing its pages, EventManager.Remove(plugin) raised no event, and an event handler without [Event] ended the registration of every handler after it (break instead of continue). The job scheduler ended for the whole process on the first exception in a minute's update; it now logs it and schedules the next minute. Tasks created concurrently threw on the second insert; ids now compare ordinally ignoring case (ConcurrentDictionary) instead of the culture-dependent ToLower, and the access check compares policy names ordinally instead of CurrentCultureIgnoreCase. Co-Authored-By: Claude Opus 5.5 --- .../Manager/UnitTestRegistryConcurrency.cs | 119 +++++++ .../Model/ApplicationDictionary.cs | 119 ++++--- .../WebEvent/EventManager.cs | 122 +++++-- .../WebIdentity/IdentityManager.cs | 199 +++++++----- .../WebInclude/IncludeManager.cs | 79 ++--- .../WebInclude/Model/IncludeDictionary.cs | 149 +++++++-- src/WebExpress.WebCore/WebJob/JobManager.cs | 151 ++++++--- .../WebPage/Model/PageDictionary.cs | 297 +++++++++++------- .../WebStatusPage/StatusPageManager.cs | 10 +- .../WebTask/Model/TaskDictionary.cs | 17 +- src/WebExpress.WebCore/WebTask/TaskManager.cs | 72 ++--- .../WebTheme/Model/ThemeItemDictionary.cs | 166 ++++++---- 12 files changed, 999 insertions(+), 501 deletions(-) create mode 100644 src/WebExpress.WebCore.Test/Manager/UnitTestRegistryConcurrency.cs diff --git a/src/WebExpress.WebCore.Test/Manager/UnitTestRegistryConcurrency.cs b/src/WebExpress.WebCore.Test/Manager/UnitTestRegistryConcurrency.cs new file mode 100644 index 0000000..dc7a2c7 --- /dev/null +++ b/src/WebExpress.WebCore.Test/Manager/UnitTestRegistryConcurrency.cs @@ -0,0 +1,119 @@ +using WebExpress.WebCore.Test.Fixture; +using WebExpress.WebCore.WebInclude; +using WebExpress.WebCore.WebPage; + +namespace WebExpress.WebCore.Test.Manager +{ + /// + /// Tests that the registries announce what they remove and stay consistent when requests use + /// them while they change. + /// + public class UnitTestRegistryConcurrency + { + /// + /// Verifies that removing a plugin announces each of its pages. The removed pages were read + /// after they had left the registry, so no page was disposed and no endpoint was told that + /// its page was gone. + /// + [Fact] + public void RemovingAPluginAnnouncesItsPages() + { + // arrange + var componentHub = UnitTestFixture.CreateAndRegisterComponentHubMock(); + var plugin = componentHub.PluginManager.GetPlugin(typeof(TestPlugin)); + var pageManager = componentHub.PageManager as PageManager; + var registered = componentHub.PageManager.Pages.Count(); + var removed = new List(); + pageManager.RemovePage += (sender, e) => removed.Add(e); + + // act + pageManager.Remove(plugin); + + // validation + Assert.True(registered > 0); + Assert.Equal(registered, removed.Count); + Assert.Empty(componentHub.PageManager.Pages); + } + + /// + /// Verifies that removing a plugin announces each of its includes and leaves none behind. + /// + [Fact] + public void RemovingAPluginAnnouncesItsIncludes() + { + // arrange + var componentHub = UnitTestFixture.CreateAndRegisterComponentHubMock(); + var plugin = componentHub.PluginManager.GetPlugin(typeof(TestPlugin)); + var includeManager = componentHub.IncludeManager as IncludeManager; + var registered = componentHub.IncludeManager.Includes.Count(); + var removed = new List(); + includeManager.RemoveInclude += (sender, e) => removed.Add(e); + + // act + includeManager.Remove(plugin); + + // validation + Assert.Equal(registered, removed.Count); + Assert.Empty(componentHub.IncludeManager.Includes); + } + + /// + /// Verifies that requests creating the same task at the same time get one task. The plain + /// dictionary threw on the second insert of an id, or was corrupted by concurrent writes. + /// + [Fact] + public void ConcurrentTaskCreationYieldsOneTask() + { + // arrange + var componentHub = UnitTestFixture.CreateAndRegisterComponentHubMock(); + var taskManager = componentHub.TaskManager; + + // act + var tasks = Enumerable.Range(0, 64) + .AsParallel() + .WithDegreeOfParallelism(16) + .Select(i => taskManager.CreateTask("Concurrent-" + (i % 4))) + .ToList(); + + // validation + Assert.Equal(4, tasks.Distinct().Count()); + Assert.Same(taskManager.GetTask("concurrent-1"), taskManager.GetTask("CONCURRENT-1")); + } + + /// + /// Verifies that reading the page registry while a plugin is removed and registered again + /// never throws. + /// + [Fact] + public void ReadingPagesWhilePluginsChange() + { + // arrange + var componentHub = UnitTestFixture.CreateAndRegisterComponentHubMock(); + var plugin = componentHub.PluginManager.GetPlugin(typeof(TestPlugin)); + var pageManager = componentHub.PageManager as PageManager; + using var stop = new CancellationTokenSource(TimeSpan.FromSeconds(2)); + var register = typeof(PageManager).GetMethod("Register", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance, [typeof(WebExpress.WebCore.WebPlugin.IPluginContext)]); + + // act + var reader = Task.Run(() => + { + while (!stop.IsCancellationRequested) + { + _ = componentHub.PageManager.Pages.Count(); + } + }); + + for (var i = 0; i < 50; i++) + { + pageManager.Remove(plugin); + register.Invoke(pageManager, [plugin]); + } + + stop.Cancel(); + + // validation + reader.Wait(); + Assert.True(reader.IsCompletedSuccessfully); + } + } +} diff --git a/src/WebExpress.WebCore/WebApplication/Model/ApplicationDictionary.cs b/src/WebExpress.WebCore/WebApplication/Model/ApplicationDictionary.cs index cc1377c..42f575b 100644 --- a/src/WebExpress.WebCore/WebApplication/Model/ApplicationDictionary.cs +++ b/src/WebExpress.WebCore/WebApplication/Model/ApplicationDictionary.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading; using WebExpress.WebCore.WebPlugin; namespace WebExpress.WebCore.WebApplication.Model @@ -8,16 +9,30 @@ namespace WebExpress.WebCore.WebApplication.Model /// /// Represents a dictionary that maps plugin contexts to application items. /// + /// + /// The package scan adds and removes applications on its own thread while requests resolve + /// them, and a dictionary written during a read can throw or loop forever. Every member + /// therefore runs under one lock and returns a list taken under it. Application ids compare + /// ordinally ignoring case, which does not depend on the culture of the calling thread. + /// internal class ApplicationDictionary { private readonly Dictionary> _dict = []; + private readonly Lock _lock = new(); /// /// Gets all application contexts from the dictionary. /// - public IEnumerable All => _dict - .Values.SelectMany(x => x.Values) - .Select(x => x.ApplicationContext); + public IEnumerable All + { + get + { + lock (_lock) + { + return [.. _dict.Values.SelectMany(x => x.Values).Select(x => x.ApplicationContext)]; + } + } + } /// /// Adds an application item to the dictionary. @@ -27,18 +42,16 @@ internal class ApplicationDictionary /// True if the application item was added successfully, false if an element with the same key already exists. public bool AddApplication(IPluginContext pluginContext, ApplicationItem applicationItem) { - if (!_dict.TryGetValue(pluginContext, out var applicationDict)) + lock (_lock) { - applicationDict = []; - _dict[pluginContext] = applicationDict; - } + if (!_dict.TryGetValue(pluginContext, out var applicationDict)) + { + applicationDict = new Dictionary(StringComparer.OrdinalIgnoreCase); + _dict[pluginContext] = applicationDict; + } - if (applicationDict.TryAdd(applicationItem.ApplicationContext.ApplicationId, applicationItem)) - { - return true; + return applicationDict.TryAdd(applicationItem.ApplicationContext.ApplicationId, applicationItem); } - - return false; } /// @@ -48,12 +61,12 @@ public bool AddApplication(IPluginContext pluginContext, ApplicationItem applica /// The items of the removed applications, so the caller can raise removal events and release the instances. public IEnumerable RemoveApplications(IPluginContext pluginContext) { - // removal events need the contexts after the registry entry has been deleted - var applicationItems = GetApplicationItems(pluginContext).ToArray(); - - _dict.Remove(pluginContext); - - return applicationItems; + lock (_lock) + { + return pluginContext is not null && _dict.Remove(pluginContext, out var applicationDict) + ? [.. applicationDict.Values] + : []; + } } /// @@ -68,9 +81,12 @@ public ApplicationItem GetApplicationItem(IApplicationContext applicationContext return null; } - return _dict - .Values.SelectMany(x => x.Values) - .FirstOrDefault(x => x.ApplicationContext == applicationContext); + lock (_lock) + { + return _dict + .Values.SelectMany(x => x.Values) + .FirstOrDefault(x => x.ApplicationContext == applicationContext); + } } /// @@ -80,13 +96,15 @@ public ApplicationItem GetApplicationItem(IApplicationContext applicationContext /// An IEnumerable of application contexts associated with the given plugin context. public IEnumerable GetApplicationItems(IPluginContext pluginContext) { - var applicationItems = _dict - .Where(x => x.Key == pluginContext) - .Select(x => x.Value) - .Select(x => x.Values) - .SelectMany(x => x); + if (pluginContext is null) + { + return []; + } - return applicationItems; + lock (_lock) + { + return _dict.TryGetValue(pluginContext, out var applicationDict) ? [.. applicationDict.Values] : []; + } } /// @@ -96,10 +114,7 @@ public IEnumerable GetApplicationItems(IPluginContext pluginCon /// An IEnumerable of application contexts associated with the given plugin context. public IEnumerable GetApplications(IPluginContext pluginContext) { - var applicationContexts = GetApplicationItems(pluginContext) - .Select(x => x.ApplicationContext); - - return applicationContexts; + return [.. GetApplicationItems(pluginContext).Select(x => x.ApplicationContext)]; } /// @@ -109,14 +124,23 @@ public IEnumerable GetApplications(IPluginContext pluginCon /// The context of the application or null if the application id is null, empty, or not found. public IApplicationContext GetApplication(string applicationId) { - if (string.IsNullOrWhiteSpace(applicationId)) return null; + if (string.IsNullOrWhiteSpace(applicationId)) + { + return null; + } - var items = _dict.Values - .Where(x => x.ContainsKey(applicationId.ToLower())) - .Select(x => x[applicationId.ToLower()]) - .FirstOrDefault(); + lock (_lock) + { + foreach (var applicationDict in _dict.Values) + { + if (applicationDict.TryGetValue(applicationId, out var item)) + { + return item.ApplicationContext; + } + } - return items?.ApplicationContext; + return null; + } } /// @@ -126,13 +150,17 @@ public IApplicationContext GetApplication(string applicationId) /// The contexts of the applications as an enumeration. public IEnumerable GetApplications(Type application) { - if (application is null) return []; - - var items = _dict.Values.SelectMany(x => x.Values) - .Where(x => x.ApplicationClass.Equals(application) || application.IsAssignableFrom(x.ApplicationClass)) - .Select(x => x.ApplicationContext); + if (application is null) + { + return []; + } - return items; + lock (_lock) + { + return [.. _dict.Values.SelectMany(x => x.Values) + .Where(x => x.ApplicationClass.Equals(application) || application.IsAssignableFrom(x.ApplicationClass)) + .Select(x => x.ApplicationContext)]; + } } /// @@ -142,7 +170,10 @@ public IEnumerable GetApplications(Type application) /// True if the plugin context exists in the dictionary, otherwise false. public bool Contains(IPluginContext pluginContext) { - return _dict.ContainsKey(pluginContext); + lock (_lock) + { + return pluginContext is not null && _dict.ContainsKey(pluginContext); + } } } } diff --git a/src/WebExpress.WebCore/WebEvent/EventManager.cs b/src/WebExpress.WebCore/WebEvent/EventManager.cs index 3298a75..fb5fc81 100644 --- a/src/WebExpress.WebCore/WebEvent/EventManager.cs +++ b/src/WebExpress.WebCore/WebEvent/EventManager.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; +using System.Threading; using WebExpress.WebCore.Internationalization; using WebExpress.WebCore.WebApplication; using WebExpress.WebCore.WebAttribute; @@ -23,6 +24,11 @@ public sealed class EventManager : IEventManager, ISystemComponent private readonly IHttpServerContext _httpServerContext; private readonly EventDictionary _dictionary = []; + // the package scan registers and removes handlers on its own thread while requests raise + // events; every access to the dictionary is taken under this lock and every result is a + // copy, so a handler runs outside it + private readonly Lock _lock = new(); + /// /// An event that fires when an event handler is added. /// @@ -36,11 +42,20 @@ public sealed class EventManager : IEventManager, ISystemComponent /// /// Gets the collection of events. /// - public IEnumerable EventHandlers => _dictionary.Values - .SelectMany(x => x.Values) - .SelectMany(x => x.Values) - .SelectMany(x => x) - .Select(x => x.EventHandlerContext); + public IEnumerable EventHandlers + { + get + { + lock (_lock) + { + return [.. _dictionary.Values + .SelectMany(x => x.Values) + .SelectMany(x => x.Values) + .SelectMany(x => x) + .Select(x => x.EventHandlerContext)]; + } + } + } /// /// Initializes a new instance of the class. @@ -77,8 +92,7 @@ private EventManager(IComponentHub componentHub, IHttpServerContext httpServerCo public IEnumerable GetEventHandlers(IApplicationContext applicationContext) where TEvent : IEvent { - return _dictionary.GetEventHandlerItems(applicationContext) - .Select(x => x.EventHandlerContext); + return GetEventHandlers(applicationContext, typeof(TEvent)); } /// @@ -89,8 +103,11 @@ public IEnumerable GetEventHandlers(IApplicationCo /// An IEnumerable of event handler contexts. public IEnumerable GetEventHandlers(IApplicationContext applicationContext, Type eventType) { - return _dictionary.GetEventHandlerItems(applicationContext, eventType) - .Select(x => x.EventHandlerContext); + lock (_lock) + { + return [.. _dictionary.GetEventHandlerItems(applicationContext, eventType) + .Select(x => x.EventHandlerContext)]; + } } /// @@ -103,7 +120,12 @@ public IEnumerable GetEventHandlers(IApplicationContext ap public void RaiseEvent(IApplicationContext applicationContext, object sender, IEventArgument argument) where TEvent : IEvent { - var eventHandlers = _dictionary.GetEventHandlerItems(applicationContext); + List eventHandlers; + + lock (_lock) + { + eventHandlers = [.. _dictionary.GetEventHandlerItems(applicationContext)]; + } foreach (var eventHandler in eventHandlers) { @@ -117,9 +139,12 @@ public void RaiseEvent(IApplicationContext applicationContext, object se /// The context of the plugin whose jobs are to be associated. private void Register(IPluginContext pluginContext) { - if (_dictionary.ContainsKey(pluginContext)) + lock (_lock) { - return; + if (pluginContext is null || _dictionary.ContainsKey(pluginContext)) + { + return; + } } Register(pluginContext, _componentHub.GetBoundApplications(pluginContext)); @@ -133,7 +158,14 @@ private void Register(IApplicationContext applicationContext) { foreach (var pluginContext in _componentHub?.PluginManager?.GetPlugins(applicationContext)) { - if (_dictionary.TryGetValue(pluginContext, out var appDict) && appDict.ContainsKey(applicationContext)) + bool known; + + lock (_lock) + { + known = _dictionary.TryGetValue(pluginContext, out var appDict) && appDict.ContainsKey(applicationContext); + } + + if (known) { continue; } @@ -185,7 +217,8 @@ private void Register(IPluginContext pluginContext, IEnumerableThe context of the plugin that contains the events to remove. internal void Remove(IPluginContext pluginContext) { - // the plugin has not been registered in the manager - if (_dictionary.TryGetValue(pluginContext, out var value)) + if (pluginContext is null) { - foreach (var eventHandlerItem in value - .SelectMany(x => x.Value) - .SelectMany(x => x.Value)) + return; + } + + List removed; + + lock (_lock) + { + // the plugin has not been registered in the manager + if (!_dictionary.Remove(pluginContext, out var value)) { - eventHandlerItem.Dispose(); + return; } - _dictionary.Remove(pluginContext); + removed = [.. value.Values.SelectMany(x => x.Values).SelectMany(x => x)]; + } + + foreach (var eventHandlerItem in removed) + { + OnRemoveEventHandler(eventHandlerItem.EventHandlerContext); + eventHandlerItem.Dispose(); } } @@ -267,18 +318,23 @@ internal void Remove(IApplicationContext applicationContext) return; } - foreach (var pluginDict in _dictionary.Values) + var removed = new List(); + + lock (_lock) { - foreach (var appDict in pluginDict.Where(x => x.Key == applicationContext).Select(x => x.Value)) + foreach (var pluginDict in _dictionary.Values) { - foreach (var eventHandlerItem in appDict.Values.SelectMany(x => x)) + if (pluginDict.Remove(applicationContext, out var appDict)) { - OnRemoveEventHandler(eventHandlerItem.EventHandlerContext); - eventHandlerItem.Dispose(); + removed.AddRange(appDict.Values.SelectMany(x => x)); } } + } - pluginDict.Remove(applicationContext); + foreach (var eventHandlerItem in removed) + { + OnRemoveEventHandler(eventHandlerItem.EventHandlerContext); + eventHandlerItem.Dispose(); } } diff --git a/src/WebExpress.WebCore/WebIdentity/IdentityManager.cs b/src/WebExpress.WebCore/WebIdentity/IdentityManager.cs index 8001a63..4818ac8 100644 --- a/src/WebExpress.WebCore/WebIdentity/IdentityManager.cs +++ b/src/WebExpress.WebCore/WebIdentity/IdentityManager.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; +using System.Threading; using WebExpress.WebCore.Internationalization; using WebExpress.WebCore.WebApplication; using WebExpress.WebCore.WebAttribute; @@ -25,21 +26,44 @@ public partial class IdentityManager : IIdentityManager private readonly IdentityPermissionDictionary _permissionDictionary = []; private readonly IdentityPolicyDictionary _policyDictionary = []; + // the package scan registers and removes policies on its own thread while every request + // checks access against them; a dictionary written during that read can throw or loop + // forever, so both dictionaries are only touched under this lock + private readonly Lock _lock = new(); + /// /// Gets all permissions. /// - public IEnumerable Permissions => _permissionDictionary.Values - .SelectMany(x => x.Values) - .SelectMany(x => x) - .Select(x => x.PermissionContext); + public IEnumerable Permissions + { + get + { + lock (_lock) + { + return [.. _permissionDictionary.Values + .SelectMany(x => x.Values) + .SelectMany(x => x) + .Select(x => x.PermissionContext)]; + } + } + } /// /// Gets all policies. /// - public IEnumerable Policies => _policyDictionary.Values - .SelectMany(x => x.Values) - .SelectMany(x => x) - .Select(x => x.PolicyContext); + public IEnumerable Policies + { + get + { + lock (_lock) + { + return [.. _policyDictionary.Values + .SelectMany(x => x.Values) + .SelectMany(x => x) + .Select(x => x.PolicyContext)]; + } + } + } /// /// Initializes a new instance of the class. @@ -73,9 +97,12 @@ private IdentityManager(IComponentHub componentHub, IHttpServerContext httpServe /// The context of the plugin whose jobs are to be associated. private void Register(IPluginContext pluginContext) { - if (_permissionDictionary.ContainsKey(pluginContext)) + lock (_lock) { - return; + if (pluginContext is null || _permissionDictionary.ContainsKey(pluginContext)) + { + return; + } } Register(pluginContext, _componentHub.GetBoundApplications(pluginContext)); @@ -89,7 +116,14 @@ private void Register(IApplicationContext applicationContext) { foreach (var pluginContext in _componentHub?.PluginManager?.GetPlugins(applicationContext)) { - if (_permissionDictionary.TryGetValue(pluginContext, out var appDict) && appDict.ContainsKey(applicationContext)) + bool known; + + lock (_lock) + { + known = _permissionDictionary.TryGetValue(pluginContext, out var appDict) && appDict.ContainsKey(applicationContext); + } + + if (known) { continue; } @@ -151,12 +185,19 @@ private void Register(IPluginContext pluginContext, IEnumerableThe context of the plugin that contains the identities to remove. internal void Remove(IPluginContext pluginContext) { - // remove permissions - if (_permissionDictionary.TryGetValue(pluginContext, out var permissionValue)) + if (pluginContext is null) { - foreach (var permissionItem in permissionValue.SelectMany(x => x.Value)) - { - permissionItem.Dispose(); - } - - _permissionDictionary.Remove(pluginContext); + return; } - // remove policies - if (_policyDictionary.TryGetValue(pluginContext, out var policyValue)) + var removed = new List(); + + lock (_lock) { - foreach (var permissionItem in policyValue.SelectMany(x => x.Value)) + if (_permissionDictionary.Remove(pluginContext, out var permissionValue)) { - permissionItem.Dispose(); + removed.AddRange(permissionValue.SelectMany(x => x.Value).Select(item => (Action)item.Dispose)); } - _policyDictionary.Remove(pluginContext); + if (_policyDictionary.Remove(pluginContext, out var policyValue)) + { + removed.AddRange(policyValue.SelectMany(x => x.Value).Select(item => (Action)item.Dispose)); + } + } + + foreach (var dispose in removed) + { + dispose(); } } @@ -298,32 +349,30 @@ internal void Remove(IApplicationContext applicationContext) return; } - // remove permissions - foreach (var pluginDict in _permissionDictionary.Values) + var removed = new List(); + + lock (_lock) { - foreach (var appDict in pluginDict.Where(x => x.Key == applicationContext).Select(x => x.Value)) + foreach (var pluginDict in _permissionDictionary.Values) { - foreach (var permissionItem in appDict) + if (pluginDict.Remove(applicationContext, out var appDict)) { - permissionItem.Dispose(); + removed.AddRange(appDict.Select(item => (Action)item.Dispose)); } } - pluginDict.Remove(applicationContext); - } - - // remove policies - foreach (var pluginDict in _policyDictionary.Values) - { - foreach (var appDict in pluginDict.Where(x => x.Key == applicationContext).Select(x => x.Value)) + foreach (var pluginDict in _policyDictionary.Values) { - foreach (var policyItem in appDict) + if (pluginDict.Remove(applicationContext, out var appDict)) { - policyItem.Dispose(); + removed.AddRange(appDict.Select(item => (Action)item.Dispose)); } } + } - pluginDict.Remove(applicationContext); + foreach (var dispose in removed) + { + dispose(); } } @@ -557,7 +606,7 @@ public bool CheckAccess(IApplicationContext applicationContext) where R : /// True if the identity policy has the permission, false otherwise. public bool CheckAccess(IApplicationContext applicationContext, Type policyType, Type permissionType) { - return CheckAccess(applicationContext, policyType.FullName.ToLower(), permissionType); + return CheckAccess(applicationContext, policyType.FullName, permissionType); } /// @@ -569,33 +618,33 @@ public bool CheckAccess(IApplicationContext applicationContext, Type policyType, /// True if the identity policy has the permission, false otherwise. private bool CheckAccess(IApplicationContext applicationContext, string policyName, Type permissionType) { - // verify policies to permissions - var policies = _policyDictionary.Values - .SelectMany(x => x) - .Where(x => x.Key == applicationContext) - .SelectMany(entry => entry.Value); - - if (policies.Any(policy => - policy.PolicyClass.FullName.Equals(policyName, StringComparison.CurrentCultureIgnoreCase) && - policy.Permissions.Contains(permissionType))) + // a policy name is an identifier, so it compares ordinally: a culture-aware comparison + // let the same name match or not depending on the culture of the request thread + lock (_lock) { - return true; - } + // verify policies to permissions + var policies = _policyDictionary.Values + .SelectMany(x => x) + .Where(x => x.Key == applicationContext) + .SelectMany(entry => entry.Value); + + if (policies.Any(policy => + policy.PolicyClass.FullName.Equals(policyName, StringComparison.OrdinalIgnoreCase) && + policy.Permissions.Contains(permissionType))) + { + return true; + } - // verify permissions to policies - var permissions = _permissionDictionary.Values - .SelectMany(x => x) - .Where(x => x.Key == applicationContext) - .SelectMany(entry => entry.Value); + // verify permissions to policies + var permissions = _permissionDictionary.Values + .SelectMany(x => x) + .Where(x => x.Key == applicationContext) + .SelectMany(entry => entry.Value); - if (permissions.Any(permission => - permission.PermissionClass == permissionType && - permission.Policies.Any(x => x.FullName.Equals(policyName, StringComparison.CurrentCultureIgnoreCase)))) - { - return true; + return permissions.Any(permission => + permission.PermissionClass == permissionType && + permission.Policies.Any(x => x.FullName.Equals(policyName, StringComparison.OrdinalIgnoreCase))); } - - return false; } /// diff --git a/src/WebExpress.WebCore/WebInclude/IncludeManager.cs b/src/WebExpress.WebCore/WebInclude/IncludeManager.cs index 9d21f90..a517a4f 100644 --- a/src/WebExpress.WebCore/WebInclude/IncludeManager.cs +++ b/src/WebExpress.WebCore/WebInclude/IncludeManager.cs @@ -20,7 +20,7 @@ public sealed class IncludeManager : IIncludeManager, ISystemComponent, IDisposa { private readonly IComponentHub _componentHub; private readonly IHttpServerContext _httpServerContext; - private readonly IncludeDictionary _dictionary = []; + private readonly IncludeDictionary _dictionary = new(); /// /// An event that fires when an include is added. @@ -35,10 +35,7 @@ public sealed class IncludeManager : IIncludeManager, ISystemComponent, IDisposa /// /// Gets all include contexts. /// - public IEnumerable Includes => _dictionary.Values - .SelectMany(x => x.Values) - .SelectMany(x => x.Values) - .Select(x => x.IncludeContext); + public IEnumerable Includes => [.. _dictionary.All.Select(x => x.IncludeContext)]; /// /// Initializes a new instance of the include manager. @@ -73,7 +70,7 @@ private void Register(IPluginContext pluginContext) return; } - if (_dictionary.ContainsKey(pluginContext)) + if (_dictionary.Contains(pluginContext)) { return; } @@ -94,7 +91,7 @@ private void Register(IApplicationContext applicationContext) foreach (var pluginContext in _componentHub?.PluginManager?.GetPlugins(applicationContext)) { - if (_dictionary.TryGetValue(pluginContext, out var appDict) && appDict.ContainsKey(applicationContext)) + if (_dictionary.Contains(pluginContext, applicationContext)) { continue; } @@ -274,24 +271,19 @@ internal void Remove(IPluginContext pluginContext) return; } - if (_dictionary.TryGetValue(pluginContext, out var value)) + // removed first and announced afterwards, outside the registry's lock + foreach (var includeItem in _dictionary.Remove(pluginContext)) { - foreach (var includeItem in value.Values.SelectMany(x => x.Values)) - { - OnRemoveInclude(includeItem.IncludeContext); - - _httpServerContext?.Log?.Debug( - I18N.Translate( - "webexpress.webcore:includemanager.removeinclude", - includeItem.IncludeId, - includeItem.ApplicationContext.ApplicationId - ) - ); + OnRemoveInclude(includeItem.IncludeContext); + includeItem.Dispose(); - includeItem.Dispose(); - } - - _dictionary.Remove(pluginContext); + _httpServerContext?.Log?.Debug( + I18N.Translate( + "webexpress.webcore:includemanager.removeinclude", + includeItem.IncludeId, + includeItem.ApplicationContext.ApplicationId + ) + ); } } @@ -306,26 +298,18 @@ internal void Remove(IApplicationContext applicationContext) return; } - foreach (var pluginDict in _dictionary.Values) + foreach (var includeItem in _dictionary.Remove(applicationContext)) { - foreach (var appDict in pluginDict.Where(x => x.Key == applicationContext).Select(x => x.Value)) - { - foreach (var includeItem in appDict.Values) - { - OnRemoveInclude(includeItem.IncludeContext); - includeItem.Dispose(); + OnRemoveInclude(includeItem.IncludeContext); + includeItem.Dispose(); - _httpServerContext?.Log?.Debug( - I18N.Translate( - "webexpress.webcore:includemanager.removeinclude", - includeItem.IncludeId, - includeItem.ApplicationContext.ApplicationId - ) - ); - } - } - - pluginDict.Remove(applicationContext); + _httpServerContext?.Log?.Debug( + I18N.Translate( + "webexpress.webcore:includemanager.removeinclude", + includeItem.IncludeId, + includeItem.ApplicationContext.ApplicationId + ) + ); } } @@ -341,11 +325,7 @@ public IEnumerable GetIncludes(IApplicationContext applicationC return []; } - return _dictionary.Values - .SelectMany(x => x.Values) - .SelectMany(x => x.Values) - .Where(x => x.IncludeContext.ApplicationContext.Equals(applicationContext)) - .Select(x => x.IncludeContext); + return [.. _dictionary.GetItems(applicationContext).Select(x => x.IncludeContext)]; } /// @@ -361,12 +341,7 @@ public IEnumerable GetIncludes(IApplicationContext applicationC return []; } - return _dictionary.Values - .SelectMany(x => x.Values) - .SelectMany(x => x.Values) - .Where(x => x.IncludeClass.Equals(includeType)) - .Where(x => x.IncludeContext.ApplicationContext.Equals(applicationContext)) - .Select(x => x.IncludeContext); + return [.. _dictionary.GetItems(applicationContext, includeType).Select(x => x.IncludeContext)]; } /// diff --git a/src/WebExpress.WebCore/WebInclude/Model/IncludeDictionary.cs b/src/WebExpress.WebCore/WebInclude/Model/IncludeDictionary.cs index b6464ec..1245f86 100644 --- a/src/WebExpress.WebCore/WebInclude/Model/IncludeDictionary.cs +++ b/src/WebExpress.WebCore/WebInclude/Model/IncludeDictionary.cs @@ -1,22 +1,47 @@ using System; using System.Collections.Generic; +using System.Linq; +using System.Threading; using WebExpress.WebCore.WebApplication; using WebExpress.WebCore.WebPlugin; namespace WebExpress.WebCore.WebInclude.Model { /// - /// Nested dictionary for includes: Plugin -> Application -> Id -> IncludeItem + /// Represents the includes by plugin and application. + /// Plugin -> Application -> include id -> IncludeItem /// - internal sealed class IncludeDictionary : Dictionary>> + /// + /// The package scan adds and removes includes on its own thread while every page render + /// reads them, and a dictionary written during a read can throw or loop forever. Every member + /// therefore runs under one lock and returns a list taken under it. + /// + internal sealed class IncludeDictionary { + private readonly Dictionary>> _dict = []; + private readonly Lock _lock = new(); + /// - /// Adds an item to the internal collection for the specified plugin and application contexts. + /// Gets all include items. /// - /// The plugin context associated with the item. Cannot be null. - /// The application context associated with the item. Cannot be null. - /// The item to add. Cannot be null. - /// True if the item was successfully added; otherwise, false if an item with the same key already exists in the collection. + public IReadOnlyList All + { + get + { + lock (_lock) + { + return [.. _dict.Values.SelectMany(x => x.Values).SelectMany(x => x.Values)]; + } + } + } + + /// + /// Adds an include item. + /// + /// The plugin context. + /// The application context. + /// The include item. + /// True if the item was added, false if it was invalid or already present. public bool AddIncludeItem(IPluginContext pluginContext, IApplicationContext applicationContext, IncludeItem includeItem) { if (pluginContext is null || applicationContext is null || includeItem is null) @@ -24,27 +49,115 @@ public bool AddIncludeItem(IPluginContext pluginContext, IApplicationContext app return false; } - if (!TryGetValue(pluginContext, out var appDict)) + var key = includeItem.IncludeId?.ToString() ?? includeItem.IncludeClass?.FullName?.ToLowerInvariant() ?? Guid.NewGuid().ToString("N"); + + lock (_lock) + { + if (!_dict.TryGetValue(pluginContext, out var appDict)) + { + appDict = []; + _dict.Add(pluginContext, appDict); + } + + if (!appDict.TryGetValue(applicationContext, out var includeMap)) + { + includeMap = new Dictionary(StringComparer.OrdinalIgnoreCase); + appDict.Add(applicationContext, includeMap); + } + + return includeMap.TryAdd(key, includeItem); + } + } + + /// + /// Checks whether includes of the plugin are registered. + /// + /// The plugin context. + /// True if the plugin is known. + public bool Contains(IPluginContext pluginContext) + { + lock (_lock) + { + return pluginContext is not null && _dict.ContainsKey(pluginContext); + } + } + + /// + /// Checks whether includes of the plugin are registered for the application. + /// + /// The plugin context. + /// The application context. + /// True if the pair is known. + public bool Contains(IPluginContext pluginContext, IApplicationContext applicationContext) + { + lock (_lock) { - appDict = []; - Add(pluginContext, appDict); + return pluginContext is not null && applicationContext is not null + && _dict.TryGetValue(pluginContext, out var appDict) && appDict.ContainsKey(applicationContext); } + } - if (!appDict.TryGetValue(applicationContext, out var includeMap)) + /// + /// Removes the includes of a plugin. + /// + /// The plugin context. + /// The removed items. + public IReadOnlyList Remove(IPluginContext pluginContext) + { + lock (_lock) { - includeMap = new Dictionary(StringComparer.OrdinalIgnoreCase); - appDict.Add(applicationContext, includeMap); + return pluginContext is not null && _dict.Remove(pluginContext, out var appDict) + ? [.. appDict.Values.SelectMany(x => x.Values)] + : []; } + } - var key = includeItem.IncludeId?.ToString() ?? includeItem.IncludeClass?.FullName?.ToLower() ?? Guid.NewGuid().ToString("N"); + /// + /// Removes the includes of an application, together with a plugin entry left empty. + /// + /// The application context. + /// The removed items. + public IReadOnlyList Remove(IApplicationContext applicationContext) + { + var removed = new List(); - if (!includeMap.ContainsKey(key)) + lock (_lock) { - includeMap[key] = includeItem; - return true; + foreach (var (pluginContext, appDict) in _dict.ToList()) + { + if (!appDict.Remove(applicationContext, out var includeMap)) + { + continue; + } + + if (appDict.Count == 0) + { + _dict.Remove(pluginContext); + } + + removed.AddRange(includeMap.Values); + } } - return false; + return removed; + } + + /// + /// Returns the include items of an application, optionally of one include class. + /// + /// The application context. + /// The include class, or null for all. + /// The include items. + public IReadOnlyList GetItems(IApplicationContext applicationContext, Type includeType = null) + { + lock (_lock) + { + return [.. _dict.Values + .SelectMany(x => x.Values) + .SelectMany(x => x.Values) + .Where(x => includeType is null || x.IncludeClass.Equals(includeType)) + .Where(x => x.IncludeContext.ApplicationContext.Equals(applicationContext))]; + } } } } diff --git a/src/WebExpress.WebCore/WebJob/JobManager.cs b/src/WebExpress.WebCore/WebJob/JobManager.cs index 15618c2..d2b4294 100644 --- a/src/WebExpress.WebCore/WebJob/JobManager.cs +++ b/src/WebExpress.WebCore/WebJob/JobManager.cs @@ -37,6 +37,12 @@ public sealed class JobManager : IJobManager, ISystemComponent, IExecutableEleme private readonly IHttpServerContext _httpServerContext; private readonly ScheduleDictionary _staticScheduleDictionary = []; private readonly List _dynamicScheduleList = []; + + // the package scan registers and removes jobs on its own thread while the scheduler walks + // them every minute; a collection changed during that walk threw out of the loop and + // ended the scheduling of the whole process. every access is taken under this lock and + // the scheduler works on a copy. + private readonly Lock _lock = new(); private readonly CancellationTokenSource _tokenSource = new(); private readonly Clock _clock = new(); @@ -53,12 +59,7 @@ public sealed class JobManager : IJobManager, ISystemComponent, IExecutableEleme /// /// Gets all job contextes. /// - public IEnumerable Jobs => _staticScheduleDictionary - .SelectMany(x => x.Value) - .SelectMany(x => x.Value) - .SelectMany(x => x.Value) - .Select(x => x.JobContext) - .Union(_dynamicScheduleList.Select(x => x.JobContext)); + public IEnumerable Jobs => [.. Snapshot().Select(x => x.JobContext)]; /// /// Initializes a new instance of the class. @@ -91,9 +92,12 @@ private JobManager(IComponentHub componentHub, IHttpServerContext httpServerCont /// The context of the plugin whose jobs are to be associated. private void Register(IPluginContext pluginContext) { - if (_staticScheduleDictionary.ContainsKey(pluginContext)) + lock (_lock) { - return; + if (pluginContext is null || _staticScheduleDictionary.ContainsKey(pluginContext)) + { + return; + } } Register(pluginContext, _componentHub.GetBoundApplications(pluginContext)); @@ -107,7 +111,14 @@ private void Register(IApplicationContext applicationContext) { foreach (var pluginContext in _componentHub?.PluginManager?.GetPlugins(applicationContext)) { - if (_staticScheduleDictionary.TryGetValue(pluginContext, out var appDict) && appDict.ContainsKey(applicationContext)) + bool known; + + lock (_lock) + { + known = _staticScheduleDictionary.TryGetValue(pluginContext, out var appDict) && appDict.ContainsKey(applicationContext); + } + + if (known) { continue; } @@ -186,12 +197,19 @@ private void Register(IPluginContext pluginContext, IEnumerable x.Values) - .SelectMany(x => x) - .ToList(); - - _staticScheduleDictionary.Remove(pluginContext); + List scheduleItems; - foreach (var scheduleItem in scheduleItems) + lock (_lock) + { + // the plugin has not been registered in the manager + if (!_staticScheduleDictionary.Remove(pluginContext, out var value)) { - OnRemoveJob(scheduleItem.JobContext); - Release(scheduleItem); + return; } + + scheduleItems = [.. value.Values + .SelectMany(x => x.Values) + .SelectMany(x => x)]; + } + + foreach (var scheduleItem in scheduleItems) + { + OnRemoveJob(scheduleItem.JobContext); + Release(scheduleItem); } } @@ -275,11 +297,14 @@ internal void Remove(IApplicationContext applicationContext) var scheduleItems = new List(); - foreach (var pluginDict in _staticScheduleDictionary.Values) + lock (_lock) { - if (pluginDict.Remove(applicationContext, out var appDict)) + foreach (var pluginDict in _staticScheduleDictionary.Values) { - scheduleItems.AddRange(appDict.Values.SelectMany(x => x)); + if (pluginDict.Remove(applicationContext, out var appDict)) + { + scheduleItems.AddRange(appDict.Values.SelectMany(x => x)); + } } } @@ -296,11 +321,14 @@ internal void Remove(IApplicationContext applicationContext) /// The job to remove. public void Remove(IJob job) { - var scheduleItems = _dynamicScheduleList - .Where(x => x.Instance == job) - .ToList(); + List scheduleItems; - _dynamicScheduleList.RemoveAll(scheduleItems.Contains); + lock (_lock) + { + scheduleItems = [.. _dynamicScheduleList.Where(x => x.Instance == job)]; + + _dynamicScheduleList.RemoveAll(scheduleItems.Contains); + } foreach (var scheduleItem in scheduleItems) { @@ -395,7 +423,17 @@ internal void Execute() using var linked = CancellationTokenSource.CreateLinkedTokenSource(stopping, _tokenSource.Token); while (!linked.IsCancellationRequested) { - Update(); + // one failing minute - a broken cron expression, an unreachable cluster store - + // is logged and the next minute is scheduled; an exception leaving the loop + // ended the scheduling of every job of the process without a trace + try + { + Update(); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _httpServerContext?.Log?.Exception(ex); + } var secondsLeft = 60 - DateTime.Now.Second; await Task.Delay(TimeSpan.FromSeconds(secondsLeft), linked.Token).ConfigureAwait(false); @@ -411,11 +449,7 @@ private void Update() { foreach (var clock in _clock.Synchronize()) { - foreach (var scheduleItemValue in _staticScheduleDictionary - .SelectMany(x => x.Value) - .SelectMany(x => x.Value) - .SelectMany(x => x.Value) - .Union(_dynamicScheduleList.Select(x => x))) + foreach (var scheduleItemValue in Snapshot()) { if (scheduleItemValue.JobContext.Cron.Matching(_clock) && Claim(scheduleItemValue.JobContext, _clock)) { @@ -495,14 +529,27 @@ internal bool Claim(IJobContext jobContext, Clock clock) /// A JobContext instance. public IJobContext GetJob(IApplicationContext applicationContext, Type jobType) { - return _staticScheduleDictionary - .SelectMany(x => x.Value) - .SelectMany(x => x.Value) - .SelectMany(x => x.Value) - .Union(_dynamicScheduleList.Select(x => x)) + return Snapshot() .FirstOrDefault(x => x.JobContext.ApplicationContext == applicationContext && x.JobClass == jobType)?.JobContext; } + /// + /// Copies the scheduled items under the lock, so the scheduler and the callers walk a list + /// that no registration can change underneath them. + /// + /// The static and dynamic schedule items. + private List Snapshot() + { + lock (_lock) + { + return [.. _staticScheduleDictionary + .SelectMany(x => x.Value) + .SelectMany(x => x.Value) + .SelectMany(x => x.Value) + .Union(_dynamicScheduleList)]; + } + } + /// /// Release of unmanaged resources reserved during use. /// @@ -515,14 +562,18 @@ public void Dispose() _tokenSource.Cancel(); - foreach (var item in _staticScheduleDictionary.Values.SelectMany(x => x.Values) - .SelectMany(x => x.Values).SelectMany(x => x).Concat(_dynamicScheduleList).Distinct()) + var items = Snapshot(); + + lock (_lock) { - Release(item); + _staticScheduleDictionary.Clear(); + _dynamicScheduleList.Clear(); } - _staticScheduleDictionary.Clear(); - _dynamicScheduleList.Clear(); + foreach (var item in items) + { + Release(item); + } } } } diff --git a/src/WebExpress.WebCore/WebPage/Model/PageDictionary.cs b/src/WebExpress.WebCore/WebPage/Model/PageDictionary.cs index 0bbbf90..c0d5111 100644 --- a/src/WebExpress.WebCore/WebPage/Model/PageDictionary.cs +++ b/src/WebExpress.WebCore/WebPage/Model/PageDictionary.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading; using WebExpress.WebCore.WebApplication; using WebExpress.WebCore.WebPlugin; @@ -11,17 +12,30 @@ namespace WebExpress.WebCore.WebPage.Model /// key = plugin context /// value = application context { key = page type, value = page item } /// + /// + /// The package scan adds and removes pages on its own thread while requests look them up, and + /// a dictionary written during a read can throw or loop forever. Every member therefore runs + /// under one lock and returns a list taken under it, never a query that would read the + /// dictionary later, outside the lock. + /// internal class PageDictionary { private readonly Dictionary>> _dict = []; + private readonly Lock _lock = new(); /// /// Gets all page contexts. /// - public IEnumerable All => _dict.Values - .SelectMany(x => x.Values) - .SelectMany(x => x.Values) - .Select(x => x.PageContext); + public IEnumerable All + { + get + { + lock (_lock) + { + return [.. Items().Select(x => x.PageContext)]; + } + } + } /// /// Adds a page item to the dictionary. @@ -39,213 +53,217 @@ public bool AddPageItem(IPluginContext pluginContext, IApplicationContext applic return false; } - if (!_dict.TryGetValue(pluginContext, out Dictionary> appContextDict)) + lock (_lock) { - appContextDict = ([]); - _dict[pluginContext] = appContextDict; - } + if (!_dict.TryGetValue(pluginContext, out var appContextDict)) + { + appContextDict = []; + _dict[pluginContext] = appContextDict; + } - if (!appContextDict.TryGetValue(applicationContext, out Dictionary pageDict)) - { - pageDict = ([]); - appContextDict[applicationContext] = pageDict; - } + if (!appContextDict.TryGetValue(applicationContext, out var pageDict)) + { + pageDict = []; + appContextDict[applicationContext] = pageDict; + } - if (!pageDict.ContainsKey(type)) - { - pageDict[type] = pageItem; - return true; + return pageDict.TryAdd(type, pageItem); } - - return false; } /// - /// Removes all page from the dictionary. + /// Removes all pages of a plugin and disposes them. /// + /// + /// The removed items are collected before they leave the dictionary; a query read after the + /// removal found nothing, so no page was disposed and no remove event fired, which left the + /// endpoints of a removed plugin to anyone listening for the removal. + /// /// The plugin context. - public IEnumerable RemovePage(IPluginContext pluginContext) + /// The page contexts that were removed. + public IReadOnlyList RemovePage(IPluginContext pluginContext) { - var removed = GetPageItems(pluginContext); - - _dict.Remove(pluginContext); + List removed; - foreach (var item in removed) + lock (_lock) { - item.Dispose(); + if (pluginContext is null || !_dict.Remove(pluginContext, out var appContextDict)) + { + return []; + } + + removed = [.. appContextDict.Values.SelectMany(x => x.Values)]; } - return removed.Select(x => x.PageContext); + return Dispose(removed); } /// - /// Removes all page from the dictionary. + /// Removes all pages of an application and disposes them. /// /// The application context. - public IEnumerable RemovePage(IApplicationContext applicationContext) + /// The page contexts that were removed. + public IReadOnlyList RemovePage(IApplicationContext applicationContext) { - var removed = GetPageItems(applicationContext); + var removed = new List(); - foreach (var applicationDict in _dict.Values) + lock (_lock) { - applicationDict.Remove(applicationContext); - } + foreach (var (pluginContext, appContextDict) in _dict.ToList()) + { + if (!appContextDict.Remove(applicationContext, out var pageDict)) + { + continue; + } - foreach (var item in removed) - { - item.Dispose(); + if (appContextDict.Count == 0) + { + _dict.Remove(pluginContext); + } + + removed.AddRange(pageDict.Values); + } } - return removed.Select(x => x.PageContext); + return Dispose(removed); } /// /// Returns the page items associated with the specified plugin context. /// - /// The plugin context to retrieve page items for. - /// An IEnumerable of associated with the specified application context. + /// The plugin context. + /// The page items. public IEnumerable GetPageItems(IPluginContext pluginContext) { - return _dict.Where(x => x.Key.Equals(pluginContext)) - .Select(x => x.Value) - .SelectMany(x => x.Values) - .SelectMany(x => x.Values); + lock (_lock) + { + return pluginContext is not null && _dict.TryGetValue(pluginContext, out var appContextDict) + ? [.. appContextDict.Values.SelectMany(x => x.Values)] + : []; + } } /// /// Returns the page items associated with the specified application context. /// - /// The application context to retrieve page items for. - /// An IEnumerable of associated with the specified application context. + /// The application context. + /// The page items. public IEnumerable GetPageItems(IApplicationContext applicationContext) { - return _dict.Values - .SelectMany(x => x) - .Where(x => x.Key.Equals(applicationContext)) - .SelectMany(x => x.Value) - .Select(x => x.Value); + lock (_lock) + { + return [.. _dict.Values + .SelectMany(x => x) + .Where(x => x.Key.Equals(applicationContext)) + .SelectMany(x => x.Value.Values)]; + } } /// /// Returns the page item associated with the specified page context. /// - /// The context of the page to retrieve. - /// The associated with the specified page context, or null if no such item exists. + /// The page context. + /// The page item, or null. public PageItem GetPageItem(IPageContext pageContext) { - return _dict.Values - .SelectMany(x => x.Values) - .SelectMany(x => x.Values) - .FirstOrDefault(x => x.PageContext.Equals(pageContext)); + lock (_lock) + { + return Items().FirstOrDefault(x => x.PageContext.Equals(pageContext)); + } } /// /// Returns the page items from the dictionary for a specific application context and page type. /// /// The application context. - /// The type of the page. - /// An IEnumerable of page items. + /// The page type. + /// The page items. public IEnumerable GetPageItems(IApplicationContext applicationContext, Type pageType) { - if (!typeof(IPage).IsAssignableFrom(pageType)) + if (!typeof(IPage).IsAssignableFrom(pageType) || applicationContext?.PluginContext is null) { return []; } - if (_dict.ContainsKey(applicationContext?.PluginContext)) + lock (_lock) { - var appContextDict = _dict[applicationContext?.PluginContext]; - - if (appContextDict.TryGetValue(applicationContext, out Dictionary pageDict)) - { - if (pageDict.TryGetValue(pageType, out PageItem value)) - { - return [value]; - } - } + return _dict.TryGetValue(applicationContext.PluginContext, out var appContextDict) + && appContextDict.TryGetValue(applicationContext, out var pageDict) + && pageDict.TryGetValue(pageType, out var value) + ? [value] + : []; } - - return []; } /// /// Returns an enumeration of all containing page contexts of a plugin. /// - /// A context of a plugin whose pages are to be registered. - /// An enumeration of page contexts. + /// The plugin context. + /// The page contexts. public IEnumerable GetPages(IPluginContext pluginContext) { - if (_dict.TryGetValue(pluginContext, out var pluginResources)) - { - return pluginResources - .SelectMany(x => x.Value) - .Select(x => x.Value.PageContext); - } - - return []; + return [.. GetPageItems(pluginContext).Select(x => x.PageContext)]; } /// /// Returns an enumeration of page contextes. /// /// The page type. - /// An enumeration of page contextes. + /// The page contexts. public IEnumerable GetPages(Type pageType) { - return _dict.Values - .SelectMany(x => x.Values) - .SelectMany(x => x.Values) - .Where(x => x.PageClass.Equals(pageType)) - .Select(x => x.PageContext); + lock (_lock) + { + return [.. Items() + .Where(x => x.PageClass.Equals(pageType)) + .Select(x => x.PageContext)]; + } } /// /// Returns an enumeration of page contextes. /// /// The page type. - /// The context of the application. - /// An enumeration of page contextes. + /// The application context. + /// The page contexts. public IEnumerable GetPages(Type pageType, IApplicationContext applicationContext) { - return _dict.Values - .SelectMany(x => x.Values) - .SelectMany(x => x.Values) - .Where(x => x.PageClass.Equals(pageType)) - .Where(x => x.PageContext.ApplicationContext.Equals(applicationContext)) - .Select(x => x.PageContext); + lock (_lock) + { + return [.. Items() + .Where(x => x.PageClass.Equals(pageType)) + .Where(x => x.PageContext.ApplicationContext.Equals(applicationContext)) + .Select(x => x.PageContext)]; + } } /// /// Returns an enumeration of page contextes. /// /// The page type. - /// The context of the application. - /// An enumeration of page contextes. + /// The application context. + /// The page contexts. public IEnumerable GetPages(IApplicationContext applicationContext) where TPage : IPage { - return _dict.Values - .SelectMany(x => x.Values) - .SelectMany(x => x.Values) - .Where(x => x.PageClass.Equals(typeof(TPage))) - .Where(x => x.PageContext.ApplicationContext.Equals(applicationContext)) - .Select(x => x.PageContext); + return GetPages(typeof(TPage), applicationContext); } /// /// Returns the page context. /// - /// The context of the application. + /// The application context. /// The page id. - /// An page context or null. + /// The page context, or null. public IPageContext GetPage(IApplicationContext applicationContext, string pageId) { - return _dict.Values - .SelectMany(x => x.Values) - .SelectMany(x => x.Values) - .Where(x => x.PageContext.ApplicationContext.Equals(applicationContext)) - .Where(x => x.PageContext.EndpointId.Equals(pageId)) - .Select(x => x.PageContext) - .FirstOrDefault(); + lock (_lock) + { + return Items() + .Where(x => x.PageContext.ApplicationContext.Equals(applicationContext)) + .Where(x => x.PageContext.EndpointId.Equals(pageId)) + .Select(x => x.PageContext) + .FirstOrDefault(); + } } /// @@ -253,16 +271,17 @@ public IPageContext GetPage(IApplicationContext applicationContext, string pageI /// /// The application id. /// The page id. - /// An page context or null. + /// The page context, or null. public IPageContext GetPage(string applicationId, string pageId) { - return _dict.Values - .SelectMany(x => x.Values) - .SelectMany(x => x.Values) - .Where(x => x.PageContext.ApplicationContext.ApplicationId.Equals(applicationId)) - .Where(x => x.PageContext.EndpointId.Equals(pageId)) - .Select(x => x.PageContext) - .FirstOrDefault(); + lock (_lock) + { + return Items() + .Where(x => x.PageContext.ApplicationContext.ApplicationId.Equals(applicationId)) + .Where(x => x.PageContext.EndpointId.Equals(pageId)) + .Select(x => x.PageContext) + .FirstOrDefault(); + } } /// @@ -272,7 +291,10 @@ public IPageContext GetPage(string applicationId, string pageId) /// True if the plugin context exists in the dictionary, otherwise false. public bool Contains(IPluginContext pluginContext) { - return _dict.ContainsKey(pluginContext); + lock (_lock) + { + return pluginContext is not null && _dict.ContainsKey(pluginContext); + } } /// @@ -283,7 +305,38 @@ public bool Contains(IPluginContext pluginContext) /// True if the plugin context and application context exist in the dictionary, otherwise false. public bool Contains(IPluginContext pluginContext, IApplicationContext applicationContext) { - return _dict.TryGetValue(pluginContext, out var appDict) && appDict.ContainsKey(applicationContext); + lock (_lock) + { + return pluginContext is not null && applicationContext is not null + && _dict.TryGetValue(pluginContext, out var appDict) && appDict.ContainsKey(applicationContext); + } + } + + /// + /// Enumerates all page items; called under the lock only. + /// + /// The page items. + private IEnumerable Items() + { + return _dict.Values + .SelectMany(x => x.Values) + .SelectMany(x => x.Values); + } + + /// + /// Disposes removed page items outside the lock, so a page's own clean-up cannot block the + /// lookups of other requests. + /// + /// The removed page items. + /// Their page contexts. + private static IReadOnlyList Dispose(List removed) + { + foreach (var item in removed) + { + item.Dispose(); + } + + return [.. removed.Select(x => x.PageContext)]; } } } diff --git a/src/WebExpress.WebCore/WebStatusPage/StatusPageManager.cs b/src/WebExpress.WebCore/WebStatusPage/StatusPageManager.cs index 1d75a81..37a13dc 100644 --- a/src/WebExpress.WebCore/WebStatusPage/StatusPageManager.cs +++ b/src/WebExpress.WebCore/WebStatusPage/StatusPageManager.cs @@ -474,12 +474,18 @@ internal void Remove(IPluginContext pluginContext) lock (_guard) { - if (!_dictionary.ContainsKey(pluginContext)) + if (!_dictionary.Remove(pluginContext, out var appDict)) { return; } - _dictionary.Remove(pluginContext); + // announced like the removal of an application, so a listener does not keep a + // status page of a plugin that is gone + foreach (var statusPageItem in appDict.Values.SelectMany(x => x.Values)) + { + OnRemoveStatusPage(statusPageItem.StatusPageContext); + statusPageItem.Dispose(); + } } } diff --git a/src/WebExpress.WebCore/WebTask/Model/TaskDictionary.cs b/src/WebExpress.WebCore/WebTask/Model/TaskDictionary.cs index f6ed37b..063ccd9 100644 --- a/src/WebExpress.WebCore/WebTask/Model/TaskDictionary.cs +++ b/src/WebExpress.WebCore/WebTask/Model/TaskDictionary.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Concurrent; namespace WebExpress.WebCore.WebTask.Model { @@ -7,7 +8,19 @@ namespace WebExpress.WebCore.WebTask.Model /// Key = The task id. /// Value = The task. /// - internal class TaskDictionary : Dictionary + /// + /// Tasks are created and removed from request threads at the same time; a plain dictionary + /// written concurrently can throw or loop forever. Ids compare ordinally ignoring case, which + /// does not depend on the culture of the thread the way lowering the id did. + /// + internal class TaskDictionary : ConcurrentDictionary { + /// + /// Initializes a new instance of the class. + /// + public TaskDictionary() + : base(StringComparer.OrdinalIgnoreCase) + { + } } } diff --git a/src/WebExpress.WebCore/WebTask/TaskManager.cs b/src/WebExpress.WebCore/WebTask/TaskManager.cs index de904f5..8fa1b2c 100644 --- a/src/WebExpress.WebCore/WebTask/TaskManager.cs +++ b/src/WebExpress.WebCore/WebTask/TaskManager.cs @@ -14,7 +14,11 @@ public class TaskManager : ITaskManager, ISystemComponent { private readonly IComponentHub _componentHub; private readonly IHttpServerContext _httpServerContext; - private readonly TaskDictionary _dictionary = []; + private readonly TaskDictionary _dictionary = new(); + + // serializes the creation of a task, so two requests asking for one id get the same task + // and its handlers are subscribed exactly once + private readonly System.Threading.Lock _lock = new(); /// /// Event is triggered when a task's changes. @@ -24,7 +28,7 @@ public class TaskManager : ITaskManager, ISystemComponent /// /// Gets the collection of tasks. /// - public IEnumerable Tasks => _dictionary.Values; + public IEnumerable Tasks => [.. _dictionary.Values]; /// /// Initializes a new instance of the class. @@ -50,7 +54,7 @@ private TaskManager(IComponentHub componentHub, IHttpServerContext httpServerCon /// True if this task already exists, false otherwise. public bool ContainsTask(string id) { - return _dictionary.ContainsKey(id?.ToLower()); + return id is not null && _dictionary.ContainsKey(id); } /// @@ -60,12 +64,7 @@ public bool ContainsTask(string id) /// The task or null. public ITask GetTask(string id) { - if (_dictionary.ContainsKey(id?.ToLower())) - { - return _dictionary[id?.ToLower()]; - } - - return null; + return id is not null && _dictionary.TryGetValue(id, out var task) ? task : null; } /// @@ -76,22 +75,25 @@ public ITask GetTask(string id) /// The task or null. public ITask CreateTask(string id, params object[] args) { - var key = id?.ToLower(); + ArgumentNullException.ThrowIfNull(id); - if (_dictionary.TryGetValue(key, out var value)) + lock (_lock) { - return value; - } + if (_dictionary.TryGetValue(id, out var value)) + { + return value; + } - var task = ComponentActivator.CreateInstance(_httpServerContext, _componentHub, [id, args]); - task.Lifetime = _httpServerContext.Lifetime; + var task = ComponentActivator.CreateInstance(_httpServerContext, _componentHub, [id, args]); + task.Lifetime = _httpServerContext.Lifetime; - // register events for the newly created task - SubscribeTaskEvents(task); + // register events for the newly created task + SubscribeTaskEvents(task); - _dictionary.Add(key, task); + _dictionary[id] = task; - return task; + return task; + } } /// @@ -117,24 +119,27 @@ public ITask CreateTask(string id, EventHandler handler, params o public ITask CreateTask(string id, EventHandler handler, params object[] args) where TTask : Task { - var key = id?.ToLower(); + ArgumentNullException.ThrowIfNull(id); - if (_dictionary.TryGetValue(key, out var value)) + lock (_lock) { - return value; - } + if (_dictionary.TryGetValue(id, out var value)) + { + return value; + } - var task = ComponentActivator.CreateInstance(_httpServerContext, _componentHub, [id, args]); - task.Lifetime = _httpServerContext.Lifetime; + var task = ComponentActivator.CreateInstance(_httpServerContext, _componentHub, [id, args]); + task.Lifetime = _httpServerContext.Lifetime; - // register events for the newly created task - SubscribeTaskEvents(task); + // register events for the newly created task + SubscribeTaskEvents(task); - _dictionary.Add(key, task); + _dictionary[id] = task; - task.Process += handler; + task.Process += handler; - return task; + return task; + } } /// @@ -148,15 +153,12 @@ public void RemoveTask(ITask task) return; } - var key = task.Id.ToLower(); - - if (_dictionary.TryGetValue(key, out var storedTask) && storedTask is Task t) + // only the stored instance is removed, never a newer task that took over the id + if (_dictionary.TryRemove(new KeyValuePair(task.Id, task)) && task is Task t) { // unregister events to prevent memory leaks UnsubscribeTaskEvents(t); } - - _dictionary.Remove(key); } /// diff --git a/src/WebExpress.WebCore/WebTheme/Model/ThemeItemDictionary.cs b/src/WebExpress.WebCore/WebTheme/Model/ThemeItemDictionary.cs index dfd2cd7..761e299 100644 --- a/src/WebExpress.WebCore/WebTheme/Model/ThemeItemDictionary.cs +++ b/src/WebExpress.WebCore/WebTheme/Model/ThemeItemDictionary.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using System.Linq; +using System.Threading; using WebExpress.WebCore.WebApplication; using WebExpress.WebCore.WebPlugin; @@ -8,16 +9,29 @@ namespace WebExpress.WebCore.WebTheme.Model /// /// Represents a dictionary that stores theme items based on plugin and application contexts. /// + /// + /// The package scan adds and removes themes on its own thread while every page render reads + /// them, and a dictionary written during a read can throw or loop forever. Every member + /// therefore runs under one lock and returns a list taken under it. + /// internal class ThemeItemDictionary { private readonly Dictionary>> _dictionary = []; + private readonly Lock _lock = new(); /// /// Gets all theme items. /// - public IEnumerable All => _dictionary.Values - .SelectMany(x => x.Values) - .SelectMany(x => x); + public IEnumerable All + { + get + { + lock (_lock) + { + return [.. _dictionary.Values.SelectMany(x => x.Values).SelectMany(x => x)]; + } + } + } /// /// Adds a theme item to the dictionary. @@ -35,32 +49,32 @@ public bool AddThemeItem(IPluginContext pluginContext, IApplicationContext appli return false; } - if (!_dictionary.ContainsKey(pluginContext)) + lock (_lock) { - _dictionary[pluginContext] = []; - } - - var appContextDict = _dictionary[pluginContext]; - - if (!appContextDict.TryGetValue(applicationContext, out List value)) - { - value = []; - appContextDict[applicationContext] = value; - } + if (!_dictionary.TryGetValue(pluginContext, out var appContextDict)) + { + appContextDict = []; + _dictionary[pluginContext] = appContextDict; + } - var assetList = value; + if (!appContextDict.TryGetValue(applicationContext, out var themeList)) + { + themeList = []; + appContextDict[applicationContext] = themeList; + } - assetList.RemoveAll(x => x.ThemeContext?.ThemeId == themeItem.ThemeContext.ThemeId); - assetList.Add(themeItem); + themeList.RemoveAll(x => x.ThemeContext?.ThemeId == themeItem.ThemeContext.ThemeId); + themeList.Add(themeItem); - return true; + return true; + } } /// - /// Removes all resources associated with the specified plugin context. + /// Removes all themes associated with the specified plugin context and disposes them. /// /// The context of the plugin that contains the resources to remove. - /// An enumeration of theme contexts that were removed. + /// The theme contexts that were removed. public IEnumerable Remove(IPluginContext pluginContext) { if (pluginContext is null) @@ -68,31 +82,27 @@ public IEnumerable Remove(IPluginContext pluginContext) return []; } - // the plugin has not been registered in the manager - if (_dictionary.TryGetValue(pluginContext, out var value)) - { - var items = value.Values - .SelectMany(x => x) - .ToList(); + List items; - foreach (var assetItem in items) + lock (_lock) + { + // the plugin has not been registered in the manager + if (!_dictionary.Remove(pluginContext, out var value)) { - assetItem.Dispose(); + return []; } - _dictionary.Remove(pluginContext); - - return items.Select(x => x.ThemeContext); + items = [.. value.Values.SelectMany(x => x)]; } - return []; + return Dispose(items); } /// - /// Removes all themes associated with the specified application context. + /// Removes all themes associated with the specified application context and disposes them. /// /// The context of the application that contains the resources to remove. - /// An enumeration of theme contexts that were removed. + /// The theme contexts that were removed. internal IEnumerable Remove(IApplicationContext applicationContext) { if (applicationContext is null) @@ -100,23 +110,20 @@ internal IEnumerable Remove(IApplicationContext applicationContex return []; } - var removedThemes = new List(); + var items = new List(); - foreach (var pluginDict in _dictionary.Values) + lock (_lock) { - foreach (var themeList in pluginDict.Where(x => x.Key == applicationContext).Select(x => x.Value)) + foreach (var pluginDict in _dictionary.Values) { - foreach (var assetItem in themeList) + if (pluginDict.Remove(applicationContext, out var themeList)) { - removedThemes.Add(assetItem.ThemeContext); - assetItem.Dispose(); + items.AddRange(themeList); } } - - pluginDict.Remove(applicationContext); } - return removedThemes; + return Dispose(items); } /// @@ -126,7 +133,10 @@ internal IEnumerable Remove(IApplicationContext applicationContex /// True if the plugin context exists in the dictionary, otherwise false. public bool ContainsPlugin(IPluginContext pluginContext) { - return _dictionary.ContainsKey(pluginContext); + lock (_lock) + { + return pluginContext is not null && _dictionary.ContainsKey(pluginContext); + } } /// @@ -137,12 +147,11 @@ public bool ContainsPlugin(IPluginContext pluginContext) /// True if the application context exists in the dictionary, otherwise false. public bool ContainsApplication(IPluginContext pluginContext, IApplicationContext applicationContext) { - if (_dictionary.TryGetValue(pluginContext, out var appDict) && appDict.ContainsKey(applicationContext)) + lock (_lock) { - return true; + return pluginContext is not null && applicationContext is not null + && _dictionary.TryGetValue(pluginContext, out var appDict) && appDict.ContainsKey(applicationContext); } - - return false; } /// @@ -152,19 +161,18 @@ public bool ContainsApplication(IPluginContext pluginContext, IApplicationContex /// An IEnumerable of theme items public IEnumerable GetThemeItems(IApplicationContext applicationContext) { - if (_dictionary.ContainsKey(applicationContext?.PluginContext)) + if (applicationContext?.PluginContext is null) { - var appContextDict = _dictionary[applicationContext?.PluginContext]; - - if (appContextDict.TryGetValue(applicationContext, out List value)) - { - var assetList = value; - - return assetList; - } + return []; } - return []; + lock (_lock) + { + return _dictionary.TryGetValue(applicationContext.PluginContext, out var appContextDict) + && appContextDict.TryGetValue(applicationContext, out var themeList) + ? [.. themeList] + : []; + } } /// @@ -174,14 +182,17 @@ public IEnumerable GetThemeItems(IApplicationContext applicationConte /// An enumeration of theme contexts. public IEnumerable GetThemes(IPluginContext pluginContext) { - if (_dictionary.TryGetValue(pluginContext, out var pluginResources)) + if (pluginContext is null) { - return pluginResources - .SelectMany(x => x.Value) - .Select(x => x.ThemeContext); + return []; } - return []; + lock (_lock) + { + return _dictionary.TryGetValue(pluginContext, out var pluginResources) + ? [.. pluginResources.SelectMany(x => x.Value).Select(x => x.ThemeContext)] + : []; + } } /// @@ -191,11 +202,30 @@ public IEnumerable GetThemes(IPluginContext pluginContext) /// An enumeration of theme contextes. public IEnumerable GetThemes(IApplicationContext applicationContext) { - return _dictionary.Values - .SelectMany(x => x.Values) - .SelectMany(x => x) - .Where(x => x.ThemeContext.ApplicationContext.Equals(applicationContext)) - .Select(x => x.ThemeContext); + lock (_lock) + { + return [.. _dictionary.Values + .SelectMany(x => x.Values) + .SelectMany(x => x) + .Where(x => x.ThemeContext.ApplicationContext.Equals(applicationContext)) + .Select(x => x.ThemeContext)]; + } + } + + /// + /// Disposes removed theme items outside the lock, so their clean-up cannot block the + /// page renders of other requests. + /// + /// The removed theme items. + /// Their theme contexts. + private static List Dispose(List items) + { + foreach (var item in items) + { + item.Dispose(); + } + + return [.. items.Select(x => x.ThemeContext)]; } } } From 08c00d105006d53994ba9baadd45fcea3b78fb21 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Schwarzer?= Date: Tue, 24 Nov 2026 22:28:38 +0100 Subject: [PATCH 09/16] fix: lock the setting page, plugin and component registries The three setting registries share one locked base (SettingItemRegistry) that hands out copies and returns what it removes. Removing a plugin dropped its setting pages without announcing them, so the endpoint registration kept their routes, and categories and groups were never removed at all; the manager now empties all three and raises RemoveSettingPage for every page. A cached setting page instance is created outside the lock and kept race-free. Plugin and component registries are concurrent dictionaries; the component list of a plugin is published as a new copy after each addition instead of being grown in place while requests may enumerate it. Co-Authored-By: Claude Opus 5.5 --- .../Manager/UnitTestRegistryConcurrency.cs | 27 +++ .../WebComponent/ComponentHub.cs | 11 +- .../WebComponent/Model/ComponentDictionary.cs | 9 +- .../WebPlugin/Model/PluginDictionary.cs | 8 +- .../WebPlugin/PluginManager.cs | 16 +- .../Model/SettingCategoryDictionary.cs | 94 ++-------- .../Model/SettingGroupDictionary.cs | 109 +++--------- .../Model/SettingItemRegistry.cs | 160 +++++++++++++++++ .../Model/SettingPageDictionary.cs | 168 +++++------------- .../WebSettingPage/SettingPageManager.cs | 17 +- 10 files changed, 314 insertions(+), 305 deletions(-) create mode 100644 src/WebExpress.WebCore/WebSettingPage/Model/SettingItemRegistry.cs diff --git a/src/WebExpress.WebCore.Test/Manager/UnitTestRegistryConcurrency.cs b/src/WebExpress.WebCore.Test/Manager/UnitTestRegistryConcurrency.cs index dc7a2c7..b8987fa 100644 --- a/src/WebExpress.WebCore.Test/Manager/UnitTestRegistryConcurrency.cs +++ b/src/WebExpress.WebCore.Test/Manager/UnitTestRegistryConcurrency.cs @@ -35,6 +35,33 @@ public void RemovingAPluginAnnouncesItsPages() Assert.Empty(componentHub.PageManager.Pages); } + /// + /// Verifies that removing a plugin announces each of its setting pages, so their routes are + /// dropped, and takes the categories and groups along. The plugin's setting pages left the + /// registry silently and its categories and groups stayed. + /// + [Fact] + public void RemovingAPluginAnnouncesItsSettingPages() + { + // arrange + var componentHub = UnitTestFixture.CreateAndRegisterComponentHubMock(); + var plugin = componentHub.PluginManager.GetPlugin(typeof(TestPlugin)); + var settingPageManager = componentHub.SettingPageManager as WebExpress.WebCore.WebSettingPage.SettingPageManager; + var registered = componentHub.SettingPageManager.SettingPages.Count(); + var removed = new List(); + settingPageManager.RemoveSettingPage += (sender, e) => removed.Add(e); + + // act + settingPageManager.Remove(plugin); + + // validation + Assert.True(registered > 0); + Assert.Equal(registered, removed.Count); + Assert.Empty(componentHub.SettingPageManager.SettingPages); + Assert.Empty(componentHub.SettingPageManager.SettingCategories); + Assert.Empty(componentHub.SettingPageManager.SettingGroups); + } + /// /// Verifies that removing a plugin announces each of its includes and leaves none behind. /// diff --git a/src/WebExpress.WebCore/WebComponent/ComponentHub.cs b/src/WebExpress.WebCore/WebComponent/ComponentHub.cs index e30f11c..e3798d7 100644 --- a/src/WebExpress.WebCore/WebComponent/ComponentHub.cs +++ b/src/WebExpress.WebCore/WebComponent/ComponentHub.cs @@ -453,7 +453,7 @@ internal void Register(IPluginContext pluginContext) // initialize the component entry as an empty list for easier manipulation var componentList = new List(); - _dictionary.Add(pluginContext, componentList); + _dictionary.TryAdd(pluginContext, []); foreach (var type in assembly .GetExportedTypes() @@ -474,6 +474,10 @@ internal void Register(IPluginContext pluginContext) ComponentInstance = componentInstance }); + // a request may be reading the stored list right now, so the grown list is + // stored as a new copy instead of being changed in place + _dictionary[pluginContext] = [.. componentList]; + _httpServerContext?.Log?.Debug ( _internationalizationManager.Translate("webexpress.webcore:componentmanager.register", id) @@ -491,8 +495,7 @@ internal void Register(IPluginContext pluginContext) } } - // make sure the dictionary uses IEnumerable as value type, if the dictionary requires it - _dictionary[pluginContext] = componentList; + _dictionary[pluginContext] = [.. componentList]; Log(); } @@ -606,7 +609,7 @@ public void Remove(IPluginContext pluginContext) } } - _dictionary.Remove(pluginContext); + _dictionary.TryRemove(pluginContext, out _); } /// diff --git a/src/WebExpress.WebCore/WebComponent/Model/ComponentDictionary.cs b/src/WebExpress.WebCore/WebComponent/Model/ComponentDictionary.cs index b80e44b..d563911 100644 --- a/src/WebExpress.WebCore/WebComponent/Model/ComponentDictionary.cs +++ b/src/WebExpress.WebCore/WebComponent/Model/ComponentDictionary.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System.Collections.Concurrent; +using System.Collections.Generic; using WebExpress.WebCore.WebPlugin; namespace WebExpress.WebCore.WebComponent.Model @@ -8,7 +9,11 @@ namespace WebExpress.WebCore.WebComponent.Model /// key = plugin /// value = component item /// - internal class ComponentDictionary : Dictionary> + /// + /// Concurrent, because plugins register their components while requests resolve managers; a + /// list stored here is not changed after it is stored; a grown list replaces it. + /// + internal class ComponentDictionary : ConcurrentDictionary> { } diff --git a/src/WebExpress.WebCore/WebPlugin/Model/PluginDictionary.cs b/src/WebExpress.WebCore/WebPlugin/Model/PluginDictionary.cs index fd436af..f0a6841 100644 --- a/src/WebExpress.WebCore/WebPlugin/Model/PluginDictionary.cs +++ b/src/WebExpress.WebCore/WebPlugin/Model/PluginDictionary.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Concurrent; using WebExpress.WebCore.WebComponent; namespace WebExpress.WebCore.WebPlugin.Model @@ -8,7 +8,11 @@ namespace WebExpress.WebCore.WebPlugin.Model /// Key = PluginId /// Value = Plugin-Metadaten /// - internal class PluginDictionary : Dictionary + /// + /// Concurrent, because the package scan loads and unloads plugins while requests and the other + /// managers look them up; a plain dictionary written during a read can throw or loop forever. + /// + internal class PluginDictionary : ConcurrentDictionary { } } diff --git a/src/WebExpress.WebCore/WebPlugin/PluginManager.cs b/src/WebExpress.WebCore/WebPlugin/PluginManager.cs index bf23dae..11633fc 100644 --- a/src/WebExpress.WebCore/WebPlugin/PluginManager.cs +++ b/src/WebExpress.WebCore/WebPlugin/PluginManager.cs @@ -232,7 +232,7 @@ internal IEnumerable Register(Assembly assembly, PluginLoadConte if (hasUnfulfilledDependencies) { - _unfulfilledDependencies.Add(id, new PluginItem() + _unfulfilledDependencies.TryAdd(id, new PluginItem() { PluginLoadContext = loadContext, PluginClass = assembly.ExportedTypes.FirstOrDefault() ?? typeof(IPlugin), @@ -244,7 +244,7 @@ internal IEnumerable Register(Assembly assembly, PluginLoadConte } else { - _dictionary.Add(id, new PluginItem() + _dictionary.TryAdd(id, new PluginItem() { PluginLoadContext = loadContext, PluginClass = assembly.ExportedTypes.FirstOrDefault() ?? typeof(IPlugin), @@ -363,7 +363,7 @@ internal IEnumerable Register(Assembly assembly, PluginLoadConte if (hasUnfulfilledDependencies) { - _unfulfilledDependencies.Add(id, new PluginItem() + _unfulfilledDependencies.TryAdd(id, new PluginItem() { PluginLoadContext = loadContext, PluginClass = type, @@ -375,7 +375,7 @@ internal IEnumerable Register(Assembly assembly, PluginLoadConte } else { - _dictionary.Add(id, new PluginItem() + _dictionary.TryAdd(id, new PluginItem() { PluginLoadContext = loadContext, PluginClass = type, @@ -442,8 +442,8 @@ public void Remove(IPluginContext pluginContext) OnRemovePlugin(pluginContext); - _dictionary.Remove(pluginContext.PluginId); - _unfulfilledDependencies.Remove(pluginContext.PluginId); + _dictionary.TryRemove(pluginContext.PluginId, out _); + _unfulfilledDependencies.TryRemove(pluginContext.PluginId, out _); Release(pluginItem); @@ -521,8 +521,8 @@ private void CheckUnfulfilledDependencies() if (!hasUnfulfilledDependencies) { fulfilledDependencies = true; - _unfulfilledDependencies.Remove(unfulfilledDependencies.Key); - _dictionary.Add(unfulfilledDependencies.Key, unfulfilledDependencies.Value); + _unfulfilledDependencies.TryRemove(unfulfilledDependencies.Key, out _); + _dictionary.TryAdd(unfulfilledDependencies.Key, unfulfilledDependencies.Value); OnAddPlugin(unfulfilledDependencies.Value.PluginContext); diff --git a/src/WebExpress.WebCore/WebSettingPage/Model/SettingCategoryDictionary.cs b/src/WebExpress.WebCore/WebSettingPage/Model/SettingCategoryDictionary.cs index 7f7c212..46cf5f7 100644 --- a/src/WebExpress.WebCore/WebSettingPage/Model/SettingCategoryDictionary.cs +++ b/src/WebExpress.WebCore/WebSettingPage/Model/SettingCategoryDictionary.cs @@ -2,112 +2,48 @@ using System.Collections.Generic; using System.Linq; using WebExpress.WebCore.WebApplication; -using WebExpress.WebCore.WebPlugin; namespace WebExpress.WebCore.WebSettingPage.Model { /// /// Represents a dictionary for managing setting categories, organized by plugin and application contexts. /// - internal class SettingCategoryDictionary + internal class SettingCategoryDictionary : SettingItemRegistry { - private readonly Dictionary>> _dict = []; - /// /// Gets the collection of setting categories. /// - public IEnumerable All => _dict.Values - .SelectMany(a => a.Values) - .SelectMany(x => x) - .Select(x => x.SettingCategoryContext); + public IEnumerable All => [.. Items().Select(x => x.SettingCategoryContext)]; /// - /// Adds a settings category. + /// Adds a setting category. /// - /// The settings category to insert. - /// True if the settings category was added successfully; otherwise, false. + /// The setting category to insert. + /// True if the setting category was added successfully; otherwise, false. public bool AddSettingCategoryItem(SettingCategoryItem item) { - if (!_dict.TryGetValue(item.PluginContext, out var appDict)) - { - appDict = []; - _dict.Add(item.PluginContext, appDict); - } - - if (!appDict.TryGetValue(item.ApplicationContext, out var list)) - { - list = []; - appDict.Add(item.ApplicationContext, list); - } - - list.Add(item); - - return true; - } - - /// - /// Removes all elements associated with the specified plugin context. - /// - /// The context of the plugin that contains the elements to remove. - public void Remove(IPluginContext pluginContext) - { - _dict.Remove(pluginContext); - } - - /// - /// Removes all setting categories associated with the specified application context. - /// - /// The context of the application that contains the fragments to remove. - /// An enumerable collection of setting categories contexts that were removed. - public IEnumerable Remove(IApplicationContext applicationContext) - { - if (applicationContext is null) - { - yield break; - } - - foreach (var pluginDict in _dict.Values) - { - var removed = pluginDict - .Where(x => x.Key == applicationContext) - .SelectMany(x => x.Value) - .ToList(); - - pluginDict.Remove(applicationContext); - - foreach (var category in removed) - { - yield return category.SettingCategoryContext; - } - } + return Add(item.PluginContext, item.ApplicationContext, item); } /// - /// Returns the setting category context for the specified application context. + /// Returns the setting categories of an application. /// - /// The application context. - /// An enumeration of category contexts associated with the specified application context. + /// The context of the application. + /// An enumeration of setting category contexts. public IEnumerable GetSettingCategories(IApplicationContext applicationContext) { - return _dict.Values - .SelectMany(x => x) - .Where(x => x.Key == applicationContext) - .SelectMany(x => x.Value) - .Select(x => x.SettingCategoryContext); + return [.. Items(applicationContext).Select(x => x.SettingCategoryContext)]; } /// - /// Returns the setting category context for the specified application context and category type. + /// Returns the setting category of a given class in an application. /// - /// The application context. - /// The type of the category. - /// >The setting category context if found; otherwise, null. + /// The context of the application. + /// The category class. + /// The setting category context, or null. public ISettingCategoryContext GetSettingCategory(IApplicationContext applicationContext, Type categoryType) { - return _dict.Values - .SelectMany(x => x) - .Where(x => x.Key == applicationContext) - .SelectMany(x => x.Value) + return Items(applicationContext) .Where(x => x.SettingCategoryClass == categoryType) .Select(x => x.SettingCategoryContext) .FirstOrDefault(); diff --git a/src/WebExpress.WebCore/WebSettingPage/Model/SettingGroupDictionary.cs b/src/WebExpress.WebCore/WebSettingPage/Model/SettingGroupDictionary.cs index c1ab03d..204c9b4 100644 --- a/src/WebExpress.WebCore/WebSettingPage/Model/SettingGroupDictionary.cs +++ b/src/WebExpress.WebCore/WebSettingPage/Model/SettingGroupDictionary.cs @@ -2,128 +2,61 @@ using System.Collections.Generic; using System.Linq; using WebExpress.WebCore.WebApplication; -using WebExpress.WebCore.WebPlugin; namespace WebExpress.WebCore.WebSettingPage.Model { /// /// Represents a dictionary for managing setting groups, organized by plugin and application contexts. /// - internal class SettingGroupDictionary + internal class SettingGroupDictionary : SettingItemRegistry { - private readonly Dictionary>> _dict = new(); - /// /// Gets the collection of setting groups. /// - public IEnumerable All => _dict.Values - .SelectMany(a => a.Values) - .SelectMany(x => x) - .Select(x => x.SettingGroupContext); + public IEnumerable All => [.. Items().Select(x => x.SettingGroupContext)]; /// - /// Adds a settings group. + /// Adds a setting group. /// - /// The settings group to insert. - /// True if the settings group was added successfully; otherwise, false. + /// The setting group to insert. + /// True if the setting group was added successfully; otherwise, false. public bool AddSettingGroupItem(SettingGroupItem item) { - if (!_dict.TryGetValue(item.PluginContext, out var appDict)) - { - appDict = []; - _dict.Add(item.PluginContext, appDict); - } - - if (!appDict.TryGetValue(item.ApplicationContext, out var list)) - { - list = []; - appDict.Add(item.ApplicationContext, list); - } - - list.Add(item); - - return true; - } - - /// - /// Removes all elements associated with the specified plugin context. - /// - /// The context of the plugin that contains the elements to remove. - public void Remove(IPluginContext pluginContext) - { - _dict.Remove(pluginContext); - } - - /// - /// Removes all setting groups associated with the specified application context. - /// - /// The context of the application that contains the fragments to remove. - /// An enumerable collection of setting groups contexts that were removed. - public IEnumerable Remove(IApplicationContext applicationContext) - { - if (applicationContext is null) - { - yield break; - } - - foreach (var pluginDict in _dict.Values) - { - var removed = pluginDict - .Where(x => x.Key == applicationContext) - .SelectMany(x => x.Value) - .ToList(); - - pluginDict.Remove(applicationContext); - - foreach (var category in removed) - { - yield return category.SettingGroupContext; - } - } + return Add(item.PluginContext, item.ApplicationContext, item); } /// - /// Returns the setting group context for the specified application context and group type. + /// Returns the setting groups of an application. /// - /// The application context. - /// An enumeration of category contexts associated with the specified application context. + /// The context of the application. + /// An enumeration of setting group contexts. public IEnumerable GetSettingGroups(IApplicationContext applicationContext) { - return _dict.Values - .SelectMany(x => x) - .Where(x => x.Key == applicationContext) - .SelectMany(x => x.Value) - .Select(x => x.SettingGroupContext); + return [.. Items(applicationContext).Select(x => x.SettingGroupContext)]; } /// - /// Returns the setting group context for the specified application context and group type. + /// Returns the setting groups of a category in an application. /// - /// The application context. - /// The category context. - /// An enumeration of category contexts associated with the specified application context. + /// The context of the application. + /// The category. + /// An enumeration of setting group contexts. public IEnumerable GetSettingGroups(IApplicationContext applicationContext, ISettingCategoryContext categoryContext) { - return _dict.Values - .SelectMany(x => x) - .Where(x => x.Key == applicationContext) - .SelectMany(x => x.Value) + return [.. Items(applicationContext) .Where(x => x.SettingGroupContext.SettingCategory == categoryContext) - .Select(x => x.SettingGroupContext); + .Select(x => x.SettingGroupContext)]; } /// - /// Returns the setting group context for the specified application context and group type. + /// Returns the setting group of a given class in an application. /// - /// The application context. - /// The type of the group. - /// The setting group context if found; otherwise, null. + /// The context of the application. + /// The group class. + /// The setting group context, or null. public ISettingGroupContext GetSettingGroup(IApplicationContext applicationContext, Type groupType) { - return _dict.Values - .SelectMany(x => x) - .Where(x => x.Key == applicationContext) - .SelectMany(x => x.Value) + return Items(applicationContext) .Where(x => x.SettingGroupClass == groupType) .Select(x => x.SettingGroupContext) .FirstOrDefault(); diff --git a/src/WebExpress.WebCore/WebSettingPage/Model/SettingItemRegistry.cs b/src/WebExpress.WebCore/WebSettingPage/Model/SettingItemRegistry.cs new file mode 100644 index 0000000..2d0ecbb --- /dev/null +++ b/src/WebExpress.WebCore/WebSettingPage/Model/SettingItemRegistry.cs @@ -0,0 +1,160 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using WebExpress.WebCore.WebApplication; +using WebExpress.WebCore.WebPlugin; + +namespace WebExpress.WebCore.WebSettingPage.Model +{ + /// + /// Holds the items of the setting pages - categories, groups or pages - by plugin and + /// application. + /// + /// + /// The package scan adds and removes them on its own thread while requests build the setting + /// navigation, and a dictionary written during a read can throw or loop forever. Every member + /// therefore runs under one lock and returns a list taken under it; removing returns the + /// removed items, so the caller can announce them. + /// + /// The type of the items. + internal abstract class SettingItemRegistry + { + private readonly Dictionary>> _dict = []; + private readonly Lock _lock = new(); + + /// + /// Adds an item. + /// + /// The plugin context. + /// The application context. + /// The item. + /// Always true. + protected bool Add(IPluginContext pluginContext, IApplicationContext applicationContext, TItem item) + { + lock (_lock) + { + if (!_dict.TryGetValue(pluginContext, out var appDict)) + { + appDict = []; + _dict.Add(pluginContext, appDict); + } + + if (!appDict.TryGetValue(applicationContext, out var list)) + { + list = []; + appDict.Add(applicationContext, list); + } + + list.Add(item); + + return true; + } + } + + /// + /// Removes all items of a plugin. + /// + /// The plugin context. + /// The removed items. + public IReadOnlyList Remove(IPluginContext pluginContext) + { + lock (_lock) + { + return pluginContext is not null && _dict.Remove(pluginContext, out var appDict) + ? [.. appDict.Values.SelectMany(x => x)] + : []; + } + } + + /// + /// Removes all items of an application. + /// + /// The application context. + /// The removed items. + public IReadOnlyList Remove(IApplicationContext applicationContext) + { + var removed = new List(); + + if (applicationContext is null) + { + return removed; + } + + lock (_lock) + { + foreach (var (pluginContext, appDict) in _dict.ToList()) + { + if (appDict.Remove(applicationContext, out var list)) + { + removed.AddRange(list); + } + + if (appDict.Count == 0) + { + _dict.Remove(pluginContext); + } + } + } + + return removed; + } + + /// + /// Determines whether items of the plugin are registered. + /// + /// The plugin context. + /// True if the plugin is known. + public bool Contains(IPluginContext pluginContext) + { + lock (_lock) + { + return pluginContext is not null && _dict.ContainsKey(pluginContext); + } + } + + /// + /// Determines whether items of the application are registered. + /// + /// The application context. + /// True if the application is known. + public bool Contains(IApplicationContext applicationContext) + { + lock (_lock) + { + return applicationContext is not null && _dict.Values.Any(x => x.ContainsKey(applicationContext)); + } + } + + /// + /// Returns a copy of the items, optionally of one application only. + /// + /// The application context, or null for all. + /// The items. + protected List Items(IApplicationContext applicationContext = null) + { + lock (_lock) + { + return [.. _dict.Values + .SelectMany(x => x) + .Where(x => applicationContext is null || x.Key == applicationContext) + .SelectMany(x => x.Value)]; + } + } + + /// + /// Runs an operation on one item under the lock, for state the item carries itself. + /// + /// The type of the result. + /// Selects the item. + /// The operation, called with the item or its default. + /// The result of the operation. + protected TResult WithItem(Func predicate, Func operation) + { + lock (_lock) + { + return operation(_dict.Values.SelectMany(x => x.Values).SelectMany(x => x).FirstOrDefault(predicate)); + } + } + } +} diff --git a/src/WebExpress.WebCore/WebSettingPage/Model/SettingPageDictionary.cs b/src/WebExpress.WebCore/WebSettingPage/Model/SettingPageDictionary.cs index 35d22b1..1c585ab 100644 --- a/src/WebExpress.WebCore/WebSettingPage/Model/SettingPageDictionary.cs +++ b/src/WebExpress.WebCore/WebSettingPage/Model/SettingPageDictionary.cs @@ -4,24 +4,18 @@ using WebExpress.WebCore.WebApplication; using WebExpress.WebCore.WebComponent; using WebExpress.WebCore.WebEndpoint; -using WebExpress.WebCore.WebPlugin; namespace WebExpress.WebCore.WebSettingPage.Model { /// /// Represents a dictionary for managing setting pages, organized by plugin and application contexts. /// - internal class SettingPageDictionary + internal class SettingPageDictionary : SettingItemRegistry { - private readonly Dictionary>> _dict = []; - /// /// Gets the collection of setting pages. /// - public IEnumerable All => _dict.Values - .SelectMany(a => a.Values) - .SelectMany(x => x) - .Select(x => x.SettingPageContext); + public IEnumerable All => [.. Items().Select(x => x.SettingPageContext)]; /// /// Adds a settings page. @@ -30,58 +24,7 @@ internal class SettingPageDictionary /// True if the settings page was added successfully; otherwise, false. public bool AddSettingPageItem(SettingPageItem item) { - if (!_dict.TryGetValue(item.PluginContext, out var appDict)) - { - appDict = []; - _dict.Add(item.PluginContext, appDict); - } - - if (!appDict.TryGetValue(item.ApplicationContext, out var list)) - { - list = []; - appDict.Add(item.ApplicationContext, list); - } - - list.Add(item); - - return true; - } - - /// - /// Removes all elemets associated with the specified plugin context. - /// - /// The context of the plugin that contains the elemets to remove. - public void Remove(IPluginContext pluginContext) - { - _dict.Remove(pluginContext); - } - - /// - /// Removes all setting pages associated with the specified application context. - /// - /// The context of the application that contains the fragments to remove. - /// An enumerable collection of setting page contexts that were removed. - public IEnumerable Remove(IApplicationContext applicationContext) - { - if (applicationContext is null) - { - yield break; - } - - foreach (var pluginDict in _dict.Values) - { - var removed = pluginDict - .Where(x => x.Key == applicationContext) - .SelectMany(x => x.Value) - .ToList(); - - pluginDict.Remove(applicationContext); - - foreach (var page in removed) - { - yield return page.SettingPageContext; - } - } + return Add(item.PluginContext, item.ApplicationContext, item); } /// @@ -91,11 +34,9 @@ public IEnumerable Remove(IApplicationContext applicationCo /// An enumeration of setting page contextes. public IEnumerable GetSettingPages(Type settingPageType) { - return _dict.Values - .SelectMany(a => a.Values) - .SelectMany(x => x) + return [.. Items() .Where(x => x.SettingPageClass.Equals(settingPageType)) - .Select(x => x.SettingPageContext); + .Select(x => x.SettingPageContext)]; } /// @@ -106,68 +47,63 @@ public IEnumerable GetSettingPages(Type settingPageType) /// An enumeration of setting page contextes. public IEnumerable GetSettingPages(Type settingPageType, IApplicationContext applicationContext) { - return _dict.Values - .SelectMany(a => a) - .Where(a => a.Key.Equals(applicationContext)) - .SelectMany(x => x.Value) + return [.. Items(applicationContext) .Where(x => x.SettingPageClass.Equals(settingPageType)) - .Select(x => x.SettingPageContext); - } - - /// - /// Determines whether the dictionary contains the specified plugin context. - /// - /// The context of the plugin to locate in the dictionary. - /// True if the dictionary contains an element with the specified plugin context; otherwise, false. - public bool Contains(IPluginContext pluginContext) - { - return _dict.ContainsKey(pluginContext); - } - - /// - /// Determines whether the dictionary contains the specified apllication context. - /// - /// The context of the application to locate in the dictionary. - /// True if the dictionary contains an element with the specified application context; otherwise, false. - public bool Contains(IApplicationContext applicationContext) - { - return _dict.Values.Any(x => x.ContainsKey(applicationContext)); + .Select(x => x.SettingPageContext)]; } /// /// Creates a new setting page instance or returns an existing cached instance. /// + /// + /// The instance is created outside the lock, so a slow page constructor does not hold up + /// other requests; when two requests create a cached page at once, both use the one kept. + /// /// The context used for setting page creation. /// The central management hub for components. /// The context of the HTTP server. /// The created or cached setting page instance. public IEndpoint CreateSettingPageInstance(ISettingPageContext settingPageContext, IComponentHub componentHub, IHttpServerContext httpServerContext) { - var settingPageItem = _dict.Values - .SelectMany(a => a.Values) - .SelectMany(x => x) - .FirstOrDefault(x => x.SettingPageContext.Equals(settingPageContext)); + var settingPageItem = Items().FirstOrDefault(x => x.SettingPageContext.Equals(settingPageContext)); - if (settingPageItem is not null && settingPageItem.Instance is null) + if (settingPageItem is null) { - var instance = ComponentActivator.CreateInstance - ( - settingPageItem.SettingPageClass, - settingPageContext, - httpServerContext, - componentHub, - settingPageContext.ApplicationContext - ); + return null; + } - if (settingPageItem.Cache) - { - settingPageItem.Instance = instance; - } + var cached = WithItem(x => x == settingPageItem, x => x?.Instance); + + if (cached is not null) + { + return cached; + } + + var instance = ComponentActivator.CreateInstance + ( + settingPageItem.SettingPageClass, + settingPageContext, + httpServerContext, + componentHub, + settingPageContext.ApplicationContext + ); + if (!settingPageItem.Cache) + { return instance; } - return settingPageItem?.Instance; + return WithItem(x => x == settingPageItem, x => + { + if (x is null) + { + return instance; + } + + x.Instance ??= instance; + + return x.Instance; + }); } /// @@ -178,12 +114,9 @@ public IEndpoint CreateSettingPageInstance(ISettingPageContext settingPageContex /// An enumeration of setting page contexts. public IEnumerable GetSettingPages(IApplicationContext applicationContext, ISettingCategoryContext categoryContext) { - return _dict.Values - .SelectMany(a => a) - .Where(a => a.Key == applicationContext) - .SelectMany(x => x.Value) - .Where(x => x.SettingPageContext?.SettingCategory == categoryContext) - .Select(x => x.SettingPageContext); + return [.. Items(applicationContext) + .Where(x => x.SettingPageContext?.SettingCategory == categoryContext) + .Select(x => x.SettingPageContext)]; } /// @@ -194,12 +127,9 @@ public IEnumerable GetSettingPages(IApplicationContext appl /// An enumeration of setting page contexts. public IEnumerable GetSettingPages(IApplicationContext applicationContext, ISettingGroupContext groupContext) { - return _dict.Values - .SelectMany(a => a) - .Where(a => a.Key == applicationContext) - .SelectMany(x => x.Value) - .Where(x => x.SettingPageContext?.SettingGroup == groupContext) - .Select(x => x.SettingPageContext); + return [.. Items(applicationContext) + .Where(x => x.SettingPageContext?.SettingGroup == groupContext) + .Select(x => x.SettingPageContext)]; } } } diff --git a/src/WebExpress.WebCore/WebSettingPage/SettingPageManager.cs b/src/WebExpress.WebCore/WebSettingPage/SettingPageManager.cs index 2b34404..35e08c6 100644 --- a/src/WebExpress.WebCore/WebSettingPage/SettingPageManager.cs +++ b/src/WebExpress.WebCore/WebSettingPage/SettingPageManager.cs @@ -653,7 +653,15 @@ var attribute in settingPageType /// The context of the plugin that contains the elemets to remove. public void Remove(IPluginContext pluginContext) { - _pageDictionary.Remove(pluginContext); + // categories and groups go with their plugin, and every removed page is announced, so + // the endpoint registration drops the route of a setting page whose plugin is gone + _categoryDictionary.Remove(pluginContext); + _groupDictionary.Remove(pluginContext); + + foreach (var settingPageItem in _pageDictionary.Remove(pluginContext)) + { + OnRemoveSettingPage(settingPageItem.SettingPageContext); + } } /// @@ -662,9 +670,12 @@ public void Remove(IPluginContext pluginContext) /// The context of the application that contains the fragments to remove. internal void Remove(IApplicationContext applicationContext) { - foreach (var settingPageContext in _pageDictionary.Remove(applicationContext)) + _categoryDictionary.Remove(applicationContext); + _groupDictionary.Remove(applicationContext); + + foreach (var settingPageItem in _pageDictionary.Remove(applicationContext)) { - OnRemoveSettingPage(settingPageContext); + OnRemoveSettingPage(settingPageItem.SettingPageContext); } } From 2292f835342b7e8abcf3450de3e352552ba00412 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Schwarzer?= Date: Tue, 24 Nov 2026 22:31:59 +0100 Subject: [PATCH 10/16] fix: build the HTML tree iteratively with a nesting limit HTML reaches the parser from users (editor content, comments, the HTML to Markdown conversion). The parser recursed once per start tag, so a few hundred kilobytes of nested tags overflowed the stack and ended the server process. It now keeps an explicit stack of open elements; elements opened deeper than MaxNestingDepth (256) stay empty and their content becomes their siblings, which also bounds every renderer recursing through the tree. End tags follow the browser: one closes the innermost open element of its name and everything opened inside it, a stray one is ignored - it used to stop the parse and drop the rest of the document. The doctype check compared in place instead of searching the rest of the input on every " --- .../Html/Parser/UnitTestHtmlParserLimits.cs | 118 ++++++++++++++++++ .../WebHtml/Parser/HtmlParser.cs | 97 +++++++------- .../WebHtml/Parser/HtmlTokenizer.cs | 4 +- 3 files changed, 174 insertions(+), 45 deletions(-) create mode 100644 src/WebExpress.WebCore.Test/Html/Parser/UnitTestHtmlParserLimits.cs diff --git a/src/WebExpress.WebCore.Test/Html/Parser/UnitTestHtmlParserLimits.cs b/src/WebExpress.WebCore.Test/Html/Parser/UnitTestHtmlParserLimits.cs new file mode 100644 index 0000000..b00847b --- /dev/null +++ b/src/WebExpress.WebCore.Test/Html/Parser/UnitTestHtmlParserLimits.cs @@ -0,0 +1,118 @@ +using System.Diagnostics; +using System.Text; +using WebExpress.WebCore.WebHtml; +using WebExpress.WebCore.WebHtml.Parser; + +namespace WebExpress.WebCore.Test.Html.Parser +{ + /// + /// Tests that HTML from users cannot exhaust the stack or the processor of the server. A + /// stack overflow cannot be caught in .NET and ended the whole process. + /// + public class UnitTestHtmlParserLimits + { + private static readonly HtmlParser Parser = new(); + + /// + /// Verifies that deeply nested elements parse into a bounded tree that renders. + /// + [Fact] + public void DeepNestingIsBounded() + { + // arrange + var html = string.Concat(Enumerable.Repeat("
", 200_000)) + "deep" + string.Concat(Enumerable.Repeat("
", 200_000)); + + // act + var nodes = Parser.Parse(html); + var rendered = new StringBuilder(); + foreach (var node in nodes) + { + node.ToString(rendered, 0); + } + + // validation + Assert.True(Depth(nodes) <= HtmlParser.MaxNestingDepth + 1); + Assert.Contains("deep", rendered.ToString()); + } + + /// + /// Verifies that nesting below the limit keeps its structure. + /// + [Fact] + public void ShallowNestingKeepsItsStructure() + { + // act + var nodes = Parser.Parse("

x

"); + + // validation + var div = Assert.IsType(Assert.Single(nodes)); + var p = Assert.IsType(Assert.Single(div.Elements)); + Assert.Single(p.Elements); + } + + /// + /// Verifies that a stray end tag is ignored instead of ending the parse; it dropped the + /// rest of the document. + /// + [Fact] + public void StrayEndTagIsIgnored() + { + // act + var nodes = Parser.Parse("

a

b

"); + + // validation + Assert.Equal(2, nodes.OfType().Count()); + } + + /// + /// Verifies that an end tag closes the elements opened inside the element it names. + /// + [Fact] + public void EndTagClosesTheElementsInside() + { + // act + var nodes = Parser.Parse("
a

b

"); + + // validation + Assert.IsType(nodes[0]); + Assert.IsType(nodes[1]); + } + + /// + /// Verifies that a document full of unknown bang constructs is tokenized in linear time; + /// every "<!" searched the rest of the input for a doctype. + /// + [Fact] + public void BangConstructsAreLinear() + { + // arrange + var html = string.Concat(Enumerable.Repeat("", 400_000)); + var watch = Stopwatch.StartNew(); + + // act + Parser.Parse(html); + + // validation + Assert.True(watch.Elapsed < TimeSpan.FromSeconds(10), $"took {watch.Elapsed}"); + } + + /// + /// Measures the depth of a node tree without recursion. + /// + /// The top-level nodes. + /// The number of levels. + private static int Depth(IEnumerable nodes) + { + var depth = 0; + var level = nodes.ToList(); + + while (level.Count > 0) + { + depth++; + level = [.. level.OfType().SelectMany(x => x.Elements)]; + } + + return depth; + } + } +} diff --git a/src/WebExpress.WebCore/WebHtml/Parser/HtmlParser.cs b/src/WebExpress.WebCore/WebHtml/Parser/HtmlParser.cs index a3567f5..878ca4b 100644 --- a/src/WebExpress.WebCore/WebHtml/Parser/HtmlParser.cs +++ b/src/WebExpress.WebCore/WebHtml/Parser/HtmlParser.cs @@ -18,6 +18,12 @@ namespace WebExpress.WebCore.WebHtml.Parser /// public class HtmlParser { + /// + /// The deepest nesting of elements the parser builds; deeper elements are kept without + /// content and their content becomes their siblings. + /// + public const int MaxNestingDepth = 256; + // ------------------------------------------------------------------ // Public entry points // ------------------------------------------------------------------ @@ -52,7 +58,6 @@ public IReadOnlyList Parse(string html) /// The first top-level , or null if the /// input produces no nodes. /// - /// Thrown when is null. public IHtmlNode ParseSingle(string html) { var nodes = Parse(html); @@ -63,90 +68,94 @@ public IHtmlNode ParseSingle(string html) // Core parsing logic // ------------------------------------------------------------------ - private IReadOnlyList ParseTokens(IReadOnlyList tokens) + /// + /// Builds the node tree from the token stream with an explicit stack of open elements. + /// + /// + /// The tree used to be built by a recursive call per start tag. HTML reaches the parser + /// from users - pasted into the editor, stored as a comment, converted to Markdown - and a + /// few hundred kilobytes of nested tags exhausted the stack; a stack overflow cannot be + /// caught in .NET and ended the server process. An element opened deeper than + /// is kept as an empty element, its content becoming its + /// siblings, so every renderer that recurses through the tree stays bounded as well. + /// + /// An end tag closes the innermost open element of its name together with everything + /// opened inside it, as a browser does; an end tag without an open element of its name is + /// ignored. A stray end tag used to stop the parse and drop the rest of the document. + /// + /// The token stream. + /// The top-level nodes. + private static List ParseTokens(IReadOnlyList tokens) { - var index = 0; var roots = new List(); + var open = new List<(HtmlElement Element, string TagName, List Children)>(); - ParseNodes(tokens, ref index, null, roots); + List Target() => open.Count > 0 ? open[^1].Children : roots; - return roots; - } - - /// - /// Recursively consumes tokens and appends the resulting nodes to - /// . Parsing stops when an end tag matching - /// is found or the stream ends. - /// - private void ParseNodes( - IReadOnlyList tokens, - ref int index, - string parentTagName, - List target) - { - while (index < tokens.Count) + void Close(int count) { - var token = tokens[index]; + for (var i = 0; i < count; i++) + { + var (element, _, children) = open[^1]; + open.RemoveAt(open.Count - 1); + element.Add([.. children]); + } + } + foreach (var token in tokens) + { switch (token.Type) { case HtmlTokenType.EndOfFile: - return; + Close(open.Count); + return roots; case HtmlTokenType.Doctype: - index++; // DOCTYPE tokens are informational; no node is emitted. break; case HtmlTokenType.Comment: - index++; - target.Add(new HtmlComment(token.Value)); + Target().Add(new HtmlComment(token.Value)); break; case HtmlTokenType.Text: - index++; - var textValue = token.Value; - if (!string.IsNullOrEmpty(textValue)) + if (!string.IsNullOrEmpty(token.Value)) { - target.Add(new HtmlText(textValue)); + Target().Add(new HtmlText(token.Value)); } break; case HtmlTokenType.SelfClosingTag: - index++; var selfClosing = HtmlElementFactory.Create(token.TagName); ApplyAttributes(selfClosing, token.Attributes); - target.Add(selfClosing); + Target().Add(selfClosing); break; case HtmlTokenType.StartTag: - index++; var element = HtmlElementFactory.Create(token.TagName); ApplyAttributes(element, token.Attributes); + Target().Add(element); - if (element.CloseTag) + if (element.CloseTag && open.Count < MaxNestingDepth) { - var children = new List(); - ParseNodes(tokens, ref index, token.TagName, children); - element.Add(children.ToArray()); + open.Add((element, token.TagName, [])); } - - target.Add(element); break; case HtmlTokenType.EndTag: - if (string.Equals(token.TagName, parentTagName, StringComparison.OrdinalIgnoreCase)) + var index = open.FindLastIndex(x => string.Equals(x.TagName, token.TagName, StringComparison.OrdinalIgnoreCase)); + + if (index >= 0) { - index++; // consume the matching end tag + Close(open.Count - index); } - // If it doesn't match our parent, stop and let the caller handle it. - return; - - default: - index++; break; } } + + Close(open.Count); + + return roots; } // ------------------------------------------------------------------ diff --git a/src/WebExpress.WebCore/WebHtml/Parser/HtmlTokenizer.cs b/src/WebExpress.WebCore/WebHtml/Parser/HtmlTokenizer.cs index 65faf6c..8b2ba6e 100644 --- a/src/WebExpress.WebCore/WebHtml/Parser/HtmlTokenizer.cs +++ b/src/WebExpress.WebCore/WebHtml/Parser/HtmlTokenizer.cs @@ -158,7 +158,9 @@ private HtmlToken ReadBangToken(int start) return ReadComment(); } - if (_input.IndexOf("DOCTYPE", _position, StringComparison.OrdinalIgnoreCase) == _position) + // compared in place: searching the rest of the input for "DOCTYPE" on every " Date: Tue, 24 Nov 2026 22:46:17 +0100 Subject: [PATCH 11/16] fix!: encode text nodes, titles and status messages; parse HTML like a browser MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit BREAKING CHANGE: HtmlText now HTML-encodes its value (&, <, >). It used to be written verbatim and left the encoding to more than a hundred callers; any that forgot turned user input into script. Markup a caller trusts goes through HtmlRaw. An element holding only text took a shortcut that appended the combined values raw; it encodes them as well. The page title ( in a record name) and the HTML comment text (a "--" could end the comment) are encoded too. BREAKING CHANGE: a StatusMessage is plain text. Every response writes it through StatusMessage.ToHtml, encoded with its line breaks kept; HttpServer describes exceptions as text instead of an HTML fragment and its built-in status page encodes the message. The parser stores text decoded (so a document round-trips with its entities), keeps the content of raw text elements raw, and drops elements and attributes whose names could not be written back safely; the writer refuses such attribute names as well. The tokenizer treats only the five HTML whitespace characters as separators - U+00A0 split "", one inert element to a browser, into an image with an event handler - and ends comments at "--!>", "" and "" like a browser, so markup the browser renders can no longer hide in a comment from whatever reads the parsed tree. Co-Authored-By: Claude Opus 5.5 --- .../Html/UnitTestHtmlEncoding.cs | 184 ++++++++++++++++++ .../Message/UnitTestResponseUnauthorized.cs | 6 +- src/WebExpress.WebCore/HttpServer.cs | 36 ++-- .../WebApplication/RootEndpoint.cs | 10 +- src/WebExpress.WebCore/WebHtml/HtmlComment.cs | 4 +- src/WebExpress.WebCore/WebHtml/HtmlElement.cs | 11 +- .../WebHtml/HtmlElementMetadataTitle.cs | 4 +- src/WebExpress.WebCore/WebHtml/HtmlName.cs | 63 ++++++ src/WebExpress.WebCore/WebHtml/HtmlText.cs | 38 +++- .../WebHtml/Parser/HtmlParser.cs | 29 ++- .../WebHtml/Parser/HtmlTokenizer.cs | 42 +++- .../WebMessage/ResponseBadGateway.cs | 2 +- .../WebMessage/ResponseBadRequest.cs | 2 +- .../WebMessage/ResponseConflict.cs | 2 +- .../WebMessage/ResponseForbidden.cs | 2 +- .../WebMessage/ResponseGatewayTimeout.cs | 2 +- .../WebMessage/ResponseGone.cs | 2 +- .../ResponseHttpVersionNotSupported.cs | 2 +- .../WebMessage/ResponseInternalServerError.cs | 2 +- .../WebMessage/ResponseLengthRequired.cs | 2 +- .../WebMessage/ResponseMethodNotAllowed.cs | 2 +- .../WebMessage/ResponseMovedPermanently.cs | 2 +- .../WebMessage/ResponseNotAcceptable.cs | 2 +- .../WebMessage/ResponseNotFound.cs | 2 +- .../WebMessage/ResponseNotImplemented.cs | 2 +- .../WebMessage/ResponsePayloadTooLarge.cs | 4 +- .../ResponsePreconditionRequired.cs | 2 +- .../WebMessage/ResponseRequestTimeout.cs | 2 +- .../WebMessage/ResponseServiceUnavailable.cs | 2 +- .../WebMessage/ResponseTooManyRequests.cs | 2 +- .../WebMessage/ResponseUnauthorized.cs | 4 +- .../WebMessage/ResponseUnprocessableEntity.cs | 2 +- .../ResponseUnsupportedMediaType.cs | 2 +- .../WebMessage/ResponseUpgradeRequired.cs | 2 +- .../WebStatusPage/StatusMessage.cs | 40 +++- 35 files changed, 446 insertions(+), 71 deletions(-) create mode 100644 src/WebExpress.WebCore.Test/Html/UnitTestHtmlEncoding.cs create mode 100644 src/WebExpress.WebCore/WebHtml/HtmlName.cs diff --git a/src/WebExpress.WebCore.Test/Html/UnitTestHtmlEncoding.cs b/src/WebExpress.WebCore.Test/Html/UnitTestHtmlEncoding.cs new file mode 100644 index 0000000..8d97a9b --- /dev/null +++ b/src/WebExpress.WebCore.Test/Html/UnitTestHtmlEncoding.cs @@ -0,0 +1,184 @@ +using System.Text; +using WebExpress.WebCore.WebHtml; +using WebExpress.WebCore.WebHtml.Parser; +using WebExpress.WebCore.WebStatusPage; + +namespace WebExpress.WebCore.Test.Html +{ + /// + /// Tests that text written through the html classes cannot become markup, and that markup read + /// by the parser is written back as the browser read it. + /// + public class UnitTestHtmlEncoding + { + private static readonly HtmlParser Parser = new(); + + /// + /// Renders nodes the way a page writes them. + /// + /// The nodes. + /// The markup. + private static string Render(params IHtmlNode[] nodes) + { + var builder = new StringBuilder(); + foreach (var node in nodes) + { + node.ToString(builder, 0); + } + + return builder.ToString(); + } + + /// + /// Verifies that a text node is encoded, alone and inside an element that holds only text. + /// + [Fact] + public void TextIsEncoded() + { + // act + var alone = Render(new HtmlText(" & co")); + var inside = Render(new HtmlElementTextContentP("")); + + // validation + Assert.Equal("<script>alert(1)</script> & co", alone); + Assert.Contains("<img src=x onerror=alert(1)>", inside); + Assert.DoesNotContain(" + /// Verifies that markup the caller trusts is still written as it is through HtmlRaw. + ///
+ [Fact] + public void RawIsWrittenAsItIs() + { + Assert.Equal("x", Render(new HtmlRaw("x"))); + } + + /// + /// Verifies that the title of a page is encoded; a record a user named could close the + /// title and open a script. + /// + [Fact] + public void TitleIsEncoded() + { + // act + var html = Render(new HtmlElementMetadataTitle("")); + + // validation + Assert.DoesNotContain("")); + + // validation + Assert.DoesNotContain("-->x", "x")] + [InlineData("", "")] + [InlineData("x", "x")] + [InlineData("x", "x")] + [InlineData("x", "x")] + [InlineData("r", "r")] + [InlineData("
d
", "
d
")] + [InlineData("", "")] + [InlineData("text", "text")] + [InlineData("a < b & c", "a < b & c")] + public void Sanitize(string html, string expected) + { + Assert.Equal(expected, HtmlSanitizer.Sanitize(html)); + } + + /// + /// Verifies the link and image address policy. + /// + [Fact] + public void UrlPolicyAllowsOnlyKnownSchemes() + { + Assert.True(UrlPolicy.IsSafeLink("https://example.com")); + Assert.True(UrlPolicy.IsSafeLink("relative/path")); + Assert.False(UrlPolicy.IsSafeLink(" JavaScript:alert(1)")); + Assert.False(UrlPolicy.IsSafeLink("data:text/html,:c\"|?*.txt", "abc.txt")] + [InlineData("", "file")] + [InlineData(null, "file")] + public void FileNameIsPlain(string declared, string expected) + { + Assert.Equal(expected, Request.SafeFileName(declared)); + } + + /// + /// Verifies that a declared content type is kept only in the form type/subtype. + /// + /// The declared type. + /// The type kept. + [Theory] + [InlineData("image/PNG", "image/png")] + [InlineData("text/plain; charset=utf-8", "text/plain")] + [InlineData("text/html\r\nX-Injected: 1", "application/octet-stream")] + [InlineData("