diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json new file mode 100644 index 0000000..074c30e --- /dev/null +++ b/.config/dotnet-tools.json @@ -0,0 +1,13 @@ +{ + "version": 1, + "isRoot": true, + "tools": { + "dotnet-reportgenerator-globaltool": { + "version": "5.5.11", + "commands": [ + "reportgenerator" + ], + "rollForward": false + } + } +} \ No newline at end of file diff --git a/.editorconfig b/.editorconfig index 45b142a..762b5db 100644 --- a/.editorconfig +++ b/.editorconfig @@ -5,3 +5,108 @@ dotnet_diagnostic.CS1570.severity = silent # CS1591: Fehledes XML-Kommentar für öffentlich sichtbaren Typ oder Element dotnet_diagnostic.CS1591.severity = silent + +[MaxLib.WebServer/**.cs] + +# CA1805: Do not initialize unnecessarily +dotnet_diagnostic.CA1805.severity = error + +# CA1507: Use nameof to express symbol names +dotnet_diagnostic.CA1507.severity = error + +# CA1510: Use ArgumentNullException throw helper +dotnet_diagnostic.CA1510.severity = error + +# CA1512: Use ArgumentOutOfRangeException throw helper +dotnet_diagnostic.CA1512.severity = error + +# CA1513: Use ObjectDisposedException throw helper +dotnet_diagnostic.CA1513.severity = error + +# CA2208: Instantiate argument exceptions correctly +dotnet_diagnostic.CA2208.severity = error + +# CA1816: Dispose methods should call SuppressFinalize +dotnet_diagnostic.CA1816.severity = error + +# CA2000: Dispose objects before losing scope +dotnet_diagnostic.CA2000.severity = error + +# CA1062: Validate arguments of public methods +dotnet_diagnostic.CA1062.severity = error + +# CA1307: Specify StringComparison for clarity +dotnet_diagnostic.CA1307.severity = error + +# CA1310: Specify StringComparison for correctness +dotnet_diagnostic.CA1310.severity = error + +# CA1309: Use ordinal string comparison +dotnet_diagnostic.CA1309.severity = error + +# CA1866: Use the 'StringComparison.Ordinal' char overload +dotnet_diagnostic.CA1866.severity = error + +# CA1834: Use StringBuilder.Append(char) for single-character string literals +dotnet_diagnostic.CA1834.severity = error + +# CA1820: Test for empty strings using string length instead of Equals("") +dotnet_diagnostic.CA1820.severity = error + +# CA1304: Specify CultureInfo +dotnet_diagnostic.CA1304.severity = error + +# CA1862: Use the 'StringComparison' method overloads for case-insensitive comparisons +dotnet_diagnostic.CA1862.severity = error + +# CA1311: Specify a culture or use an invariant version to avoid implicit dependency on current culture +dotnet_diagnostic.CA1311.severity = error + +# CA1305: Specify IFormatProvider +dotnet_diagnostic.CA1305.severity = error + +# CA2007: Consider calling ConfigureAwait on the awaited task +dotnet_diagnostic.CA2007.severity = error + +# CA1849: Call async methods when in an async method +dotnet_diagnostic.CA1849.severity = error + +# CA1861: Avoid constant arrays as arguments +dotnet_diagnostic.CA1861.severity = error + +# CA1825: Avoid zero-length array allocations +dotnet_diagnostic.CA1825.severity = error + +# CA1864: Prefer the 'TryAdd' method +dotnet_diagnostic.CA1864.severity = error + +# CA1868: Unnecessary call to 'Contains' for 'HashSet'/dictionary/list before Add/Remove +dotnet_diagnostic.CA1868.severity = error + +# CA1822: Mark members as static +dotnet_diagnostic.CA1822.severity = error + +# CA1844: Provide memory-based overrides of async methods when subclassing 'Stream' +dotnet_diagnostic.CA1844.severity = error + +# CA1835: Prefer the memory-based overloads for 'ReadAsync'/'WriteAsync' +dotnet_diagnostic.CA1835.severity = error + +# IDE0300: Use collection expression for array +dotnet_diagnostic.IDE0300.severity = error + +# IDE0301: Use collection expression for empty +dotnet_diagnostic.IDE0301.severity = error + +# IDE0057: Use range operator +dotnet_diagnostic.IDE0057.severity = error + +# SYSLIB1045: Use 'GeneratedRegexAttribute' to generate the regular expression +# implementation at compile-time +dotnet_diagnostic.SYSLIB1045.severity = error + +# IDE0038: Use pattern matching to avoid 'is' check followed by a cast +dotnet_diagnostic.IDE0038.severity = error + +# IDE0005: Remove unnecessary usings/imports +dotnet_diagnostic.IDE0005.severity = error diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index f7857c9..4ba97e2 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -10,15 +10,19 @@ jobs: build: runs-on: ubuntu-latest + timeout-minutes: 20 + permissions: + contents: read + statuses: write steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 - name: Setup .NET Core - uses: actions/setup-dotnet@v1 + uses: actions/setup-dotnet@v4 with: dotnet-version: | + 10.0 8.0 - 6.0.102 - name: Install dependencies run: dotnet restore - name: Build @@ -30,10 +34,41 @@ jobs: name: build-fail-artifact path: ${{ github.workspace }} - name: Test - run: dotnet test --no-restore + run: dotnet test --configuration Release --no-build --collect:"XPlat Code Coverage" --results-directory ./TestResults - name: Upload Test Fail Artifacts uses: actions/upload-artifact@v4 if: failure() with: name: test-fail-artifact path: ${{ github.workspace }} + - name: Restore .NET tools + run: dotnet tool restore + - name: Generate coverage report + run: > + dotnet tool run reportgenerator + "-reports:./TestResults/**/coverage.cobertura.xml" + -targetdir:./coveragereport + -reporttypes:"Html;MarkdownSummaryGithub;Badges;JsonSummary" + "-classfilters:+*;-System.Text.RegularExpressions.Generated*" + - name: Publish coverage summary + run: cat ./coveragereport/SummaryGithub.md >> "$GITHUB_STEP_SUMMARY" + - name: Upload coverage report + uses: actions/upload-artifact@v4 + with: + name: coverage-report + path: coveragereport + - name: Set coverage commit status + # GITHUB_TOKEN is read-only for pull_request events from forks, so this + # write would fail there regardless of the `statuses: write` permission above. + if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository + env: + GH_TOKEN: ${{ github.token }} + run: | + LINE_COV=$(jq -r '.summary.linecoverage' ./coveragereport/Summary.json) + BRANCH_COV=$(jq -r '.summary.branchcoverage' ./coveragereport/Summary.json) + SHA="${{ github.event.pull_request.head.sha || github.sha }}" + gh api "repos/${{ github.repository }}/statuses/$SHA" \ + -f state=success \ + -f context="coverage" \ + -f description="Line: ${LINE_COV}% · Branch: ${BRANCH_COV}%" \ + -f target_url="${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}" diff --git a/.github/workflows/nuget.yml b/.github/workflows/nuget.yml index 8a1c127..19f6315 100644 --- a/.github/workflows/nuget.yml +++ b/.github/workflows/nuget.yml @@ -1,28 +1,122 @@ -name: NuGet Publish +name: Release + +# Release process: +# 1. Bump in MaxLib.WebServer/MaxLib.WebServer.csproj.include and push/merge to main +# 2. This workflow builds and tests the solution +# 3. It tags the commit as vX.Y.Z +# 4. It packs and publishes the package to NuGet.org +# 5. It creates a matching GitHub release +# +# Any other push to main (that doesn't change the version) only runs the +# check-version job and stops there - no tag, package or release is created. on: push: branches: [ main ] +concurrency: + group: release-${{ github.ref }} + cancel-in-progress: false + +permissions: + contents: read + jobs: - build: + check-version: runs-on: ubuntu-latest + timeout-minutes: 5 + outputs: + changed: ${{ steps.diff.outputs.changed }} + version: ${{ steps.diff.outputs.version }} steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Check if package version changed + id: diff + run: | + FILE=MaxLib.WebServer/MaxLib.WebServer.csproj.include + BEFORE_SHA="${{ github.event.before }}" + + NEW=$(grep -oP '(?<=)[^<]+' "$FILE" | head -1) + + OLD="" + if [ -n "$BEFORE_SHA" ] && [ "$BEFORE_SHA" != "0000000000000000000000000000000000000000" ] && git cat-file -e "$BEFORE_SHA" 2>/dev/null; then + OLD=$(git show "$BEFORE_SHA:$FILE" 2>/dev/null | grep -oP '(?<=)[^<]+' | head -1 || true) + fi + + echo "Previous version: '$OLD', new version: '$NEW'" + if [ -n "$NEW" ] && [ "$NEW" != "$OLD" ]; then + echo "changed=true" >> "$GITHUB_OUTPUT" + else + echo "changed=false" >> "$GITHUB_OUTPUT" + fi + echo "version=$NEW" >> "$GITHUB_OUTPUT" + + release: + needs: check-version + if: needs.check-version.outputs.changed == 'true' + runs-on: ubuntu-latest + timeout-minutes: 20 + permissions: + contents: write + id-token: write # enable GitHub OIDC token issuance for this job - - name: Init git submodules - run: git submodule init && git submodule update + steps: + - uses: actions/checkout@v4 - - name: Setup .NET Core - uses: actions/setup-dotnet@v1 + - name: Setup .NET + uses: actions/setup-dotnet@v4 with: - dotnet-version: '8.0' + dotnet-version: | + 10.0 + 8.0 + - name: Install dependencies run: dotnet restore + - name: Build + run: dotnet build --configuration Release --no-restore + + - name: Test + run: dotnet test --configuration Release --no-restore --no-build + - name: Create NuGet package - run: dotnet pack MaxLib.WebServer/MaxLib.WebServer.csproj + run: dotnet pack MaxLib.WebServer/MaxLib.WebServer.csproj --configuration Release --no-build --output ./nupkg + + - name: Tag release + env: + VERSION: ${{ needs.check-version.outputs.version }} + run: | + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + if git ls-remote --exit-code --tags origin "refs/tags/v$VERSION" >/dev/null 2>&1; then + echo "Tag v$VERSION already exists, skipping" + else + git tag "v$VERSION" + git push origin "v$VERSION" + fi + + - name: NuGet login (OIDC -> temp API key) + uses: NuGet/login@v1 + id: login + with: + user: ${{ secrets.NUGET_USER }} - name: Publish to NuGet.org - run: dotnet nuget push "**/*.nupkg" --api-key ${{ secrets.NUGET_PUSH_KEY }} --source "https://api.nuget.org/v3/index.json" + run: dotnet nuget push "./nupkg/*.nupkg" --api-key ${{ steps.login.outputs.NUGET_API_KEY }} --source "https://api.nuget.org/v3/index.json" --skip-duplicate + + - name: Create GitHub release + env: + GH_TOKEN: ${{ github.token }} + VERSION: ${{ needs.check-version.outputs.version }} + run: | + if gh release view "v$VERSION" >/dev/null 2>&1; then + echo "Release v$VERSION already exists, skipping" + else + gh release create "v$VERSION" ./nupkg/*.nupkg \ + --title "v$VERSION" \ + --generate-notes + fi diff --git a/.gitignore b/.gitignore index 0375a1d..51cb712 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ bin obj TestResults +coveragereport # vscode files .vscode # under development diff --git a/MaxLib.WebServer.sln b/MaxLib.WebServer.sln index 4533fcc..de4cbb1 100644 --- a/MaxLib.WebServer.sln +++ b/MaxLib.WebServer.sln @@ -18,6 +18,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution .editorconfig = .editorconfig EndProjectSection EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MaxLib.WebServer.Builder.Debugger.Example", "example\MaxLib.WebServer.Builder.Debugger.Example\MaxLib.WebServer.Builder.Debugger.Example.csproj", "{C1C6D975-A634-409F-87DE-521A45DF775F}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -76,6 +78,18 @@ Global {01C302FF-8E99-4D54-8234-D4BA59862176}.Release|x64.Build.0 = Release|Any CPU {01C302FF-8E99-4D54-8234-D4BA59862176}.Release|x86.ActiveCfg = Release|Any CPU {01C302FF-8E99-4D54-8234-D4BA59862176}.Release|x86.Build.0 = Release|Any CPU + {C1C6D975-A634-409F-87DE-521A45DF775F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C1C6D975-A634-409F-87DE-521A45DF775F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C1C6D975-A634-409F-87DE-521A45DF775F}.Debug|x64.ActiveCfg = Debug|Any CPU + {C1C6D975-A634-409F-87DE-521A45DF775F}.Debug|x64.Build.0 = Debug|Any CPU + {C1C6D975-A634-409F-87DE-521A45DF775F}.Debug|x86.ActiveCfg = Debug|Any CPU + {C1C6D975-A634-409F-87DE-521A45DF775F}.Debug|x86.Build.0 = Debug|Any CPU + {C1C6D975-A634-409F-87DE-521A45DF775F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C1C6D975-A634-409F-87DE-521A45DF775F}.Release|Any CPU.Build.0 = Release|Any CPU + {C1C6D975-A634-409F-87DE-521A45DF775F}.Release|x64.ActiveCfg = Release|Any CPU + {C1C6D975-A634-409F-87DE-521A45DF775F}.Release|x64.Build.0 = Release|Any CPU + {C1C6D975-A634-409F-87DE-521A45DF775F}.Release|x86.ActiveCfg = Release|Any CPU + {C1C6D975-A634-409F-87DE-521A45DF775F}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -83,6 +97,7 @@ Global GlobalSection(NestedProjects) = preSolution {6616448A-1AD7-4897-9124-F1560FB12461} = {39740782-6F07-470C-92B8-C0A07A5C0DFB} {01C302FF-8E99-4D54-8234-D4BA59862176} = {39740782-6F07-470C-92B8-C0A07A5C0DFB} + {C1C6D975-A634-409F-87DE-521A45DF775F} = {39740782-6F07-470C-92B8-C0A07A5C0DFB} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {E8A0EB3B-E5B8-4120-92DD-1C11CEE7017F} diff --git a/MaxLib.WebServer/Api/ApiService.cs b/MaxLib.WebServer/Api/ApiService.cs deleted file mode 100644 index 3c727fb..0000000 --- a/MaxLib.WebServer/Api/ApiService.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System; -using System.Threading.Tasks; - -#nullable enable - -namespace MaxLib.WebServer.Api -{ - [Obsolete("The ApiService and the RestApiService classes are no longer maintained and will be removed in a future update. Use the Builder system instead.")] - public abstract class ApiService : WebService - { - public ApiService(params string[] endpoint) - : base(ServerStage.CreateDocument) - { - this.endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); - } - - private string[] endpoint; - public string[] Endpoint - { - get => endpoint; - set => endpoint = value ?? throw new ArgumentNullException(nameof(Endpoint)); - } - - public bool IgnoreCase { get; set; } - - protected abstract Task HandleRequest(WebProgressTask task, string[] location); - - public override bool CanWorkWith(WebProgressTask task) - { - _ = task ?? throw new ArgumentNullException(nameof(task)); - return task.Request.Location.StartsUrlWith(endpoint, IgnoreCase); - } - - public override async Task ProgressTask(WebProgressTask task) - { - _ = task ?? throw new ArgumentNullException(nameof(task)); - var tiles = task.Request.Location.DocumentPathTiles; - var location = new string[tiles.Length - endpoint.Length]; - Array.Copy(tiles, endpoint.Length, location, 0, location.Length); - var data = await HandleRequest(task, location).ConfigureAwait(false); - if (data != null) - task.Document.DataSources.Add(data); - else task.Response.StatusCode = HttpStateCode.InternalServerError; - } - } -} diff --git a/MaxLib.WebServer/Api/Rest/ApiGetRule.cs b/MaxLib.WebServer/Api/Rest/ApiGetRule.cs deleted file mode 100644 index 08ee9d4..0000000 --- a/MaxLib.WebServer/Api/Rest/ApiGetRule.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; - -#nullable enable - -namespace MaxLib.WebServer.Api.Rest -{ - [Obsolete("The ApiService and the RestApiService classes are no longer maintained and will be removed in a future update. Use the Builder system instead.")] - public abstract class ApiGetRule : ApiRule - { - private string? key; - public string? Key - { - get => key; - set => key = value ?? throw new ArgumentNullException(nameof(Key)); - } - } -} diff --git a/MaxLib.WebServer/Api/Rest/ApiLocationRule.cs b/MaxLib.WebServer/Api/Rest/ApiLocationRule.cs deleted file mode 100644 index 55990e5..0000000 --- a/MaxLib.WebServer/Api/Rest/ApiLocationRule.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; - -#nullable enable - -namespace MaxLib.WebServer.Api.Rest -{ - [Obsolete("The ApiService and the RestApiService classes are no longer maintained and will be removed in a future update. Use the Builder system instead.")] - public abstract class ApiLocationRule : ApiRule - { - private int index = 0; - public int Index - { - get => index; - set - { - if (value < 0) - throw new ArgumentOutOfRangeException(nameof(Index)); - index = value; - } - } - } -} diff --git a/MaxLib.WebServer/Api/Rest/ApiRule.cs b/MaxLib.WebServer/Api/Rest/ApiRule.cs deleted file mode 100644 index b10341d..0000000 --- a/MaxLib.WebServer/Api/Rest/ApiRule.cs +++ /dev/null @@ -1,14 +0,0 @@ -#nullable enable - -using System; - -namespace MaxLib.WebServer.Api.Rest -{ - [Obsolete("The ApiService and the RestApiService classes are no longer maintained and will be removed in a future update. Use the Builder system instead.")] - public abstract class ApiRule - { - public bool Required { get; set; } = true; - - public abstract bool Check(RestQueryArgs args); - } -} diff --git a/MaxLib.WebServer/Api/Rest/ApiRuleFactory.cs b/MaxLib.WebServer/Api/Rest/ApiRuleFactory.cs deleted file mode 100644 index dff097e..0000000 --- a/MaxLib.WebServer/Api/Rest/ApiRuleFactory.cs +++ /dev/null @@ -1,323 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -#nullable enable - -namespace MaxLib.WebServer.Api.Rest -{ - [Obsolete("The ApiService and the RestApiService classes are no longer maintained and will be removed in a future update. Use the Builder system instead.")] - public class ApiRuleFactory - { - public class HostRule : ApiRule - { - public string? Key { get; set; } - - public string? Host { get; set; } - - public bool EndsWith { get; set; } - - public override bool Check(RestQueryArgs args) - { - _ = args ?? throw new ArgumentNullException(nameof(args)); - var success = Host is null ? true - : EndsWith - ? args.Host.EndsWith(Host, StringComparison.InvariantCultureIgnoreCase) - : string.Equals(Host, args.Host, StringComparison.InvariantCultureIgnoreCase); - if (success && Key != null) - args.ParsedArguments[Key] = args.Host; - return success; - } - } - - public class UrlConstantRule : ApiLocationRule - { - public string? Constant { get; set; } - - public bool IgnoreCase { get; set; } = false; - - public override bool Check(RestQueryArgs args) - { - _ = args ?? throw new ArgumentNullException(nameof(args)); - if (args.Location.Length <= Index || Constant is null) - return false; - var comparison = IgnoreCase ? StringComparison.InvariantCultureIgnoreCase : StringComparison.InvariantCulture; - return string.Equals(Constant, args.Location[Index], comparison); - } - } - - public class UrlArgumentRule : ApiLocationRule - { - public delegate bool ParseArgumentHandle(string variable, out T value); - - public ParseArgumentHandle? ParseArgument { get; set; } - - public string? Key { get; set; } - - public override bool Check(RestQueryArgs args) - { - _ = args ?? throw new ArgumentNullException(nameof(args)); - if (args.Location.Length <= Index) - return false; - if (ParseArgument == null) - return false; - if (!ParseArgument(args.Location[Index], out T value)) - return false; - if (Key != null) - args.ParsedArguments[Key] = value; - return true; - } - } - - public class MaxLengthRule : ApiLocationRule - { - public override bool Check(RestQueryArgs args) - { - _ = args ?? throw new ArgumentNullException(nameof(args)); - return args.Location.Length <= Index; - } - } - - public class KeyExistsRule : ApiGetRule - { - public override bool Check(RestQueryArgs args) - { - _ = args ?? throw new ArgumentNullException(nameof(args)); - return Key != null && args.GetArgs.ContainsKey(Key); - } - } - - public class GetArgumentRule : ApiGetRule - { - public delegate bool ParseArgumentHandle(string variable, out T value); - - public ParseArgumentHandle? ParseArgument { get; set; } - - public override bool Check(RestQueryArgs args) - { - _ = args ?? throw new ArgumentNullException(nameof(args)); - if (Key == null || !args.GetArgs.TryGetValue(Key, out string? strValue)) - return false; - if (ParseArgument == null) - return false; - if (!ParseArgument(strValue, out T value)) - return false; - args.ParsedArguments[Key] = value; - return true; - } - } - - public class GroupRule : ApiRule - { - public List Rules { get; } = new List(); - - public override bool Check(RestQueryArgs args) - { - _ = args ?? throw new ArgumentNullException(nameof(args)); - foreach (var rule in Rules) - { - if (rule == null) - continue; - var success = rule.Check(args); - if (!success && rule.Required) - return false; - } - return true; - } - } - - public class ConditionalRule : ApiRule - { - public ApiRule? Condition { get; set; } - - public ApiRule? Success { get; set; } - - public ApiRule? Fail { get; set; } - - public override bool Check(RestQueryArgs args) - { - _ = args ?? throw new ArgumentNullException(nameof(args)); - if (Condition?.Check(args) ?? false) - { - return Success != null && (Success.Check(args) || !Success.Required); - } - else - { - return Fail != null && (Fail.Check(args) || !Fail.Required); - } - } - } - - public class SessionRule : ApiRule - { - public string? SessionKey { get; set; } - - public string? Key { get; set; } - - public override bool Check(RestQueryArgs args) - { - _ = args ?? throw new ArgumentNullException(nameof(args)); - if (args.Session == null || Key == null || SessionKey == null) - return false; - if (args.Session.TryGetValue(SessionKey, out object? value)) - { - args.ParsedArguments[Key] = value; - return true; - } - else return false; - } - } - - public HostRule Host(string host, bool endsWith = false) - { - return new HostRule - { - Host = host, - EndsWith = endsWith, - }; - } - - public HostRule Host(string key, string? host, bool endsWith = false) - { - return new HostRule - { - Key = key, - Host = host, - EndsWith = endsWith, - }; - } - - public UrlConstantRule UrlConstant(string constant, bool ignoreCase = false, int index = 0) - { - return new UrlConstantRule - { - Index = index, - Constant = constant, - IgnoreCase = ignoreCase, - }; - } - - public UrlArgumentRule UrlArgument(string key, UrlArgumentRule.ParseArgumentHandle parseArgument, int index = 0) - { - return new UrlArgumentRule - { - Index = index, - Key = key, - ParseArgument = parseArgument, - }; - } - - public UrlArgumentRule UrlArgument(string key, int index = 0) - { - return new UrlArgumentRule - { - Index = index, - Key = key, - ParseArgument = (string val, out string v) => - { - v = val; - return true; - }, - }; - } - - public MaxLengthRule MaxLength(int maxLength = 0) - { - return new MaxLengthRule - { - Index = maxLength, - }; - } - - public KeyExistsRule KeyExists(string key) - { - return new KeyExistsRule - { - Key = key, - }; - } - - public GetArgumentRule GetArgument(string key, GetArgumentRule.ParseArgumentHandle parseArgument) - { - return new GetArgumentRule - { - Key = key, - ParseArgument = parseArgument, - }; - } - - public GetArgumentRule GetArgument(string key) - { - return new GetArgumentRule - { - Key = key, - ParseArgument = (string value, out string v) => - { - v = value; - return true; - }, - }; - } - - public GroupRule Group(params ApiRule[] rules) - { - var group = new GroupRule(); - if (rules != null) - group.Rules.AddRange(rules); - return group; - } - - public GroupRule Location(params ApiLocationRule[] rules) - => Location(0, rules); - - public GroupRule Location(int offset, params ApiLocationRule[] rules) - { - var group = new GroupRule(); - if (rules == null) - return group; - group.Rules.AddRange(rules.Select((r, ind) => - { - r.Index = offset + ind; - return r; - })); - return group; - } - - public T Optional(T rule) - where T : ApiRule - { - if (rule is null) - throw new ArgumentNullException(nameof(rule)); - rule.Required = false; - return rule; - } - - public ConditionalRule Conditional(ApiRule condition, ApiRule success, ApiRule fail) - { - return new ConditionalRule - { - Condition = condition, - Success = success, - Fail = fail, - }; - } - - public SessionRule Session(string key) - { - return new SessionRule - { - Key = key, - SessionKey = key, - }; - } - - public SessionRule Session(string sessionKey, string key) - { - return new SessionRule - { - Key = key, - SessionKey = sessionKey, - }; - } - } -} diff --git a/MaxLib.WebServer/Api/Rest/RestActionEndpoint.cs b/MaxLib.WebServer/Api/Rest/RestActionEndpoint.cs deleted file mode 100644 index c52e9a4..0000000 --- a/MaxLib.WebServer/Api/Rest/RestActionEndpoint.cs +++ /dev/null @@ -1,239 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.IO; -using System.Reflection; -using System.Threading.Tasks; - -#nullable enable - -namespace MaxLib.WebServer.Api.Rest -{ - [Obsolete("The ApiService and the RestApiService classes are no longer maintained and will be removed in a future update. Use the Builder system instead.")] - public class RestActionEndpoint : RestEndpoint - { - public Func, Task> HandleRequest { get; set; } - - public RestActionEndpoint(Func, Task> handleRequest) - => HandleRequest = handleRequest; - - public override Task GetSource(Dictionary args) - { - _ = args ?? throw new ArgumentNullException(nameof(args)); - var task = HandleRequest?.Invoke(args); - if (task == null) - return Task.FromResult(null); - else return task; - } - - public static RestActionEndpoint Create(Func, Task> handler) - => new RestActionEndpoint(handler); - - public static RestActionEndpoint Create(Func, Task> handler) - => new RestActionEndpoint(async args => - { - var result = await handler(args).ConfigureAwait(false); - if (result == null) - return null; - return new HttpStreamDataSource(result); - }); - - public static RestActionEndpoint Create(Func, Task> handler) - => new RestActionEndpoint(async args => - { - var result = await handler(args).ConfigureAwait(false); - if (result == null) - return null; - return new HttpStringDataSource(result); - }); - - public static RestActionEndpoint Create(Func> handler) - => new RestActionEndpoint(async args => - { - var result = await handler().ConfigureAwait(false); - if (result == null) - return null; - return result; - }); - - public static RestActionEndpoint Create(Func> handler) - => new RestActionEndpoint(async args => - { - var result = await handler().ConfigureAwait(false); - if (result == null) - return null; - return new HttpStreamDataSource(result); - }); - - public static RestActionEndpoint Create(Func> handler) - => new RestActionEndpoint(async args => - { - var result = await handler().ConfigureAwait(false); - if (result == null) - return null; - return new HttpStringDataSource(result); - }); - - public static RestActionEndpoint Create(Func> handler, string argName) - => new RestActionEndpoint(async args => - { - if (!GetValue(args, argName, out T arg)) - return null; - var result = await handler(arg).ConfigureAwait(false); - if (result == null) - return null; - return result; - }); - - public static RestActionEndpoint Create(Func> handler, string argName) - => new RestActionEndpoint(async args => - { - if (!GetValue(args, argName, out T arg)) - return null; - var result = await handler(arg).ConfigureAwait(false); - if (result == null) - return null; - return new HttpStreamDataSource(result); - }); - - public static RestActionEndpoint Create(Func> handler, string argName) - => new RestActionEndpoint(async args => - { - if (!GetValue(args, argName, out T arg)) - return null; - var result = await handler(arg).ConfigureAwait(false); - if (result == null) - return null; - return new HttpStringDataSource(result); - }); - - public static RestActionEndpoint Create(Func> handler, string argName1, string argName2) - => new RestActionEndpoint(async args => - { - if (!GetValue(args, argName1, out T1 arg1) || - !GetValue(args, argName2, out T2 arg2)) - return null; - var result = await handler(arg1, arg2).ConfigureAwait(false); - if (result == null) - return null; - return result; - }); - - public static RestActionEndpoint Create(Func> handler, string argName1, string argName2) - => new RestActionEndpoint(async args => - { - if (!GetValue(args, argName1, out T1 arg1) || - !GetValue(args, argName2, out T2 arg2)) - return null; - var result = await handler(arg1, arg2).ConfigureAwait(false); - if (result == null) - return null; - return new HttpStreamDataSource(result); - }); - - public static RestActionEndpoint Create(Func> handler, string argName1, string argName2) - => new RestActionEndpoint(async args => - { - if (!GetValue(args, argName1, out T1 arg1) || - !GetValue(args, argName2, out T2 arg2)) - return null; - var result = await handler(arg1, arg2).ConfigureAwait(false); - if (result == null) - return null; - return new HttpStringDataSource(result); - }); - - public static RestActionEndpoint Create(Func> handler, string argName1, string argName2, string argName3) - => new RestActionEndpoint(async args => - { - if (!GetValue(args, argName1, out T1 arg1) || - !GetValue(args, argName2, out T2 arg2) || - !GetValue(args, argName3, out T3 arg3)) - return null; - var result = await handler(arg1, arg2, arg3).ConfigureAwait(false); - if (result == null) - return null; - return result; - }); - - public static RestActionEndpoint Create(Func> handler, string argName1, string argName2, string argName3) - => new RestActionEndpoint(async args => - { - if (!GetValue(args, argName1, out T1 arg1) || - !GetValue(args, argName2, out T2 arg2) || - !GetValue(args, argName3, out T3 arg3)) - return null; - var result = await handler(arg1, arg2, arg3).ConfigureAwait(false); - if (result == null) - return null; - return new HttpStreamDataSource(result); - }); - - public static RestActionEndpoint Create(Func> handler, string argName1, string argName2, string argName3) - => new RestActionEndpoint(async args => - { - if (!GetValue(args, argName1, out T1 arg1) || - !GetValue(args, argName2, out T2 arg2) || - !GetValue(args, argName3, out T3 arg3)) - return null; - var result = await handler(arg1, arg2, arg3).ConfigureAwait(false); - if (result == null) - return null; - return new HttpStringDataSource(result); - }); - - public static RestActionEndpoint Create(Delegate handler, string[] argsOrder) - => new RestActionEndpoint(async args => - { - var use = new object?[argsOrder?.Length ?? 0]; - for (int i = 0; i < use.Length; ++i) - if (args.TryGetValue(argsOrder![i], out object? value)) - use[i] = value; - var result = handler.DynamicInvoke(use); - if (result is Task task) - { - await task.ConfigureAwait(false); - if (!GetTaskValue(task, out result)) - result = null; - } - if (result is HttpDataSource dataSource) - return dataSource; - if (result is Stream stream) - return new HttpStreamDataSource(stream); - if (result is string text) - return new HttpStringDataSource(text); - var resText = result?.ToString() ?? ""; - if (result is IDisposable disposable) - disposable.Dispose(); - return new HttpStringDataSource(resText); - }); - - private static bool GetTaskValue(Task task, out object? value) - { - // thx to: https://stackoverflow.com/a/52500763/12469007 - value = default; - var voidTaskType = typeof(Task<>).MakeGenericType(Type.GetType("System.Threading.Tasks.VoidTaskResult")!); - if (voidTaskType.IsAssignableFrom(task.GetType())) - return false; - var property = task.GetType().GetProperty("Result", BindingFlags.Public | BindingFlags.Instance); - if (property == null) - return false; - value = property.GetValue(task); - return true; - } - - private static bool GetValue(Dictionary args, string name, [NotNullWhen(true)] out T value) - { - if (args.TryGetValue(name, out object? rawValue) && rawValue is T value_) - { - value = value_; - return true; - } - else - { - value = default!; - return false; - } - } - } -} diff --git a/MaxLib.WebServer/Api/Rest/RestApiService.cs b/MaxLib.WebServer/Api/Rest/RestApiService.cs deleted file mode 100644 index b4e5e98..0000000 --- a/MaxLib.WebServer/Api/Rest/RestApiService.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; - -#nullable enable - -namespace MaxLib.WebServer.Api.Rest -{ - [Obsolete("The ApiService and the RestApiService classes are no longer maintained and will be removed in a future update. Use the Builder system instead.")] - public class RestApiService : ApiService - { - public List RestEndpoints { get; } = new List(); - - public RestApiService(params string[] endpoint) - : base(endpoint) - { } - - protected override async Task HandleRequest(WebProgressTask task, string[] location) - { - _ = task ?? throw new ArgumentNullException(nameof(task)); - _ = location ?? throw new ArgumentNullException(nameof(location)); - var query = GetQueryArgs(task, location); - foreach (var endpoint in RestEndpoints) - { - if (endpoint == null) - continue; - var q = endpoint.Check(query); - if (q == null) - continue; - var result = await endpoint.GetSource(q.ParsedArguments) - .ConfigureAwait(false); - if (result != null) - return result; - } - return NoEndpoint(task, query); - } - - protected virtual RestQueryArgs GetQueryArgs(WebProgressTask task, string[] location) - { - _ = task ?? throw new ArgumentNullException(nameof(task)); - _ = location ?? throw new ArgumentNullException(nameof(location)); - return new RestQueryArgs(task.Request.Host, location, task.Request.Location.GetParameter, task.Request.Post, task.Session); - } - - protected virtual HttpDataSource NoEndpoint(WebProgressTask task, RestQueryArgs args) - { - _ = task ?? throw new ArgumentNullException(nameof(task)); - _ = args ?? throw new ArgumentNullException(nameof(args)); - task.Response.StatusCode = HttpStateCode.NotFound; - return new HttpStringDataSource("no endpoint"); - } - } -} diff --git a/MaxLib.WebServer/Api/Rest/RestEndpoint.cs b/MaxLib.WebServer/Api/Rest/RestEndpoint.cs deleted file mode 100644 index d6d2d43..0000000 --- a/MaxLib.WebServer/Api/Rest/RestEndpoint.cs +++ /dev/null @@ -1,59 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -#nullable enable - -namespace MaxLib.WebServer.Api.Rest -{ - [Obsolete("The ApiService and the RestApiService classes are no longer maintained and will be removed in a future update. Use the Builder system instead.")] - public class RestEndpoint - { - readonly private ApiRuleFactory.GroupRule rules = new ApiRuleFactory.GroupRule(); - - public List Rules => rules.Rules; - - public RestEndpoint Add(ApiRule rule) - { - if (rule != null) - Rules.Add(rule); - return this; - } - - public RestEndpoint Add(IEnumerable rules) - { - if (rules != null) - Rules.AddRange(rules.Where(r => r != null)); - return this; - } - - public RestEndpoint Add(params ApiRule[] rules) - { - if (rules != null) - Rules.AddRange(rules.Where(r => r != null)); - return this; - } - - public virtual RestQueryArgs? Check(RestQueryArgs args) - { - _ = args ?? throw new ArgumentNullException(nameof(args)); - var realArgs = new RestQueryArgs(args.Host, args.Location, args.GetArgs, args.Post, args.Session); - if (rules.Check(realArgs)) - return realArgs; - else return null; - } - - public virtual Task GetSource(Dictionary args) - { - _ = args ?? throw new ArgumentNullException(nameof(args)); - var sb = new StringBuilder(); - foreach (var kvp in args) - { - sb.AppendLine($"{kvp.Key}: {kvp.Value}"); - } - return Task.FromResult(new HttpStringDataSource(sb.ToString())); - } - } -} diff --git a/MaxLib.WebServer/Api/Rest/RestQueryArgs.cs b/MaxLib.WebServer/Api/Rest/RestQueryArgs.cs deleted file mode 100644 index 5755c38..0000000 --- a/MaxLib.WebServer/Api/Rest/RestQueryArgs.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; -using System.Collections.Generic; - -#nullable enable - -namespace MaxLib.WebServer.Api.Rest -{ - [Obsolete("The ApiService and the RestApiService classes are no longer maintained and will be removed in a future update. Use the Builder system instead.")] - public class RestQueryArgs - { - public string[] Location { get; } - - public Dictionary GetArgs { get; } - - public HttpPost Post { get; } - - public Sessions.Session? Session { get; } - - public string Host { get; } - - public Dictionary ParsedArguments { get; } - - public RestQueryArgs(string host, string[] location, Dictionary getArgs, HttpPost post, Sessions.Session? session = null) - { - Host = host; - Location = location ?? throw new ArgumentNullException(nameof(location)); - GetArgs = getArgs ?? throw new ArgumentNullException(nameof(getArgs)); - Post = post ?? throw new ArgumentNullException(nameof(post)); - Session = session; - ParsedArguments = new Dictionary(); - } - } -} diff --git a/MaxLib.WebServer/Builder/Converter/SystemConverter.cs b/MaxLib.WebServer/Builder/Converter/SystemConverter.cs index 60c03bc..3cc65a9 100644 --- a/MaxLib.WebServer/Builder/Converter/SystemConverter.cs +++ b/MaxLib.WebServer/Builder/Converter/SystemConverter.cs @@ -1,4 +1,5 @@ using System; +using System.Globalization; namespace MaxLib.WebServer.Builder.Converter { @@ -6,17 +7,53 @@ public class SystemConverter : Tools.IConverter { public Func? GetConverter(Type source, Type target) { + ArgumentNullException.ThrowIfNull(target); // simple conversion if (source == target || target.IsAssignableFrom(source)) return value => value; - + + // Convert.ChangeType throws InvalidCastException for enums, and string and enums are both IConvertible, + // so enums must be handled before the IConvertible branch below + if (target.IsEnum && source == typeof(string)) + return value => + { + var parsed = Enum.Parse(target, (string)value!, ignoreCase: true); + // Enum.Parse accepts numeric strings outside the enum's named members (e.g. "99"); reject them like unknown names. + // Exception: a [Flags] enum's comma-separated syntax ("Read,Write") is accepted if every bit it sets + // is covered by a named member. + if (!Enum.IsDefined(target, parsed) && + !(Attribute.IsDefined(target, typeof(FlagsAttribute)) && IsValidFlagsCombination(target, parsed))) + throw new ArgumentException( + $"'{value}' is not a defined member of enum {target}.", nameof(value)); + return parsed; + }; + // check if IConvertible is implemented var iConvertible = typeof(IConvertible); if (iConvertible.IsAssignableFrom(source) && iConvertible.IsAssignableFrom(target)) - return value => Convert.ChangeType(value, target); + return value => Convert.ChangeType(value, target, CultureInfo.InvariantCulture); // unknown conversion return null; } + + // True if every bit set in `parsedValue` is also set in the OR of all of `enumType`'s named member values. + private static bool IsValidFlagsCombination(Type enumType, object parsedValue) + { + ulong combined; + ulong allFlags = 0; + try + { + combined = Convert.ToUInt64(parsedValue, CultureInfo.InvariantCulture); + foreach (var member in Enum.GetValues(enumType)) + allFlags |= Convert.ToUInt64(member, CultureInfo.InvariantCulture); + } + catch (OverflowException) + { + // a negative underlying value (e.g. the sign bit used as a flag) is not supported; treat as invalid + return false; + } + return (combined & ~allFlags) == 0; + } } } \ No newline at end of file diff --git a/MaxLib.WebServer/Builder/ConverterAttribute.cs b/MaxLib.WebServer/Builder/ConverterAttribute.cs index 3708843..a930c9c 100644 --- a/MaxLib.WebServer/Builder/ConverterAttribute.cs +++ b/MaxLib.WebServer/Builder/ConverterAttribute.cs @@ -42,5 +42,7 @@ protected ConverterAttribute(Type converter, bool createInstance) Instance = null; } } + + public override string ToString() => $"Converter: {Converter.Name}"; } } \ No newline at end of file diff --git a/MaxLib.WebServer/Builder/DataConverterAttribute.cs b/MaxLib.WebServer/Builder/DataConverterAttribute.cs index 87ada32..39d7c88 100644 --- a/MaxLib.WebServer/Builder/DataConverterAttribute.cs +++ b/MaxLib.WebServer/Builder/DataConverterAttribute.cs @@ -42,5 +42,7 @@ protected DataConverterAttribute(Type converter, bool createInstance) Instance = null; } } + + public override string ToString() => $"DataConverter: {Converter.Name}"; } } \ No newline at end of file diff --git a/MaxLib.WebServer/Builder/Debugger/BuildReasonCode.cs b/MaxLib.WebServer/Builder/Debugger/BuildReasonCode.cs new file mode 100644 index 0000000..9e01615 --- /dev/null +++ b/MaxLib.WebServer/Builder/Debugger/BuildReasonCode.cs @@ -0,0 +1,85 @@ +namespace MaxLib.WebServer.Builder.Debugger +{ + /// + /// The specific reason why the assigned a particular + /// to a scanned type, method, parameter or result. + /// + public enum BuildReasonCode + { + /// + /// The node was built successfully. + /// + Accepted = 0, + /// + /// The type has the set. + /// + TypeIgnoredByAttribute, + /// + /// The type is abstract and no instance can be created from it. + /// + TypeAbstract, + /// + /// The type is generic and the generator has no means to fill the generic variables. + /// + TypeGeneric, + /// + /// No public parameterless constructor for the type was found. + /// + TypeNoConstructor, + /// + /// The type does not inherit from . + /// + TypeNotService, + /// + /// The method has the set. + /// + MethodIgnoredByAttribute, + /// + /// The method is abstract and has no implementation. + /// + MethodAbstract, + /// + /// The method is generic and the generator has no means to fill the generic variables. + /// + MethodGeneric, + /// + /// The method is not public. + /// + MethodNotPublic, + /// + /// The method was declared in or in . + /// + MethodDeclaredInObject, + /// + /// The constructor of the declaring type threw an exception when the generator tried to + /// create an instance to bind the method to. + /// + MethodConstructorThrew, + /// + /// A parameter has a converter attribute set which doesn't provide a converter instance. + /// + ParamMissingConverterInstance, + /// + /// A parameter has a converter attribute set whose converter has no way to convert the + /// type of the parameter itself. + /// + ParamNoConverterFound, + /// + /// A parameter has no converter attribute set and the generator has no way to convert the + /// type to suit the parameter. + /// + ParamNoCoreConverterFound, + /// + /// The converter type for the result converter is invalid. + /// + ResultInvalidConverterType, + /// + /// The converter instance for the result converter cannot be created. + /// + ResultCannotCreateConverterInstance, + /// + /// No suitable converter was found or set for the result type of the method. + /// + ResultNoConverter, + } +} diff --git a/MaxLib.WebServer/Builder/Debugger/BuildReport.cs b/MaxLib.WebServer/Builder/Debugger/BuildReport.cs new file mode 100644 index 0000000..14af649 --- /dev/null +++ b/MaxLib.WebServer/Builder/Debugger/BuildReport.cs @@ -0,0 +1,72 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace MaxLib.WebServer.Builder.Debugger +{ + /// + /// The full, structured record of a single + /// (or one of its overloads) run: what was scanned, what was built, and why anything that + /// wasn't built got skipped or failed. + /// + public sealed class BuildReport + { + /// + /// The point in time the build ran. + /// + public DateTimeOffset GeneratedAt { get; init; } = DateTimeOffset.UtcNow; + + /// + /// A display name for what was scanned (the type, assembly or app domain name). + /// + public string Source { get; init; } = ""; + + /// + /// The report for every top-level scanned type. + /// + public List Roots { get; } = []; + + /// + /// How many exported types were skipped during an assembly/app-domain scan because they + /// don't inherit from . These are not attached to individually to avoid flooding the report with unrelated classes. + /// + public int SkippedNonServiceTypeCount { get; set; } + + /// + /// Flattens the whole report tree depth-first for search, filtering or counting. + /// + public IEnumerable Walk() + { + foreach (var root in Roots) + foreach (var node in WalkType(root)) + yield return node; + } + + private static IEnumerable WalkType(TypeReportNode type) + { + yield return type; + foreach (var method in type.Methods) + foreach (var node in WalkMethod(method)) + yield return node; + foreach (var nested in type.NestedTypes) + foreach (var node in WalkType(nested)) + yield return node; + } + + private static IEnumerable WalkMethod(MethodReportNode method) + { + yield return method; + foreach (var parameter in method.Parameters) + yield return parameter; + if (method.Result != null) + yield return method.Result; + } + + /// + /// Counts every node in the report tree with the given . + /// + public int CountByStatus(BuildReportStatus status) + => Walk().Count(node => node.Status == status); + } +} diff --git a/MaxLib.WebServer/Builder/Debugger/BuildReportNode.cs b/MaxLib.WebServer/Builder/Debugger/BuildReportNode.cs new file mode 100644 index 0000000..b8de740 --- /dev/null +++ b/MaxLib.WebServer/Builder/Debugger/BuildReportNode.cs @@ -0,0 +1,30 @@ +namespace MaxLib.WebServer.Builder.Debugger +{ + /// + /// A single scanned candidate (type, method, parameter or result) encountered while the + /// walked a type for building services, together with the + /// outcome of that scan. + /// + public abstract class BuildReportNode + { + /// + /// The display name of the scanned candidate (type/method/parameter name). + /// + public string Name { get; init; } = ""; + + /// + /// The outcome of the scan. + /// + public BuildReportStatus Status { get; set; } = BuildReportStatus.Accepted; + + /// + /// The specific reason for . + /// + public BuildReasonCode Reason { get; set; } = BuildReasonCode.Accepted; + + /// + /// A human-readable explanation of . + /// + public string Message { get; set; } = ""; + } +} diff --git a/MaxLib.WebServer/Builder/Debugger/BuildReportStatus.cs b/MaxLib.WebServer/Builder/Debugger/BuildReportStatus.cs new file mode 100644 index 0000000..efc046e --- /dev/null +++ b/MaxLib.WebServer/Builder/Debugger/BuildReportStatus.cs @@ -0,0 +1,23 @@ +namespace MaxLib.WebServer.Builder.Debugger +{ + /// + /// The outcome of a single scanned type, method, parameter or result during a builder run. + /// + public enum BuildReportStatus + { + /// + /// The node was successfully turned into a working part of the service tree. + /// + Accepted, + /// + /// The node was deliberately excluded (e.g. , abstract, + /// generic, not public). This is usually intentional. + /// + Ignored, + /// + /// The node could not be built although it looked like it should have been (e.g. a + /// missing converter or a constructor that threw). This is usually a misconfiguration. + /// + Failed, + } +} diff --git a/MaxLib.WebServer/Builder/Debugger/DebuggerService.cs b/MaxLib.WebServer/Builder/Debugger/DebuggerService.cs new file mode 100644 index 0000000..ee1acec --- /dev/null +++ b/MaxLib.WebServer/Builder/Debugger/DebuggerService.cs @@ -0,0 +1,158 @@ +using System; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace MaxLib.WebServer.Builder.Debugger +{ + /// + /// An opt-in, hand-written diagnostics endpoint for the + /// builder pipeline. Register it exactly like any other + /// - server.AddWebService(new DebuggerService(server, report)) + /// - to expose: + /// + /// a self-contained HTML page at with a foldable/searchable + /// view of the and a request-routing simulator, + /// {BasePath}/api/build-report: the as JSON, + /// {BasePath}/api/route: a JSON array of one result + /// per (or just the one requested), against the live + /// , driven by method/path/stage query parameters + /// and h.<name>=<value> for simulated headers. Omit stage to + /// simulate every stage at once. + /// + /// Nothing about registering this service changes the behavior of + /// or any of its overloads - it is entirely opt-in and has no + /// cost when not registered. + /// + public sealed class DebuggerService : WebService + { + private static readonly JsonSerializerOptions JsonOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }, + }; + + /// + /// The build report to display. Can be replaced at any time (e.g. after re-running + /// ). + /// + public BuildReport? BuildReport { get; set; } + + /// + /// The server whose live the + /// routing simulator dry-runs against. + /// + public Server Server { get; } + + /// + /// The URL path prefix this service answers to. Defaults to /_debugger. + /// + public string BasePath { get; } + + public DebuggerService(Server server, BuildReport? buildReport = null, string basePath = "/_debugger") + : base(ServerStage.CreateDocument) + { + ArgumentNullException.ThrowIfNull(server); + ArgumentNullException.ThrowIfNull(basePath); + Server = server; + BuildReport = buildReport; + BasePath = basePath; + // must win before user services register their own catch-alls for this sub-tree. + Priority = WebServicePriority.High; + } + + public override bool CanWorkWith(WebProgressTask task) + { + ArgumentNullException.ThrowIfNull(task); + var path = task.Request.Location.DocumentPath; + return string.Equals(path, BasePath, StringComparison.OrdinalIgnoreCase) + || path.StartsWith(BasePath + "/", StringComparison.OrdinalIgnoreCase); + } + + public override Task ProgressTask(WebProgressTask task) + { + ArgumentNullException.ThrowIfNull(task); + var path = task.Request.Location.DocumentPath; + var rest = path.Length <= BasePath.Length ? "" : path[BasePath.Length..]; + return rest switch + { + "" or "/" => ServeHtmlShell(task), + "/api/build-report" => ServeBuildReportJson(task), + "/api/route" => ServeRouteJson(task), + _ => ServeNotFound(task), + }; + } + + private Task ServeHtmlShell(WebProgressTask task) + { + var html = $"\n" + + Properties.Resources.Debugger_Shell; + task.Document.DataSources.Add(new HttpStringDataSource(html) + { + MimeType = MimeType.TextHtml, + TextEncoding = "utf-8", + }); + return Task.CompletedTask; + } + + private Task ServeBuildReportJson(WebProgressTask task) + => WriteJson(task, BuildReport ?? new BuildReport()); + + /// + /// Every real (non-alias) , in dispatch order. + /// + private static readonly ServerStage[] AllStages = + [ + ServerStage.ReadRequest, + ServerStage.ParseRequest, + ServerStage.CreateDocument, + ServerStage.ProcessDocument, + ServerStage.CreateResponse, + ServerStage.SendResponse, + ServerStage.Cleanup, + ]; + + private Task ServeRouteJson(WebProgressTask task) + { + var query = task.Request.Location.GetParameter; + var method = query.TryGetValue("method", out var m) ? m : "GET"; + var path = query.TryGetValue("path", out var p) ? p : "/"; + var stageParam = query.TryGetValue("stage", out var s) ? s : ""; + var headers = query + .Where(kv => kv.Key.StartsWith("h.", StringComparison.Ordinal)) + .ToDictionary(kv => kv.Key[2..], kv => kv.Value); + + var stages = !string.IsNullOrEmpty(stageParam) && Enum.TryParse(stageParam, true, out var parsed) + ? [parsed] + : AllStages; + + var reports = stages + .Select(stage => RoutingDryRun.Run(Server.WebServiceGroups[stage], method, path, headers)) + .ToList(); + return WriteJson(task, reports); + } + + private static Task ServeNotFound(WebProgressTask task) + { + task.Response.StatusCode = HttpStateCode.NotFound; + task.Document.DataSources.Add(new HttpStringDataSource("Not Found") + { + MimeType = MimeType.TextPlain, + TextEncoding = "utf-8", + }); + return Task.CompletedTask; + } + + private static Task WriteJson(WebProgressTask task, T value) + { + var json = JsonSerializer.Serialize(value, JsonOptions); + task.Document.DataSources.Add(new HttpStringDataSource(json) + { + MimeType = MimeType.ApplicationJson, + TextEncoding = "utf-8", + }); + return Task.CompletedTask; + } + } +} diff --git a/MaxLib.WebServer/Builder/Debugger/IExplainableRule.cs b/MaxLib.WebServer/Builder/Debugger/IExplainableRule.cs new file mode 100644 index 0000000..1101ae2 --- /dev/null +++ b/MaxLib.WebServer/Builder/Debugger/IExplainableRule.cs @@ -0,0 +1,27 @@ +using System.Collections.Generic; + +namespace MaxLib.WebServer.Builder.Debugger +{ + /// + /// An additive, opt-in capability a can implement to + /// give a precise reason for a rejection instead of the generic + /// "rule rejected the request" fallback. Kept as a separate interface (rather than changing + /// 's signature) since that method is a public contract already implemented by third-party + /// rule attributes. + /// + public interface IExplainableRule + { + /// + /// Works exactly like , but additionally explains a rejection. + /// + /// The task that is currently executed. + /// The variables collected so far for this request. + /// + /// Set to a human-readable explanation when this returns false; otherwise + /// null. + /// + bool CanWorkWith(WebProgressTask task, Dictionary vars, out string? reason); + } +} diff --git a/MaxLib.WebServer/Builder/Debugger/MethodReportNode.cs b/MaxLib.WebServer/Builder/Debugger/MethodReportNode.cs new file mode 100644 index 0000000..3b8575b --- /dev/null +++ b/MaxLib.WebServer/Builder/Debugger/MethodReportNode.cs @@ -0,0 +1,60 @@ +using System; +using System.Collections.Generic; +using System.Text.Json.Serialization; + +namespace MaxLib.WebServer.Builder.Debugger +{ + /// + /// The build report for a single scanned method. + /// + public sealed class MethodReportNode : BuildReportNode + { + /// + /// The full name of the type the method was declared on. + /// + public string DeclaringType { get; init; } = ""; + + /// + /// The rule attributes (e.g. , ) found on the method, rendered via their . + /// + public List Rules { get; } = []; + + /// + /// The method's dispatch priority, set only when a is + /// explicitly present - empty when the method uses the inherited default (). + /// + public string Priority { get; set; } = ""; + + /// + /// The report for every scanned parameter, in declaration order. + /// + public List Parameters { get; } = []; + + /// + /// The report for the method's return value conversion, if the scan got that far. + /// + public ResultReportNode? Result { get; set; } + + /// + /// Set when applies: the message of + /// the exception the declaring type's constructor threw. + /// + public string? ExceptionMessage { get; set; } + + /// + /// Set when applies: the stack trace + /// of the exception the declaring type's constructor threw. + /// + public string? ExceptionStackTrace { get; set; } + + /// + /// Set when applies: the exception + /// the declaring type's constructor threw. Not serialized, since an arbitrary + /// subclass may not be safely reflectable. + /// + [JsonIgnore] + public Exception? Exception { get; set; } + } +} diff --git a/MaxLib.WebServer/Builder/Debugger/ParameterReportNode.cs b/MaxLib.WebServer/Builder/Debugger/ParameterReportNode.cs new file mode 100644 index 0000000..68d623f --- /dev/null +++ b/MaxLib.WebServer/Builder/Debugger/ParameterReportNode.cs @@ -0,0 +1,25 @@ +namespace MaxLib.WebServer.Builder.Debugger +{ + /// + /// The build report for a single method parameter. + /// + public sealed class ParameterReportNode : BuildReportNode + { + /// + /// The full name of the parameter's declared type. + /// + public string ParameterType { get; init; } = ""; + + /// + /// How the parameter's value is resolved: the short name of the attribute applied to it plus the key it actually + /// reads (e.g. "Var: id", "Get: bar" - which can differ from the + /// parameter's own name), or "Core parameter" if none is set and it was + /// successfully resolved as a framework-injected type. Null if neither applies - e.g. an + /// unattributed parameter whose type isn't a known framework type either, so there is no + /// meaningful source to report (see ). + /// + public string? Source { get; set; } + } +} diff --git a/MaxLib.WebServer/Builder/Debugger/ResultReportNode.cs b/MaxLib.WebServer/Builder/Debugger/ResultReportNode.cs new file mode 100644 index 0000000..2b7fe9e --- /dev/null +++ b/MaxLib.WebServer/Builder/Debugger/ResultReportNode.cs @@ -0,0 +1,24 @@ +namespace MaxLib.WebServer.Builder.Debugger +{ + /// + /// The build report for a method's return value conversion. + /// + public sealed class ResultReportNode : BuildReportNode + { + /// + /// The full name of the method's declared return type. + /// + public string ReturnType { get; init; } = ""; + + /// + /// The name of the that was actually used to convert + /// the result - either from a or, if none is set, + /// the inherited default (). Also set to the + /// attempted converter's type name when a is + /// present but invalid or fails to construct. Null when no converter was ever + /// successfully resolved and none was explicitly requested either (see ) - there's nothing meaningful to report. + /// + public string? Converter { get; set; } + } +} diff --git a/MaxLib.WebServer/Builder/Debugger/RoutingDryRun.cs b/MaxLib.WebServer/Builder/Debugger/RoutingDryRun.cs new file mode 100644 index 0000000..e72ab89 --- /dev/null +++ b/MaxLib.WebServer/Builder/Debugger/RoutingDryRun.cs @@ -0,0 +1,268 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace MaxLib.WebServer.Builder.Debugger +{ + /// + /// Answers "which of my registered services would accept this request, and why did the + /// others reject it (or never see it)?" without ever invoking a service's + /// /side effects - only the read-only + /// CanWorkWith path is exercised, against a synthetic request. + /// + /// + /// RoutingDryRun does not catch exceptions thrown by custom rules or a service's CanWorkWith; they + /// propagate to the caller. Rule attributes must not throw from ToString(); it is used for report + /// labels. Exceptions thrown by custom rules and services must not throw from Message; it is + /// included in the report. + /// + public static class RoutingDryRun + { + /// + /// Simulates against every service registered in + /// , in priority order. + /// + public static RoutingReport Run(WebServiceGroup group, WebProgressTask task) + { + ArgumentNullException.ThrowIfNull(group); + ArgumentNullException.ThrowIfNull(task); + + var report = new RoutingReport + { + RequestSummary = $"{task.Request.ProtocolMethod} {task.Request.Url}", + Stage = group.Stage, + }; + + var vars = new Dictionary(); + var matched = false; + foreach (var service in group.GetAll()) + { + RoutingReportNode node; + if (matched && group.SingleExecution) + { + node = new RoutingReportNode + { + Label = DescribeService(service), + Source = DescribeSource(service), + Priority = service.Priority, + Outcome = RoutingOutcome.NotReached, + }; + } + else + { + node = EvaluateService(service, task, vars); + if (node.Outcome == RoutingOutcome.Accepted) + { + matched = true; + report.MatchedLabel = FindMatchedLabel(node); + } + } + report.Services.Add(node); + } + + if (task.Monitor.Enabled) + { + using var writer = new StringWriter(); + task.Monitor.WriteTo(writer); + report.MonitorTrace = writer.ToString(); + } + return report; + } + + /// + /// Builds a synthetic request from // + /// and simulates it against , just + /// like . + /// + public static RoutingReport Run(WebServiceGroup group, string method, string url, + IReadOnlyDictionary? headers = null) + { + ArgumentNullException.ThrowIfNull(method); + ArgumentNullException.ThrowIfNull(url); + using var task = new WebProgressTask(); + task.Request.ProtocolMethod = method; + task.Request.Url = url; + if (headers != null) + foreach (var (key, value) in headers) + task.Request.HeaderParameter[key] = value; + task.EnableMonitoring(); + return Run(group, task); + } + + private static string FindMatchedLabel(RoutingReportNode node) + { + foreach (var child in node.Children) + if (child.Outcome == RoutingOutcome.Accepted) + return FindMatchedLabel(child); + return node.Label; + } + + private static string DescribeService(WebService service) => service switch + { + Runtime.MethodService method => $"{method.Method.DeclaringType?.Name}.{method.Method.Name}()", + Runtime.ServiceGroup group when group.Rules.Count > 0 => + string.Join(", ", group.Rules), + _ => service.GetType().Name, + }; + + /// + /// The user type was generated from, if the builder can + /// supply one. Null for a hand-written , and for a + /// - its label + /// already names the declaring type and method. + /// + private static string? DescribeSource(WebService service) => service switch + { + Runtime.ServiceGroup { SourceType: not null } group => group.SourceType!.FullName, + _ => null, + }; + + private static RoutingReportNode EvaluateService(WebService service, WebProgressTask task, + Dictionary vars) + { + var node = new RoutingReportNode + { + Label = DescribeService(service), + Source = DescribeSource(service), + Priority = service.Priority, + }; + + switch (service) + { + case Runtime.ServiceGroup group: + EvaluateServiceGroup(group, task, vars, node); + break; + case Runtime.MethodService method: + EvaluateMethodService(method, task, vars, node); + break; + default: + EvaluateGenericService(service, task, node); + break; + } + return node; + } + + private static void EvaluateServiceGroup(Runtime.ServiceGroup group, WebProgressTask task, + Dictionary vars, RoutingReportNode node) + { + foreach (var rule in group.Rules) + { + if (!EvaluateRule(rule, task, vars, out var reason)) + { + node.Outcome = RoutingOutcome.Rejected; + node.Reasons.Add(reason); + return; + } + } + + var matched = false; + foreach (var child in group) + { + RoutingReportNode childNode; + if (matched) + { + childNode = new RoutingReportNode + { + Label = DescribeService(child), + Source = DescribeSource(child), + Priority = child.Priority, + Outcome = RoutingOutcome.NotReached, + }; + } + else + { + childNode = EvaluateService(child, task, vars); + if (childNode.Outcome == RoutingOutcome.Accepted) + matched = true; + } + node.Children.Add(childNode); + } + node.Outcome = matched ? RoutingOutcome.Accepted : RoutingOutcome.Rejected; + if (!matched) + node.Reasons.Add("none of the contained services matched the request"); + } + + private static void EvaluateMethodService(Runtime.MethodService method, WebProgressTask task, + Dictionary vars, RoutingReportNode node) + { + var rulesOk = true; + foreach (var rule in method.Rules) + { + if (!EvaluateRule(rule, task, vars, out var reason)) + { + rulesOk = false; + node.Reasons.Add(reason); + } + } + + var parametersOk = true; + foreach (var parameter in method.Parameters) + { + Tools.Result result; + try + { + result = parameter.GetValue(task, vars); + } + catch (HttpException e) + { + // Parameter.GetValue throws when type conversion fails; a dry run must report that + // as a rejection instead of throwing + parametersOk = false; + node.Reasons.Add( + $"parameter '{DescribeParameterName(method, parameter)}' failed to convert: {e.Message}"); + continue; + } + if (!result.HasValue) + { + parametersOk = false; + node.Reasons.Add(DescribeUnresolvedParameter(method, parameter)); + } + } + + node.Outcome = rulesOk && parametersOk ? RoutingOutcome.Accepted : RoutingOutcome.Rejected; + } + + private static string DescribeParameterName(Runtime.MethodService method, Runtime.IParameter parameter) + { + var name = (parameter as Runtime.Parameter)?.Name; + if (string.IsNullOrEmpty(name)) + { + var index = method.Parameters.IndexOf(parameter); + var infos = method.Method.GetParameters(); + if (index >= 0 && index < infos.Length) + name = infos[index].Name; + } + return name ?? ""; + } + + private static string DescribeUnresolvedParameter(Runtime.MethodService method, Runtime.IParameter parameter) + { + var name = DescribeParameterName(method, parameter); + return $"parameter '{name}' could not be resolved from the request"; + } + + private static void EvaluateGenericService(WebService service, WebProgressTask task, RoutingReportNode node) + { + var ok = service is WebService2 service2 + ? service2.CanWorkWith(task, out _) + : service.CanWorkWith(task); + node.Outcome = ok ? RoutingOutcome.Accepted : RoutingOutcome.Rejected; + if (!ok) + node.Reasons.Add("CanWorkWith() returned false"); + } + + private static bool EvaluateRule(Tools.RuleAttributeBase rule, WebProgressTask task, + Dictionary vars, out string reason) + { + if (rule is IExplainableRule explainable) + { + var ok = explainable.CanWorkWith(task, vars, out var explained); + reason = ok ? "" : explained ?? $"rule {rule} rejected the request"; + return ok; + } + var accepted = rule.CanWorkWith(task, vars); + reason = accepted ? "" : $"rule {rule} rejected the request"; + return accepted; + } + } +} diff --git a/MaxLib.WebServer/Builder/Debugger/RoutingOutcome.cs b/MaxLib.WebServer/Builder/Debugger/RoutingOutcome.cs new file mode 100644 index 0000000..1f5520b --- /dev/null +++ b/MaxLib.WebServer/Builder/Debugger/RoutingOutcome.cs @@ -0,0 +1,22 @@ +namespace MaxLib.WebServer.Builder.Debugger +{ + /// + /// The outcome of a single candidate service during a . + /// + public enum RoutingOutcome + { + /// + /// The service would have handled the request. + /// + Accepted, + /// + /// The service was evaluated but rejected the request. + /// + Rejected, + /// + /// A higher-priority sibling already matched first (the stage only allows a single + /// service to run), so this candidate was never evaluated. + /// + NotReached, + } +} diff --git a/MaxLib.WebServer/Builder/Debugger/RoutingReport.cs b/MaxLib.WebServer/Builder/Debugger/RoutingReport.cs new file mode 100644 index 0000000..0eae837 --- /dev/null +++ b/MaxLib.WebServer/Builder/Debugger/RoutingReport.cs @@ -0,0 +1,38 @@ +using System.Collections.Generic; + +namespace MaxLib.WebServer.Builder.Debugger +{ + /// + /// The full result of a : for a single synthetic request, which + /// registered services would have accepted, rejected or never seen it, and why. + /// + public sealed class RoutingReport + { + /// + /// A human-readable summary of the simulated request (e.g. "GET /foo/2"). + /// + public string RequestSummary { get; init; } = ""; + + /// + /// The that was simulated. + /// + public ServerStage Stage { get; init; } + + /// + /// The report for every top-level registered service, in priority order. + /// + public List Services { get; } = []; + + /// + /// The of the service that would actually have + /// handled the request, or null if none did. + /// + public string? MatchedLabel { get; set; } + + /// + /// An optional raw trace of the dry run, for the parts + /// of the request that already emit log lines. + /// + public string? MonitorTrace { get; set; } + } +} diff --git a/MaxLib.WebServer/Builder/Debugger/RoutingReportNode.cs b/MaxLib.WebServer/Builder/Debugger/RoutingReportNode.cs new file mode 100644 index 0000000..8aa6901 --- /dev/null +++ b/MaxLib.WebServer/Builder/Debugger/RoutingReportNode.cs @@ -0,0 +1,47 @@ +using System.Collections.Generic; + +namespace MaxLib.WebServer.Builder.Debugger +{ + /// + /// The routing outcome for a single candidate , and (for a + /// ) its nested candidates. + /// + public sealed class RoutingReportNode + { + /// + /// A human-readable label for the candidate (e.g. its method name or class-level rules). + /// + public string Label { get; init; } = ""; + + /// + /// The user type or method this candidate maps to, if the builder can supply one (a + /// 's originating type, or a + /// 's declaring type and method). Null for a + /// hand-written with no such mapping. + /// + public string? Source { get; init; } + + /// + /// The dispatch priority of the candidate. + /// + public WebServicePriority Priority { get; init; } + + /// + /// The outcome of evaluating this candidate. + /// + public RoutingOutcome Outcome { get; set; } + + /// + /// One entry per reason the candidate rejected the request (a failing rule and/or an + /// unresolvable parameter). Empty when is + /// or . + /// + public List Reasons { get; } = []; + + /// + /// The nested candidates, if this node represents a . + /// Empty for a leaf service. + /// + public List Children { get; } = []; + } +} diff --git a/MaxLib.WebServer/Builder/Debugger/TypeReportNode.cs b/MaxLib.WebServer/Builder/Debugger/TypeReportNode.cs new file mode 100644 index 0000000..2352d7d --- /dev/null +++ b/MaxLib.WebServer/Builder/Debugger/TypeReportNode.cs @@ -0,0 +1,31 @@ +using System.Collections.Generic; + +namespace MaxLib.WebServer.Builder.Debugger +{ + /// + /// The build report for a single scanned type. + /// + public sealed class TypeReportNode : BuildReportNode + { + /// + /// The full name of the scanned type. + /// + public string TypeFullName { get; init; } = ""; + + /// + /// The class-level rule attributes (e.g. ) found on the type, + /// rendered via their . + /// + public List Rules { get; } = []; + + /// + /// The report for every scanned public method, in reflection order. + /// + public List Methods { get; } = []; + + /// + /// The report for every scanned nested type. + /// + public List NestedTypes { get; } = []; + } +} diff --git a/MaxLib.WebServer/Builder/GetAttribute.cs b/MaxLib.WebServer/Builder/GetAttribute.cs index c2586cd..9d0a171 100644 --- a/MaxLib.WebServer/Builder/GetAttribute.cs +++ b/MaxLib.WebServer/Builder/GetAttribute.cs @@ -38,5 +38,7 @@ public GetAttribute(string name) return new Result(); return new Result(value); } + + public override string ToString() => Name != null ? $"Get: {Name}" : "Get"; } } \ No newline at end of file diff --git a/MaxLib.WebServer/Builder/HostVarAttribute.cs b/MaxLib.WebServer/Builder/HostVarAttribute.cs index 480c566..d63daf4 100644 --- a/MaxLib.WebServer/Builder/HostVarAttribute.cs +++ b/MaxLib.WebServer/Builder/HostVarAttribute.cs @@ -13,6 +13,7 @@ public class HostVarAttribute : Tools.ParamAttributeBase public override Result GetValue(WebProgressTask task, string field, Dictionary vars) { + ArgumentNullException.ThrowIfNull(task); return new Result(task.Request.Host); } } diff --git a/MaxLib.WebServer/Builder/IgnoreAttribute.cs b/MaxLib.WebServer/Builder/IgnoreAttribute.cs index 8a45731..f361fa8 100644 --- a/MaxLib.WebServer/Builder/IgnoreAttribute.cs +++ b/MaxLib.WebServer/Builder/IgnoreAttribute.cs @@ -14,5 +14,7 @@ public sealed class IgnoreAttribute : System.Attribute public IgnoreAttribute() { } + + public override string ToString() => "Ignore"; } } \ No newline at end of file diff --git a/MaxLib.WebServer/Builder/JsonConverterAttribute.cs b/MaxLib.WebServer/Builder/JsonConverterAttribute.cs index 660e88f..e4a5126 100644 --- a/MaxLib.WebServer/Builder/JsonConverterAttribute.cs +++ b/MaxLib.WebServer/Builder/JsonConverterAttribute.cs @@ -27,50 +27,44 @@ public class JsonConverterAttribute : ConverterAttribute, Tools.IConverter /// /// Create a new converter that can convert JSON data into the property value /// - public JsonConverterAttribute() + public JsonConverterAttribute() : base(typeof(JsonConverterAttribute), false) { Instance = this; } - public Func? GetConverter(Type source, Type target) - { - Func? preParse = null; + public override string ToString() => + CustomConverter != null ? $"JsonConverter: {CustomConverter.Name}" : "JsonConverter"; + // The JsonDocument backing the parsed element, if this method created it (string/Stream input). + // A JsonDocument/JsonElement passed in stays owned by the caller and is not disposed here. + private static (JsonElement Element, JsonDocument? Owned)? PreParse(object? x, Type source) + { + if (x is null) + return null; if (typeof(string).IsAssignableFrom(source)) - preParse = x => - { - if (x is null) - return null; - try { return JsonDocument.Parse((string)x).RootElement; } - catch { return null; } - }; + { + var doc = JsonDocument.Parse((string)x); + return (doc.RootElement, doc); + } if (typeof(Stream).IsAssignableFrom(source)) - preParse = x => - { - if (x is null) - return null; - try { return JsonDocument.Parse((Stream)x).RootElement; } - catch { return null; } - }; + { + var doc = JsonDocument.Parse((Stream)x); + return (doc.RootElement, doc); + } if (typeof(JsonDocument).IsAssignableFrom(source)) - preParse = x => - { - if (x is null) - return null; - return ((JsonDocument)x).RootElement; - }; + return (((JsonDocument)x).RootElement, null); if (typeof(JsonElement).IsAssignableFrom(source)) - preParse = x => - { - if (x is null) - return null; - return (JsonElement)x; - }; + return ((JsonElement)x, null); + return null; + } - if (preParse is null) + public Func? GetConverter(Type source, Type target) + { + if (!typeof(string).IsAssignableFrom(source) && !typeof(Stream).IsAssignableFrom(source) + && !typeof(JsonDocument).IsAssignableFrom(source) && !typeof(JsonElement).IsAssignableFrom(source)) return null; - + if (CustomConverter != null) { ICustomJsonConverter conv; @@ -79,13 +73,17 @@ public JsonConverterAttribute() return x => { - var res = preParse(x); + var res = PreParse(x, source); if (res is null) return null; - else return conv.Convert(res.Value, target); + using var owned = res.Value.Owned; + // Clone the result: a converter may return the JsonElement itself, which becomes invalid + // once `owned` is disposed below. + var element = owned != null ? res.Value.Element.Clone() : res.Value.Element; + return conv.Convert(element, target); }; } - else + else { var options = new JsonSerializerOptions { @@ -95,9 +93,16 @@ public JsonConverterAttribute() { var constructor = Options.GetConstructor(Type.EmptyTypes); if (constructor != null) - options = ((IJsonSerializerOptions)constructor.Invoke(Array.Empty())).Options; + options = ((IJsonSerializerOptions)constructor.Invoke([])).Options; } - return x => preParse(x)?.Deserialize(target, options); + return x => + { + var res = PreParse(x, source); + if (res is null) + return null; + using var owned = res.Value.Owned; + return res.Value.Element.Deserialize(target, options); + }; } } } diff --git a/MaxLib.WebServer/Builder/JsonDataConverterAttribute.cs b/MaxLib.WebServer/Builder/JsonDataConverterAttribute.cs index c4f3cb2..3d5c490 100644 --- a/MaxLib.WebServer/Builder/JsonDataConverterAttribute.cs +++ b/MaxLib.WebServer/Builder/JsonDataConverterAttribute.cs @@ -2,6 +2,7 @@ using System.IO; using System.Text.Json; using MaxLib.WebServer.Builder.Converter; +using Microsoft.Extensions.Logging; namespace MaxLib.WebServer.Builder { @@ -10,6 +11,8 @@ namespace MaxLib.WebServer.Builder /// public partial class JsonDataConverterAttribute : DataConverterAttribute, Tools.IDataConverter { + static readonly ILogger logger = WebServerLog.LoggerFactory.CreateLogger(); + static readonly EventId JsonConvertEventId = new(0, "JSON Convert"); /// /// The options that should be used for the default JSON conversion. This will @@ -49,6 +52,9 @@ public JsonDataConverterAttribute(Type customConverter) CustomConverter = customConverter; } + public override string ToString() => + CustomConverter != null ? $"JsonDataConverter: {CustomConverter.Name}" : "JsonDataConverter"; + public Func? GetConverter(Type data) { Func? writer = null; @@ -59,10 +65,8 @@ public JsonDataConverterAttribute(Type customConverter) try { conv = (ICustomJsonDataConverter)Activator.CreateInstance(CustomConverter)!; } catch (Exception e) { - WebServerLog.Add(ServerLogType.Error, GetType(), "JSON Convert", - $"Error: {e}" - ); - return null; + logger.LogError(JsonConvertEventId, e, "Error creating custom JSON converter instance"); + return null; } writer = conv.Convert; } @@ -76,12 +80,15 @@ public JsonDataConverterAttribute(Type customConverter) { var constructor = Options.GetConstructor(Type.EmptyTypes); if (constructor != null) - options = ((IJsonSerializerOptions)constructor.Invoke(Array.Empty())).Options; + options = ((IJsonSerializerOptions)constructor.Invoke([])).Options; } writer = (w, value) => { if (value == null) + { w.WriteNullValue(); + return true; + } try { JsonSerializer.Serialize(w, value, options); } catch { return false; } return true; @@ -99,9 +106,9 @@ public JsonDataConverterAttribute(Type customConverter) { var constructor = JsonWriterOptions.GetConstructor(Type.EmptyTypes); if (constructor != null) - writerOptions = ((IJsonWriterOptions)constructor.Invoke(Array.Empty())).Options; + writerOptions = ((IJsonWriterOptions)constructor.Invoke([])).Options; } - + return value => { var m = new MemoryStream(); @@ -115,6 +122,7 @@ public JsonDataConverterAttribute(Type customConverter) } w.Flush(); + w.Dispose(); return new HttpStreamDataSource(m) { @@ -123,4 +131,4 @@ public JsonDataConverterAttribute(Type customConverter) }; } } -} \ No newline at end of file +} diff --git a/MaxLib.WebServer/Builder/MethodAttribute.cs b/MaxLib.WebServer/Builder/MethodAttribute.cs index ce7478d..98787b0 100644 --- a/MaxLib.WebServer/Builder/MethodAttribute.cs +++ b/MaxLib.WebServer/Builder/MethodAttribute.cs @@ -1,20 +1,37 @@ +using System; using System.Collections.Generic; using MaxLib.WebServer.Builder.Tools; namespace MaxLib.WebServer.Builder { - public class MethodAttribute : RuleAttributeBase + public class MethodAttribute : RuleAttributeBase, Debugger.IExplainableRule { public string Method { get; } public MethodAttribute(string method) { + ArgumentNullException.ThrowIfNull(method); Method = method.ToUpperInvariant(); } public override bool CanWorkWith(WebProgressTask task, Dictionary vars) { - return Method == task.Request.ProtocolMethod.ToUpperInvariant(); + ArgumentNullException.ThrowIfNull(task); + return string.Equals(Method, task.Request.ProtocolMethod, StringComparison.OrdinalIgnoreCase); + } + + public override string ToString() => $"Method: {Method}"; + + bool Debugger.IExplainableRule.CanWorkWith(WebProgressTask task, Dictionary vars, out string? reason) + { + ArgumentNullException.ThrowIfNull(task); + if (string.Equals(Method, task.Request.ProtocolMethod, StringComparison.OrdinalIgnoreCase)) + { + reason = null; + return true; + } + reason = $"expected HTTP method {Method}, request was {task.Request.ProtocolMethod}"; + return false; } } } \ No newline at end of file diff --git a/MaxLib.WebServer/Builder/MimeAttribute.cs b/MaxLib.WebServer/Builder/MimeAttribute.cs index b9e3f90..c970f3a 100644 --- a/MaxLib.WebServer/Builder/MimeAttribute.cs +++ b/MaxLib.WebServer/Builder/MimeAttribute.cs @@ -19,5 +19,7 @@ public MimeAttribute(string mime) { Mime = mime; } + + public override string ToString() => $"Mime: {Mime}"; } } \ No newline at end of file diff --git a/MaxLib.WebServer/Builder/PathAttribute.cs b/MaxLib.WebServer/Builder/PathAttribute.cs index efe63a6..188faa6 100644 --- a/MaxLib.WebServer/Builder/PathAttribute.cs +++ b/MaxLib.WebServer/Builder/PathAttribute.cs @@ -1,13 +1,24 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Text; namespace MaxLib.WebServer.Builder { /// - /// Limits the call to a specific URL path. You can also assign variables here. + /// Limits the call to a specific URL path. You can also assign variables here.
+ /// When two methods on the same type have overlapping paths, orders them by specificity before falling back to : + /// an exact match outranks a match, and among two exact (or two + /// prefix) matches, more literal segments and fewer {var} segments outrank fewer + /// literal segments/more variables. If two overlapping routes tie on both specificity and + /// priority, which one wins is not guaranteed - add an explicit + /// to make the outcome deterministic. + /// Specificity ordering only applies to methods declared on the same type; nested + /// types and separately built types are not ordered by specificity, so + /// use when their routes overlap. ///
- public sealed class PathAttribute : Tools.RuleAttributeBase + public sealed class PathAttribute : Tools.RuleAttributeBase, Debugger.IExplainableRule { private readonly List<(string, bool)> parts = new List<(string, bool)>(); @@ -35,15 +46,39 @@ public sealed class PathAttribute : Tools.RuleAttributeBase /// the path string public PathAttribute(string path) { + ArgumentNullException.ThrowIfNull(path); var parts = path.Split('/', StringSplitOptions.RemoveEmptyEntries); foreach (var part in parts) { if (part.StartsWith('{') && part.EndsWith('}')) - this.parts.Add((part.Substring(1, part.Length - 2), true)); + this.parts.Add((part[1..^1], true)); else this.parts.Add((part, false)); } } + /// + /// Used by to order overlapping routes that share the + /// same : higher wins. See the class doc comment for + /// the exact ordering rules. + /// + internal int Specificity + { + get + { + var literalCount = 0; + var varCount = 0; + foreach (var (_, isVar) in parts) + { + if (isVar) + ++varCount; + else + ++literalCount; + } + var score = literalCount * 1000 - varCount; + return Prefix ? score : score + 1_000_000; + } + } + public override string ToString() { var sb = new StringBuilder(); @@ -51,8 +86,8 @@ public override string ToString() foreach (var (part, mode) in parts) { if (mode) - sb.AppendFormat("/{{{0}}}", part); - else sb.AppendFormat("/{0}", part); + sb.AppendFormat(CultureInfo.InvariantCulture, "/{{{0}}}", part); + else sb.AppendFormat(CultureInfo.InvariantCulture, "/{0}", part); } if (Prefix) sb.Append("/*"); @@ -75,7 +110,41 @@ public override bool CanWorkWith(WebProgressTask task, Dictionary vars, out string? reason) + { + var url = task.Request.Location.DocumentPathTiles; + for (int i = 0; i < parts.Count && i < url.Length; ++i) + { + var (match, isVar) = parts[i]; + if (isVar) + { + vars[match] = url[i]; + } + else if (!string.Equals(match, url[i], StringComparison)) + { + reason = $"URL segment {i} was '{url[i]}', expected '{match}'"; + return false; + } + } + if (url.Length < parts.Count) + { + reason = $"the URL has {url.Length} segment(s), expected at least {parts.Count}"; + return false; + } + if (!Prefix && url.Length != parts.Count) + { + reason = $"the URL has {url.Length} segment(s), expected exactly {parts.Count}"; + return false; + } + reason = null; + return true; } } } \ No newline at end of file diff --git a/MaxLib.WebServer/Builder/PriorityAttribute.cs b/MaxLib.WebServer/Builder/PriorityAttribute.cs index 1c7cc3f..f68d108 100644 --- a/MaxLib.WebServer/Builder/PriorityAttribute.cs +++ b/MaxLib.WebServer/Builder/PriorityAttribute.cs @@ -1,9 +1,11 @@ -using System; - namespace MaxLib.WebServer.Builder { /// - /// Sets the Priority the method will run. + /// Sets the Priority the method will run.
+ /// For two methods with overlapping routes, this is only + /// needed to break a tie once 's own specificity ordering + /// (an exact match over a prefix match, more literal segments over {var} ones) is + /// also equal - which resolution order is otherwise not guaranteed. ///
[System.AttributeUsage(System.AttributeTargets.Method, Inherited = true, AllowMultiple = false)] public sealed class PriorityAttribute : System.Attribute @@ -18,5 +20,7 @@ public PriorityAttribute(WebServicePriority priority) { Priority = priority; } + + public override string ToString() => $"Priority: {Priority}"; } } \ No newline at end of file diff --git a/MaxLib.WebServer/Builder/Runtime/CoreParameter.cs b/MaxLib.WebServer/Builder/Runtime/CoreParameter.cs index 3723194..465e59a 100644 --- a/MaxLib.WebServer/Builder/Runtime/CoreParameter.cs +++ b/MaxLib.WebServer/Builder/Runtime/CoreParameter.cs @@ -20,7 +20,7 @@ public CoreParameter(Func> getter) } private static readonly (Type type, Func> getter)[] coreTypes = - { + [ (typeof(WebProgressTask), x => new Result(x)), (typeof(HttpDocument), x => new Result(x.Document)), (typeof(Server), x => new Result(x.Server)), @@ -36,15 +36,17 @@ private static readonly (Type type, Func> (typeof(Task), x => x.Request.Post.DataAsync == null ? new Result() : new Result(x.Request.Post.DataAsync)), (typeof(Post.MultipartFormData), x => x.Request.Post.Data is Post.MultipartFormData data ? new Result(data) : new Result()), (typeof(Post.UnknownPostData), x => x.Request.Post.Data is Post.UnknownPostData data ? new Result(data) : new Result()), + (typeof(Post.RawPostData), x => x.Request.Post.Data is Post.RawPostData data ? new Result(data) : new Result()), (typeof(Post.UrlEncodedData), x => x.Request.Post.Data is Post.UrlEncodedData data ? new Result(data) : new Result()), (typeof(Monitoring.Monitor), x => new Result(x.Monitor)), (typeof(Monitoring.IWatch), x => new Result(x.Monitor.Current)), (typeof(System.Net.IPEndPoint), x => x.Connection?.NetworkClient?.Client.RemoteEndPoint is System.Net.IPEndPoint data ? new Result(data) : new Result()), (typeof(System.Net.IPAddress), x => x.Connection?.NetworkClient?.Client.RemoteEndPoint is System.Net.IPEndPoint data ? new Result(data.Address) : new Result()), - }; + ]; public static CoreParameter? GetCoreParameter(Type target) { + ArgumentNullException.ThrowIfNull(target); foreach (var (type, getter) in coreTypes) if (target.IsAssignableFrom(type)) return new CoreParameter(getter); diff --git a/MaxLib.WebServer/Builder/Runtime/IParameter.cs b/MaxLib.WebServer/Builder/Runtime/IParameter.cs index 319092b..c2a31e9 100644 --- a/MaxLib.WebServer/Builder/Runtime/IParameter.cs +++ b/MaxLib.WebServer/Builder/Runtime/IParameter.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace MaxLib.WebServer.Builder.Runtime diff --git a/MaxLib.WebServer/Builder/Runtime/MethodService.cs b/MaxLib.WebServer/Builder/Runtime/MethodService.cs index 2cafab3..f2f0149 100644 --- a/MaxLib.WebServer/Builder/Runtime/MethodService.cs +++ b/MaxLib.WebServer/Builder/Runtime/MethodService.cs @@ -23,6 +23,7 @@ WebServicePriority priority ) : base(ServerStage.CreateDocument) { + ArgumentNullException.ThrowIfNull(method); Rules = rules; Parameters = parameters; Method = method; @@ -33,10 +34,15 @@ WebServicePriority priority public override Task ProgressTask(WebProgressTask task, object?[]? data) { + ArgumentNullException.ThrowIfNull(task); if (data is null) return Task.CompletedTask; using var watch = task.Monitor.Watch(MethodClass, $"Execute {Method.Name}()"); - var result = Method.Invoke(MethodClass, data); + // BindingFlags.DoNotWrapExceptions makes a synchronous handler's thrown exception + // (e.g. HttpException, the documented way to cancel a request with a specific + // status code) surface here as-is, instead of wrapped in a TargetInvocationException + // that WebServiceGroup.Execute's `catch (HttpException e)` would never match. + var result = Method.Invoke(MethodClass, BindingFlags.DoNotWrapExceptions, null, data, null); GC.KeepAlive(watch); return Result(task, result); } @@ -45,6 +51,7 @@ public override Task ProgressTask(WebProgressTask task, object?[]? data) public override bool CanWorkWith(WebProgressTask task, out object?[]? data) { + ArgumentNullException.ThrowIfNull(task); using var watch = task.Monitor.Watch(MethodClass, $"Check {Method.Name}()"); data = new object[Parameters.Count]; Dictionary vars; @@ -77,6 +84,7 @@ public override bool CanWorkWith(WebProgressTask task, out object?[]? data) public override void Dispose() { base.Dispose(); + GC.SuppressFinalize(this); if (MethodClass is IDisposable disposable) disposable.Dispose(); } diff --git a/MaxLib.WebServer/Builder/Runtime/Parameter.cs b/MaxLib.WebServer/Builder/Runtime/Parameter.cs index 3d31098..e4189b6 100644 --- a/MaxLib.WebServer/Builder/Runtime/Parameter.cs +++ b/MaxLib.WebServer/Builder/Runtime/Parameter.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Globalization; namespace MaxLib.WebServer.Builder.Runtime { @@ -11,17 +12,42 @@ public class Parameter : IParameter public string Name { get; } - public Parameter(string name, Tools.ParamAttributeBase source, Func converter) + /// + /// The parameter type the converted value must end up as - i.e. the target method + /// parameter's own type. Only used to build a descriptive message if throws. + /// + public Type TargetType { get; } + + public Parameter(string name, Tools.ParamAttributeBase source, Func converter, + Type targetType + ) { Name = name; ParamSource = source; Converter = converter; + TargetType = targetType; } + /// + /// Converters must throw exceptions whose Message does not throw; it is embedded in the 400 + /// response. + /// public Tools.Result GetValue(WebProgressTask task, Dictionary vars) { var value = ParamSource.GetValue(task, Name, vars); - return value.Map(Converter); + try + { + return value.Map(Converter); + } + catch (Exception ex) when (ex is not HttpException) + { + var message = string.Format(CultureInfo.InvariantCulture, + "Parameter '{0}' has an invalid value: could not convert '{1}' to '{2}' ({3}: {4})", + Name, value.Value, TargetType, ex.GetType().Name, ex.Message + ); + throw new HttpException(HttpStateCode.BadRequest, new HttpStringDataSource(message)); + } } } } \ No newline at end of file diff --git a/MaxLib.WebServer/Builder/Runtime/ServiceGroup.cs b/MaxLib.WebServer/Builder/Runtime/ServiceGroup.cs index db51fa8..f44e2e9 100644 --- a/MaxLib.WebServer/Builder/Runtime/ServiceGroup.cs +++ b/MaxLib.WebServer/Builder/Runtime/ServiceGroup.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Threading.Tasks; namespace MaxLib.WebServer.Builder.Runtime { @@ -8,6 +7,12 @@ public class ServiceGroup : WebServiceCollection { public List Rules { get; } + /// + /// The type this group was generated from, if it was built by + /// . Null for a hand-assembled group. + /// + public Type? SourceType { get; set; } + public ServiceGroup(List rules) { Rules = rules; @@ -15,6 +20,7 @@ public ServiceGroup(List rules) public override bool CheckPrecondition(WebProgressTask task) { + ArgumentNullException.ThrowIfNull(task); if (!base.CheckPrecondition(task)) return false; diff --git a/MaxLib.WebServer/Builder/Service.cs b/MaxLib.WebServer/Builder/Service.cs index 25c7bc1..27574d3 100644 --- a/MaxLib.WebServer/Builder/Service.cs +++ b/MaxLib.WebServer/Builder/Service.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Reflection; +using MaxLib.WebServer.Builder.Debugger; namespace MaxLib.WebServer.Builder { @@ -8,6 +9,14 @@ namespace MaxLib.WebServer.Builder /// This is the base class that needs all Builder Services to be found by . /// + /// + /// Every public, non-generic instance method of a subclass becomes a + /// route; a method without rule attributes matches every request that reaches its group, so + /// mark helper methods with or make them non-public. + /// Each route method is invoked on a single instance created at build time and shared by all + /// concurrent requests (every method gets its own instance), so do not keep per-request state + /// in instance fields. + /// /// /// A Builder Service /// @@ -51,6 +60,7 @@ public static Tools.GeneratorLogFlag LogBuildWarnings /// public virtual void Dispose() { + GC.SuppressFinalize(this); } /// @@ -94,6 +104,7 @@ public virtual void Dispose() /// public static WebService? Build(Assembly assembly) { + ArgumentNullException.ThrowIfNull(assembly); var group = new Runtime.ServiceGroup(new List()); foreach (var type in assembly.GetExportedTypes()) { @@ -119,6 +130,7 @@ public virtual void Dispose() /// public static WebService? Build(AppDomain appDomain) { + ArgumentNullException.ThrowIfNull(appDomain); var group = new Runtime.ServiceGroup(new List()); foreach (var assembly in appDomain.GetAssemblies()) { @@ -142,5 +154,131 @@ public virtual void Dispose() { return Build(AppDomain.CurrentDomain); } + + /// + /// Builds a from the specified type just + /// like , but additionally returns a structured + /// describing what was scanned and why anything was skipped or + /// failed. + /// + /// The type of the to build. + /// The build report for . + /// the if succeed; otherwise null + public static WebService? Build(out BuildReport report) + where T : Service, new() + { + return Build(typeof(T), out report); + } + + /// + /// Builds a from the specified type just + /// like , but additionally returns a structured + /// describing what was scanned and why anything was skipped or + /// failed. + /// + /// The that should be created + /// The build report for . + /// the if succeed; otherwise null + public static WebService? Build(Type type, out BuildReport report) + { + ArgumentNullException.ThrowIfNull(type); + WebService? result; + TypeReportNode node; + if (!typeof(Service).IsAssignableFrom(type)) + { + node = new TypeReportNode { Name = type.Name, TypeFullName = type.FullName ?? type.Name }; + Tools.Generator.LogTypeNotService(type, node); + result = null; + } + else + { + result = Tools.Generator.GenerateClass(type, out node); + } + report = new BuildReport { Source = type.FullName ?? type.Name }; + report.Roots.Add(node); + return result; + } + + /// + /// Search in for all suitable and + /// create their services just like , but additionally + /// returns a structured describing what was scanned and why + /// anything was skipped or failed. Exported types that don't inherit from + /// are only counted in + /// , not attached individually, to + /// avoid flooding the report with unrelated classes. + /// + /// The assembly to search in. + /// The build report for . + /// + /// the web service that contains all for the or null if no suitable was found. + /// + public static WebService? Build(Assembly assembly, out BuildReport report) + { + ArgumentNullException.ThrowIfNull(assembly); + report = new BuildReport { Source = assembly.GetName().Name ?? assembly.FullName ?? "" }; + var group = new Runtime.ServiceGroup(new List()); + foreach (var type in assembly.GetExportedTypes()) + { + if (!typeof(Service).IsAssignableFrom(type)) + { + report.SkippedNonServiceTypeCount++; + continue; + } + var service = Tools.Generator.GenerateClass(type, out var node); + report.Roots.Add(node); + if (service != null) + group.Add(service); + } + return group.Count == 0 ? null : group; + } + + /// + /// Search in for all suitable and + /// create their services just like , but additionally + /// returns a structured describing what was scanned and why + /// anything was skipped or failed. + /// + /// + /// The where each loaded should be + /// searched for suitable . + /// + /// The merged build report for every assembly in . + /// + /// the web service that contains all for the or null if no suitable was found. + /// + public static WebService? Build(AppDomain appDomain, out BuildReport report) + { + ArgumentNullException.ThrowIfNull(appDomain); + report = new BuildReport { Source = $"AppDomain: {appDomain.FriendlyName}" }; + var group = new Runtime.ServiceGroup(new List()); + foreach (var assembly in appDomain.GetAssemblies()) + { + var service = Build(assembly, out var assemblyReport); + report.Roots.AddRange(assemblyReport.Roots); + report.SkippedNonServiceTypeCount += assemblyReport.SkippedNonServiceTypeCount; + if (service != null) + group.Add(service); + } + return group.Count == 0 ? null : group; + } + + /// + /// Search in the current for all suitable + /// and create their services just like , but additionally returns a + /// structured describing what was scanned and why anything was + /// skipped or failed. + /// + /// The merged build report for the current . + /// + /// the web service that contains all for the or null if no suitable was found. + /// + public static WebService? Build(out BuildReport report) + { + return Build(AppDomain.CurrentDomain, out report); + } } } diff --git a/MaxLib.WebServer/Builder/TextPostAttribute.cs b/MaxLib.WebServer/Builder/TextPostAttribute.cs index 6cea614..c779ef0 100644 --- a/MaxLib.WebServer/Builder/TextPostAttribute.cs +++ b/MaxLib.WebServer/Builder/TextPostAttribute.cs @@ -11,17 +11,17 @@ public class TextPostAttribute : ParamAttributeBase public override Result GetValue(WebProgressTask task, string field, Dictionary vars) { + ArgumentNullException.ThrowIfNull(task); var post = task.Request.Post.Data; - if (!(post is MaxLib.WebServer.Post.UnknownPostData data)) + if (post is not MaxLib.WebServer.Post.RawPostData data) return new Result(); - using var reader = new StreamReader( - data.Data, - System.Text.Encoding.UTF8, - bufferSize: -1, - detectEncodingFromByteOrderMarks: false, - leaveOpen: true - ); - return new Result(reader.ReadToEnd()); + if (data.Entry.Content is ReadOnlyMemory content) + return new Result(data.Encoding.GetString(content.Span)); + if (data.Entry.TempFile is FileInfo tempFile) + return new Result(File.ReadAllText(tempFile.FullName, data.Encoding)); + return new Result(""); } + + public override string ToString() => "TextPost"; } } \ No newline at end of file diff --git a/MaxLib.WebServer/Builder/Tools/Generator.cs b/MaxLib.WebServer/Builder/Tools/Generator.cs index 97195a3..741060f 100644 --- a/MaxLib.WebServer/Builder/Tools/Generator.cs +++ b/MaxLib.WebServer/Builder/Tools/Generator.cs @@ -3,206 +3,350 @@ using System.Linq; using System.Reflection; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using MaxLib.WebServer.Builder.Debugger; namespace MaxLib.WebServer.Builder.Tools { + /// + /// Rule and parameter attributes must not throw from ToString(); build reports use it for labels. + /// Converters and converter attributes must not throw from ToString(); build reports and logs use + /// it. Exceptions thrown by Service constructors and custom converters must have a non-throwing + /// ToString(), Message and StackTrace; they are passed to the logger as-is and read when building + /// reports. + /// public static class Generator { #region Logs + static readonly ILogger logger = WebServerLog.LoggerFactory.CreateLogger(typeof(Generator)); + static readonly EventId GenerateClassEventId = new(0, "generate class"); + /// /// The flags that specify the errors the generator will report to the log output. /// public static GeneratorLogFlag LogBuildWarnings { get; set; } = GeneratorLogFlag.Default; - private static void LogTypeAbstract(Type type, bool set) + /// + /// Wraps in a marker a + /// consumer can recognize and style by (e.g. the debugger's web + /// UI renders type/method/param/return/attr identifiers + /// with distinct styling). Plain text outside a marker is rendered as-is. + /// + private static string Mark(string kind, object? value) => $"{{{{{kind}|{value}}}}}"; + + private static void LogTypeIgnored(Type type, TypeReportNode? report) + { + const GeneratorLogFlag code = GeneratorLogFlag.TypeIgnoredByAttribute; + if ((LogBuildWarnings & code) == code) + logger.LogInformation(GenerateClassEventId, + "[{Code:X4}] Type {Type} ignored because of the {Attribute} attribute", + (int)code, + type, + nameof(IgnoreAttribute) + ); + if (report != null) + { + report.Status = BuildReportStatus.Ignored; + report.Reason = BuildReasonCode.TypeIgnoredByAttribute; + report.Message = $"Type {Mark("type", type)} ignored because of the {Mark("attr", nameof(IgnoreAttribute))} attribute"; + } + } + + private static void LogTypeAbstract(Type type, bool set, TypeReportNode? report) { const GeneratorLogFlag code = GeneratorLogFlag.TypeAbstract; - if ((LogBuildWarnings & code) == code && set) - WebServerLog.Add( - ServerLogType.Information, - typeof(Generator), - "generate class", - "[{0:X4}] Type {1} ignored because it's abstract", + if (!set) + return; + if ((LogBuildWarnings & code) == code) + logger.LogInformation(GenerateClassEventId, + "[{Code:X4}] Type {Type} ignored because it's abstract", (int)code, type ); + if (report != null) + { + report.Status = BuildReportStatus.Ignored; + report.Reason = BuildReasonCode.TypeAbstract; + report.Message = $"Type {Mark("type", type)} ignored because it's abstract"; + } } - private static void LogTypeGeneric(Type type, bool set) + private static void LogTypeGeneric(Type type, bool set, TypeReportNode? report) { const GeneratorLogFlag code = GeneratorLogFlag.TypeGeneric; - if ((LogBuildWarnings & code) == code && set) - WebServerLog.Add( - ServerLogType.Information, - typeof(Generator), - "generate class", - "[{0:X4}] Type {1} ignored because it's generic", + if (!set) + return; + if ((LogBuildWarnings & code) == code) + logger.LogInformation(GenerateClassEventId, + "[{Code:X4}] Type {Type} ignored because it's generic", (int)code, type ); + if (report != null) + { + report.Status = BuildReportStatus.Ignored; + report.Reason = BuildReasonCode.TypeGeneric; + report.Message = $"Type {Mark("type", type)} ignored because it's generic"; + } } - private static void LogTypeNoConstructor(Type type) + private static void LogTypeNoConstructor(Type type, TypeReportNode? report) { const GeneratorLogFlag code = GeneratorLogFlag.TypeNoConstructor; if ((LogBuildWarnings & code) == code) - WebServerLog.Add( - ServerLogType.Information, - typeof(Generator), - "generate class", - "[{0:X4}] Type {1} ignored because it has no parameterless constructor", + logger.LogInformation(GenerateClassEventId, + "[{Code:X4}] Type {Type} ignored because it has no parameterless constructor", (int)code, type ); + if (report != null) + { + report.Status = BuildReportStatus.Ignored; + report.Reason = BuildReasonCode.TypeNoConstructor; + report.Message = $"Type {Mark("type", type)} ignored because it has no parameterless constructor"; + } } - private static void LogMethodAbstract(MethodInfo method, bool set) + /// + /// Records that was rejected by because it doesn't inherit from . Reported only through + /// ; there is no corresponding , + /// so this is never written to the log. + /// + internal static void LogTypeNotService(Type type, TypeReportNode? report) + { + if (report != null) + { + report.Status = BuildReportStatus.Failed; + report.Reason = BuildReasonCode.TypeNotService; + report.Message = $"Type {Mark("type", type)} does not inherit from {Mark("type", nameof(Service))}"; + } + } + + private static void LogMethodIgnored(MethodInfo method, MethodReportNode? report) + { + const GeneratorLogFlag code = GeneratorLogFlag.MethodIgnoredByAttribute; + if ((LogBuildWarnings & code) == code) + logger.LogInformation(GenerateClassEventId, + "[{Code:X4}] Method {Method} ignored because of the {Attribute} attribute", + (int)code, + method, + nameof(IgnoreAttribute) + ); + if (report != null) + { + report.Status = BuildReportStatus.Ignored; + report.Reason = BuildReasonCode.MethodIgnoredByAttribute; + report.Message = $"Method {Mark("method", method)} ignored because of the {Mark("attr", nameof(IgnoreAttribute))} attribute"; + } + } + + private static void LogMethodAbstract(MethodInfo method, bool set, MethodReportNode? report) { const GeneratorLogFlag code = GeneratorLogFlag.MethodAbstract; - if ((LogBuildWarnings & code) == code && set) - WebServerLog.Add( - ServerLogType.Information, - typeof(Generator), - "generate class", - "[{0:X4}] Method {1} ignored because it's abstract", + if (!set) + return; + if ((LogBuildWarnings & code) == code) + logger.LogInformation(GenerateClassEventId, + "[{Code:X4}] Method {Method} ignored because it's abstract", (int)code, method ); + if (report != null) + { + report.Status = BuildReportStatus.Ignored; + report.Reason = BuildReasonCode.MethodAbstract; + report.Message = $"Method {Mark("method", method)} ignored because it's abstract"; + } } - private static void LogMethodGeneric(MethodInfo method, bool set) + private static void LogMethodGeneric(MethodInfo method, bool set, MethodReportNode? report) { const GeneratorLogFlag code = GeneratorLogFlag.MethodGeneric; - if ((LogBuildWarnings & code) == code && set) - WebServerLog.Add( - ServerLogType.Information, - typeof(Generator), - "generate class", - "[{0:X4}] Method {1} ignored because it's generic", + if (!set) + return; + if ((LogBuildWarnings & code) == code) + logger.LogInformation(GenerateClassEventId, + "[{Code:X4}] Method {Method} ignored because it's generic", (int)code, method ); + if (report != null) + { + report.Status = BuildReportStatus.Ignored; + report.Reason = BuildReasonCode.MethodGeneric; + report.Message = $"Method {Mark("method", method)} ignored because it's generic"; + } } - private static void LogMethodNotPublic(MethodInfo method, bool set) + private static void LogMethodNotPublic(MethodInfo method, bool set, MethodReportNode? report) { const GeneratorLogFlag code = GeneratorLogFlag.MethodNotPublic; - if ((LogBuildWarnings & code) == code && set) - WebServerLog.Add( - ServerLogType.Information, - typeof(Generator), - "generate class", - "[{0:X4}] Method {1} ignored because it's not public", + if (!set) + return; + if ((LogBuildWarnings & code) == code) + logger.LogInformation(GenerateClassEventId, + "[{Code:X4}] Method {Method} ignored because it's not public", + (int)code, method ); + if (report != null) + { + report.Status = BuildReportStatus.Ignored; + report.Reason = BuildReasonCode.MethodNotPublic; + report.Message = $"Method {Mark("method", method)} ignored because it's not public"; + } } - private static void LogMethodDeclaredInObject(MethodInfo method) + private static void LogMethodDeclaredInObject(MethodInfo method, MethodReportNode? report) { const GeneratorLogFlag code = GeneratorLogFlag.MethodDeclaredInObject; if ((LogBuildWarnings & code) == code) - WebServerLog.Add( - ServerLogType.Information, - typeof(Generator), - "generate class", - "[{0:X4}] Method {1} ignored because is was declared in {2} or {3}", + logger.LogInformation(GenerateClassEventId, + "[{Code:X4}] Method {Method} ignored because is was declared in {ObjectType} or {ServiceType}", (int)code, method, typeof(object), typeof(Service) ); + if (report != null) + { + report.Status = BuildReportStatus.Ignored; + report.Reason = BuildReasonCode.MethodDeclaredInObject; + report.Message = $"Method {Mark("method", method)} ignored because is was declared in {Mark("type", typeof(object))} or {Mark("type", typeof(Service))}"; + } } - private static void LogParamMissingConvInstance(MethodInfo method, ParameterInfo param, ConverterAttribute attr) + private static void LogMethodConstructorThrew(MethodInfo method, Exception exception, MethodReportNode? report) + { + const GeneratorLogFlag code = GeneratorLogFlag.MethodConstructorThrew; + if ((LogBuildWarnings & code) == code) + logger.LogInformation(GenerateClassEventId, + exception, + "[{Code:X4}] Method {Method} ignored because the constructor of {Type} threw an exception", + (int)code, + method, + method.ReflectedType + ); + if (report != null) + { + report.Status = BuildReportStatus.Failed; + report.Reason = BuildReasonCode.MethodConstructorThrew; + report.Message = $"Method {Mark("method", method)} ignored because the constructor of {Mark("type", method.ReflectedType)} threw an exception: {exception.Message}"; + report.ExceptionMessage = exception.Message; + report.ExceptionStackTrace = exception.StackTrace; + report.Exception = exception; + } + } + + private static void LogParamMissingConvInstance(MethodInfo method, ParameterInfo param, ConverterAttribute attr, ParameterReportNode? report) { const GeneratorLogFlag code = GeneratorLogFlag.ParamMissingConverterInstance; if ((LogBuildWarnings & code) == code) - WebServerLog.Add( - ServerLogType.Information, - typeof(Generator), - "generate class", - "[{0:X4}] Method {1} ignored because parameter {2} has no converter instance set for attribute {3}", + logger.LogInformation(GenerateClassEventId, + "[{Code:X4}] Method {Method} ignored because parameter {Parameter} has no converter instance set for attribute {Attribute}", (int)code, method, param, attr ); + if (report != null) + { + report.Status = BuildReportStatus.Failed; + report.Reason = BuildReasonCode.ParamMissingConverterInstance; + report.Message = $"Parameter {Mark("param", param.Name)} has no converter instance set for attribute {Mark("attr", attr)}"; + } } - private static void LogParamNoConverterFound(MethodInfo method, ParameterInfo param, Tools.IConverter converter) + private static void LogParamNoConverterFound(MethodInfo method, ParameterInfo param, Tools.IConverter converter, ParameterReportNode? report) { const GeneratorLogFlag code = GeneratorLogFlag.ParamNoConverterFound; if ((LogBuildWarnings & code) == code) - WebServerLog.Add( - ServerLogType.Information, - typeof(Generator), - "generate class", - "[{0:X4}] Method {1} ignored because converter {2} cannot convert the type of parameter {3}", + logger.LogInformation(GenerateClassEventId, + "[{Code:X4}] Method {Method} ignored because converter {Converter} cannot convert the type of parameter {Parameter}", (int)code, method, converter, param ); + if (report != null) + { + report.Status = BuildReportStatus.Failed; + report.Reason = BuildReasonCode.ParamNoConverterFound; + report.Message = $"Converter {Mark("type", converter)} cannot convert the type of parameter {Mark("param", param.Name)}"; + } } - private static void LogParamNoCoreConverterFound(MethodInfo method, ParameterInfo param) + private static void LogParamNoCoreConverterFound(MethodInfo method, ParameterInfo param, ParameterReportNode? report) { const GeneratorLogFlag code = GeneratorLogFlag.ParamNoCoreConverterFound; if ((LogBuildWarnings & code) == code) - WebServerLog.Add( - ServerLogType.Information, - typeof(Generator), - "generate class", - "[{0:X4}] Method {1} ignored because the core generator cannot convert the type of parameter {2}", + logger.LogInformation(GenerateClassEventId, + "[{Code:X4}] Method {Method} ignored because the core generator cannot convert the type of parameter {Parameter}", (int)code, method, param ); + if (report != null) + { + report.Status = BuildReportStatus.Failed; + report.Reason = BuildReasonCode.ParamNoCoreConverterFound; + report.Message = $"The core generator cannot convert the type of parameter {Mark("param", param.Name)}"; + } } - private static void LogResultInvalidConverterType(MethodInfo method, DataConverterAttribute attr) + private static void LogResultInvalidConverterType(MethodInfo method, DataConverterAttribute attr, ResultReportNode? report) { const GeneratorLogFlag code = GeneratorLogFlag.ResultInvalidConverterType; if ((LogBuildWarnings & code) == code) - WebServerLog.Add( - ServerLogType.Information, - typeof(Generator), - "generate class", - "[{0:X4}] Method {1} ignored because the result data converter {2} has an invalid type provided", + logger.LogInformation(GenerateClassEventId, + "[{Code:X4}] Method {Method} ignored because the result data converter {Attribute} has an invalid type provided", (int)code, method, attr ); + if (report != null) + { + report.Status = BuildReportStatus.Failed; + report.Reason = BuildReasonCode.ResultInvalidConverterType; + report.Message = $"The result data converter {Mark("attr", attr)} has an invalid type provided"; + } } - private static void LogResultCannotCreateConverterInstance(MethodInfo method, DataConverterAttribute attr) + private static void LogResultCannotCreateConverterInstance(MethodInfo method, DataConverterAttribute attr, ResultReportNode? report) { const GeneratorLogFlag code = GeneratorLogFlag.ResultCannotCreateConverterInstance; if ((LogBuildWarnings & code) == code) - WebServerLog.Add( - ServerLogType.Information, - typeof(Generator), - "generate class", - "[{0:X4}] Method {1} ignored because there cannot be created an instance for the result data converter {2}", + logger.LogInformation(GenerateClassEventId, + "[{Code:X4}] Method {Method} ignored because there cannot be created an instance for the result data converter {Converter}", (int)code, method, attr.Converter ); + if (report != null) + { + report.Status = BuildReportStatus.Failed; + report.Reason = BuildReasonCode.ResultCannotCreateConverterInstance; + report.Message = $"There cannot be created an instance for the result data converter {Mark("type", attr.Converter)}"; + } } - private static void LogResultNoConverter(MethodInfo method) + private static void LogResultNoConverter(MethodInfo method, ResultReportNode? report) { const GeneratorLogFlag code = GeneratorLogFlag.ResultNoConverter; if ((LogBuildWarnings & code) == code) - WebServerLog.Add( - ServerLogType.Information, - typeof(Generator), - "generate class", - "[{0:X4}] Method {1} ignored because for the result type is no suitable converter found or set", + logger.LogInformation(GenerateClassEventId, + "[{Code:X4}] Method {Method} ignored because for the result type is no suitable converter found or set", (int)code, method ); + if (report != null) + { + report.Status = BuildReportStatus.Failed; + report.Reason = BuildReasonCode.ResultNoConverter; + report.Message = $"For the result type {Mark("return", method.ReturnType)} is no suitable converter found or set"; + } } @@ -214,82 +358,290 @@ private static readonly Converter.DataConverter dataConverter = new Builder.Converter.DataConverter(); public static Runtime.ServiceGroup? GenerateClass(Type type) + { + ArgumentNullException.ThrowIfNull(type); + return GenerateClassCore(type, null); + } + + /// + /// Builds a from just like + /// , but additionally returns a structured + /// of the type, its methods, their parameters and results, + /// including why anything that wasn't built got skipped or failed. + /// + public static Runtime.ServiceGroup? GenerateClass(Type type, out TypeReportNode report) + { + ArgumentNullException.ThrowIfNull(type); + var node = new TypeReportNode + { + Name = type.Name, + TypeFullName = type.FullName ?? type.Name, + }; + var result = GenerateClassCore(type, node); + report = node; + return result; + } + + /// + /// The specificity of 's own + /// rule, if it has one, else 0 - used to order overlapping routes that share the same + /// . See . + /// + private static int MethodSpecificity(Runtime.MethodService method) + => method.Rules.OfType().FirstOrDefault()?.Specificity ?? 0; + + private static Runtime.ServiceGroup? GenerateClassCore(Type type, TypeReportNode? report) { var ignore = type.GetCustomAttribute(); - if (ignore != null || type.IsAbstract || type.IsGenericType) + if (ignore != null) { - LogTypeAbstract(type, type.IsAbstract); - LogTypeGeneric(type, type.IsGenericType); + LogTypeIgnored(type, report); return null; } - + if (type.IsAbstract || type.IsGenericType) + { + LogTypeAbstract(type, type.IsAbstract, report); + LogTypeGeneric(type, type.IsGenericType, report); + return null; + } + var constructor = type.GetConstructor(Type.EmptyTypes); if (constructor == null) { - LogTypeNoConstructor(type); + LogTypeNoConstructor(type, report); return null; } var rules = type.GetCustomAttributes().ToList(); - var group = new Runtime.ServiceGroup(rules); + var group = new Runtime.ServiceGroup(rules) + { + SourceType = type, + }; + if (report != null) + report.Rules.AddRange(rules.Select(r => r.ToString() ?? r.GetType().Name)); + var generatedMethods = new List(); foreach (var methodInfo in type.GetMethods()) { - var method = GenerateMethod(methodInfo); + MethodReportNode? methodReport = report != null + ? new MethodReportNode + { + Name = methodInfo.Name, + DeclaringType = methodInfo.DeclaringType?.FullName ?? "", + } + : null; + var method = GenerateMethodCore(methodInfo, methodReport); if (method != null) - group.Add(method); + generatedMethods.Add(method); + if (methodReport != null) + report!.Methods.Add(methodReport); } + // Type.GetMethods() order is documented as unspecified. Adding the more specific + // route first, for methods that end up sharing the same WebServicePriority, makes + // its PriorityList place it ahead - see PathAttribute.Specificity. + foreach (var method in generatedMethods.OrderByDescending(MethodSpecificity)) + group.Add(method); foreach (var nested in type.GetNestedTypes()) { - var service = GenerateClass(nested); + TypeReportNode? nestedReport = report != null + ? new TypeReportNode + { + Name = nested.Name, + TypeFullName = nested.FullName ?? nested.Name, + } + : null; + var service = GenerateClassCore(nested, nestedReport); if (service != null) group.Add(service); + if (nestedReport != null) + report!.NestedTypes.Add(nestedReport); } + if (report != null) + { + report.Status = BuildReportStatus.Accepted; + report.Reason = BuildReasonCode.Accepted; + report.Message = $"Type {Mark("type", type)} built successfully with {group.Count} contained service(s)"; + } return group; } public static Runtime.MethodService? GenerateMethod(MethodInfo method) { + ArgumentNullException.ThrowIfNull(method); + return GenerateMethodCore(method, null); + } + + /// + /// Builds a from just like + /// , but additionally returns a structured + /// of the method, its parameters and its result, including why + /// it might have been skipped or failed. + /// + public static Runtime.MethodService? GenerateMethod(MethodInfo method, out MethodReportNode report) + { + ArgumentNullException.ThrowIfNull(method); + var node = new MethodReportNode + { + Name = method.Name, + DeclaringType = method.DeclaringType?.FullName ?? "", + }; + var result = GenerateMethodCore(method, node); + report = node; + return result; + } + + private static Runtime.MethodService? GenerateMethodCore(MethodInfo method, MethodReportNode? report) + { + var priorityAttr = method.GetCustomAttribute(); + var priority = priorityAttr?.Priority ?? WebServicePriority.Normal; + if (report != null && priorityAttr != null) + report.Priority = priority.ToString(); + var ignore = method.GetCustomAttribute(); - if (ignore != null || method.IsAbstract || method.IsGenericMethod || !method.IsPublic) + if (ignore != null) + { + LogMethodIgnored(method, report); + return null; + } + if (method.IsAbstract || method.IsGenericMethod || !method.IsPublic) { - LogMethodAbstract(method, method.IsAbstract); - LogMethodGeneric(method, method.IsGenericMethod); - LogMethodNotPublic(method, !method.IsPublic); + LogMethodAbstract(method, method.IsAbstract, report); + LogMethodGeneric(method, method.IsGenericMethod, report); + LogMethodNotPublic(method, !method.IsPublic, report); return null; } - + if (method.DeclaringType == typeof(object) || method.DeclaringType == typeof(Service)) { - LogMethodDeclaredInObject(method); + LogMethodDeclaredInObject(method, report); return null; } - + var rules = method.GetCustomAttributes().ToList(); + if (report != null) + report.Rules.AddRange(rules.Select(r => r.ToString() ?? r.GetType().Name)); + var parameter = new List(); foreach (var parInfo in method.GetParameters()) { - var par = GenerateParameter(method, parInfo); + ParameterReportNode? paramReport = report != null + ? new ParameterReportNode + { + Name = parInfo.Name ?? "", + ParameterType = parInfo.ParameterType.FullName ?? parInfo.ParameterType.Name, + } + : null; + var par = GenerateParameterCore(method, parInfo, paramReport); + if (paramReport != null) + report!.Parameters.Add(paramReport); if (par == null) + { + if (report != null) + { + report.Status = BuildReportStatus.Failed; + report.Reason = paramReport!.Reason; + report.Message = $"Method {Mark("method", method)} ignored because parameter {Mark("param", parInfo.Name)} could not be generated: {paramReport.Message}"; + } return null; + } parameter.Add(par); } - var result = GenerateResult(method); + ResultReportNode? resultReport = report != null + ? new ResultReportNode + { + Name = "return", + ReturnType = method.ReturnType.FullName ?? method.ReturnType.Name, + } + : null; + var result = GenerateResultCore(method, resultReport); + if (resultReport != null) + report!.Result = resultReport; if (result == null) + { + if (report != null) + { + report.Status = BuildReportStatus.Failed; + report.Reason = resultReport!.Reason; + report.Message = $"Method {Mark("method", method)} ignored because the result could not be generated: {resultReport.Message}"; + } + return null; + } + + try + { + var service = new Runtime.MethodService(rules, parameter, method, result, priority); + if (report != null) + { + report.Status = BuildReportStatus.Accepted; + report.Reason = BuildReasonCode.Accepted; + report.Message = $"Method {Mark("method", method)} built successfully"; + } + return service; + } + catch (Exception e) + { + var inner = e is TargetInvocationException tie && tie.InnerException != null + ? tie.InnerException + : e; + LogMethodConstructorThrew(method, inner, report); return null; - - var priority = method.GetCustomAttribute(); - return new Runtime.MethodService(rules, parameter, method, result, - priority != null ? priority.Priority : WebServicePriority.Normal - ); + } } public static Runtime.IParameter? GenerateParameter(MethodInfo method, ParameterInfo parameter) + { + ArgumentNullException.ThrowIfNull(parameter); + return GenerateParameterCore(method, parameter, null); + } + + /// + /// Builds a from just like + /// , but additionally returns a + /// structured describing why it might have failed. + /// + public static Runtime.IParameter? GenerateParameter(MethodInfo method, ParameterInfo parameter, out ParameterReportNode report) + { + ArgumentNullException.ThrowIfNull(parameter); + var node = new ParameterReportNode + { + Name = parameter.Name ?? "", + ParameterType = parameter.ParameterType.FullName ?? parameter.ParameterType.Name, + }; + var result = GenerateParameterCore(method, parameter, node); + report = node; + return result; + } + + /// + /// Describes how a parameter's value is resolved via : the + /// attribute plus the key it actually reads - which can differ from 's own name via e.g. [Var("foo")]. Delegates to the + /// attribute's own when it has an explicit name to report + /// (read generically via reflection on a conventional string? Name property, since + /// attributes like // all expose it the same way but don't share an + /// interface for it); otherwise falls back to the parameter's own name, since that's + /// contextual information the attribute instance alone doesn't have. + /// + private static string DescribeParamSource(ParamAttributeBase paramAttr, ParameterInfo parameter) + { + var nameProperty = paramAttr.GetType().GetProperty("Name", typeof(string)); + if (nameProperty?.GetValue(paramAttr) is string { Length: > 0 }) + return paramAttr.ToString() ?? paramAttr.GetType().Name; + var typeName = paramAttr.GetType().Name; + if (typeName.EndsWith("Attribute", StringComparison.Ordinal)) + typeName = typeName[..^9]; + return $"{typeName}: {parameter.Name}"; + } + + private static Runtime.IParameter? GenerateParameterCore(MethodInfo method, ParameterInfo parameter, ParameterReportNode? report) { var convAttr = parameter.GetCustomAttribute(true); var paramAttr = parameter.GetCustomAttribute(true); + if (report != null && paramAttr != null) + report.Source = DescribeParamSource(paramAttr, parameter); if (paramAttr != null) { Tools.IConverter converter; @@ -297,7 +649,7 @@ private static readonly Converter.DataConverter dataConverter { if (convAttr.Instance == null) { - LogParamMissingConvInstance(method, parameter, convAttr); + LogParamMissingConvInstance(method, parameter, convAttr, report); return null; } converter = convAttr.Instance; @@ -306,21 +658,55 @@ private static readonly Converter.DataConverter dataConverter var convFunc = converter.GetConverter(paramAttr.Type, parameter.ParameterType); if (convFunc == null) { - LogParamNoConverterFound(method, parameter, converter); + LogParamNoConverterFound(method, parameter, converter, report); return null; } - return new Runtime.Parameter(parameter.Name ?? "", paramAttr, convFunc); + if (report != null) + report.Message = $"Parameter {Mark("param", parameter.Name)} resolved via {Mark("attr", paramAttr.GetType().Name)}"; + return new Runtime.Parameter(parameter.Name ?? "", paramAttr, convFunc, parameter.ParameterType); } else { var param = Runtime.CoreParameter.GetCoreParameter(parameter.ParameterType); if (param is null) - LogParamNoCoreConverterFound(method, parameter); + { + LogParamNoCoreConverterFound(method, parameter, report); + return null; + } + if (report != null) + { + report.Source = "Core parameter"; + report.Message = $"Parameter {Mark("param", parameter.Name)} resolved as core parameter"; + } return param; } } public static Func? GenerateResult(MethodInfo method) + { + ArgumentNullException.ThrowIfNull(method); + return GenerateResultCore(method, null); + } + + /// + /// Builds a result converter from 's return type just like + /// , but additionally returns a structured + /// describing why it might have failed. + /// + public static Func? GenerateResult(MethodInfo method, out ResultReportNode report) + { + ArgumentNullException.ThrowIfNull(method); + var node = new ResultReportNode + { + Name = "return", + ReturnType = method.ReturnType.FullName ?? method.ReturnType.Name, + }; + var result = GenerateResultCore(method, node); + report = node; + return result; + } + + private static Func? GenerateResultCore(MethodInfo method, ResultReportNode? report) { var convAttr = method.ReturnParameter.GetCustomAttribute(); IDataConverter converter; @@ -330,32 +716,41 @@ private static readonly Converter.DataConverter dataConverter { if (!typeof(Tools.IDataConverter).IsAssignableFrom(convAttr.Converter)) { - LogResultInvalidConverterType(method, convAttr); + if (report != null) + report.Converter = convAttr.Converter.Name; + LogResultInvalidConverterType(method, convAttr, report); return null; } var constructed = convAttr.Converter.GetConstructor(Type.EmptyTypes)? - .Invoke(Array.Empty()); + .Invoke([]); if (constructed == null) { - LogResultCannotCreateConverterInstance(method, convAttr); + if (report != null) + report.Converter = convAttr.Converter.Name; + LogResultCannotCreateConverterInstance(method, convAttr, report); return null; } converter = (Tools.IDataConverter)constructed; } else converter = dataConverter; - + var resultMethod = GenerateResult(converter, method.ReturnType); if (resultMethod == null) { - LogResultNoConverter(method); + LogResultNoConverter(method, report); return null; } + if (report != null) + { + report.Converter = converter.GetType().Name; + report.Message = $"Result type {Mark("return", method.ReturnType)} resolved successfully"; + } var mime = method.ReturnParameter.GetCustomAttribute(); if (mime != null) { - return async (t, v) => + return async (t, v) => { - await resultMethod(t, v); + await resultMethod(t, v).ConfigureAwait(false); t.Document.PrimaryMime = mime.Mime; }; } @@ -364,6 +759,7 @@ private static readonly Converter.DataConverter dataConverter public static Func? GenerateResult(IDataConverter converter, Type type) { + ArgumentNullException.ThrowIfNull(type); if (type == typeof(void)) return (_, __) => Task.CompletedTask; if (type == typeof(Task)) @@ -381,7 +777,7 @@ private static readonly Converter.DataConverter dataConverter { if (value is null) return; - await (Task)value; + await ((Task)value).ConfigureAwait(false); var result = getResult.GetValue(value); applier(task, result); }; @@ -397,7 +793,7 @@ private static readonly Converter.DataConverter dataConverter { if (value is null) return; - await (ValueTask)value; + await ((ValueTask)value).ConfigureAwait(false); var result = getResult.GetValue(value); applier(task, result); }; @@ -417,10 +813,11 @@ private static readonly Converter.DataConverter dataConverter public static Action? ApplyResult(IDataConverter converter, Type type) { + ArgumentNullException.ThrowIfNull(converter); var conv = converter.GetConverter(type); if (conv is null) return null; - return (task, value) => + return (task, value) => { if (value != null) { @@ -436,4 +833,4 @@ private static readonly Converter.DataConverter dataConverter }; } } -} \ No newline at end of file +} diff --git a/MaxLib.WebServer/Builder/Tools/GeneratorLogFlag.cs b/MaxLib.WebServer/Builder/Tools/GeneratorLogFlag.cs index 83e1652..a745d0d 100644 --- a/MaxLib.WebServer/Builder/Tools/GeneratorLogFlag.cs +++ b/MaxLib.WebServer/Builder/Tools/GeneratorLogFlag.cs @@ -68,14 +68,31 @@ public enum GeneratorLogFlag : int /// ResultNoConverter = 0x1000, /// + /// The type has the set. This is usually + /// intentional and therefore not part of . + /// + TypeIgnoredByAttribute = 0x2000, + /// + /// The method has the set. This is usually + /// intentional and therefore not part of . + /// + MethodIgnoredByAttribute = 0x4000, + /// + /// The constructor of the declaring type threw an exception when the generator tried to + /// create an instance to bind the method to. This is always unintentional, so it is part + /// of . + /// + MethodConstructorThrew = 0x8000, + /// /// The default configuration generator logs. This will report anything that is more /// difficult to find and has a high probability to be miss configured. /// Default = ParamMissingConverterInstance | ParamNoConverterFound | ParamNoCoreConverterFound - | ResultInvalidConverterType | ResultCannotCreateConverterInstance | ResultNoConverter, + | ResultInvalidConverterType | ResultCannotCreateConverterInstance | ResultNoConverter + | MethodConstructorThrew, /// /// Reports everything /// - All = 0x1fff, + All = 0xffff, } } \ No newline at end of file diff --git a/MaxLib.WebServer/Builder/Tools/ParamAttributeBase.cs b/MaxLib.WebServer/Builder/Tools/ParamAttributeBase.cs index 6055837..046783e 100644 --- a/MaxLib.WebServer/Builder/Tools/ParamAttributeBase.cs +++ b/MaxLib.WebServer/Builder/Tools/ParamAttributeBase.cs @@ -3,6 +3,11 @@ namespace MaxLib.WebServer.Builder.Tools { + /// + /// A ParamAttributeBase's Name property must not throw; build reports read it via reflection. + /// Values produced by a custom ParamAttributeBase must have a non-throwing ToString(); it is used + /// in conversion error messages. + /// [System.AttributeUsage(System.AttributeTargets.Parameter, Inherited = true, AllowMultiple = false)] public abstract class ParamAttributeBase : Attribute { @@ -14,6 +19,10 @@ public abstract class ParamAttributeBase : Attribute /// public abstract Type Type { get; } + /// + /// Reject a request by returning an empty result or throwing ; + /// any other exception propagates out of routing and RoutingDryRun unhandled. + /// public abstract Tools.Result GetValue(WebProgressTask task, string field, Dictionary vars ); diff --git a/MaxLib.WebServer/Builder/Tools/Result.cs b/MaxLib.WebServer/Builder/Tools/Result.cs index c8d5491..fa24c1d 100644 --- a/MaxLib.WebServer/Builder/Tools/Result.cs +++ b/MaxLib.WebServer/Builder/Tools/Result.cs @@ -28,6 +28,7 @@ public T Value public Result Map(Func mapper) { + ArgumentNullException.ThrowIfNull(mapper); if (hasValue) return new Result(mapper(value)); else return new Result(); @@ -35,6 +36,7 @@ public Result Map(Func mapper) public Result AndThen(Func> func) { + ArgumentNullException.ThrowIfNull(func); if (hasValue) return func(value); else return new Result(); diff --git a/MaxLib.WebServer/Builder/UrlEncodedPostAttribute.cs b/MaxLib.WebServer/Builder/UrlEncodedPostAttribute.cs index cbf9102..1607bbc 100644 --- a/MaxLib.WebServer/Builder/UrlEncodedPostAttribute.cs +++ b/MaxLib.WebServer/Builder/UrlEncodedPostAttribute.cs @@ -1,5 +1,8 @@ using System; using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; using MaxLib.WebServer.Builder.Tools; namespace MaxLib.WebServer.Builder @@ -36,12 +39,26 @@ public UrlEncodedPostAttribute(string name) public override Result GetValue(WebProgressTask task, string field, Dictionary vars) { + ArgumentNullException.ThrowIfNull(task); var post = task.Request.Post.Data; if (!(post is Post.UrlEncodedData data)) return new Result(); - if (!data.Parameter.TryGetValue(Name ?? field, out string? value)) + var key = Name ?? field; + if (data.Parameter.TryGetValue(key, out string? value)) + return new Result(value); + // above UrlEncodedData.MaximumCacheSize every field lives in Overflow and Parameter stays empty + var entry = data.Overflow?.Entries + .OfType() + .FirstOrDefault(e => e.Name == key); + if (entry == null) return new Result(); - return new Result(value); + if (entry.Content is ReadOnlyMemory content) + return new Result(Encoding.UTF8.GetString(content.Span)); + if (entry.TempFile is FileInfo tempFile) + return new Result(File.ReadAllText(tempFile.FullName, Encoding.UTF8)); + return new Result(""); } + + public override string ToString() => Name != null ? $"UrlEncodedPost: {Name}" : "UrlEncodedPost"; } } \ No newline at end of file diff --git a/MaxLib.WebServer/Builder/VarAttribute.cs b/MaxLib.WebServer/Builder/VarAttribute.cs index c502e71..0101322 100644 --- a/MaxLib.WebServer/Builder/VarAttribute.cs +++ b/MaxLib.WebServer/Builder/VarAttribute.cs @@ -42,5 +42,7 @@ public VarAttribute(string name) return new Result(); return new Result(value); } + + public override string ToString() => Name != null ? $"Var: {Name}" : "Var"; } } \ No newline at end of file diff --git a/MaxLib.WebServer/Chunked/ChunkedResponseCreator.cs b/MaxLib.WebServer/Chunked/ChunkedResponseCreator.cs index 1c65624..0269f7a 100644 --- a/MaxLib.WebServer/Chunked/ChunkedResponseCreator.cs +++ b/MaxLib.WebServer/Chunked/ChunkedResponseCreator.cs @@ -1,4 +1,5 @@ using MaxLib.WebServer.Lazy; +using System; using System.Linq; using System.Threading.Tasks; @@ -20,25 +21,29 @@ public ChunkedResponseCreator(bool onlyWithLazy = false) public override bool CanWorkWith(WebProgressTask task) { + ArgumentNullException.ThrowIfNull(task); +#pragma warning disable CS0618 // Remote.MarshalSource is obsolete; support kept until its removal return !OnlyWithLazy || (task.Document.DataSources.Count > 0 && task.Document.DataSources.Any((s) => s is LazySource || (s is Remote.MarshalSource ms && ms.IsLazy) )) || task.Document.DataSources.Any(s => s.Length() is null); +#pragma warning restore CS0618 } public override async Task ProgressTask(WebProgressTask task) { + ArgumentNullException.ThrowIfNull(task); var request = task.Request; var response = task.Response; response.FieldContentType = task.Document.PrimaryMime; response.SetActualDate(); response.HttpProtocol = request.HttpProtocol; - response.SetHeader(new (string, string?)[] - { + response.SetHeader( + [ ("Connection", "keep-alive"), ("X-UA-Compatible", "IE=Edge"), ("Transfer-Encoding", "chunked"), - }); + ]); if (task.Document.PrimaryEncoding != null) response.HeaderParameter["Content-Type"] += "; charset=" + task.Document.PrimaryEncoding; diff --git a/MaxLib.WebServer/Chunked/ChunkedSender.cs b/MaxLib.WebServer/Chunked/ChunkedSender.cs index d41daad..02bb953 100644 --- a/MaxLib.WebServer/Chunked/ChunkedSender.cs +++ b/MaxLib.WebServer/Chunked/ChunkedSender.cs @@ -1,5 +1,7 @@ using MaxLib.WebServer.Lazy; +using Microsoft.Extensions.Logging; using System; +using System.Globalization; using System.IO; using System.Linq; using System.Threading.Tasks; @@ -11,86 +13,129 @@ namespace MaxLib.WebServer.Chunked { public class ChunkedSender : Services.HttpSender { + static readonly ILogger logger = WebServerLog.LoggerFactory.CreateLogger(); + static readonly EventId SendEventId = new(0, "Send"); + static readonly EventId WriteStreamEventId = new(1, "Write Stream"); + + /// + /// Thrown by 's unbounded-length path when the + /// source's WriteStream fails after the response has started. Deliberately neither an + /// (the send loop treats that as a client disconnect) nor an HttpException + /// (that would build a new response that can no longer reach the client), so it reaches + /// Server.ProcessTask, which closes the connection and leaves the chunked body unterminated. + /// + internal sealed class WriteStreamFailedException : Exception + { + public WriteStreamFailedException(Exception innerException) + : base("WriteStream failed while bridging an unbounded-length source through ChunkedSender.", innerException) + { + } + } + + private sealed class WriteFaultBox + { + public volatile Exception? Exception; + } + public bool OnlyWithLazy { get; private set; } public ChunkedSender(bool onlyWithLazy = false) : base() { OnlyWithLazy = onlyWithLazy; - if (onlyWithLazy) + if (onlyWithLazy) Priority = WebServicePriority.High; } public override bool CanWorkWith(WebProgressTask task) { + ArgumentNullException.ThrowIfNull(task); +#pragma warning disable CS0618 // Remote.MarshalSource is obsolete; support kept until its removal return !OnlyWithLazy || (task.Document.DataSources.Count > 0 && task.Document.DataSources.Any((s) => s is LazySource || (s is Remote.MarshalSource ms && ms.IsLazy) )) || task.Document.DataSources.Any(s => s.Length() is null); +#pragma warning restore CS0618 } public override async Task ProgressTask(WebProgressTask task) { + ArgumentNullException.ThrowIfNull(task); var header = task.Response; var stream = task.NetworkStream; if (stream is null) return; - var writer = new StreamWriter(stream); - await writer.WriteAsync(header.HttpProtocol).ConfigureAwait(false); - await writer.WriteAsync(" ").ConfigureAwait(false); - await writer.WriteAsync(((int)header.StatusCode).ToString()).ConfigureAwait(false); - await writer.WriteAsync(" ").ConfigureAwait(false); - await writer.WriteLineAsync(StatusCodeText(header.StatusCode)).ConfigureAwait(false); - for (int i = 0; i < header.HeaderParameter.Count; ++i) //Parameter - { - var e = header.HeaderParameter.ElementAt(i); - if (e.Key == "Content-Length") - continue; - await writer.WriteAsync(e.Key).ConfigureAwait(false); - await writer.WriteAsync(": ").ConfigureAwait(false); - await writer.WriteLineAsync(e.Value).ConfigureAwait(false); - } - foreach (var cookie in task.Request.Cookie.AddedCookies) //Cookies - { - await writer.WriteAsync("Set-Cookie: ").ConfigureAwait(false); - await writer.WriteLineAsync(cookie.ToString()).ConfigureAwait(false); - } - await writer.WriteLineAsync().ConfigureAwait(false); - try { await writer.FlushAsync().ConfigureAwait(false); await stream.FlushAsync().ConfigureAwait(false); } - catch (ObjectDisposedException) - { - WebServerLog.Add(ServerLogType.Information, GetType(), "Send", "Connection closed by remote host."); - return; - } - catch (IOException) - { - WebServerLog.Add(ServerLogType.Information, GetType(), "Send", "Connection closed by remote host."); - return; - } - //send data try { - if (!(task.Document.Information.ContainsKey("Only Header") && (bool)task.Document.Information["Only Header"]!)) +#pragma warning disable CA2000 // must not dispose: would close the still-needed connection stream, and StreamWriter's default no-BOM encoding must not be swapped just to add leaveOpen + var writer = new StreamWriter(stream); +#pragma warning restore CA2000 + await writer.WriteAsync(header.HttpProtocol).ConfigureAwait(false); + await writer.WriteAsync(" ").ConfigureAwait(false); + await writer.WriteAsync(((int)header.StatusCode).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false); + await writer.WriteAsync(" ").ConfigureAwait(false); + await writer.WriteLineAsync(StatusCodeText(header.StatusCode)).ConfigureAwait(false); + for (int i = 0; i < header.HeaderParameter.Count; ++i) //Parameter { - foreach (var s in task.Document.DataSources) - await SendChunk(writer, stream, s).ConfigureAwait(false); - await writer.WriteLineAsync("0").ConfigureAwait(false); - await writer.WriteLineAsync().ConfigureAwait(false); - await writer.FlushAsync().ConfigureAwait(false); - await stream.FlushAsync().ConfigureAwait(false); + var e = header.HeaderParameter.ElementAt(i); + if (e.Key == "Content-Length") + continue; + await writer.WriteAsync(WebServerUtils.RemoveCrLf(e.Key)).ConfigureAwait(false); + await writer.WriteAsync(": ").ConfigureAwait(false); + await writer.WriteLineAsync(WebServerUtils.RemoveCrLf(e.Value)).ConfigureAwait(false); + } + foreach (var cookie in task.Request.Cookie.AddedCookies) //Cookies + { + await writer.WriteAsync("Set-Cookie: ").ConfigureAwait(false); + await writer.WriteLineAsync(cookie.Value.ToString()).ConfigureAwait(false); + } + await writer.WriteLineAsync().ConfigureAwait(false); + try { await writer.FlushAsync().ConfigureAwait(false); await stream.FlushAsync().ConfigureAwait(false); } + catch (ObjectDisposedException) + { + logger.LogInformation(SendEventId, "Connection closed by remote host."); + return; + } + catch (IOException) + { + logger.LogInformation(SendEventId, "Connection closed by remote host."); + return; + } + //send data + try + { + if (!(task.Document.Information.ContainsKey("Only Header") && (bool)task.Document.Information["Only Header"]!)) + { + foreach (var s in task.Document.DataSources) + await SendChunk(writer, stream, s).ConfigureAwait(false); + await writer.WriteLineAsync("0").ConfigureAwait(false); + await writer.WriteLineAsync().ConfigureAwait(false); + await writer.FlushAsync().ConfigureAwait(false); + await stream.FlushAsync().ConfigureAwait(false); + } + } + catch (IOException) + { + logger.LogInformation(SendEventId, "Connection closed by remote host."); + return; } } - catch (IOException) + finally { - WebServerLog.Add(ServerLogType.Information, GetType(), "Send", "Connection closed by remote host."); - return; + // replaces HttpSender.ProgressTask entirely, so it must dispose the request's POST data itself + // (temp files, unread body bytes on a keep-alive connection) + await DisposeRequestPostAsync(task).ConfigureAwait(false); } } protected virtual async Task SendChunk(StreamWriter writer, Stream stream, HttpDataSource source) { + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(stream); + ArgumentNullException.ThrowIfNull(source); if (source is LazySource lazySource) foreach (var s in lazySource.GetAllSources()) await SendChunk(writer, stream, s).ConfigureAwait(false); +#pragma warning disable CS0618 // Remote.MarshalSource is obsolete; support kept until its removal else if (source is Remote.MarshalSource ms && ms.IsLazy) { var lazySources = ms.GetAllSources(); @@ -98,6 +143,7 @@ protected virtual async Task SendChunk(StreamWriter writer, Stream stream, HttpD foreach (var s in lazySources) await SendChunk(writer, stream, s).ConfigureAwait(false); } +#pragma warning restore CS0618 else if (source is HttpChunkedStream) { await stream.FlushAsync().ConfigureAwait(false); @@ -112,12 +158,38 @@ protected virtual async Task SendChunk(StreamWriter writer, Stream stream, HttpD if (length == null) using (var sink = new BufferedSinkStream()) { + var fault = new WriteFaultBox(); _ = Task.Run(async () => { - await source.WriteStream(sink).ConfigureAwait(false); - sink.FinishWrite(); + try + { + await source.WriteStream(sink).ConfigureAwait(false); + } + catch (Exception e) + { + // The reader must always observe completion, even if WriteStream fails before calling FinishWrite(), + // or it blocks forever. The captured exception is surfaced below once the reader has drained the written data. + fault.Exception = e; + try + { + logger.LogError(WriteStreamEventId, e, + "WriteStream failed while bridging an unbounded-length source through ChunkedSender"); + } + catch (Exception) + { + // logging itself must never crash this background task + } + } + finally + { + sink.FinishWrite(); + } }); +#pragma warning disable CA2000 // sink already has its own using-block; HttpChunkedStream.Dispose() disposing it a second time is safe, adding a using here isn't await SendChunk(writer, stream, new HttpChunkedStream(sink)).ConfigureAwait(false); +#pragma warning restore CA2000 + if (fault.Exception is Exception writeException) + throw new WriteStreamFailedException(writeException); } //using (var m = new MemoryStream()) //{ @@ -132,7 +204,7 @@ protected virtual async Task SendChunk(StreamWriter writer, Stream stream, HttpD else { if (length.Value == 0) return; - await writer.WriteLineAsync(length.Value.ToString("X")).ConfigureAwait(false); + await writer.WriteLineAsync(length.Value.ToString("X", CultureInfo.InvariantCulture)).ConfigureAwait(false); await writer.FlushAsync().ConfigureAwait(false); await source.WriteStream(stream).ConfigureAwait(false); } diff --git a/MaxLib.WebServer/Chunked/HttpChunkedStream.cs b/MaxLib.WebServer/Chunked/HttpChunkedStream.cs index 00daf83..3a9ef33 100644 --- a/MaxLib.WebServer/Chunked/HttpChunkedStream.cs +++ b/MaxLib.WebServer/Chunked/HttpChunkedStream.cs @@ -1,4 +1,5 @@ using System; +using Microsoft.Extensions.Logging; using System.IO; using System.Text; using System.Globalization; @@ -11,11 +12,13 @@ namespace MaxLib.WebServer.Chunked [Serializable] public class HttpChunkedStream : HttpDataSource { + static readonly ILogger logger = WebServerLog.LoggerFactory.CreateLogger(); + static readonly EventId WriteEventId = new(0, "write"); + public HttpChunkedStream(Stream baseStream, int readBufferLength = 0x8000) { BaseStream = baseStream ?? throw new ArgumentNullException(nameof(baseStream)); - if (readBufferLength <= 0) - throw new ArgumentOutOfRangeException(nameof(readBufferLength)); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(readBufferLength); ReadBufferLength = readBufferLength; } @@ -28,10 +31,12 @@ public HttpChunkedStream(Stream baseStream, int readBufferLength = 0x8000) public override void Dispose() { BaseStream.Dispose(); + GC.SuppressFinalize(this); } protected override async Task WriteStreamInternal(Stream stream) { + ArgumentNullException.ThrowIfNull(stream); long total = 0; int read; Memory buffer = new byte[ReadBufferLength]; @@ -42,7 +47,7 @@ protected override async Task WriteStreamInternal(Stream stream) read = await BaseStream.ReadAsync(buffer).ConfigureAwait(false); if (read <= 0) return total; - ReadOnlyMemory length = ascii.GetBytes(read.ToString("X")); + ReadOnlyMemory length = ascii.GetBytes(read.ToString("X", CultureInfo.InvariantCulture)); try { await stream.WriteAsync(length).ConfigureAwait(false); @@ -54,7 +59,7 @@ protected override async Task WriteStreamInternal(Stream stream) } catch (IOException) { - WebServerLog.Add(ServerLogType.Information, GetType(), "write", "connection closed"); + logger.LogInformation(WriteEventId, "Connection closed"); return total; } } diff --git a/MaxLib.WebServer/HttpConnection.cs b/MaxLib.WebServer/HttpConnection.cs index 78cb59a..09eeeda 100644 --- a/MaxLib.WebServer/HttpConnection.cs +++ b/MaxLib.WebServer/HttpConnection.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.IO; using System.Net.Sockets; diff --git a/MaxLib.WebServer/HttpCookie.cs b/MaxLib.WebServer/HttpCookie.cs index f9c9d12..cdf2ded 100644 --- a/MaxLib.WebServer/HttpCookie.cs +++ b/MaxLib.WebServer/HttpCookie.cs @@ -10,6 +10,37 @@ namespace MaxLib.WebServer [Serializable] public class HttpCookie { + /// + /// The SameSite attribute of a , controlling whether it is + /// sent along with cross-site requests. + /// + public enum SameSiteMode + { + /// + /// No SameSite attribute is emitted at all. Browsers then fall back to their + /// own default (currently in every major browser). + /// + Unspecified, + /// + /// The cookie is withheld on cross-site requests entirely, including top-level + /// navigation (e.g. following a link from another site). The strongest CSRF + /// protection, at the cost of the cookie not being sent on the first request a user + /// makes after such a navigation. + /// + Strict, + /// + /// The cookie is withheld on cross-site requests except top-level navigation (e.g. + /// following a link from another site still sends it). The common default balance + /// between CSRF protection and not breaking ordinary cross-site links. + /// + Lax, + /// + /// The cookie is sent on every request, including cross-site ones. Requires + /// to be set, or browsers reject the cookie outright. + /// + None, + } + [Serializable] public readonly struct Cookie { @@ -21,8 +52,30 @@ public readonly struct Cookie public string ValueString => Value.ToString(); public DateTime Expires { get; } public int MaxAge { get; } + /// + /// Must not contain ';' or control characters; the value is written into the Set-Cookie line without escaping. + /// public ReadOnlyMemory Path { get; } + /// + /// If true, this cookie is inaccessible to JavaScript (document.cookie) + /// and is only ever sent as part of an HTTP request - the primary defense against + /// cookie theft via XSS. + /// + public bool HttpOnly { get; } + + /// + /// If true, this cookie is only ever sent over an encrypted (HTTPS) + /// connection. + /// + public bool Secure { get; } + + /// + /// Controls whether this cookie is sent along with cross-site requests. See + /// . + /// + public SameSiteMode SameSite { get; } + public Cookie(string name, string value) : this(name, value, new DateTime(9999, 12, 31), -1, "") { } @@ -36,16 +89,36 @@ public Cookie(string name, string value, int maxAge) { } public Cookie(string name, string value, string path) - : this(name, value, new DateTime(9999, 12, 31), -1, path) + : this(name, value, new DateTime(9999, 12, 31), -1, path) { } public Cookie(string name, string value, DateTime expires, int maxAge, string path) + : this(name, value, expires, maxAge, path, false, false, SameSiteMode.Unspecified) + { } + + /// + /// Creates a cookie with explicit // + /// attributes. See + /// for how the session cookie derives sensible defaults for these automatically. + /// + public Cookie( + string name, + string value, + DateTime expires, + int maxAge, + string path, + bool httpOnly, + bool secure, + SameSiteMode sameSite) { Name = name?.AsMemory() ?? throw new ArgumentNullException(nameof(name)); Value = value?.AsMemory() ?? throw new ArgumentNullException(nameof(value)); Expires = expires; MaxAge = maxAge; Path = path?.AsMemory() ?? throw new ArgumentNullException(nameof(path)); + HttpOnly = httpOnly; + Secure = secure; + SameSite = sameSite; } public override string ToString() @@ -65,7 +138,19 @@ public override string ToString() sb.Append(MaxAge); } sb.Append(";Path="); - sb.Append(Path); + // Path legitimately contains "/" (unlike Name/Value, it is not fully + // URI-encoded), so only strip the one thing that can never be legitimate in a + // cookie attribute - a raw CRLF - rather than escaping the whole value. + sb.Append(WebServerUtils.RemoveCrLf(Path.ToString())); + if (HttpOnly) + sb.Append(";HttpOnly"); + if (Secure) + sb.Append(";Secure"); + if (SameSite != SameSiteMode.Unspecified) + { + sb.Append(";SameSite="); + sb.Append(SameSite.ToString()); + } return sb.ToString(); } } @@ -78,7 +163,7 @@ public override string ToString() public HttpCookie(string cookie) { - if (cookie == null) throw new ArgumentNullException("Cookie"); + ArgumentNullException.ThrowIfNull(cookie); AddedCookies = new Dictionary(); RequestedCookies = new ReadOnlyDictionary(new Dictionary()); SetRequestCookieString(cookie); @@ -98,12 +183,12 @@ public virtual void SetRequestCookieString(string cookie) CompleteRequestCookie = cookie ?? throw new ArgumentNullException(nameof(cookie)); AddedCookies.Clear(); var reqCookie = new Dictionary(); - if (CompleteRequestCookie != "") + if (CompleteRequestCookie.Length != 0) { var tiles = CompleteRequestCookie.Split('&', ';'); foreach (var tile in tiles) { - var ind = tile.IndexOf('='); + var ind = tile.IndexOf('=', StringComparison.Ordinal); if (ind == -1) { var key = WebServerUtils.DecodeUri(tile.Trim()); @@ -112,7 +197,7 @@ public virtual void SetRequestCookieString(string cookie) } else { - var key = WebServerUtils.DecodeUri(tile.Remove(ind).Trim()); + var key = WebServerUtils.DecodeUri(tile[..ind].Trim()); var value = ind + 1 == tile.Length ? "" : WebServerUtils.DecodeUri(tile[(ind + 1)..]); if (!reqCookie.ContainsKey(key)) reqCookie.Add(key, new Cookie(key, value)); diff --git a/MaxLib.WebServer/HttpDataSource.cs b/MaxLib.WebServer/HttpDataSource.cs index e8c45b7..7842007 100644 --- a/MaxLib.WebServer/HttpDataSource.cs +++ b/MaxLib.WebServer/HttpDataSource.cs @@ -1,4 +1,5 @@ using MaxLib.IO; +using Microsoft.Extensions.Logging; using System; using System.IO; using System.Threading.Tasks; @@ -10,6 +11,12 @@ namespace MaxLib.WebServer [Serializable] public abstract class HttpDataSource : IDisposable { + static readonly ILogger logger = WebServerLog.LoggerFactory.CreateLogger(typeof(HttpDataSource)); + static readonly EventId TransformToStreamEventId = new(0, "Transform To Stream"); + + /// + /// HttpDataSource.Dispose implementations must not throw. + /// public abstract void Dispose(); public abstract long? Length(); @@ -43,13 +50,78 @@ public async Task WriteStream(Stream stream) public static Stream TransformToStream(HttpDataSource dataSource) { _ = dataSource ?? throw new ArgumentNullException(nameof(dataSource)); +#pragma warning disable CA2000 // ownership passes to the returned FaultPropagatingStream, whose Dispose() disposes this in turn var buffered = new BufferedSinkStream(); - _ = new Task(async () => +#pragma warning restore CA2000 + var fault = new WriteFaultBox(); + _ = Task.Run(async () => { - await dataSource.WriteStream(buffered).ConfigureAwait(false); - buffered.FinishWrite(); + try + { + await dataSource.WriteStream(buffered).ConfigureAwait(false); + } + catch (Exception e) + { + // The reader of `buffered` must always observe completion, even if WriteStream fails before calling + // FinishWrite(), or it blocks forever. The captured exception is surfaced through FaultPropagatingStream. + fault.Exception = e; + try + { + logger.LogError(TransformToStreamEventId, e, + "WriteStream failed while transforming a HttpDataSource into a Stream"); + } + catch (Exception) + { + // logging itself must never crash this background task + } + } + finally + { + buffered.FinishWrite(); + } }); - return buffered; + return new FaultPropagatingStream(buffered, fault); + } + + private sealed class WriteFaultBox + { + public volatile Exception? Exception; + } + + /// + /// Wraps the returned by . Once the wrapped + /// stream reports end-of-stream, rethrows the captured WriteStream failure (wrapped in an + /// ) so a caller can tell an early failure from a legitimate end. + /// + private sealed class FaultPropagatingStream(Stream inner, WriteFaultBox fault) : Stream + { + public override bool CanRead => inner.CanRead; + public override bool CanSeek => inner.CanSeek; + public override bool CanWrite => inner.CanWrite; + public override long Length => inner.Length; + public override long Position { get => inner.Position; set => inner.Position = value; } + + public override void Flush() => inner.Flush(); + + public override int Read(byte[] buffer, int offset, int count) + { + var read = inner.Read(buffer, offset, count); + if (read <= 0 && fault.Exception is Exception e) + throw new IOException( + "WriteStream failed while transforming a HttpDataSource into a Stream.", e); + return read; + } + + public override long Seek(long offset, SeekOrigin origin) => inner.Seek(offset, origin); + public override void SetLength(long value) => inner.SetLength(value); + public override void Write(byte[] buffer, int offset, int count) => inner.Write(buffer, offset, count); + + protected override void Dispose(bool disposing) + { + if (disposing) + inner.Dispose(); + base.Dispose(disposing); + } } } } diff --git a/MaxLib.WebServer/HttpDocument.cs b/MaxLib.WebServer/HttpDocument.cs index cc70250..fd7149c 100644 --- a/MaxLib.WebServer/HttpDocument.cs +++ b/MaxLib.WebServer/HttpDocument.cs @@ -19,7 +19,7 @@ public string? PrimaryMime set => primaryMime = value; } - public string? PrimaryEncoding { get; set; } = null; + public string? PrimaryEncoding { get; set; } public Dictionary Information { get; } = new Dictionary(); @@ -31,12 +31,13 @@ public object? this[object identifer] public void Dispose() { + GC.SuppressFinalize(this); foreach (var ds in DataSources.ToArray()) ds.Dispose(); DataSources.Clear(); foreach (var kvp in Information.ToArray()) { - if (kvp.Key is IDisposable) ((IDisposable)kvp.Key).Dispose(); - if (kvp.Value is IDisposable) ((IDisposable)kvp.Value).Dispose(); + if (kvp.Key is IDisposable keyDisposable) keyDisposable.Dispose(); + if (kvp.Value is IDisposable valueDisposable) valueDisposable.Dispose(); } Information.Clear(); } diff --git a/MaxLib.WebServer/HttpException.cs b/MaxLib.WebServer/HttpException.cs index cea9a32..54f0df5 100644 --- a/MaxLib.WebServer/HttpException.cs +++ b/MaxLib.WebServer/HttpException.cs @@ -1,14 +1,13 @@ -using System; - #nullable enable namespace MaxLib.WebServer { /// - /// Cancel the operation of the single . - /// The engine will automatically set the resulting status to the . These exceptions are intended to simplify the control flow. These messages are not - /// logged to the output. + /// Cancel the operation of the single + /// - or, for a , its CanWorkWith as well (e.g. thrown while + /// resolving a Builder method's parameters). The engine will automatically set the resulting + /// status to the . These exceptions are intended to simplify + /// the control flow. These messages are not logged to the output. /// [System.Serializable] public class HttpException : System.Exception diff --git a/MaxLib.WebServer/HttpHeader.cs b/MaxLib.WebServer/HttpHeader.cs index f6e9507..738a1d0 100644 --- a/MaxLib.WebServer/HttpHeader.cs +++ b/MaxLib.WebServer/HttpHeader.cs @@ -9,11 +9,11 @@ namespace MaxLib.WebServer [Serializable] public abstract class HttpHeader { - private bool lockReset = false; + private bool lockReset; public HttpHeader() { - var param = new ObservableDictionary(StringComparer.InvariantCultureIgnoreCase); + var param = new ObservableDictionary(StringComparer.OrdinalIgnoreCase); param.CollectionChanged += (_, __) => { if (!lockReset) diff --git a/MaxLib.WebServer/HttpLocation.cs b/MaxLib.WebServer/HttpLocation.cs index 75db800..cebe093 100644 --- a/MaxLib.WebServer/HttpLocation.cs +++ b/MaxLib.WebServer/HttpLocation.cs @@ -8,7 +8,7 @@ namespace MaxLib.WebServer { [Serializable] - public class HttpLocation + public partial class HttpLocation { public string Url { get; private set; } @@ -20,20 +20,17 @@ public class HttpLocation public Dictionary GetParameter { get; } - static readonly Regex UrlRegex = new Regex(@"^((?:\/+([^\/?]+))*\/?)(?:\?((?:([^&$]*)&?)*))?$", RegexOptions.Compiled); - - static readonly Regex ArgsRegex = new Regex(@"^([^=]*)=(.*)$", RegexOptions.Compiled); - public virtual void SetLocation(string url) { Url = url ?? throw new ArgumentNullException(url); GetParameter.Clear(); - var match = UrlRegex.Match(url); + var match = UrlRegex().Match(url); if (!match.Success) { DocumentPath = url; - DocumentPathTiles = new[] { url }; + DocumentPathTiles = [url]; CompleteGet = ""; + return; } DocumentPath = match.Groups[1].Value; DocumentPathTiles = match.Groups[2].Captures @@ -41,19 +38,20 @@ public virtual void SetLocation(string url) .Select(c => WebServerUtils.DecodeUri(c.Value)) .ToArray(); CompleteGet = match.Groups[3].Success ? match.Groups[3].Value ?? "" : ""; - foreach (Capture capture in match.Groups[4].Captures) - { - var submatch = ArgsRegex.Match(capture.Value); - if (submatch.Success) - { - GetParameter[WebServerUtils.DecodeUri(submatch.Groups[1].Value)] - = WebServerUtils.DecodeUri(submatch.Groups[2].Value); - } - else + if (CompleteGet.Length != 0) + foreach (var token in CompleteGet.Split('&')) { - GetParameter[capture.Value] = ""; + var submatch = ArgsRegex().Match(token); + if (submatch.Success) + { + GetParameter[WebServerUtils.DecodeUri(submatch.Groups[1].Value)] + = WebServerUtils.DecodeUri(submatch.Groups[2].Value); + } + else + { + GetParameter[token] = ""; + } } - } } public HttpLocation(string url) @@ -61,7 +59,7 @@ public HttpLocation(string url) Url = url ?? throw new ArgumentNullException(nameof(url)); GetParameter = new Dictionary(); DocumentPath = ""; - DocumentPathTiles = new string[0]; + DocumentPathTiles = []; CompleteGet = ""; SetLocation(url); } @@ -73,11 +71,12 @@ public override string ToString() public bool IsUrl(string[] urlTiles, bool ignoreCase = false) { + ArgumentNullException.ThrowIfNull(urlTiles); if (urlTiles.Length != DocumentPathTiles.Length) return false; for (int i = 0; i < urlTiles.Length; ++i) if (ignoreCase) { - if (urlTiles[i].ToLower() != DocumentPathTiles[i].ToLower()) return false; + if (!string.Equals(urlTiles[i], DocumentPathTiles[i], StringComparison.OrdinalIgnoreCase)) return false; } else { @@ -88,11 +87,12 @@ public bool IsUrl(string[] urlTiles, bool ignoreCase = false) public bool StartsUrlWith(string[] urlTiles, bool ignoreCase = false) { + ArgumentNullException.ThrowIfNull(urlTiles); if (urlTiles.Length > DocumentPathTiles.Length) return false; for (int i = 0; i < urlTiles.Length; ++i) if (ignoreCase) { - if (urlTiles[i].ToLower() != DocumentPathTiles[i].ToLower()) return false; + if (!string.Equals(urlTiles[i], DocumentPathTiles[i], StringComparison.OrdinalIgnoreCase)) return false; } else { @@ -100,5 +100,12 @@ public bool StartsUrlWith(string[] urlTiles, bool ignoreCase = false) } return true; } + + // The query is captured as one flat `[^$]*` and split on '&' in SetLocation; a nested repeated group + // here backtracks catastrophically on a query ending in an unmatched '$'. + [GeneratedRegex(@"^((?:\/+([^\/?]+))*\/?)(?:\?([^$]*))?$")] + private static partial Regex UrlRegex(); + [GeneratedRegex(@"^([^=]*)=(.*)$")] + private static partial Regex ArgsRegex(); } } diff --git a/MaxLib.WebServer/HttpPartialSource.cs b/MaxLib.WebServer/HttpPartialSource.cs index 01e1a8c..89ed6c6 100644 --- a/MaxLib.WebServer/HttpPartialSource.cs +++ b/MaxLib.WebServer/HttpPartialSource.cs @@ -32,8 +32,7 @@ public class HttpPartialSource : HttpDataSource public HttpPartialSource(HttpDataSource dataSource, long start, long? count) { - if (start < 0) - throw new ArgumentOutOfRangeException(nameof(start)); + ArgumentOutOfRangeException.ThrowIfNegative(start); if (count != null && count < 0) throw new ArgumentOutOfRangeException(nameof(count)); BaseSource = dataSource ?? throw new ArgumentNullException(nameof(dataSource)); @@ -44,19 +43,20 @@ public HttpPartialSource(HttpDataSource dataSource, long start, long? count) if (dataSource is HttpPartialSource partial) { BaseSource = partial.BaseSource; - Start += partial.Start; if (Count != null && partial.Count != null) - Count = Math.Min(Count.Value, partial.Count.Value - Start); + Count = Math.Min(Count.Value, partial.Count.Value - start); else { - Count ??= partial.Count - Start; + Count ??= partial.Count - start; } + Start += partial.Start; } } public override void Dispose() { BaseSource.Dispose(); + GC.SuppressFinalize(this); } public override long? Length() @@ -72,13 +72,13 @@ protected override async Task WriteStreamInternal(Stream stream) // optimize if stream based if (BaseSource is HttpStreamDataSource streamDataSource) { - var window = new StreamWindow(stream, 0, Count); - return await streamDataSource.WriteStream(window, Start, Count); + using var window = new StreamWindow(stream, 0, Count); + return await streamDataSource.WriteStream(window, Start, Count).ConfigureAwait(false); } else { - var window = new StreamWindow(stream, Start, Count); - return await BaseSource.WriteStream(window); + using var window = new StreamWindow(stream, Start, Count); + return await BaseSource.WriteStream(window).ConfigureAwait(false); } } diff --git a/MaxLib.WebServer/HttpPost.cs b/MaxLib.WebServer/HttpPost.cs index 63bc700..db46c09 100644 --- a/MaxLib.WebServer/HttpPost.cs +++ b/MaxLib.WebServer/HttpPost.cs @@ -8,7 +8,7 @@ namespace MaxLib.WebServer { [Serializable] - public class HttpPost : IDisposable + public class HttpPost : IDisposable, IAsyncDisposable { public string? MimeType { get; private set; } @@ -18,8 +18,9 @@ public class HttpPost : IDisposable public Task? DataAsync => LazyData?.Value; public IPostData? Data => DataAsync?.Result; + // RFC 9110 §8.3.1: the media-type token is case-insensitive, so this lookup must be too public static Dictionary> DataHandler { get; } - = new Dictionary>(); + = new Dictionary>(StringComparer.OrdinalIgnoreCase); static HttpPost() { @@ -27,55 +28,76 @@ static HttpPost() () => new UrlEncodedData(); DataHandler[WebServer.MimeType.MultipartFormData] = () => new MultipartFormData(); + DataHandler[WebServer.MimeType.ApplicationJson] = + () => new RawPostData(WebServer.MimeType.ApplicationJson); + DataHandler[WebServer.MimeType.ApplicationOctetStream] = + () => new RawPostData(WebServer.MimeType.ApplicationOctetStream); } + /// + /// SetPost must be called at most once per instance; a second call does not dispose the + /// previously set content or parsed data. + /// public virtual void SetPost(WebProgressTask task, IO.ContentStream content, string? mime) { Content = content; string args = ""; if (mime != null) { - var ind = mime.IndexOf(';'); + var ind = mime.IndexOf(';', StringComparison.Ordinal); if (ind >= 0) { - args = mime.Substring(ind + 1); - mime = mime.Remove(ind); + args = mime[(ind + 1)..]; + mime = mime[..ind]; } } + MimeType = mime; - if ((MimeType = mime) != null && - DataHandler.TryGetValue(mime!, out Func? constructor) - ) - LazyData = new Lazy>(() => + // an unrecognized (or missing) Content-Type still gets its body read and stored via + // RawPostData, exactly like a registered mime type would - it is never left as an + // unread reference to the live connection stream + var constructor = mime != null && DataHandler.TryGetValue(mime, out Func? found) + ? found + : () => new RawPostData(mime); + LazyData = new Lazy>(() => + { + return Task.Run(async () => { - return Task.Run(async () => + var data = constructor(); + try { - var data = constructor(); await data.SetAsync(task, content, args).ConfigureAwait(false); - return data; - }); - }, System.Threading.LazyThreadSafetyMode.ExecutionAndPublication); - else LazyData = new Lazy>( - Task.FromResult(new UnknownPostData(content, mime)) - ); + } + catch + { + // SetAsync may already have written entries/temp files; `data` is unreachable once this task + // faults, so it must be disposed here + data.Dispose(); + throw; + } + return data; + }); + }, System.Threading.LazyThreadSafetyMode.ExecutionAndPublication); } public HttpPost() { } +#pragma warning disable CA2000 // ownership transfers through the chained ctor into Content, disposed by HttpPost.Dispose() public HttpPost(WebProgressTask task, ReadOnlyMemory content, string? mime) : this( task, new IO.ContentStream( new IO.NetworkReader(new IO.SpanStream(content)), content.Length - ), + ), mime ) { } +#pragma warning restore CA2000 public HttpPost(WebProgressTask task, IO.ContentStream content, string? mime) : this() @@ -87,8 +109,13 @@ public override string ToString() return $"{MimeType}: {Data}"; } + /// + /// Do not call Dispose while a DataAsync parse may still be running; use DisposeAsync, which + /// waits for it. + /// public void Dispose() { + GC.SuppressFinalize(this); if (LazyData != null && LazyData.IsValueCreated) { Task.Run(async () => @@ -99,5 +126,35 @@ public void Dispose() } Content?.Dispose(); } + + /// + /// Disposes the resolved (if one was ever requested via /) and the underlying request content, without + /// blocking a thread on a synchronous socket read while doing so. Prefer this over , which cannot wait for the (possibly still in-flight) to finish parsing before disposing it. + /// + /// + /// Only call this once nothing further needs the request's connection — in + /// particular, only after any response on it has already been sent (see , which does exactly this). If the underlying drain + /// is cancelled (e.g. a read timeout), + /// closes that connection; doing so any earlier could prevent a response from ever + /// reaching the client. + /// + public async ValueTask DisposeAsync() + { + GC.SuppressFinalize(this); + if (LazyData != null && LazyData.IsValueCreated) + { + var data = await LazyData.Value.ConfigureAwait(false); + if (data is IAsyncDisposable asyncDisposable) + await asyncDisposable.DisposeAsync().ConfigureAwait(false); + else + data.Dispose(); + } + if (Content != null) + await Content.DisposeAsync().ConfigureAwait(false); + } } } diff --git a/MaxLib.WebServer/HttpProtocolDefinition.cs b/MaxLib.WebServer/HttpProtocolDefinition.cs index 7afb162..1179bbc 100644 --- a/MaxLib.WebServer/HttpProtocolDefinition.cs +++ b/MaxLib.WebServer/HttpProtocolDefinition.cs @@ -18,10 +18,10 @@ public static bool IsSupported(string Version, string[] SupportedVersions) if (SupportedVersions.Length == 0) return false; if (SupportedVersions.Contains(Version)) return true; - var ind = Version.IndexOf('.'); - if (ind != -1) Version = Version.Remove(ind); + var ind = Version.IndexOf('.', StringComparison.Ordinal); + if (ind != -1) Version = Version[..ind]; for (int i = 0; i < SupportedVersions.Length; ++i) - if (SupportedVersions[i].StartsWith(Version)) return true; + if (SupportedVersions[i].StartsWith(Version, StringComparison.Ordinal)) return true; return false; } } diff --git a/MaxLib.WebServer/HttpRequestHeader.cs b/MaxLib.WebServer/HttpRequestHeader.cs index a0bcc31..c40704e 100644 --- a/MaxLib.WebServer/HttpRequestHeader.cs +++ b/MaxLib.WebServer/HttpRequestHeader.cs @@ -8,6 +8,8 @@ namespace MaxLib.WebServer [Serializable] public class HttpRequestHeader : HttpHeader { + private static readonly char[] AcceptListSeparators = [',', ' ']; + protected override void ResetCache() { base.ResetCache(); @@ -27,7 +29,7 @@ public string Url public HttpLocation Location { get; } = new HttpLocation("/"); - private Lazy? host = null; + private Lazy? host; public string Host { get @@ -41,7 +43,7 @@ public string Host } set { - _ = host ?? throw new ArgumentNullException(nameof(value)); + ArgumentNullException.ThrowIfNull(value); SetResetLock(true); HeaderParameter["Host"] = value; host = new Lazy(value); @@ -51,7 +53,7 @@ public string Host public HttpPost Post { get; } = new HttpPost(); - private Lazy>? fieldAccept = null; + private Lazy>? fieldAccept; public ReadOnlyCollection FieldAccept { get @@ -62,9 +64,9 @@ public ReadOnlyCollection FieldAccept () => new ReadOnlyCollection( HeaderParameter.TryGetValue("Accept", out string value) ? value.Split( - new[] { ',', ' ' }, + AcceptListSeparators, StringSplitOptions.RemoveEmptyEntries - ) : new string[0] + ) : [] ) )).Value; } @@ -79,7 +81,7 @@ public ReadOnlyCollection FieldAccept } } - private Lazy>? fieldAcceptCharset = null; + private Lazy>? fieldAcceptCharset; public ReadOnlyCollection FieldAcceptCharset { get @@ -90,9 +92,9 @@ public ReadOnlyCollection FieldAcceptCharset () => new ReadOnlyCollection( HeaderParameter.TryGetValue("Accept-Charset", out string value) ? value.Split( - new[] { ',', ' ' }, + AcceptListSeparators, StringSplitOptions.RemoveEmptyEntries - ) : new string[0] + ) : [] ) )).Value; } @@ -107,7 +109,7 @@ public ReadOnlyCollection FieldAcceptCharset } } - private Lazy>? fieldAcceptEncoding = null; + private Lazy>? fieldAcceptEncoding; public ReadOnlyCollection FieldAcceptEncoding { get @@ -118,9 +120,9 @@ public ReadOnlyCollection FieldAcceptEncoding () => new ReadOnlyCollection( HeaderParameter.TryGetValue("Accept-Encoding", out string value) ? value.Split( - new[] { ',', ' ' }, + AcceptListSeparators, StringSplitOptions.RemoveEmptyEntries - ) : new string[0] + ) : [] ) )).Value; } @@ -135,7 +137,7 @@ public ReadOnlyCollection FieldAcceptEncoding } } - private Lazy? fieldConnection = null; + private Lazy? fieldConnection; public HttpConnectionType FieldConnection { get @@ -144,7 +146,7 @@ public HttpConnectionType FieldConnection return fieldConnection.Value; return (fieldConnection = new Lazy( () => HeaderParameter.TryGetValue("Connection", out string value) - && value.ToLower() == "keep-alive" ? + && string.Equals(value, "keep-alive", StringComparison.OrdinalIgnoreCase) ? HttpConnectionType.KeepAlive : HttpConnectionType.Close )).Value; @@ -169,7 +171,7 @@ public HttpConnectionType FieldConnection } } - private Lazy? cookie = null; + private Lazy? cookie; public HttpCookie Cookie { get diff --git a/MaxLib.WebServer/HttpStreamDataSource.cs b/MaxLib.WebServer/HttpStreamDataSource.cs index 2ea7d91..576a770 100644 --- a/MaxLib.WebServer/HttpStreamDataSource.cs +++ b/MaxLib.WebServer/HttpStreamDataSource.cs @@ -1,5 +1,5 @@ -using MaxLib.IO; -using System; +using System; +using Microsoft.Extensions.Logging; using System.IO; using System.Threading.Tasks; @@ -10,6 +10,9 @@ namespace MaxLib.WebServer [Serializable] public class HttpStreamDataSource : HttpDataSource { + static readonly ILogger logger = WebServerLog.LoggerFactory.CreateLogger(); + static readonly EventId SendEventId = new(0, "Send"); + public Stream Stream { get; } public HttpStreamDataSource(Stream stream) @@ -23,7 +26,10 @@ public HttpStreamDataSource(Stream stream) } public override void Dispose() - => Stream.Dispose(); + { + Stream.Dispose(); + GC.SuppressFinalize(this); + } public override long? Length() => Stream.Length; @@ -35,6 +41,7 @@ protected override Task WriteStreamInternal(Stream stream) public async Task WriteStream(Stream stream, long offset, long? count) { + ArgumentNullException.ThrowIfNull(stream); if (Stream.CanSeek) Stream.Position = offset; long total = 0; @@ -42,16 +49,19 @@ public async Task WriteStream(Stream stream, long offset, long? count) try { int read; - int job = count == null ? buffer.Length : (int)Math.Min(buffer.Length, count.Value - total); - while ((read = await Stream.ReadAsync(buffer[..job])) > 0) + while (count == null || total < count.Value) { - await stream.WriteAsync(buffer[0..read]); + int job = count == null ? buffer.Length : (int)Math.Min(buffer.Length, count.Value - total); + read = await Stream.ReadAsync(buffer[..job]).ConfigureAwait(false); + if (read <= 0) + break; + await stream.WriteAsync(buffer[0..read]).ConfigureAwait(false); total += read; } } catch (IOException) { - WebServerLog.Add(ServerLogType.Information, GetType(), "Send", "Connection closed by remote Host"); + logger.LogInformation(SendEventId, "Connection closed by remote host"); } return total; } diff --git a/MaxLib.WebServer/HttpStringDataSource.cs b/MaxLib.WebServer/HttpStringDataSource.cs index c6ecb4b..a420d70 100644 --- a/MaxLib.WebServer/HttpStringDataSource.cs +++ b/MaxLib.WebServer/HttpStringDataSource.cs @@ -1,5 +1,5 @@ -using MaxLib.IO; -using System; +using System; +using Microsoft.Extensions.Logging; using System.IO; using System.Text; using System.Threading.Tasks; @@ -11,6 +11,9 @@ namespace MaxLib.WebServer [Serializable] public class HttpStringDataSource : HttpDataSource { + static readonly ILogger logger = WebServerLog.LoggerFactory.CreateLogger(); + static readonly EventId SendEventId = new(0, "Send"); + private string data = ""; public string Data { @@ -40,6 +43,7 @@ public HttpStringDataSource(string data) public override void Dispose() { + GC.SuppressFinalize(this); } public override long? Length() @@ -52,7 +56,7 @@ protected override async Task WriteStreamInternal(Stream stream) try { await m.CopyToAsync(stream).ConfigureAwait(false); } catch (IOException) { - WebServerLog.Add(ServerLogType.Information, GetType(), "Send", "Connection closed by remote Host"); + logger.LogInformation(SendEventId, "Connection closed by remote host"); return m.Position; } return m.Length; diff --git a/MaxLib.WebServer/IO/ContentStream.cs b/MaxLib.WebServer/IO/ContentStream.cs index ee75765..7d56e66 100644 --- a/MaxLib.WebServer/IO/ContentStream.cs +++ b/MaxLib.WebServer/IO/ContentStream.cs @@ -2,6 +2,7 @@ using System; using System.Threading; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; #nullable enable @@ -13,7 +14,11 @@ namespace MaxLib.WebServer.IO /// public class ContentStream : Stream { + static readonly ILogger logger = WebServerLog.LoggerFactory.CreateLogger(); + static readonly EventId ReadEventId = new(0, "Read"); + private NetworkReader reader; + private readonly CancellationTokenSource? timeoutSource; /// /// The count of bytes that are already read. @@ -28,12 +33,65 @@ public class ContentStream : Stream /// public long UnreadData => FullLength - ReadData; + /// + /// The cancellation token that is triggered once the read timeout configured via the + /// timeout constructor parameter elapses. if + /// no timeout was configured. All *Async methods on this stream (including + /// ) observe this token in addition to any token passed in + /// explicitly, so a client that stalls mid-upload can't block a reader on this stream + /// forever, however that reader is layered on top of it. + /// + public CancellationToken TimeoutToken => timeoutSource?.Token ?? CancellationToken.None; + public ContentStream(NetworkReader reader, long maximum) + : this(reader, maximum, null) + { + } + + /// + /// Creates a new content stream that is additionally cancelled once elapses (measured from construction), protecting against a client + /// that stalls mid-upload from blocking a reader on this stream indefinitely. Pass + /// null to not apply any such timeout. + /// + public ContentStream(NetworkReader reader, long maximum, TimeSpan? timeout) { this.reader = reader; FullLength = maximum; + if (timeout.HasValue) + timeoutSource = new CancellationTokenSource(timeout.Value); } + /// + /// Combines with a caller-supplied token, avoiding the + /// allocation of a linked when the caller didn't + /// actually pass one in (the overwhelming common case for every caller in this library). + /// + private readonly struct EffectiveToken : IDisposable + { + public CancellationToken Token { get; } + private readonly CancellationTokenSource? linked; + + public EffectiveToken(CancellationToken timeoutToken, CancellationToken callerToken) + { + if (callerToken == default || callerToken == timeoutToken) + { + Token = timeoutToken; + linked = null; + } + else + { + linked = CancellationTokenSource.CreateLinkedTokenSource(timeoutToken, callerToken); + Token = linked.Token; + } + } + + public void Dispose() => linked?.Dispose(); + } + + private EffectiveToken Link(CancellationToken cancellationToken) + => new(TimeoutToken, cancellationToken); + public override bool CanRead => UnreadData > 0; public override bool CanSeek => false; @@ -42,10 +100,10 @@ public ContentStream(NetworkReader reader, long maximum) public override long Length => FullLength; - public override long Position + public override long Position { - get => ReadData; - set => throw new InvalidOperationException("cannot seek on this stream"); + get => ReadData; + set => throw new InvalidOperationException("cannot seek on this stream"); } public override void Flush() @@ -53,8 +111,7 @@ public override void Flush() } /// - /// This will discard any unread data and release the underlying . + /// Discards any unread data and ignore any timeouts. /// public virtual void Discard() { @@ -62,42 +119,46 @@ public virtual void Discard() while (UnreadData > 0) { var length = reader.Read(buffer, 0, (int)Math.Min(buffer.Length, UnreadData)); + if (length == 0) + break; // the connection reached EOF before the declared length; nothing more will ever arrive ReadData += length; } } /// - /// This will discard any unread data and release the underlying . + /// Discards any unread data, bounded by if a timeout was + /// configured. Never closes the underlying , even if + /// cancelled — this may run before a response has been sent on this connection (e.g. + /// while still parsing the request), so the connection must stay usable regardless of + /// the outcome. /// public virtual Task DiscardAsync() => DiscardAsync(CancellationToken.None); - /// - /// This will discard any unread data and release the underlying . - /// + /// public virtual async Task DiscardAsync(CancellationToken cancellationToken) { - cancellationToken.ThrowIfCancellationRequested(); + using var token = Link(cancellationToken); + token.Token.ThrowIfCancellationRequested(); var buffer = new byte[64 * 1024]; while (UnreadData > 0) { var length = await reader.ReadAsync( - buffer, - 0, - (int)Math.Min(buffer.Length, UnreadData), - cancellationToken + buffer, + 0, + (int)Math.Min(buffer.Length, UnreadData), + token.Token ) .ConfigureAwait(false); + if (length == 0) + break; // the connection reached EOF before the declared length; nothing more will ever arrive ReadData += length; } } public override int Read(byte[] buffer, int offset, int count) { - if (buffer is null) - throw new ArgumentNullException(nameof(buffer)); + ArgumentNullException.ThrowIfNull(buffer); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count + offset > buffer.Length) @@ -111,22 +172,34 @@ public override int Read(byte[] buffer, int offset, int count) public override async Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { - cancellationToken.ThrowIfCancellationRequested(); - - if (buffer is null) - throw new ArgumentNullException(nameof(buffer)); + ArgumentNullException.ThrowIfNull(buffer); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count + offset > buffer.Length) throw new ArgumentOutOfRangeException(nameof(count)); + + using var token = Link(cancellationToken); + token.Token.ThrowIfCancellationRequested(); if (count > UnreadData) count = (int)UnreadData; - var length = await reader.ReadAsync(buffer, offset, count, cancellationToken) + var length = await reader.ReadAsync(buffer, offset, count, token.Token) .ConfigureAwait(false); ReadData += length; return length; } + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + using var token = Link(cancellationToken); + token.Token.ThrowIfCancellationRequested(); + var count = buffer.Length; + if (count > UnreadData) + count = (int)UnreadData; + var length = await reader.ReadAsync(buffer[..count], token.Token).ConfigureAwait(false); + ReadData += length; + return length; + } + public override long Seek(long offset, SeekOrigin origin) { throw new InvalidOperationException("Cannot seek on this stream"); @@ -142,16 +215,38 @@ public override void Write(byte[] buffer, int offset, int count) throw new InvalidOperationException("Cannot write on this stream"); } + /// + /// The synchronous Dispose drains unread body data without honoring the read timeout and can + /// block on a stalled client; prefer DisposeAsync. + /// protected override void Dispose(bool disposing) { - Discard(); - base.Dispose(disposing); + try + { + Discard(); + } + finally + { + reader.Dispose(); + timeoutSource?.Dispose(); + base.Dispose(disposing); + } } +#pragma warning disable CA2215 // deliberate: would call sync Dispose again, which would block on a potentially stalled client public override async ValueTask DisposeAsync() { - await DiscardAsync().ConfigureAwait(false); - await base.DisposeAsync().ConfigureAwait(false); + GC.SuppressFinalize(this); + try + { + await DiscardAsync().ConfigureAwait(false); + } + finally + { + reader.Dispose(); + timeoutSource?.Dispose(); + } } +#pragma warning restore CA2215 } -} \ No newline at end of file +} diff --git a/MaxLib.WebServer/IO/NetworkReader.cs b/MaxLib.WebServer/IO/NetworkReader.cs index 37efb15..0702fc4 100644 --- a/MaxLib.WebServer/IO/NetworkReader.cs +++ b/MaxLib.WebServer/IO/NetworkReader.cs @@ -1,4 +1,3 @@ -using System.Linq; using System.Threading; using System; using System.Text; @@ -71,7 +70,7 @@ public Encoding Encoding /// The number of unread chars in . /// int charBufferCount; - bool disposed = false; + bool disposed; readonly int expectedCharBytes; public NetworkReader(Stream stream) @@ -150,7 +149,7 @@ protected async ValueTask RefillBufferAsync(CancellationToken cancellationToken, if (readBufferCount >= expectLength) return; // move the data to the left only if less then the half buffer is available - if ((readBufferOffset << 1) > readBuffer.Length && readBufferCount > 0) + if ((readBufferOffset << 1) > readBuffer.Length) { readBuffer.Span.Slice(readBufferOffset, readBufferCount) .CopyTo(readBuffer.Span[ .. readBufferCount]); @@ -170,7 +169,7 @@ protected async ValueTask RefillBufferAsync(CancellationToken cancellationToken, while (readBufferCount < expectLength); } - int lastBytesUsed = 0; + int lastBytesUsed; protected int RefillCharBuffer() { @@ -227,12 +226,12 @@ protected void MoveByteBufferFromCharBuffer(int fromCharIndex, int toCharIndex) protected void ThrowIfDisposed() { - if (disposed) - throw new ObjectDisposedException(null); + ObjectDisposedException.ThrowIf(disposed, this); } public void Dispose() { + GC.SuppressFinalize(this); disposed = true; if (!leaveOpen) BaseStream.Dispose(); @@ -240,6 +239,7 @@ public void Dispose() public async ValueTask DisposeAsync() { + GC.SuppressFinalize(this); disposed = true; if (!leaveOpen) await BaseStream.DisposeAsync().ConfigureAwait(false); @@ -324,6 +324,7 @@ public async ValueTask DisposeAsync() if (charBuffer[charBufferOffset] == '\n') { charBufferOffset++; + charBufferCount--; } } } @@ -356,7 +357,7 @@ public async ValueTask DisposeAsync() ) { if (limit < 0) - return await ReadLineAsync(cancellationToken); + return await ReadLineAsync(cancellationToken).ConfigureAwait(false); ThrowIfDisposed(); StringBuilder? sb = null; @@ -393,6 +394,7 @@ public async ValueTask DisposeAsync() if (charBuffer[charBufferOffset] == '\n') { charBufferOffset++; + charBufferCount--; } } } @@ -447,6 +449,7 @@ public async ValueTask DisposeAsync() if (charBuffer[charBufferOffset] == '\n') { charBufferOffset++; + charBufferCount--; } } } @@ -526,7 +529,7 @@ public async ValueTask ReadAsync(byte[] buffer, int offset, int count, if (count <= length) return length; - return length + await BaseStream.ReadAsync(buffer, offset + length, count - length, cancellationToken).ConfigureAwait(false); + return length + await BaseStream.ReadAsync(buffer.AsMemory(offset + length, count - length), cancellationToken).ConfigureAwait(false); } public async ValueTask ReadAsync(Memory buffer, @@ -559,8 +562,7 @@ public async ValueTask ReadBytesAsync(int count, CancellationToken cancellationToken = default) { ThrowIfDisposed(); - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count)); + ArgumentOutOfRangeException.ThrowIfNegative(count); var buffer = new byte[count]; var read = 0; @@ -598,10 +600,8 @@ public async ValueTask ReadAsync(Stream buffer, int count, _ = buffer ?? throw new ArgumentNullException(nameof(buffer)); if (!buffer.CanWrite) throw new ArgumentException("stream is not writable", nameof(buffer)); - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count)); - if (blockSize <= 0) - throw new ArgumentOutOfRangeException(nameof(blockSize)); + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(blockSize); var originalCount = count; var bytes = new byte[blockSize]; @@ -610,7 +610,7 @@ public async ValueTask ReadAsync(Stream buffer, int count, int read = await ReadAsync(bytes, 0, Math.Min(count, blockSize), cancellationToken).ConfigureAwait(false); if (read == 0) break; - await buffer.WriteAsync(bytes, 0, read, cancellationToken).ConfigureAwait(false); + await buffer.WriteAsync(bytes.AsMemory(0, read), cancellationToken).ConfigureAwait(false); count -= read; } @@ -629,6 +629,7 @@ public long ReadUntil( Stream target ) { + ArgumentNullException.ThrowIfNull(target); if (marking.Length == 0) return 0; long fullRead = 0; @@ -642,8 +643,8 @@ Stream target charBufferCount = charBufferOffset = lastBytesUsed = 0; // loop until we found the signature - int length; - do + bool found = false; + while (!found) { // ensure we have enough bytes in buffer RefillBuffer(marking.Length); @@ -658,30 +659,33 @@ Stream target break; } + // only scan positions with at least marking.Length bytes buffered: a marker straddling a refill + // must not be flushed before a later refill gives it the chance to match + // add the data until the pattern (or the safe boundary, if not found yet) to the stream + int safeEnd = readBufferOffset + readBufferCount - (marking.Length - 1); int i = readBufferOffset; - // move the check window until we found the pattern - do + while (i < safeEnd) { if (readBuffer.Span[i ..].StartsWith(marking)) + { + found = true; break; + } i++; } - while (i < readBufferOffset + readBufferCount); - // add the data until the pattern to the stream + // add the data until the pattern (or the safe boundary, if not found yet) to the stream target.Write(readBuffer.Span[readBufferOffset .. i]); // move the index to the end - length = i - readBufferOffset; + var length = i - readBufferOffset; readBufferOffset = i; readBufferCount -= length; fullRead += length; - // break if the length is 0 } - while (length > 0); return fullRead; } - + public async ValueTask> ReadUntilAsync( ReadOnlyMemory marking, CancellationToken cancellationToken = default @@ -699,9 +703,10 @@ public async ValueTask ReadUntilAsync( CancellationToken cancellationToken = default ) { + ArgumentNullException.ThrowIfNull(target); if (marking.Length == 0) return 0; - + long fullRead = 0; if (marking.Length * 2 > readBuffer.Length) @@ -713,8 +718,8 @@ public async ValueTask ReadUntilAsync( charBufferCount = charBufferOffset = lastBytesUsed = 0; // loop until we found the signature - int length; - do + bool found = false; + while (!found) { // ensure we have enough bytes in buffer await RefillBufferAsync(cancellationToken, marking.Length).ConfigureAwait(false); @@ -729,25 +734,28 @@ public async ValueTask ReadUntilAsync( break; } + // only scan positions with at least marking.Length bytes buffered: a marker straddling a refill + // must not be flushed before a later refill gives it the chance to match + // add the data until the pattern (or the safe boundary, if not found yet) to the stream + int safeEnd = readBufferOffset + readBufferCount - (marking.Length - 1); int i = readBufferOffset; - // move the check window until we found the pattern - do + while (i < safeEnd) { if (readBuffer.Span[i ..].StartsWith(marking.Span)) + { + found = true; break; + } i++; } - while (i < readBufferOffset + readBufferCount); - // add the data until the pattern to the stream + // add the data until the pattern (or the safe boundary, if not found yet) to the stream target.Write(readBuffer.Span[readBufferOffset .. i]); // move the index to the end - length = i - readBufferOffset; + var length = i - readBufferOffset; readBufferOffset = i; readBufferCount -= length; fullRead += length; - // break if the length is 0 } - while (length > 0); return fullRead; } diff --git a/MaxLib.WebServer/IO/SpanStream.cs b/MaxLib.WebServer/IO/SpanStream.cs index 1d73aa9..f7fce80 100644 --- a/MaxLib.WebServer/IO/SpanStream.cs +++ b/MaxLib.WebServer/IO/SpanStream.cs @@ -23,7 +23,7 @@ public class SpanStream : Stream public override long Length => Memory.Length; - int position = 0; + int position; public override long Position { get => position; diff --git a/MaxLib.WebServer/Lazy/LazySource.cs b/MaxLib.WebServer/Lazy/LazySource.cs index 5649ee8..81049ed 100644 --- a/MaxLib.WebServer/Lazy/LazySource.cs +++ b/MaxLib.WebServer/Lazy/LazySource.cs @@ -1,5 +1,4 @@ -using MaxLib.IO; -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -45,6 +44,7 @@ public IEnumerable GetAllSources() public override void Dispose() { + GC.SuppressFinalize(this); if (list != null) foreach (var s in list) s.Dispose(); diff --git a/MaxLib.WebServer/Lazy/LazyTask.cs b/MaxLib.WebServer/Lazy/LazyTask.cs index c0c3a06..445eba1 100644 --- a/MaxLib.WebServer/Lazy/LazyTask.cs +++ b/MaxLib.WebServer/Lazy/LazyTask.cs @@ -1,5 +1,4 @@ -using System.Data; -using System; +using System; using System.Collections.Generic; #nullable enable @@ -26,8 +25,8 @@ public object? this[object identifer] public LazyTask(WebProgressTask task) { _ = task ?? throw new ArgumentNullException(nameof(task)); - Server = task.Server ?? throw new ArgumentNullException(nameof(task.Server)); - Connection = task.Connection ?? throw new ArgumentNullException(nameof(task.Connection)); + Server = task.Server ?? throw new ArgumentNullException(nameof(task)); + Connection = task.Connection ?? throw new ArgumentNullException(nameof(task)); Header = task.Request; Information = task.Document.Information; } diff --git a/MaxLib.WebServer/MaxLib.WebServer.csproj b/MaxLib.WebServer/MaxLib.WebServer.csproj index c5c7af5..6875757 100644 --- a/MaxLib.WebServer/MaxLib.WebServer.csproj +++ b/MaxLib.WebServer/MaxLib.WebServer.csproj @@ -3,7 +3,7 @@ - net8.0;net6.0 + net10.0;net8.0 MaxLib.WebServer garados007 Max Brauer @@ -14,6 +14,9 @@ enable + + true @@ -23,7 +26,7 @@ - + diff --git a/MaxLib.WebServer/MaxLib.WebServer.csproj.include b/MaxLib.WebServer/MaxLib.WebServer.csproj.include index 88dfa8e..44738fb 100644 --- a/MaxLib.WebServer/MaxLib.WebServer.csproj.include +++ b/MaxLib.WebServer/MaxLib.WebServer.csproj.include @@ -2,7 +2,7 @@ - 4.0.0 + 5.0.0 $(Version).0 $(Version).0 diff --git a/MaxLib.WebServer/MimeType.cs b/MaxLib.WebServer/MimeType.cs index 23d4b9c..43d966f 100644 --- a/MaxLib.WebServer/MimeType.cs +++ b/MaxLib.WebServer/MimeType.cs @@ -1,11 +1,11 @@ using System; using System.Collections.Generic; using System.IO; -using System.Net; using System.Net.Http; using System.Text.Json; using System.Text.RegularExpressions; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; #nullable enable @@ -15,8 +15,10 @@ namespace MaxLib.WebServer /// This class holds some constants for popular mime types. It also holds some /// functionality for working with mime types. /// - public static class MimeType + public static partial class MimeType { + static readonly ILogger logger = WebServerLog.LoggerFactory.CreateLogger(typeof(MimeType)); + static readonly EventId LoadMimeEventId = new(0, "load mime"); public const string ApplicationXWwwFromUrlencoded = "application/x-www-form-urlencoded"; /// @@ -108,7 +110,7 @@ public static class MimeType /// public const string MultipartEncrypted = "multipart/encrypted"; /// - /// multipart data from a HTTP formular (z.B. File-Upload) + /// multipart data from a HTTP formular (z.B. File-Upload) /// public const string MultipartFormData = "multipart/form-data"; /// @@ -160,16 +162,16 @@ public static bool Check(string mime, string pattern) { _ = mime ?? throw new ArgumentNullException(nameof(mime)); _ = pattern ?? throw new ArgumentNullException(nameof(pattern)); - var ind = mime.IndexOf('/'); - if (ind == -1) + var ind = mime.IndexOf('/', StringComparison.Ordinal); + if (ind == -1) throw new ArgumentException("no Mime", nameof(mime)); - var ml = mime.Remove(ind).ToLower(); - var mh = mime.Substring(ind + 1).ToLower(); - ind = pattern.IndexOf('/'); - if (ind == -1) + var ml = mime[..ind].ToLowerInvariant(); + var mh = mime[(ind + 1)..].ToLowerInvariant(); + ind = pattern.IndexOf('/', StringComparison.Ordinal); + if (ind == -1) throw new ArgumentException("no Mime", nameof(pattern)); - var pl = pattern.Remove(ind).ToLower(); - var ph = pattern.Substring(ind + 1).ToLower(); + var pl = pattern[..ind].ToLowerInvariant(); + var ph = pattern[(ind + 1)..].ToLowerInvariant(); return (pl == "*" || pl == ml) && (ph == "*" || ph == mh); } @@ -186,7 +188,7 @@ public static bool Check(string mime, string pattern) _ = extension ?? throw new ArgumentNullException(nameof(extension)); if (extension.StartsWith('.')) return GetMimeTypeForExtension(extension[1..]); - if (mimeTypes.TryGetValue(extension.ToLower(), out string? mime)) + if (mimeTypes.TryGetValue(extension.ToLowerInvariant(), out string? mime)) return mime; else return null; } @@ -194,11 +196,11 @@ public static bool Check(string mime, string pattern) /// /// load the data for . If no /// cache file exists or is false it loads - /// the data from - /// http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types + /// the data from + /// https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types /// ///
- /// If is true it uses the cache file at + /// If is true it uses the cache file at /// ./mime-cache.json. ///
/// true if to use the cache file @@ -215,7 +217,7 @@ public static async Task LoadMimeTypesForExtensions(bool useLocalCache, string? var mimeTypes = new Dictionary(); if (useLocalCache && File.Exists(localCachePath)) { - WebServerLog.Add(ServerLogType.Debug, typeof(MimeType), "load mime", "load mime cache"); + logger.LogDebug(LoadMimeEventId, "load mime cache"); using var file = new FileStream(localCachePath, FileMode.Open, FileAccess.Read, FileShare.Read ); @@ -225,21 +227,18 @@ public static async Task LoadMimeTypesForExtensions(bool useLocalCache, string? mimeTypes[entry.Name] = entry.Value.GetString()!; } - WebServerLog.Add(ServerLogType.Debug, typeof(MimeType), "load mime", "mime cache loaded"); + logger.LogDebug(LoadMimeEventId, "mime cache loaded"); } else { - WebServerLog.Add(ServerLogType.Debug, typeof(MimeType), "load mime", "Update Mime Cachce"); + logger.LogDebug(LoadMimeEventId, "Update Mime Cachce"); using var client = new HttpClient(); var reader = new StringReader(await client.GetStringAsync( - @"http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types" - )); - var regex = new Regex( - @"^(?[^#][^\s]*)(\s+(?\w+))+$", - RegexOptions.Compiled - ); + @"https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types" + ).ConfigureAwait(false)); + var regex = MimeTypesLineRegex(); string? line; - while ((line = reader.ReadLine()) != null) + while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) { var match = regex.Match(line); if (!match.Success) @@ -260,9 +259,12 @@ public static async Task LoadMimeTypesForExtensions(bool useLocalCache, string? writer.WriteEndObject(); await writer.FlushAsync().ConfigureAwait(false); } - WebServerLog.Add(ServerLogType.Debug, typeof(MimeType), "load mime", "Mime Cache updated"); + logger.LogDebug(LoadMimeEventId, "Mime Cache updated"); } MimeType.mimeTypes = mimeTypes; } + + [GeneratedRegex(@"^(?[^#][^\s]*)(\s+(?\w+))+$")] + private static partial Regex MimeTypesLineRegex(); } } diff --git a/MaxLib.WebServer/Monitoring/DiscardWatch.cs b/MaxLib.WebServer/Monitoring/DiscardWatch.cs index 626ae5c..ee9f707 100644 --- a/MaxLib.WebServer/Monitoring/DiscardWatch.cs +++ b/MaxLib.WebServer/Monitoring/DiscardWatch.cs @@ -15,6 +15,7 @@ public DiscardWatch() public void Dispose() { + GC.SuppressFinalize(this); } public void Log(string format, params object[] args) diff --git a/MaxLib.WebServer/Monitoring/Monitor.cs b/MaxLib.WebServer/Monitoring/Monitor.cs index fa4f5b9..8285578 100644 --- a/MaxLib.WebServer/Monitoring/Monitor.cs +++ b/MaxLib.WebServer/Monitoring/Monitor.cs @@ -1,17 +1,26 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Text; using System.Threading.Tasks; using System.Diagnostics; +using Microsoft.Extensions.Logging; namespace MaxLib.WebServer.Monitoring { /// /// This enables to trace and monitor the operation inside the handling of a web request /// + /// + /// Exceptions reaching the monitor must have a non-throwing ToString(); Monitor.Save writes it to + /// the log file. + /// public class Monitor { + static readonly ILogger logger = WebServerLog.LoggerFactory.CreateLogger(); + static readonly EventId WriteLogsEventId = new(0, "write logs"); + /// /// Gets if monitoring for this single request is allowed. /// @@ -62,7 +71,7 @@ internal async Task Save(string path, DateTime started, WebProgressTask task) var callName = SanitizePath(task.Request.Location.DocumentPath); if (callName.Length == 0) callName = "_"; - var date = started.ToString("yyyy-MM-dd_HH-mm-ss-fffffff"); + var date = started.ToString("yyyy-MM-dd_HH-mm-ss-fffffff", CultureInfo.InvariantCulture); var dir = $"{path}/{callName}"; if (!Directory.Exists(dir)) @@ -80,15 +89,14 @@ internal async Task Save(string path, DateTime started, WebProgressTask task) try { WriteTo(writer); } catch (Exception e) { - WebServerLog.Add(ServerLogType.FatalError, GetType(), "write logs", e.ToString()); - writer.WriteLine(e); + logger.LogCritical(WriteLogsEventId, e, "Failed to write monitor logs"); + await writer.WriteLineAsync(e.ToString()).ConfigureAwait(false); } - await writer.FlushAsync(); - writer.Flush(); - await stream.FlushAsync(); + await writer.FlushAsync().ConfigureAwait(false); + await stream.FlushAsync().ConfigureAwait(false); } - private static char[] allowedChars = new[] { '-', '_', '+', '(', ')', }; + private static char[] allowedChars = ['-', '_', '+', '(', ')',]; private static string SanitizePath(string path) { var sb = new StringBuilder(path.Length); @@ -99,4 +107,4 @@ private static string SanitizePath(string path) return sb.ToString(); } } -} \ No newline at end of file +} diff --git a/MaxLib.WebServer/Monitoring/MonitoringWatch.cs b/MaxLib.WebServer/Monitoring/MonitoringWatch.cs index 0aee848..19d25ae 100644 --- a/MaxLib.WebServer/Monitoring/MonitoringWatch.cs +++ b/MaxLib.WebServer/Monitoring/MonitoringWatch.cs @@ -1,6 +1,5 @@ using System; using System.IO; -using System.Diagnostics; using System.Collections.Generic; namespace MaxLib.WebServer.Monitoring @@ -55,7 +54,7 @@ public void WriteTo(TextWriter writer) if (!typeDict.TryGetValue(Caller, out int id)) typeDict.Add(Caller, id = typeDict.Count + 1); var name = type.FullName ?? ""; - if (name.StartsWith("MaxLib.WebServer")) + if (name.StartsWith("MaxLib.WebServer", StringComparison.Ordinal)) name = $"<{type.Name}>"; writer.WriteLine($"[{started:G}] [{Elapsed:G}] {name} #{id} {Info}"); diff --git a/MaxLib.WebServer/MultipartRanges.cs b/MaxLib.WebServer/MultipartRanges.cs index 7283e29..948e69e 100644 --- a/MaxLib.WebServer/MultipartRanges.cs +++ b/MaxLib.WebServer/MultipartRanges.cs @@ -1,5 +1,4 @@ -using MaxLib.IO; -using System; +using System; using System.Collections.Generic; using System.IO; using System.Text; @@ -23,7 +22,7 @@ public static long JoinGap get => joinGap; set { - if (value < 0) throw new ArgumentOutOfRangeException(nameof(JoinGap)); + ArgumentOutOfRangeException.ThrowIfNegative(value, nameof(JoinGap)); joinGap = value; } } @@ -38,9 +37,9 @@ public string ToString(long total) var sb = new StringBuilder(); sb.Append("bytes "); sb.Append(From); - sb.Append("-"); + sb.Append('-'); sb.Append(To); - sb.Append("/"); + sb.Append('/'); sb.Append(total); return sb.ToString(); } @@ -63,8 +62,8 @@ public string ToString(long total) public MultipartRanges(Stream stream, WebProgressTask task, string? mime) : this( stream, - task?.Request ?? throw new ArgumentNullException(nameof(task.Request)), - task?.Response ?? throw new ArgumentNullException(nameof(task.Response)), + task?.Request ?? throw new ArgumentNullException(nameof(task)), + task?.Response ?? throw new ArgumentNullException(nameof(task)), mime ) { @@ -94,7 +93,8 @@ public MultipartRanges(Stream stream, HttpRequestHeader request, ParseRanges(request.HeaderParameter["Range"]); var valid = ranges.Count > 0; foreach (var r in ranges) - if (r.From < 0 || r.From >= baseStream.Length || r.To < 0 || r.To >= baseStream.Length) + if (r.From < 0 || r.From >= baseStream.Length || r.To < 0 || r.To >= baseStream.Length || + r.From > r.To) valid = false; if (!valid) { @@ -115,9 +115,9 @@ public MultipartRanges(Stream stream, HttpRequestHeader request, void ParseRanges(string code) { code = code.Trim(); - if (!code.StartsWith("bytes")) return; + if (!code.StartsWith("bytes", StringComparison.Ordinal)) return; code = code[5..].TrimStart(); - if (!code.StartsWith("=")) return; + if (!code.StartsWith('=')) return; code = code[1..].TrimStart(); foreach (var part in code.Split(',')) { @@ -140,7 +140,7 @@ void ParseRanges(string code) void FormatRanges() { if (ranges.Count < 2) return; - ranges.Sort((r1, r2) => r1.From.CompareTo(r2.To)); + ranges.Sort((r1, r2) => r1.From.CompareTo(r2.From)); var nr = new List(ranges.Count); Range? last = null; for (int i = 0; i < ranges.Count; ++i) @@ -170,7 +170,7 @@ void SinglePart() streams.Add(new HttpPartialSource( new HttpStreamDataSource(baseStream), ranges[0].From, - ranges[0].To - ranges[0].From + ranges[0].To - ranges[0].From + 1 )); } @@ -178,7 +178,7 @@ void MultiPart() { var b = new byte[8]; new Random().NextBytes(b); - var boundary = BitConverter.ToString(b).Replace("-", ""); + var boundary = BitConverter.ToString(b).Replace("-", "", StringComparison.Ordinal); base.MimeType = WebServer.MimeType.MultipartByteranges + "; boundary=" + boundary; response.StatusCode = HttpStateCode.PartialContent; var sb = new StringBuilder(); @@ -195,11 +195,13 @@ void MultiPart() sb.AppendLine(r.ToString(baseStream.Length)); sb.AppendLine(); streams.Add(new HttpStringDataSource(sb.ToString())); +#pragma warning disable CA2000 // ownership transfers to the streams list, disposed by MultipartRanges.Dispose() streams.Add(new HttpPartialSource( new HttpStreamDataSource(baseStream), r.From, - r.To - r.From + r.To - r.From + 1 )); +#pragma warning restore CA2000 sb.Clear(); } sb.Append("--"); @@ -225,6 +227,7 @@ public override void Dispose() { baseStream.Dispose(); foreach (var s in streams) s.Dispose(); + GC.SuppressFinalize(this); } protected override async Task WriteStreamInternal(Stream stream) diff --git a/MaxLib.WebServer/Post/IPostData.cs b/MaxLib.WebServer/Post/IPostData.cs index 521d223..23d1fa4 100644 --- a/MaxLib.WebServer/Post/IPostData.cs +++ b/MaxLib.WebServer/Post/IPostData.cs @@ -5,6 +5,12 @@ namespace MaxLib.WebServer.Post { + /// + /// Custom IPostData implementations and EncodingProviders must throw exceptions with a non-throwing + /// ToString(); they are passed to the logger as-is. SetAsync must be called at most once per + /// instance; a second call leaks the previous call's temp files. Dispose is not thread-safe: await + /// SetAsync before calling Dispose, otherwise temp files may leak. + /// public interface IPostData : IDisposable { string MimeType { get; } diff --git a/MaxLib.WebServer/Post/MultipartFormData.cs b/MaxLib.WebServer/Post/MultipartFormData.cs index c61564c..3f8cabf 100644 --- a/MaxLib.WebServer/Post/MultipartFormData.cs +++ b/MaxLib.WebServer/Post/MultipartFormData.cs @@ -3,18 +3,26 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Globalization; using System.Text.RegularExpressions; using MaxLib.WebServer.IO; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; #nullable enable namespace MaxLib.WebServer.Post { - public class MultipartFormData : IPostData + public partial class MultipartFormData : IPostData { + static readonly ILogger logger = WebServerLog.LoggerFactory.CreateLogger(); + static readonly EventId PostEventId = new(0, "POST"); + public class FormEntry : IDisposable { + static readonly ILogger logger = WebServerLog.LoggerFactory.CreateLogger(); + static readonly EventId PostEventId = new(0, "POST"); + public ReadOnlyDictionary Header { get; } public ReadOnlyMemory? Content { get; private set; } @@ -31,34 +39,45 @@ public void Set(ReadOnlyMemory content) { Content = content; if (TempFile != null && TempFile.Exists) - try + try { TempFile.Delete(); } catch (Exception) { - WebServerLog.Add(ServerLogType.Information, GetType(), "POST", "Cannot delete temp file"); + logger.LogInformation(PostEventId, "Cannot delete temp file"); } TempFile = null; } public void Set(FileInfo tempFile) { + ArgumentNullException.ThrowIfNull(tempFile); Content = null; if (TempFile != null && TempFile.FullName != tempFile.FullName) - try + try { TempFile.Delete(); } catch (Exception) { - WebServerLog.Add(ServerLogType.Information, GetType(), "POST", "Cannot delete temp file"); + logger.LogInformation(PostEventId, "Cannot delete temp file"); } TempFile = tempFile; } public virtual void Dispose() { + if (TempFile != null && TempFile.Exists) + try + { + TempFile.Delete(); + } + catch (Exception) + { + logger.LogInformation(PostEventId, "Cannot delete temp file"); + } + GC.SuppressFinalize(this); } } @@ -91,35 +110,18 @@ public FormDataFile(Dictionary header, string name, string fileN public List Entries { get; } = new List(); - static Regex boundaryRegex = new Regex( - "boundary\\s*=\\s*(?:\"(?[^\"]*)\"|(?[^\"]*))", - RegexOptions.Compiled - ); - static Regex nameRegex = new Regex( - "[^\\w]name\\s*=\\s*\"(?[^\"]*)\"", - RegexOptions.Compiled | RegexOptions.IgnoreCase - ); - static Regex filenameRegex = new Regex( - "[^\\w]filename\\s*=\\s*\"(?[^\"]*)\"", - RegexOptions.Compiled | RegexOptions.IgnoreCase - ); - static Regex headerSplit = new Regex( - "^(?[^:\\s]+)\\s*:\\s*(?.*)$", - RegexOptions.Compiled - ); - protected virtual FormEntry GetEntry(Dictionary header) { _ = header ?? throw new ArgumentNullException(nameof(header)); if (header.TryGetValue("Content-Disposition", out string? disposition)) { - if (!disposition.StartsWith("form-data")) + if (!disposition.StartsWith("form-data", StringComparison.Ordinal)) return new FormEntry(header); - var nameResult = nameRegex.Match(disposition); + var nameResult = nameRegex().Match(disposition); var name = nameResult.Success ? nameResult.Groups["name"].Value : null; - var filenameResult = filenameRegex.Match(disposition); + var filenameResult = filenameRegex().Match(disposition); var filename = filenameResult.Success ? filenameResult.Groups["name"].Value : null; if (filename != null && name != null) @@ -149,32 +151,120 @@ protected virtual FormEntry GetEntry(Dictionary header) ///
public static bool AlwaysStoreFiles { get; set; } = true; + /// + /// The maximum number of parts a single multipart body may contain. This is independent + /// of /: + /// a body composed of a huge number of minimal parts can stay well under any byte-size + /// limit while still being expensive to process, since each part carries its own + /// object/dictionary/regex overhead regardless of how few raw bytes it represents. + /// Exceeding this rejects the request with . Set this to a negative value to + /// disable this check. Default is 10,000. + /// + public static int MaximumPartCount { get; set; } = 10_000; + + /// + /// The maximum length, in characters, of a part's boundary line or header line. Exceeding it rejects the + /// request with . Use a negative value to disable + /// the check. Default is 8 KB. + /// + public static long MaxPartHeaderLineLength { get; set; } = 8192; + + /// + /// SetAsync must be called at most once per instance; a second call leaks the previous call's + /// temp files. + /// public async Task SetAsync(WebProgressTask task, IO.ContentStream content, string options) { - var match = boundaryRegex.Match(options); - var boundary = match.Success ? match.Groups["name"].Value : ""; - boundary = $"--{boundary}"; - ReadOnlyMemory rawBoundary = Encoding.UTF8.GetBytes(boundary); + ArgumentNullException.ThrowIfNull(task); + ArgumentNullException.ThrowIfNull(content); + + var match = boundaryRegex().Match(options); + var boundaryName = match.Success ? match.Groups["name"].Value : ""; + if (string.IsNullOrEmpty(boundaryName)) + { + // a missing/empty boundary can never be parsed correctly: falling back to + // "--" as the delimiter is a 2-byte sequence virtually guaranteed to occur + // inside real content, producing nonsensical/truncated entries instead of a + // clean rejection + task.Response.StatusCode = HttpStateCode.BadRequest; + task.NextStage = ServerStage.CreateResponse; + await content.DiscardAsync().ConfigureAwait(false); + return; + } + var boundary = $"--{boundaryName}"; + ReadOnlyMemory rawBoundary = Encoding.UTF8.GetBytes("\r\n" + boundary); Entries.Clear(); using var reader = new NetworkReader(content, null, true); + async Task RejectHeaderTooLarge() + { + task.Response.StatusCode = HttpStateCode.RequestHeaderFieldsTooLarge; + task.NextStage = ServerStage.CreateResponse; + await content.DiscardAsync().ConfigureAwait(false); + } + // parse the content + var firstPart = true; while (true) { + if (!firstPart) + { + // consume the CRLF that precedes this boundary; it was left unread by + // the previous ReadUntilAsync call, since it is now part of the search + // marking above rather than the previous part's content. The very + // first boundary of the body has no preceding CRLF to consume (per RFC + // 2046, it may be the first line of the body). + var crlf = await reader.ReadBytesAsync(2).ConfigureAwait(false); + if (crlf.Length != 2 || crlf[0] != (byte)'\r' || crlf[1] != (byte)'\n') + break; + } + firstPart = false; + // expect boundary - if (reader.ReadLine() != boundary) + string? boundaryLine; + try + { + boundaryLine = await reader.ReadLineAsync(MaxPartHeaderLineLength).ConfigureAwait(false); + } + catch (IO.ReadLineOverflowException) + { + await RejectHeaderTooLarge().ConfigureAwait(false); + return; + } + if (boundaryLine != boundary) break; + if (MaximumPartCount >= 0 && Entries.Count >= MaximumPartCount) + { + // reject before spending any work parsing this (excess) part's headers + // or content - a huge part count is itself the attack, regardless of + // how small each individual part is + task.Response.StatusCode = HttpStateCode.RequestEntityTooLarge; + task.NextStage = ServerStage.CreateResponse; + await content.DiscardAsync().ConfigureAwait(false); + return; + } + // read headers until an empty line is found - var dict = new Dictionary(StringComparer.InvariantCultureIgnoreCase); + var dict = new Dictionary(StringComparer.OrdinalIgnoreCase); string? line; - while (!string.IsNullOrWhiteSpace(line = reader.ReadLine())) + try { - var header = headerSplit.Match(line); - if (!header.Success) - break; - dict.Add(header.Groups["name"].Value, header.Groups["value"].Value); + while (!string.IsNullOrWhiteSpace(line = await reader.ReadLineAsync(MaxPartHeaderLineLength).ConfigureAwait(false))) + { + var header = headerSplit().Match(line); + if (!header.Success) + break; + // last-wins on a repeated header name within one part (Dictionary.Add would throw) + dict[header.Groups["name"].Value] = header.Groups["value"].Value; + } + } + catch (IO.ReadLineOverflowException) + { + await RejectHeaderTooLarge().ConfigureAwait(false); + return; } var entry = GetEntry(dict); @@ -186,11 +276,30 @@ public async Task SetAsync(WebProgressTask task, IO.ContentStream content, strin if (storeInTemp) { var name = Path.GetTempFileName(); - using var file = new FileStream(name, FileMode.OpenOrCreate, FileAccess.Write, - FileShare.None - ); - using var stream = StorageMapper?.Invoke(task, file) ?? file; - await reader.ReadUntilAsync(rawBoundary, stream).ConfigureAwait(false); + try + { +#pragma warning disable CA2000 // already disposed via the using declaration below; the analyzer is confused by the `StorageMapper?.Invoke(task, file) ?? file` fallback + using var file = new FileStream(name, FileMode.OpenOrCreate, FileAccess.Write, + FileShare.None + ); +#pragma warning restore CA2000 + using var stream = StorageMapper?.Invoke(task, file) ?? file; + await reader.ReadUntilAsync(rawBoundary, stream).ConfigureAwait(false); + } + catch + { + // the write above never finished, so `name` is not attached to `entry` and FormEntry.Dispose + // will never delete it + try + { + File.Delete(name); + } + catch (Exception) + { + logger.LogInformation(PostEventId, "Cannot delete temp file"); + } + throw; + } entry.Set(new FileInfo(name)); } else @@ -203,7 +312,7 @@ public async Task SetAsync(WebProgressTask task, IO.ContentStream content, strin } // there should nothing left but to be sure just discard the rest - content.Discard(); + await content.DiscardAsync().ConfigureAwait(false); } /// @@ -216,7 +325,9 @@ public async Task SetAsync(WebProgressTask task, IO.ContentStream content, strin /// is not secure enough. ///
/// Any temp file that is not moved away until the processing of the request is finished - /// will automatically deleted from . + /// is automatically deleted by once the request's + /// is disposed — which + /// does after the response has been fully sent. ///
/// This stream is only used for storing the data from the POST request. After that this /// will automatically disposed. The entries contain only the references to the files as @@ -228,26 +339,39 @@ public async Task SetAsync(WebProgressTask task, IO.ContentStream content, strin public override string ToString() { var sb = new StringBuilder(); - sb.AppendLine($"[{Entries.Count:#,#0} Entries]"); + sb.AppendLine(CultureInfo.InvariantCulture, $"[{Entries.Count:#,#0} Entries]"); var boundary = new string('-', 20); foreach (var entry in Entries) { sb.AppendLine(boundary); foreach (var (key, value) in entry.Header) - sb.AppendLine($"{key}: {value}"); + sb.AppendLine(CultureInfo.InvariantCulture, $"{key}: {value}"); sb.AppendLine(); if (entry.Content != null) - sb.AppendLine($"[{entry.Content.Value.Length:#,#0} Bytes]"); + sb.AppendLine(CultureInfo.InvariantCulture, $"[{entry.Content.Value.Length:#,#0} Bytes]"); if (entry.TempFile != null && entry.TempFile.Exists) - sb.AppendLine($"[{entry.TempFile.Length:#,#0} Bytes in {entry.TempFile.FullName}]"); + sb.AppendLine(CultureInfo.InvariantCulture, $"[{entry.TempFile.Length:#,#0} Bytes in {entry.TempFile.FullName}]"); } sb.AppendLine(boundary); return sb.ToString(); } + /// + /// Not thread-safe: await SetAsync before calling Dispose, otherwise temp files may leak. + /// public void Dispose() { Entries.ForEach(x => x.Dispose()); + GC.SuppressFinalize(this); } + + [GeneratedRegex("boundary\\s*=\\s*(?:\"(?[^\"]*)\"|(?[^\";\\s]*))")] + private static partial Regex boundaryRegex(); + [GeneratedRegex("[^\\w]name\\s*=\\s*\"(?[^\"]*)\"", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)] + private static partial Regex nameRegex(); + [GeneratedRegex("[^\\w]filename\\s*=\\s*\"(?[^\"]*)\"", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)] + private static partial Regex filenameRegex(); + [GeneratedRegex("^(?[^:\\s]+)\\s*:\\s*(?.*)$")] + private static partial Regex headerSplit(); } -} \ No newline at end of file +} diff --git a/MaxLib.WebServer/Post/RawPostData.cs b/MaxLib.WebServer/Post/RawPostData.cs new file mode 100644 index 0000000..3da0170 --- /dev/null +++ b/MaxLib.WebServer/Post/RawPostData.cs @@ -0,0 +1,138 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; + +#nullable enable + +namespace MaxLib.WebServer.Post +{ + /// + /// Handles any request body whose Content-Type has no dedicated + /// (application/json, application/octet-stream, anything else unrecognized, or a + /// missing Content-Type entirely) by storing the whole body as one nameless + /// , in memory or spilled to a temp file depending on + /// its size - exactly like an individual multipart part already is. + /// + public sealed partial class RawPostData : IPostData + { + static readonly ILogger logger = WebServerLog.LoggerFactory.CreateLogger(); + static readonly EventId PostEventId = new(0, "POST"); + + public string MimeType { get; } + + /// + /// The whole request body, as a single entry with no name and no headers of its own. + /// + public MultipartFormData.FormEntry Entry { get; } + = new MultipartFormData.FormEntry(new Dictionary()); + + /// + /// The charset this body was declared with, resolved once in . + /// Falls back to UTF-8 if none or an unknown one was declared. + /// + public Encoding Encoding { get; private set; } = Encoding.UTF8; + + /// + /// The maximum number of bytes the body can have to be cached in memory. If the body is + /// larger than this it is stored in a temp file instead - the same threshold multipart + /// parts already use. Set this to a negative value to always cache in memory regardless + /// of size. + /// + public static long MaximumCacheSize { get; set; } = 50 * 1024 * 1024; + + public RawPostData(string? mime) + { + MimeType = mime ?? WebServer.MimeType.ApplicationOctetStream; + } + + public async Task SetAsync(WebProgressTask task, IO.ContentStream content, string options) + { + ArgumentNullException.ThrowIfNull(task); + ArgumentNullException.ThrowIfNull(content); + Encoding = ResolveEncoding(options); + + // Content-Length is mandatory by the time a ContentStream exists at all + // (HttpRequestParser rejects Transfer-Encoding and validates Content-Length before + // ever constructing one), so the body's length is always known here. + if (MaximumCacheSize >= 0 && content.FullLength > MaximumCacheSize) + { + var name = Path.GetTempFileName(); + try + { +#pragma warning disable CA2000 // already disposed via the using declaration below; the analyzer is confused by the `StorageMapper?.Invoke(task, file) ?? file` fallback + using var file = new FileStream(name, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); +#pragma warning restore CA2000 + using var stream = MultipartFormData.StorageMapper?.Invoke(task, file) ?? file; + await content.CopyToAsync(stream).ConfigureAwait(false); + } + catch + { + // the copy above never finished, so `name` is not attached to `Entry` and FormEntry.Dispose + // will never delete it + try + { + File.Delete(name); + } + catch (Exception) + { + logger.LogInformation(PostEventId, "Cannot delete temp file"); + } + throw; + } + Entry.Set(new FileInfo(name)); + } + else + { + var buffer = new byte[content.UnreadData]; + await content.ReadExactlyAsync(buffer.AsMemory()).ConfigureAwait(false); + Entry.Set(buffer); + } + } + + private static Encoding ResolveEncoding(string options) + { + var match = charsetRegex().Match(options); + Encoding? encoding = null; + if (match.Success) + try + { + var charset = match.Groups["charset"].Value; + // RFC 9110 §5.6.6: a parameter value may be a quoted-string (charset="iso-8859-1"); the regex + // captures the quotes, so unwrap them before the lookup. + if (charset.Length >= 2 && charset[0] == '"' && charset[^1] == '"') + charset = charset[1..^1]; + encoding = Encoding.GetEncoding(charset); + } + catch (Exception e) + { + logger.LogError(PostEventId, e, "Invalid encoding {Charset}", match.Groups["charset"].Value); + } + return encoding ?? Encoding.UTF8; + } + + [GeneratedRegex("charset\\s*=\\s*(?[^\\s;]+)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)] + private static partial Regex charsetRegex(); + + public override string ToString() + { + if (Entry.Content is ReadOnlyMemory content) + return string.Create(CultureInfo.InvariantCulture, $"[{content.Length:#,#0} Bytes]"); + if (Entry.TempFile is FileInfo tempFile && tempFile.Exists) + return string.Create(CultureInfo.InvariantCulture, $"[{tempFile.Length:#,#0} Bytes in {tempFile.FullName}]"); + return "[empty]"; + } + + /// + /// Not thread-safe: await SetAsync before calling Dispose, otherwise temp files may leak. + /// + public void Dispose() + { + Entry.Dispose(); + } + } +} diff --git a/MaxLib.WebServer/Post/UnknownPostData.cs b/MaxLib.WebServer/Post/UnknownPostData.cs index 9f0db5e..6e6c0de 100644 --- a/MaxLib.WebServer/Post/UnknownPostData.cs +++ b/MaxLib.WebServer/Post/UnknownPostData.cs @@ -1,4 +1,3 @@ -using System.Text; using System; using System.Threading.Tasks; @@ -6,7 +5,7 @@ namespace MaxLib.WebServer.Post { - public sealed class UnknownPostData : IPostData + public sealed class UnknownPostData : IPostData, IAsyncDisposable { public IO.ContentStream Data { get; private set; } @@ -29,9 +28,23 @@ public override string ToString() return $"[{Data.Length:#,#0} Bytes]"; } + /// + /// The synchronous Dispose drains the body without the read timeout; prefer DisposeAsync. + /// This only drains the remaining body of Data; the ContentStream itself is not disposed and + /// remains owned by its creator (e.g. HttpPost). + /// public void Dispose() { Data.Discard(); } + + /// + /// This only drains the remaining body of Data; the ContentStream itself is not disposed and + /// remains owned by its creator (e.g. HttpPost). + /// + public async ValueTask DisposeAsync() + { + await Data.DiscardAsync().ConfigureAwait(false); + } } } \ No newline at end of file diff --git a/MaxLib.WebServer/Post/UrlEncodedData.cs b/MaxLib.WebServer/Post/UrlEncodedData.cs index 3fcbe18..85da148 100644 --- a/MaxLib.WebServer/Post/UrlEncodedData.cs +++ b/MaxLib.WebServer/Post/UrlEncodedData.cs @@ -2,81 +2,233 @@ using System.Text; using System; using System.Collections.Generic; +using System.Globalization; +using System.IO; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; #nullable enable namespace MaxLib.WebServer.Post { - public class UrlEncodedData : IPostData + public partial class UrlEncodedData : IPostData { + static readonly ILogger logger = WebServerLog.LoggerFactory.CreateLogger(); + static readonly EventId SetPostEventId = new(0, "SetPost"); + public string MimeType => WebServer.MimeType.ApplicationXWwwFromUrlencoded; public Dictionary Parameter { get; } = new Dictionary(); + /// + /// Populated instead of once the whole body exceeds . Every entry is represented as a + /// instead (its name the url-decoded key), + /// individually eligible for the same in-memory-vs-temp-file storage decision a + /// multipart part already gets - a single request can't have any one key or value + /// larger than its own total declared length, so deciding this once, up front, from + /// that length is always correct; there is no case where already-collected + /// entries would need to be converted after the fact. + /// + public MultipartFormData? Overflow { get; private set; } + + /// + /// The maximum size, in bytes, the whole body can have to be parsed directly into + /// . Above this, is used instead, so that + /// a request built from one huge value isn't forced entirely into memory just to + /// populate a . Set this to a negative value to + /// always use regardless of size. Default is 50 MB, matching + /// . + /// + public static long MaximumCacheSize { get; set; } = 50 * 1024 * 1024; + public void Set(string content, string options) { _ = content ?? throw new ArgumentNullException(nameof(content)); Parameter.Clear(); - if (content != "") + if (content.Length != 0) { var tiles = content.Split('&'); foreach (var tile in tiles) { - var ind = tile.IndexOf('='); + var ind = tile.IndexOf('=', StringComparison.Ordinal); if (ind == -1) { var t = WebServerUtils.DecodeUri(tile); - if (!Parameter.ContainsKey(t)) - Parameter.Add(t, ""); + Parameter.TryAdd(t, ""); } else { - var key = WebServerUtils.DecodeUri(tile.Remove(ind)); - var value = ind + 1 == tile.Length ? "" : tile.Substring(ind + 1); - if (!Parameter.ContainsKey(key)) - Parameter.Add(key, WebServerUtils.DecodeUri(value)); + var key = WebServerUtils.DecodeUri(tile[..ind]); + var value = ind + 1 == tile.Length ? "" : tile[(ind + 1)..]; + Parameter.TryAdd(key, WebServerUtils.DecodeUri(value)); } } } } - static readonly Regex charsetRegex = new Regex( - "charset\\s*=\\s*(?[^\\s;]+)", - RegexOptions.Compiled | RegexOptions.IgnoreCase - ); - - public async Task SetAsync(WebProgressTask task, IO.ContentStream content, string options) + private static Encoding ResolveEncoding(string options) { - var match = charsetRegex.Match(options); + var match = charsetRegex().Match(options); Encoding? encoding = null; if (match.Success) try - { - encoding = Encoding.GetEncoding(match.Groups["charset"].Value); + { + var charset = match.Groups["charset"].Value; + // RFC 9110 §5.6.6: a parameter value may be a quoted-string (charset="iso-8859-1"); the regex + // captures the quotes, so unwrap them before the lookup. + if (charset.Length >= 2 && charset[0] == '"' && charset[^1] == '"') + charset = charset[1..^1]; + encoding = Encoding.GetEncoding(charset); } catch (Exception e) { - WebServerLog.Add(ServerLogType.Error, GetType(), "SetPost", - $"invalid encoding {match.Groups["charset"].Value}: {e}"); + logger.LogError(SetPostEventId, e, "Invalid encoding {Charset}", match.Groups["charset"].Value); } - encoding ??= Encoding.UTF8; - var buffer = new byte[content.UnreadData]; - await content.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false); - Set(encoding.GetString(buffer), options); + return encoding ?? Encoding.UTF8; + } + + /// + /// SetAsync must be called at most once per instance; a second call leaks the previous call's + /// temp files. + /// + public async Task SetAsync(WebProgressTask task, IO.ContentStream content, string options) + { + ArgumentNullException.ThrowIfNull(task); + ArgumentNullException.ThrowIfNull(content); + var encoding = ResolveEncoding(options); + + if (MaximumCacheSize < 0 || content.FullLength <= MaximumCacheSize) + { + var buffer = new byte[content.UnreadData]; + await content.ReadExactlyAsync(buffer.AsMemory()).ConfigureAwait(false); + Set(encoding.GetString(buffer), options); + return; + } + + // the body is large enough that a single key or value could plausibly need + // file-backed storage; spill it to disk first - streamed, never buffered as one + // block - and parse token-by-token from there instead + Parameter.Clear(); + Overflow = new MultipartFormData(); + var rawFileName = Path.GetTempFileName(); + using var rawFile = new FileStream( + rawFileName, FileMode.Create, FileAccess.ReadWrite, FileShare.None, + 4096, FileOptions.DeleteOnClose + ); + await content.CopyToAsync(rawFile).ConfigureAwait(false); + rawFile.Position = 0; + await ParseTokensAsync(task, rawFile, encoding).ConfigureAwait(false); + } + + private async Task ParseTokensAsync(WebProgressTask task, Stream rawFile, Encoding encoding) + { + var seenKeys = new HashSet(); + using var tokenBuffer = new MemoryStream(); + var chunk = new byte[81920]; + int read; + while ((read = await rawFile.ReadAsync(chunk.AsMemory()).ConfigureAwait(false)) > 0) + { + var start = 0; + for (var i = 0; i < read; i++) + { + // a literal '&' can only ever appear as a delimiter here - any '&' that was + // part of a key/value's actual content was necessarily percent-encoded + // (%26) by any conformant client, so splitting on the raw byte is safe + // regardless of the request's declared charset + if (chunk[i] != (byte)'&') + continue; + tokenBuffer.Write(chunk.AsSpan(start, i - start)); + await AddTokenAsync(task, tokenBuffer, encoding, seenKeys).ConfigureAwait(false); + tokenBuffer.SetLength(0); + start = i + 1; + } + if (start < read) + tokenBuffer.Write(chunk.AsSpan(start, read - start)); + } + if (tokenBuffer.Length > 0) + await AddTokenAsync(task, tokenBuffer, encoding, seenKeys).ConfigureAwait(false); + } + + private async Task AddTokenAsync( + WebProgressTask task, MemoryStream tokenBuffer, Encoding encoding, HashSet seenKeys + ) + { + // a token here is still the raw, percent-encoded "key" or "key=value" text; decode + // it exactly the same way Set(string, string) already does for the small-body path + var text = encoding.GetString(tokenBuffer.ToArray()); + var ind = text.IndexOf('=', StringComparison.Ordinal); + string key, value; + if (ind == -1) + { + key = WebServerUtils.DecodeUri(text); + value = ""; + } + else + { + key = WebServerUtils.DecodeUri(text[..ind]); + value = WebServerUtils.DecodeUri(text[(ind + 1)..]); + } + + // first-value-wins, matching Parameter.TryAdd's semantics in the small-body path + if (!seenKeys.Add(key)) + return; + + var entry = new MultipartFormData.FormData(new Dictionary(), key); + var valueBytes = Encoding.UTF8.GetBytes(value); + if (MaximumCacheSize >= 0 && valueBytes.LongLength > MaximumCacheSize) + { + var name = Path.GetTempFileName(); + try + { +#pragma warning disable CA2000 // already disposed via the using declaration below; the analyzer is confused by the `StorageMapper?.Invoke(task, file) ?? file` fallback + using var file = new FileStream(name, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); +#pragma warning restore CA2000 + using var stream = MultipartFormData.StorageMapper?.Invoke(task, file) ?? file; + await stream.WriteAsync(valueBytes).ConfigureAwait(false); + } + catch + { + // the write above never finished, so `name` is not attached to `entry` and FormEntry.Dispose + // will never delete it + try + { + File.Delete(name); + } + catch (Exception) + { + logger.LogInformation(SetPostEventId, "Cannot delete temp file"); + } + throw; + } + entry.Set(new FileInfo(name)); + } + else + { + entry.Set(valueBytes); + } + Overflow!.Entries.Add(entry); } public override string ToString() { var sb = new StringBuilder(); foreach (var (key, value) in Parameter) - sb.AppendLine($"{key}: {value}"); + sb.AppendLine(CultureInfo.InvariantCulture, $"{key}: {value}"); return sb.ToString(); } + /// + /// Not thread-safe: await SetAsync before calling Dispose, otherwise temp files may leak. + /// public void Dispose() { + Overflow?.Dispose(); + GC.SuppressFinalize(this); } + + [GeneratedRegex("charset\\s*=\\s*(?[^\\s;]+)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)] + private static partial Regex charsetRegex(); } -} \ No newline at end of file +} diff --git a/MaxLib.WebServer/PrefixKind.cs b/MaxLib.WebServer/PrefixKind.cs new file mode 100644 index 0000000..4ae59c4 --- /dev/null +++ b/MaxLib.WebServer/PrefixKind.cs @@ -0,0 +1,20 @@ +namespace MaxLib.WebServer +{ + /// + /// The unit prefix system used by + /// to format a byte count. + /// + public enum PrefixKind + { + /// + /// Binary prefixes (KiB, MiB, GiB, ...) as defined by IEC 80000-13. Each step is a + /// factor of 1024. + /// + IEC, + /// + /// Decimal prefixes (KB, MB, GB, ...) as defined by the International System of Units. + /// Each step is a factor of 1000. + /// + SI, + } +} diff --git a/MaxLib.WebServer/Properties/AssemblyInfo.cs b/MaxLib.WebServer/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..7a7b531 --- /dev/null +++ b/MaxLib.WebServer/Properties/AssemblyInfo.cs @@ -0,0 +1,3 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("MaxLib.WebServer.Test")] diff --git a/MaxLib.WebServer/Properties/Resources.cs b/MaxLib.WebServer/Properties/Resources.cs index 1bc663d..1c228c1 100644 --- a/MaxLib.WebServer/Properties/Resources.cs +++ b/MaxLib.WebServer/Properties/Resources.cs @@ -6,11 +6,11 @@ namespace MaxLib.WebServer.Properties { public static class Resources { - private static string? files_ViewHtmlCss = null; + private static string? files_ViewHtmlCss; public static string Files_ViewHtmlCss { - get + get { if (files_ViewHtmlCss != null) return files_ViewHtmlCss; @@ -20,5 +20,24 @@ public static string Files_ViewHtmlCss return files_ViewHtmlCss = reader.ReadToEnd(); } } + + private static string? debugger_Shell; + + /// + /// The self-contained HTML/CSS/JS shell + /// serves at its base path. + /// + public static string Debugger_Shell + { + get + { + if (debugger_Shell != null) + return debugger_Shell; + var assembly = typeof(Resources).Assembly; + using var stream = assembly.GetManifestResourceStream("MaxLib.WebServer.Resources.Debugger.Shell.html")!; + using var reader = new StreamReader(stream); + return debugger_Shell = reader.ReadToEnd(); + } + } } -} \ No newline at end of file +} diff --git a/MaxLib.WebServer/Remote/MarshalContainer.cs b/MaxLib.WebServer/Remote/MarshalContainer.cs index 21a2f97..3544474 100644 --- a/MaxLib.WebServer/Remote/MarshalContainer.cs +++ b/MaxLib.WebServer/Remote/MarshalContainer.cs @@ -7,6 +7,15 @@ namespace MaxLib.WebServer.Remote { + /// + /// Backing for . + /// + /// + /// See the remarks on - this type shares the same + /// cross-AppDomain limitation and will be removed alongside it. + /// + [Obsolete("Cross-AppDomain remoting is not supported on .NET (Core) 5+ and this type does " + + "not function on net8.0/net10.0. It will be removed in a future major version.")] internal class MarshalContainer : MarshalByRefObject { public HttpDataSource? Origin { get; private set; } diff --git a/MaxLib.WebServer/Remote/MarshalSource.cs b/MaxLib.WebServer/Remote/MarshalSource.cs index e608e12..1e0a3e1 100644 --- a/MaxLib.WebServer/Remote/MarshalSource.cs +++ b/MaxLib.WebServer/Remote/MarshalSource.cs @@ -6,7 +6,19 @@ namespace MaxLib.WebServer.Remote { + /// + /// Marshals an across an boundary. + /// + /// + /// Cross- remoting via is not + /// supported on .NET (Core) 5+ and does not function on this library's net8.0/net10.0 + /// targets - throws + /// at runtime. This type is kept for source + /// compatibility only and will be removed in a future major version. + /// [Serializable] + [Obsolete("Cross-AppDomain remoting is not supported on .NET (Core) 5+ and this type does " + + "not function on net8.0/net10.0. It will be removed in a future major version.")] public class MarshalSource : HttpDataSource { public bool IsLazy => Container.IsLazy(); @@ -23,7 +35,10 @@ public MarshalSource(HttpDataSource source) => Container.Length(); public override void Dispose() - => Container.Dispose(); + { + Container.Dispose(); + GC.SuppressFinalize(this); + } protected override Task WriteStreamInternal(Stream stream) => Container.WriteStream(stream); diff --git a/MaxLib.WebServer/Resources/Debugger.Shell.html b/MaxLib.WebServer/Resources/Debugger.Shell.html new file mode 100644 index 0000000..d9301a0 --- /dev/null +++ b/MaxLib.WebServer/Resources/Debugger.Shell.html @@ -0,0 +1,587 @@ + + + + +MaxLib.WebServer Builder Debugger + + + +

MaxLib.WebServer — Builder Debugger

+

Why a scanned type/method was skipped, and why a request does (or doesn't) reach a service.

+ +

Build report

+
+ + +
+ +
+
Loading…
+ +

Request routing simulator

+
+ + + + +
+
+ +
+ + +
+
+
+ + + + + + diff --git a/MaxLib.WebServer/SSL/DualSecureWebServer.cs b/MaxLib.WebServer/SSL/DualSecureWebServer.cs index 7513632..d991edb 100644 --- a/MaxLib.WebServer/SSL/DualSecureWebServer.cs +++ b/MaxLib.WebServer/SSL/DualSecureWebServer.cs @@ -1,42 +1,97 @@ using System; using System.IO; using System.Net.Security; -using System.Net.Sockets; using System.Security.Authentication; +using System.Security.Cryptography.X509Certificates; +using System.Threading; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; -#nullable enable +#nullable enable namespace MaxLib.WebServer.SSL { + /// + /// The configured logging provider must not throw while rendering exceptions; the server does not + /// guard its log calls. + /// public class DualSecureWebServer : Server { + static readonly ILogger logger = WebServerLog.LoggerFactory.CreateLogger(); + static readonly EventId StartUpEventId = new(0, "StartUp"); + static readonly EventId HandshakeEventId = new(0, "Handshake"); + public DualSecureWebServerSettings DualSettings => (DualSecureWebServerSettings)Settings; public DualSecureWebServer(DualSecureWebServerSettings settings) : base(settings) { - WebServerLog.Add(ServerLogType.Information, GetType(), "StartUp", "The use of dual mode is critical"); + logger.LogInformation(StartUpEventId, "The use of dual mode is critical"); } protected override async Task ClientStartListen(HttpConnection connection) { + ArgumentNullException.ThrowIfNull(connection); if (connection.NetworkStream == null && connection.NetworkClient != null) { var peaker = new StreamPeaker(connection.NetworkClient.GetStream()); + try + { + using var peekTimeout = DualSettings.HandshakeTimeout > TimeSpan.Zero + ? new CancellationTokenSource(DualSettings.HandshakeTimeout) + : null; + await peaker.EnsureFirstByteAsync(peekTimeout?.Token ?? CancellationToken.None) + .ConfigureAwait(false); + } + catch (OperationCanceledException) + { + // a client that never sends a byte would otherwise occupy this connection indefinitely + await peaker.DisposeAsync().ConfigureAwait(false); + connection.NetworkClient.Close(); + AllConnections.Remove(connection); + return; + } + catch (Exception e) + { + // e.g. a connection reset before the first byte; without this the exception escapes to + // SafeClientStartListen, which only logs it and never cleans up the connection + logger.LogInformation(HandshakeEventId, e, + "Connection failed before the protocol peek completed for {RemoteEndPoint}", connection.NetworkClient.Client.RemoteEndPoint); + await peaker.DisposeAsync().ConfigureAwait(false); + connection.NetworkClient.Close(); + AllConnections.Remove(connection); + return; + } var mark = peaker.FirstByte; if (mark != 0 && (mark < 32 || mark >= 127)) { var ssl = new SslStream(peaker, false); connection.NetworkStream = ssl; - ssl.AuthenticateAsServer( - serverCertificate: DualSettings.Certificate, - clientCertificateRequired: false, - enabledSslProtocols: SslProtocols.None, - checkCertificateRevocation: true - ); + try + { + using var handshakeTimeout = DualSettings.HandshakeTimeout > TimeSpan.Zero + ? new CancellationTokenSource(DualSettings.HandshakeTimeout) + : null; + await ssl.AuthenticateAsServerAsync( + new SslServerAuthenticationOptions + { + ServerCertificate = DualSettings.Certificate, + ClientCertificateRequired = false, + EnabledSslProtocols = SslProtocols.None, + CertificateRevocationCheckMode = X509RevocationMode.Online, + }, + handshakeTimeout?.Token ?? CancellationToken.None + ).ConfigureAwait(false); + } + catch (Exception e) + { + // a failed handshake leaves ssl.IsAuthenticated false, so the + // existing cleanup branch below still runs + logger.LogInformation(HandshakeEventId, e, + "TLS handshake failed for {RemoteEndPoint}", connection.NetworkClient.Client.RemoteEndPoint); + } if (!ssl.IsAuthenticated) { - ssl.Dispose(); + await ssl.DisposeAsync().ConfigureAwait(false); connection.NetworkClient.Close(); AllConnections.Remove(connection); return; @@ -47,17 +102,18 @@ protected override async Task ClientStartListen(HttpConnection connection) await base.ClientStartListen(connection).ConfigureAwait(false); } - class StreamPeaker : Stream + internal class StreamPeaker : Stream { - public StreamPeaker(NetworkStream baseStream) + public StreamPeaker(Stream baseStream) { - BaseStream = baseStream ?? throw new ArgumentNullException("baseStream"); + BaseStream = baseStream ?? throw new ArgumentNullException(nameof(baseStream)); } - public NetworkStream BaseStream { get; private set; } + public Stream BaseStream { get; private set; } int firstByte = -1; - bool FirstByteReaded = false; + bool firstByteRead; + bool baseStreamAtEnd; public override bool CanRead => true; @@ -78,41 +134,109 @@ public override void Flush() BaseStream.Flush(); } + // 0x00 is also returned once the underlying stream has ended before sending any + // byte at all, so callers must not treat FirstByte alone as proof that a byte + // was actually received - it is only meaningful together with HasFirstByte. public byte FirstByte { get { - if (firstByte == -1) + if (firstByte == -1 && !baseStreamAtEnd) + GetFirstByte(); + return baseStreamAtEnd ? (byte)0 : (byte)firstByte; + } + } + + public bool HasFirstByte + { + get + { + if (firstByte == -1 && !baseStreamAtEnd) GetFirstByte(); - return (byte)firstByte; + return !baseStreamAtEnd; } } void GetFirstByte() { var b = new byte[1]; - BaseStream.Read(b, 0, 1); + var read = BaseStream.Read(b, 0, 1); + if (read == 0) + { + baseStreamAtEnd = true; + return; + } + firstByte = b[0]; + } + + /// + /// Asynchronous, cancellable counterpart to ; the byte is cached + /// for /. + /// + public async ValueTask EnsureFirstByteAsync(CancellationToken cancellationToken) + { + if (firstByte != -1 || baseStreamAtEnd) + return; + var b = new byte[1]; + var read = await BaseStream.ReadAsync(b.AsMemory(0, 1), cancellationToken).ConfigureAwait(false); + if (read == 0) + { + baseStreamAtEnd = true; + return; + } firstByte = b[0]; } public override int Read(byte[] buffer, int offset, int count) { - if (buffer == null) throw new ArgumentNullException("buffer"); + ArgumentNullException.ThrowIfNull(buffer); if (offset < 0 || offset + count > buffer.Length) - throw new ArgumentOutOfRangeException("offset"); - if (count < 0) - throw new ArgumentOutOfRangeException("count"); + throw new ArgumentOutOfRangeException(nameof(offset)); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (count == 0) return 0; - if (firstByte == -1) GetFirstByte(); - if (!FirstByteReaded) + if (firstByte == -1 && !baseStreamAtEnd) GetFirstByte(); + if (!firstByteRead) { + firstByteRead = true; + if (baseStreamAtEnd) return 0; buffer[offset] = FirstByte; - FirstByteReaded = true; - return BaseStream.Read(buffer, offset +1 , count - 1) + 1; + if (count == 1) return 1; + var read = BaseStream.Read(buffer, offset + 1, count - 1); + return read + 1; } return BaseStream.Read(buffer, offset, count); } + /// + /// Async, cancellable counterpart to . Without it, a timeout + /// could not abort the reads of the TLS handshake. + /// + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + if (buffer.Length == 0) + return 0; + if (firstByte == -1 && !baseStreamAtEnd) + await EnsureFirstByteAsync(cancellationToken).ConfigureAwait(false); + if (!firstByteRead) + { + firstByteRead = true; + if (baseStreamAtEnd) + return 0; + buffer.Span[0] = FirstByte; + if (buffer.Length == 1) + return 1; + var read = await BaseStream.ReadAsync(buffer[1..], cancellationToken).ConfigureAwait(false); + return read + 1; + } + return await BaseStream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); + } + + public override async Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(buffer); + return await ReadAsync(buffer.AsMemory(offset, count), cancellationToken).ConfigureAwait(false); + } + public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); diff --git a/MaxLib.WebServer/SSL/DualSecureWebServerSettings.cs b/MaxLib.WebServer/SSL/DualSecureWebServerSettings.cs index 5f9c6a3..b640fb8 100644 --- a/MaxLib.WebServer/SSL/DualSecureWebServerSettings.cs +++ b/MaxLib.WebServer/SSL/DualSecureWebServerSettings.cs @@ -1,4 +1,5 @@ -using System.Security.Cryptography.X509Certificates; +using System; +using System.Security.Cryptography.X509Certificates; #nullable enable @@ -8,6 +9,15 @@ public class DualSecureWebServerSettings : WebServerSettings { public X509Certificate Certificate { get; set; } + /// + /// The maximum time the protocol-detection peek and the TLS handshake may each take before the connection + /// is dropped. Defaults to 10 seconds; zero or a negative value disables the timeout. + /// + public TimeSpan HandshakeTimeout { get; set; } = TimeSpan.FromSeconds(10); + + /// The port to listen on. + /// The connection timeout in milliseconds. + /// Must not be null; a null certificate makes every HTTPS handshake fail at connection time. public DualSecureWebServerSettings(int port, int connectionTimeout, X509Certificate certificate) : base(port, connectionTimeout) { diff --git a/MaxLib.WebServer/SSL/SecureWebServer.cs b/MaxLib.WebServer/SSL/SecureWebServer.cs index 9154c43..2465748 100644 --- a/MaxLib.WebServer/SSL/SecureWebServer.cs +++ b/MaxLib.WebServer/SSL/SecureWebServer.cs @@ -1,38 +1,56 @@ -using System.Diagnostics; +using System; +using System.Diagnostics; +using System.Globalization; using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Security.Authentication; +using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; #nullable enable namespace MaxLib.WebServer.SSL { + /// + /// The configured logging provider must not throw while rendering exceptions; the server does not + /// guard its log calls. + /// public class SecureWebServer : Server { + static readonly ILogger logger = WebServerLog.LoggerFactory.CreateLogger(); + static readonly EventId StartUpEventId = new(0, "StartUp"); + static readonly EventId HandshakeEventId = new(0, "Handshake"); + static readonly EventId UnhandledExceptionEventId = new(0, "Unhandled Exception"); + public SecureWebServerSettings SecureSettings => (SecureWebServerSettings)Settings; //Secure Server protected TcpListener? SecureListener; protected Thread? SecureServerThread; + // Whether Start() started the base (plain-HTTP) accept loop. Unlike EnableUnsafePort this cannot + // change later, so SecureMainTask's keep-alive guard stays in sync with Server.ServerMainTask. + private bool baseLoopStarted; + public SecureWebServer(SecureWebServerSettings settings) : base(settings) { } public override void Start() { - if (SecureSettings.EnableUnsafePort) + baseLoopStarted = SecureSettings.EnableUnsafePort; + if (baseLoopStarted) base.Start(); - WebServerLog.Add(ServerLogType.Information, GetType(), "StartUp", "Start Secure Server on Port {0}", SecureSettings.SecurePort); + logger.LogInformation(StartUpEventId, "Start Secure Server on Port {Port}", SecureSettings.SecurePort); ServerExecution = true; SecureListener = new TcpListener(new IPEndPoint(Settings.IPFilter, SecureSettings.SecurePort)); SecureListener.Start(); SecureServerThread = new Thread(SecureMainTask) { - Name = "SecureServerThread - Port: " + SecureSettings.SecurePort.ToString() + Name = "SecureServerThread - Port: " + SecureSettings.SecurePort.ToString(CultureInfo.InvariantCulture) }; SecureServerThread.Start(); } @@ -41,13 +59,13 @@ public override void Stop() { if (SecureSettings.EnableUnsafePort) base.Stop(); - WebServerLog.Add(ServerLogType.Information, GetType(), "StartUp", "Stopped Secure Server"); + logger.LogInformation(StartUpEventId, "Stopped Secure Server"); ServerExecution = false; } protected virtual void SecureMainTask() { - WebServerLog.Add(ServerLogType.Information, GetType(), "StartUp", "Secure Server succesfuly started"); + logger.LogInformation(StartUpEventId, "Secure Server successfully started"); var watch = new Stopwatch(); while (ServerExecution) { @@ -57,26 +75,56 @@ protected virtual void SecureMainTask() for (; step < 10; step++) { if (!SecureListener!.Pending()) break; - SecureClientConnected(SecureListener.AcceptTcpClient()); + TcpClient client; + try + { + client = SecureListener.AcceptTcpClient(); + } + catch (Exception e) + { + // like Server.ServerMainTask: this runs on a raw Thread, where an unhandled exception would take + // down the process. Nothing was accepted, so there is nothing to clean up. + logger.LogCritical(UnhandledExceptionEventId, e, "Unhandled exception while accepting a connection"); + continue; + } + try + { + SecureClientConnected(client); + } + catch (Exception e) + { + // SecureClientConnected failed before registering the client in AllConnections; + // close it, or its socket leaks + client.Close(); + logger.LogCritical(UnhandledExceptionEventId, e, "Unhandled exception while accepting a connection"); + } } + //request keep alive connections - only needed here when Start() didn't start the base accept loop, + //which already polls the shared KeepAliveConnections list on its own thread (running both would race) + if (!baseLoopStarted) + ProcessKeepAliveConnections(); + //wait - if (SecureListener!.Pending()) + if (SecureListener!.Pending()) continue; var time = watch.ElapsedMilliseconds % 20; Thread.Sleep(20 - (int)time); } watch.Stop(); SecureListener!.Stop(); - WebServerLog.Add(ServerLogType.Information, GetType(), "StartUp", "Secure Server succesfuly stopped"); + logger.LogInformation(StartUpEventId, "Secure Server successfully stopped"); } protected virtual void SecureClientConnected(TcpClient client) { + ArgumentNullException.ThrowIfNull(client); if (SecureSettings.Certificate == null) { client.Close(); return; } + if (!TryAdmitConnection(client)) + return; //prepare session var connection = new HttpConnection() { @@ -92,15 +140,32 @@ protected virtual void SecureClientConnected(TcpClient client) //authentificate as server and establish ssl connection var stream = new SslStream(client.GetStream(), false); connection.NetworkStream = stream; - stream.AuthenticateAsServer( - serverCertificate: SecureSettings.Certificate, - clientCertificateRequired: false, - enabledSslProtocols: SslProtocols.None, - checkCertificateRevocation: true - ); + try + { + using var handshakeTimeout = SecureSettings.HandshakeTimeout > TimeSpan.Zero + ? new CancellationTokenSource(SecureSettings.HandshakeTimeout) + : null; + await stream.AuthenticateAsServerAsync( + new SslServerAuthenticationOptions + { + ServerCertificate = SecureSettings.Certificate, + ClientCertificateRequired = false, + EnabledSslProtocols = SslProtocols.None, + CertificateRevocationCheckMode = X509RevocationMode.Online, + }, + handshakeTimeout?.Token ?? CancellationToken.None + ).ConfigureAwait(false); + } + catch (Exception e) + { + // a failed handshake (bad ClientHello, disconnect, timeout) leaves stream.IsAuthenticated false, + // so the cleanup branch below still runs + logger.LogInformation(HandshakeEventId, e, + "TLS handshake failed for {RemoteEndPoint}", client.Client.RemoteEndPoint); + } if (!stream.IsAuthenticated) { - stream.Dispose(); + await stream.DisposeAsync().ConfigureAwait(false); client.Close(); AllConnections.Remove(connection); return; diff --git a/MaxLib.WebServer/SSL/SecureWebServerSettings.cs b/MaxLib.WebServer/SSL/SecureWebServerSettings.cs index ec66dd1..96915c1 100644 --- a/MaxLib.WebServer/SSL/SecureWebServerSettings.cs +++ b/MaxLib.WebServer/SSL/SecureWebServerSettings.cs @@ -1,4 +1,5 @@ -using System.Security.Cryptography.X509Certificates; +using System; +using System.Security.Cryptography.X509Certificates; #nullable enable @@ -11,6 +12,12 @@ public class SecureWebServerSettings : WebServerSettings public X509Certificate? Certificate { get; set; } + /// + /// The maximum time the TLS handshake may take before the connection is dropped. + /// Defaults to 10 seconds; zero or a negative value disables the timeout. + /// + public TimeSpan HandshakeTimeout { get; set; } = TimeSpan.FromSeconds(10); + public SecureWebServerSettings(int port, int securePort, int connectionTimeout) : base(port, connectionTimeout) { diff --git a/MaxLib.WebServer/Server.cs b/MaxLib.WebServer/Server.cs index c34c8b5..c91815c 100644 --- a/MaxLib.WebServer/Server.cs +++ b/MaxLib.WebServer/Server.cs @@ -1,7 +1,9 @@ using MaxLib.Collections; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.Linq; using System.Net; using System.Net.Sockets; @@ -16,8 +18,21 @@ namespace MaxLib.WebServer /// A web server that supports the HTTP protocol. This is the bare bone of the server stack. /// For functionality you need to add the needed . ///
+ /// + /// The configured logging provider must not throw while rendering exceptions; the server does not + /// guard its log calls. + /// public class Server : IDisposable { + static readonly ILogger logger = WebServerLog.LoggerFactory.CreateLogger(); + static readonly EventId StartUpEventId = new(0, "StartUp"); + static readonly EventId ConnectionEventId = new(0, "Connection"); + static readonly EventId UnhandledExceptionEventId = new(0, "Unhandled Exception"); + static readonly EventId RuntimeExceptionEventId = new(0, "runtime exception"); + static readonly EventId FallbackResponseEventId = new(0, "Fallback response"); + static readonly EventId CancelEventId = new(0, "cancel"); + static readonly EventId ConnectionLimitEventId = new(0, "Connection limit"); + /// /// The added divided in their . These /// are called in their order for handling user requests. @@ -72,6 +87,7 @@ public Server(WebServerSettings settings) /// .
With these you have basic functionality and a /// working web server that can deliver 404 answers for every request. ///
+#pragma warning disable CA2000 // ownership transfers to WebServiceGroups via AddWebService, disposed by Server.Dispose() public virtual void InitialDefault() { //Pre parse request @@ -85,6 +101,7 @@ public virtual void InitialDefault() //send response AddWebService(new Services.HttpSender()); } +#pragma warning restore CA2000 /// /// Add a new web service to the server and integrate its services. This can be done at @@ -104,7 +121,7 @@ public virtual void AddWebService(WebService webService) /// true if found; otherwise false public virtual bool ContainsWebService(WebService webService) { - if (webService == null) + if (webService == null) return false; return WebServiceGroups[webService.Stage].Contains(webService); } @@ -115,7 +132,7 @@ public virtual bool ContainsWebService(WebService webService) /// the web service to remove public virtual void RemoveWebService(WebService webService) { - if (webService == null) + if (webService == null) return; WebServiceGroups[webService.Stage].Remove(webService); } @@ -148,13 +165,13 @@ public virtual IEnumerable GetWebServices() /// public virtual void Start() { - WebServerLog.Add(ServerLogType.Information, GetType(), "StartUp", "Start Server on Port {0}", Settings.Port); + logger.LogInformation(StartUpEventId, "Start Server on Port {Port}", Settings.Port); ServerExecution = true; Listener = new TcpListener(new IPEndPoint(Settings.IPFilter, Settings.Port)); Listener.Start(); ServerThread = new Thread(ServerMainTask) { - Name = "ServerThread - Port: " + Settings.Port.ToString() + Name = "ServerThread - Port: " + Settings.Port.ToString(CultureInfo.InvariantCulture) }; ServerThread.Start(); } @@ -165,16 +182,16 @@ public virtual void Start() /// public virtual void Stop() { - WebServerLog.Add(ServerLogType.Information, GetType(), "StartUp", "Stopped Server"); + logger.LogInformation(StartUpEventId, "Stopped Server"); ServerExecution = false; ServerThread?.Join(); } - + protected virtual void ServerMainTask() { if (Listener == null) return; - WebServerLog.Add(ServerLogType.Information, GetType(), "StartUp", "Server successfully started"); + logger.LogInformation(StartUpEventId, "Server successfully started"); var watch = new Stopwatch(); while (ServerExecution) { @@ -185,41 +202,36 @@ protected virtual void ServerMainTask() { if (!Listener.Pending()) break; step++; - ClientConnected(Listener.AcceptTcpClient()); - } - //request keep alive connections - for (int i = 0; i < KeepAliveConnections.Count; ++i) - { - HttpConnection kas; - try { kas = KeepAliveConnections[i]; } - catch { continue; } - if (kas == null) - continue; - - if ((kas.NetworkClient != null && !kas.NetworkClient.Connected) || - (kas.LastWorkTime != -1 && - kas.LastWorkTime + Settings.ConnectionTimeout < Environment.TickCount - ) - ) + TcpClient client; + try { - kas.NetworkClient?.Close(); - kas.NetworkStream?.Dispose(); - AllConnections.Remove(kas); - KeepAliveConnections.Remove(kas); - --i; + client = Listener.AcceptTcpClient(); + } + catch (Exception e) + { + // AcceptTcpClient() can throw for reasons unrelated to other connections (handle exhaustion, a client + // reset in the backlog). This runs on a raw Thread, where an unhandled exception would take down the + // process. Nothing was accepted, so there is nothing to clean up. + logger.LogCritical(UnhandledExceptionEventId, e, "Unhandled exception while accepting a connection"); continue; } - - if (kas.NetworkClient != null && kas.NetworkClient.Available > 0 && - kas.LastWorkTime != -1 - ) + try + { + ClientConnected(client); + } + catch (Exception e) { - _ = Task.Run(() => SafeClientStartListen(kas)); + // ClientConnected failed before registering the client in AllConnections (e.g. RemoteEndPoint on a + // peer that already reset); close it, or its socket leaks + client.Close(); + logger.LogCritical(UnhandledExceptionEventId, e, "Unhandled exception while accepting a connection"); } } + //request keep alive connections + ProcessKeepAliveConnections(); //Warten - if (Listener.Pending()) + if (Listener.Pending()) continue; var delay = Settings.ConnectionDelay; if (delay > TimeSpan.Zero) @@ -232,15 +244,57 @@ protected virtual void ServerMainTask() } watch.Stop(); Listener.Stop(); - for (int i = 0; i < AllConnections.Count; ++i) + for (int i = 0; i < AllConnections.Count; ++i) AllConnections[i].NetworkClient?.Close(); AllConnections.Clear(); KeepAliveConnections.Clear(); - WebServerLog.Add(ServerLogType.Information, GetType(), "StartUp", "Server successfully stopped"); + logger.LogInformation(StartUpEventId, "Server successfully stopped"); + } + + /// + /// Scans , re-dispatching connections that have data available and + /// evicting disconnected or timed-out ones. Called from both accept loops. + /// + protected void ProcessKeepAliveConnections() + { + for (int i = 0; i < KeepAliveConnections.Count; ++i) + { + HttpConnection kas; + try { kas = KeepAliveConnections[i]; } + catch { continue; } + if (kas == null) + continue; + + if ((kas.NetworkClient != null && !kas.NetworkClient.Connected) || + (kas.LastWorkTime != -1 && + kas.LastWorkTime + Settings.ConnectionTimeout < Environment.TickCount + ) + ) + { + kas.NetworkClient?.Close(); + kas.NetworkStream?.Dispose(); + AllConnections.Remove(kas); + KeepAliveConnections.Remove(kas); + --i; + continue; + } + + if (kas.NetworkClient != null && kas.NetworkClient.Available > 0 && + kas.LastWorkTime != -1 + ) + { + // claim it synchronously: otherwise the next pass could re-dispatch this connection to a second task + kas.LastWorkTime = -1; + _ = Task.Run(() => SafeClientStartListen(kas)); + } + } } protected virtual void ClientConnected(TcpClient client) { + ArgumentNullException.ThrowIfNull(client); + if (!TryAdmitConnection(client)) + return; //prepare session var connection = new HttpConnection() { @@ -251,7 +305,29 @@ protected virtual void ClientConnected(TcpClient client) }; AllConnections.Add(connection); //listen to connection - _ = Task.Run(async () => await SafeClientStartListen(connection)).ConfigureAwait(false); + _ = Task.Run(async () => await SafeClientStartListen(connection).ConfigureAwait(false)); + } + + /// + /// Checks a newly-accepted against + /// . If the limit is already + /// reached, closes immediately (it is never added to + /// or processed at all) and returns false - the + /// caller must not do anything further with it in that case. Shared by every accept + /// path ( and 's own), + /// since they all draw from the same count. + /// + protected bool TryAdmitConnection(TcpClient client) + { + ArgumentNullException.ThrowIfNull(client); + if (Settings.MaxConcurrentConnections < 0 || + AllConnections.Count < Settings.MaxConcurrentConnections) + return true; + logger.LogWarning(ConnectionLimitEventId, + "Rejecting connection from {RemoteEndPoint}: at the configured limit of {Limit}", + client.Client.RemoteEndPoint, Settings.MaxConcurrentConnections); + client.Close(); + return false; } protected virtual async Task SafeClientStartListen(HttpConnection connection) @@ -263,33 +339,46 @@ protected virtual async Task SafeClientStartListen(HttpConnection connection) try { await ClientStartListen(connection).ConfigureAwait(false); } catch (Exception e) { - WebServerLog.Add( - ServerLogType.FatalError, - GetType(), - "Unhandled Exception", - $"{e.GetType().FullName}: {e.Message} in {e.StackTrace}"); + logger.LogCritical(UnhandledExceptionEventId, e, "Unhandled exception"); } } } protected virtual async Task ClientStartListen(HttpConnection connection) { + ArgumentNullException.ThrowIfNull(connection); connection.LastWorkTime = -1; if (connection.NetworkClient != null && connection.NetworkClient.Connected) { - WebServerLog.Add(ServerLogType.Information, GetType(), "Connection", "Listen to Connection {0}", + logger.LogInformation(ConnectionEventId, "Listen to Connection {RemoteEndPoint}", connection.NetworkClient?.Client.RemoteEndPoint); var task = PrepairProgressTask(connection); if (task == null) { - WebServerLog.Add(ServerLogType.Information, GetType(), "Connection", - $"Cannot establish data stream to {connection.Ip}"); + logger.LogInformation(ConnectionEventId, "Cannot establish data stream to {Ip}", connection.Ip); RemoveConnection(connection); return; } - var start = task.Monitor.Enabled ? DateTime.UtcNow : DateTime.MinValue; + await ProcessTask(task, connection).ConfigureAwait(false); + } + else RemoveConnection(connection); + } + + /// + /// Runs through the whole service chain and then applies the + /// resulting connection bookkeeping (Keep-Alive registration, protocol switch, or + /// removal). + /// + protected virtual async Task ProcessTask(WebProgressTask task, HttpConnection connection) + { + _ = task ?? throw new ArgumentNullException(nameof(task)); + _ = connection ?? throw new ArgumentNullException(nameof(connection)); + + var start = task.Monitor.Enabled ? DateTime.UtcNow : DateTime.MinValue; + try + { try { await ExecuteTaskChain(task).ConfigureAwait(false); @@ -297,44 +386,82 @@ protected virtual async Task ClientStartListen(HttpConnection connection) catch (Exception e) { task.Monitor.Current.Log("Unhandled exception: {0}", e); - WebServerLog.Add(ServerLogType.Error, GetType(), "runtime exception", $"unhandled exception: {e}"); - throw; + logger.LogError(RuntimeExceptionEventId, e, "Unhandled exception"); + await SendFallbackErrorResponse(task).ConfigureAwait(false); } - finally - { + } + finally + { - if (Settings.MonitoringOutputDirectory is string monitorOut && task.Monitor.Enabled) - await task.Monitor.Save(monitorOut, start, task); + if (Settings.MonitoringOutputDirectory is string monitorOut && task.Monitor.Enabled) + await task.Monitor.Save(monitorOut, start, task).ConfigureAwait(false); - } - - if (task.SwitchProtocolHandler != null) - { - KeepAliveConnections.Remove(connection); - AllConnections.Remove(connection); - task.Dispose(); - _ = task.SwitchProtocolHandler(); - return; - } - - if (task.Request.FieldConnection == HttpConnectionType.KeepAlive) - { - if (!KeepAliveConnections.Contains(connection)) - KeepAliveConnections.Add(connection); - } - else RemoveConnection(connection); + } - connection.LastWorkTime = Environment.TickCount; + if (task.SwitchProtocolHandler != null) + { + KeepAliveConnections.Remove(connection); + AllConnections.Remove(connection); task.Dispose(); + _ = task.SwitchProtocolHandler(); + return; + } + + if (task.Request.FieldConnection == HttpConnectionType.KeepAlive) + { + if (!KeepAliveConnections.Contains(connection)) + KeepAliveConnections.Add(connection); } else RemoveConnection(connection); + + connection.LastWorkTime = Environment.TickCount; + task.Dispose(); + } + + /// + /// Best-effort recovery for an exception that escaped + /// without ever being turned into a response. If the response hasn't started sending yet + /// ( hasn't run), this discards whatever partial + /// document was built so far, forces a + /// status, and replays through to actually build and send that response. The connection + /// is always marked to close afterwards, because its state is unknown (a handler could have + /// consumed part of the request body, for example) and reusing it for a further request + /// isn't safe. + /// + /// + /// If already ran (or is running) when the + /// exception happened, bytes may already be on the wire, so no further response is + /// attempted. Doing so could corrupt whatever was already sent. + /// + protected virtual async Task SendFallbackErrorResponse(WebProgressTask task) + { + _ = task ?? throw new ArgumentNullException(nameof(task)); + + task.Request.FieldConnection = HttpConnectionType.Close; + if (task.CurrentStage >= ServerStage.SendResponse || task.NetworkStream == null) + return; + + task.Document.Dispose(); + task.Response.StatusCode = HttpStateCode.InternalServerError; + task.CurrentStage = ServerStage.CreateResponse; + task.NextStage = ServerStage.SendResponse; + + try + { + await ExecuteTaskChain(task).ConfigureAwait(false); + } + catch (Exception e) + { + logger.LogError(FallbackResponseEventId, e, + "Failed to send a fallback error response after an unhandled exception"); + } } protected void RemoveConnection(HttpConnection connection) { _ = connection ?? throw new ArgumentNullException(nameof(connection)); - if (KeepAliveConnections.Contains(connection)) - KeepAliveConnections.Remove(connection); + KeepAliveConnections.Remove(connection); AllConnections.Remove(connection); connection.NetworkClient?.Close(); } @@ -346,7 +473,7 @@ internal protected virtual async Task ExecuteTaskChain(WebProgressTask task, Ser { using var watch = task.Monitor.Watch(this, $"Web Service Group: {task.CurrentStage}"); await WebServiceGroups[task.CurrentStage].Execute(task).ConfigureAwait(false); - if (task.CurrentStage == terminationState) + if (task.CurrentStage == terminationState) break; task.CurrentStage = task.NextStage; task.NextStage = task.NextStage == ServerStage.FINAL_STAGE @@ -357,6 +484,7 @@ internal protected virtual async Task ExecuteTaskChain(WebProgressTask task, Ser protected virtual WebProgressTask? PrepairProgressTask(HttpConnection connection) { + ArgumentNullException.ThrowIfNull(connection); var stream = connection.NetworkStream; if (stream == null) try @@ -421,9 +549,9 @@ internal protected virtual async Task ExecuteTaskChain(WebProgressTask task, Ser #endif public async Task RunAsync( bool cancelFromConsoleEvent = true, -#if NET5_0_OR_GREATER +#if NET5_0_OR_GREATER bool cancelFromAssemblyUnload = true, -#endif +#endif bool cancelFromConsoleInput = false ) { @@ -436,29 +564,18 @@ public async Task RunAsync( if (token != RunToken) return; e.Cancel = true; - WebServerLog.Add( - ServerLogType.Information, - GetType(), - "cancel", - "console cancel received: {0}", - e.SpecialKey - ); + logger.LogInformation(CancelEventId, "Console cancel received: {SpecialKey}", e.SpecialKey); if (!token.IsCancellationRequested) token.Cancel(); }; - + #if NET5_0_OR_GREATER if (cancelFromAssemblyUnload) System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += _ => { if (token != RunToken) return; - WebServerLog.Add( - ServerLogType.Information, - GetType(), - "cancel", - "assembly unload received" - ); + logger.LogInformation(CancelEventId, "Assembly unload received"); if (!token.IsCancellationRequested) token.Cancel(); }; @@ -470,20 +587,15 @@ public async Task RunAsync( if (token != RunToken) return; while (Console.Read() != (int)'q'); - WebServerLog.Add( - ServerLogType.Information, - GetType(), - "cancel", - "console key q received" - ); + logger.LogInformation(CancelEventId, "Console key 'q' received"); if (!token.IsCancellationRequested) token.Cancel(); }); - + if (!ServerExecution) Start(); - try { await Task.Delay(-1, token.Token); } + try { await Task.Delay(-1, token.Token).ConfigureAwait(false); } catch (TaskCanceledException) {} Stop(); @@ -494,6 +606,7 @@ public async Task RunAsync( /// public void Dispose() { + GC.SuppressFinalize(this); if (RunToken != null && !RunToken.IsCancellationRequested) RunToken.Cancel(); if (ServerExecution) diff --git a/MaxLib.WebServer/ServerLogAddedHandler.cs b/MaxLib.WebServer/ServerLogAddedHandler.cs deleted file mode 100644 index 6ceb744..0000000 --- a/MaxLib.WebServer/ServerLogAddedHandler.cs +++ /dev/null @@ -1,6 +0,0 @@ -#nullable enable - -namespace MaxLib.WebServer -{ - public delegate void ServerLogAddedHandler(ServerLogArgs eventArgs); -} diff --git a/MaxLib.WebServer/ServerLogArgs.cs b/MaxLib.WebServer/ServerLogArgs.cs deleted file mode 100644 index a94a67a..0000000 --- a/MaxLib.WebServer/ServerLogArgs.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; - -#nullable enable - -namespace MaxLib.WebServer -{ - public class ServerLogArgs : EventArgs - { - public ServerLogItem LogItem { get; } - - public bool Discard { get; set; } = false; - - public ServerLogArgs(ServerLogItem logItem) - => LogItem = logItem; - } -} diff --git a/MaxLib.WebServer/ServerLogItem.cs b/MaxLib.WebServer/ServerLogItem.cs deleted file mode 100644 index 077bc61..0000000 --- a/MaxLib.WebServer/ServerLogItem.cs +++ /dev/null @@ -1,57 +0,0 @@ -using System; - -#nullable enable - -namespace MaxLib.WebServer -{ - [Serializable] - public readonly struct ServerLogItem - { - public DateTime Date { get; } - - public ServerLogType Type { get; } - - public string SenderType => SenderTypeMemory.ToString(); - - public ReadOnlyMemory SenderTypeMemory { get; } - - public string InfoType => InfoTypeMemory.ToString(); - - public ReadOnlyMemory InfoTypeMemory { get; } - - public string Information => InformationMemory.ToString(); - - public ReadOnlyMemory InformationMemory { get; } - - public ServerLogItem(DateTime date, ServerLogType type, Type sender, string infoType, string information) - { - Date = date; - Type = type; - SenderTypeMemory = (sender ?? throw new ArgumentNullException(nameof(sender))).FullName.AsMemory(); - InfoTypeMemory = infoType.AsMemory(); - InformationMemory = information.AsMemory(); - } - - public ServerLogItem(DateTime date, ServerLogType type, Type sender, string infoType, string mask, params object?[] data) - : this(date, type, sender, infoType, string.Format(mask, data)) - { } - - public ServerLogItem(ServerLogType type, Type sender, string infoType, string information) - : this(DateTime.Now, type, sender, infoType, information) - { - } - - public ServerLogItem(ServerLogType type, Type sender, string infoType, string mask, params object?[] data) - : this(type, sender, infoType, string.Format(mask, data)) - { } - - - public override string ToString() - { - if (Date == new DateTime()) - return $"[{Type}] {SenderType} : {InfoType} -> {Information}"; - else - return $"[{Date}] [{Type}] {SenderType} : {InfoType} -> {Information}"; - } - } -} diff --git a/MaxLib.WebServer/ServerLogType.cs b/MaxLib.WebServer/ServerLogType.cs deleted file mode 100644 index 8d5c57f..0000000 --- a/MaxLib.WebServer/ServerLogType.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace MaxLib.WebServer -{ - public enum ServerLogType : byte - { - Information, - Debug, - Error, - FatalError - } -} diff --git a/MaxLib.WebServer/Services/Http404Service.cs b/MaxLib.WebServer/Services/Http404Service.cs index 49971c2..a8571b3 100644 --- a/MaxLib.WebServer/Services/Http404Service.cs +++ b/MaxLib.WebServer/Services/Http404Service.cs @@ -1,4 +1,5 @@ using System; +using System.Globalization; using System.Net; using System.Text; using System.Threading.Tasks; @@ -22,21 +23,25 @@ public override bool CanWorkWith(WebProgressTask task) public override Task ProgressTask(WebProgressTask task) { + ArgumentNullException.ThrowIfNull(task); task.Response.StatusCode = HttpStateCode.NotFound; var sb = new StringBuilder(); sb.Append("404 NOT FOUND"); sb.Append("

Error 404: Not Found

The requested resource is not found.

"); sb.AppendLine("
");
-            sb.AppendLine($"Protocol: {WebUtility.HtmlEncode(task.Request.HttpProtocol)}");
-            sb.AppendLine($"Method:   {WebUtility.HtmlEncode(task.Request.ProtocolMethod)}");
-            sb.AppendLine($"Url:      {WebUtility.HtmlEncode(task.Request.Location.Url)}");
+            sb.AppendLine(CultureInfo.InvariantCulture, $"Protocol: {WebUtility.HtmlEncode(task.Request.HttpProtocol)}");
+            sb.AppendLine(CultureInfo.InvariantCulture, $"Method:   {WebUtility.HtmlEncode(task.Request.ProtocolMethod)}");
+            sb.AppendLine(CultureInfo.InvariantCulture, $"Url:      {WebUtility.HtmlEncode(task.Request.Location.Url)}");
             sb.AppendLine($"Header:");
             foreach (var (key, value) in task.Request.HeaderParameter)
-                sb.AppendLine($"\t{WebUtility.HtmlEncode(key)}: {WebUtility.HtmlEncode(value)}");
+                sb.AppendLine(CultureInfo.InvariantCulture, $"\t{WebUtility.HtmlEncode(key)}: {WebUtility.HtmlEncode(value)}");
             sb.AppendLine($"Body:");
-            sb.AppendLine(WebUtility.HtmlEncode(task.Request.Post.ToString()));
+            // Post.ToString() would block synchronously on the lazily-parsed body, and a read failure would turn the 404
+            // into an unhandled exception. The dump only needs the MIME type, which is known without reading the body.
+            sb.AppendLine(WebUtility.HtmlEncode(
+                task.Request.Post.MimeType is string mimeType ? $"[{mimeType}]" : "[no body]"));
             sb.Append($"

Try to change the request to get your expected response.

"); - sb.Append($"Created by Created by MaxLib.WebServer {Version}: {DateTime.UtcNow:r}"); task.Document.DataSources.Add(new HttpStringDataSource(sb.ToString()) { diff --git a/MaxLib.WebServer/Services/HttpRequestParser.cs b/MaxLib.WebServer/Services/HttpRequestParser.cs index ebe360f..c693c8f 100644 --- a/MaxLib.WebServer/Services/HttpRequestParser.cs +++ b/MaxLib.WebServer/Services/HttpRequestParser.cs @@ -2,9 +2,11 @@ using System.Text; using System.IO; using System; +using System.Globalization; using System.Threading.Tasks; using MaxLib.WebServer.IO; using System.Net.Sockets; +using Microsoft.Extensions.Logging; #nullable enable @@ -16,32 +18,39 @@ namespace MaxLib.WebServer.Services /// public class HttpRequestParser : WebService { + static readonly ILogger logger = WebServerLog.LoggerFactory.CreateLogger(); + static readonly EventId HeaderEventId = new(0, "Header"); + /// - /// If this property is set to a file name this parser will write + /// If this property is set to a file name this parser will write /// the content of each request to the request file. This file contains /// the request time, the full HTTP header and full POST content. ///
/// If either this or is set then /// this parser will handle all requests synchronously (only one request - /// is at the same time parsing). + /// is at the same time parsing). ///
/// Do not use this in production! + /// Set this before the server starts and do not change it while requests are being + /// processed. ///
- public string? DebugWriteRequestFile { get; set; } = null; + public string? DebugWriteRequestFile { get; set; } /// /// If this property is set to a file name this parser will writer - /// a brief description of each request to the connection file. + /// a brief description of each request to the connection file. /// This file contains only the request time, the remote IP and port, /// the requested host and url path. ///
/// If either this or is set then /// this parser will handle all requests synchronously (only one request - /// is at the same time parsing). + /// is at the same time parsing). ///
/// Do not use this in production! + /// Set this before the server starts and do not change it while requests are being + /// processed. ///
- public string? DebugLogConnectionFile { get; set; } = null; + public string? DebugLogConnectionFile { get; set; } /// /// Sometimes the data is not available at instant. This can happen with slow @@ -51,6 +60,18 @@ public class HttpRequestParser : WebService /// public TimeSpan MaxConnectionDelay { get; set; } = TimeSpan.FromSeconds(5); + /// + /// The maximum time the request-line and header-reading phase is given to complete as a + /// whole, measured from when this parser starts reading (right after + /// succeeds) - not a per-line timeout. Without this, a client + /// that trickles its request one byte (or one header line) at a time - the classic + /// "Slowloris" attack - could hold the connection open indefinitely once 's wait for the very first byte had already been + /// satisfied. Set this to zero or a negative value to disable this timeout entirely. + /// Default is 10 seconds. + /// + public TimeSpan MaxHeaderReadTime { get; set; } = TimeSpan.FromSeconds(10); + /// /// The maximum length the request method, url and http type combined are allowed to be. If /// this value exceeds this limit the parsing will be canceled and a public long MaxHeaderLength { get; set; } = 1_000_000; // 1 MB + /// + /// The maximum request body size (in byte) that is automatically accepted without + /// consulting . A request whose declared + /// Content-Length exceeds this value triggers that callback (if one is registered) + /// to obtain a possibly higher limit for this specific request; if no callback is + /// registered, or the limit it returns is still exceeded, the request is rejected with + /// and its connection is closed (the + /// client's body is never read, so the connection can't safely be reused). Set this to a + /// negative value to disable this base limit. Default is 100 MB (100 000 000 byte). + /// + public long MaxContentLength { get; set; } = 100_000_000; // 100 MB + + /// + /// Called when an incoming request's declared Content-Length (the second argument) + /// exceeds . Return the content length limit to apply for + /// this specific request instead — or null to allow any size. If this is not set, + /// any request exceeding is rejected outright. This allows + /// e.g. raising the limit for specific paths, users, or temporarily, without changing the + /// default for every other request. + /// + public Func>? ContentLengthLimitExceeded { get; set; } + + /// + /// The fixed base component ("x") of the read timeout applied while receiving a request's + /// body. The full timeout is this value plus a size-dependent component derived from + /// — see there for details. Unlike , this value applies uniformly to every request and cannot be + /// overridden per-request. Default is 5 seconds. + /// + public TimeSpan ContentReadBaseTimeout { get; set; } = TimeSpan.FromSeconds(5); + + /// + /// The minimum transmission speed (in byte/s) a client is assumed to sustain while sending + /// a request body. Used to derive the size-dependent component ("y") of the body read + /// timeout: y = Content-Length / MinimumContentTransferRate. The full timeout for a + /// request is + y, so a larger declared body is given + /// proportionally more time to arrive, while a client that stalls mid-upload is still + /// bounded rather than blocking the reader forever. Set this to zero or a negative value to + /// disable the size-dependent component (every request then only gets ). Unlike , this value + /// applies uniformly to every request and cannot be overridden per-request. Default is + /// 16 000 byte/s (16 kB/s). + /// + public double MinimumContentTransferRate { get; set; } = 16_000; // 16 kB/s + /// /// This reads the request and put their data in the current /// . /// - public HttpRequestParser() + public HttpRequestParser() : base(ServerStage.ReadRequest) { } @@ -85,7 +151,7 @@ public override bool CanWorkWith(WebProgressTask task) { if (DebugLogConnectionFile == null && DebugWriteRequestFile == null) return null; - + // enter locked debug zone await debugSemaphore.WaitAsync().ConfigureAwait(false); @@ -93,7 +159,7 @@ public override bool CanWorkWith(WebProgressTask task) { var sb = new StringBuilder(); sb.AppendLine(new string('=', 100)); - sb.AppendLine($"= {WebServerUtils.GetDateString(DateTime.UtcNow).PadRight(95, ' ')}="); + sb.AppendLine(CultureInfo.InvariantCulture, $"= {WebServerUtils.GetDateString(DateTime.UtcNow).PadRight(95, ' ')}="); sb.AppendLine(new string('=', 100)); sb.AppendLine(); return sb; @@ -121,21 +187,22 @@ private async ValueTask DebugConnection(WebProgressTask task) { if (DebugLogConnectionFile == null) return; - + var sb = new StringBuilder(); - sb.AppendLine($"{WebServerUtils.GetDateString(DateTime.UtcNow)} " + + sb.AppendLine(CultureInfo.InvariantCulture, $"{WebServerUtils.GetDateString(DateTime.UtcNow)} " + $"{task.Connection?.NetworkClient?.Client.RemoteEndPoint}"); var host = task.Request.HeaderParameter.TryGetValue("Host", out string? host_) ? host_ : ""; sb.AppendLine(" " + host + task.Request.Location.DocumentPath); sb.AppendLine(); - + await File.AppendAllTextAsync(DebugLogConnectionFile, sb.ToString()).ConfigureAwait(false); } protected virtual async ValueTask WaitForData(WebProgressTask task) { - try + ArgumentNullException.ThrowIfNull(task); + try { if (task.NetworkStream is NetworkStream ns && !ns.DataAvailable) { @@ -149,7 +216,7 @@ protected virtual async ValueTask WaitForData(WebProgressTask task) } if (!ns.DataAvailable) { - WebServerLog.Add(ServerLogType.Error, GetType(), "Header", "Request Timeout"); + logger.LogError(HeaderEventId, "Request Timeout"); task.Request.FieldConnection = HttpConnectionType.KeepAlive; task.Response.StatusCode = HttpStateCode.RequestTimeOut; task.NextStage = ServerStage.CreateResponse; @@ -159,7 +226,7 @@ protected virtual async ValueTask WaitForData(WebProgressTask task) } catch (ObjectDisposedException) { - WebServerLog.Add(ServerLogType.Error, GetType(), "Header", "Connection closed by remote host"); + logger.LogError(HeaderEventId, "Connection closed by remote host"); task.Response.StatusCode = HttpStateCode.RequestTimeOut; task.NextStage = ServerStage.FINAL_STAGE; return false; @@ -168,26 +235,41 @@ protected virtual async ValueTask WaitForData(WebProgressTask task) } protected virtual async ValueTask ReadLine(WebProgressTask task, - NetworkReader reader, long limit, HttpStateCode exceedState + NetworkReader reader, long limit, HttpStateCode exceedState, + CancellationToken cancellationToken = default ) { + ArgumentNullException.ThrowIfNull(task); + ArgumentNullException.ThrowIfNull(reader); string? line; - try { line = await reader.ReadLineAsync(limit).ConfigureAwait(false); } + try { line = await reader.ReadLineAsync(limit, cancellationToken).ConfigureAwait(false); } catch (IO.ReadLineOverflowException e) { e.State = exceedState; throw; } + catch (OperationCanceledException) + { + // unlike the generic catch below, the connection itself is still fine here - + // only the wait timed out - so still attempt a response on it, same as + // WaitForData's own timeout; but its remaining bytes (if the client is still + // sending more) are now abandoned mid-stream, so it can't safely be reused + logger.LogError(HeaderEventId, "Timed out while reading the request header"); + task.Response.StatusCode = HttpStateCode.RequestTimeOut; + task.Request.FieldConnection = HttpConnectionType.Close; + task.NextStage = ServerStage.CreateResponse; + return null; + } catch { - WebServerLog.Add(ServerLogType.Error, GetType(), "Header", "Connection closed by remote host"); + logger.LogError(HeaderEventId, "Connection closed by remote host"); task.Response.StatusCode = HttpStateCode.RequestTimeOut; task.NextStage = ServerStage.FINAL_STAGE; return null; } if (line == null) { - WebServerLog.Add(ServerLogType.Error, GetType(), "Header", "Can't read Header line"); + logger.LogError(HeaderEventId, "Can't read Header line"); task.Response.StatusCode = HttpStateCode.BadRequest; task.NextStage = ServerStage.CreateResponse; } @@ -196,11 +278,13 @@ protected virtual async ValueTask WaitForData(WebProgressTask task) protected virtual bool ParseFirstHeaderLine(WebProgressTask task, string line) { - WebServerLog.Add(ServerLogType.Debug, GetType(), "Header", line); + ArgumentNullException.ThrowIfNull(task); + ArgumentNullException.ThrowIfNull(line); + logger.LogDebug(HeaderEventId, "{Line}", line); var parts = line.Split(' '); if (parts.Length != 3) { - WebServerLog.Add(ServerLogType.Error, GetType(), "Header", "Bad Request"); + logger.LogError(HeaderEventId, "Bad Request"); task.Response.StatusCode = HttpStateCode.BadRequest; task.NextStage = ServerStage.CreateResponse; return false; @@ -215,36 +299,110 @@ protected virtual bool ParseFirstHeaderLine(WebProgressTask task, string line) protected virtual bool ParseOtherHeaderLine(WebProgressTask task, string line) { - var ind = line.IndexOf(':'); + ArgumentNullException.ThrowIfNull(task); + ArgumentNullException.ThrowIfNull(line); + var ind = line.IndexOf(':', StringComparison.Ordinal); if (ind < 0) { - WebServerLog.Add(ServerLogType.Error, GetType(), "Header", "Bad Request"); + logger.LogError(HeaderEventId, "Bad Request"); task.Response.StatusCode = HttpStateCode.BadRequest; task.NextStage = ServerStage.CreateResponse; return false; } - var key = line.Remove(ind).Trim(); - var value = line.Substring(ind + 1).Trim(); - task.Request.HeaderParameter.Add(key, value); + var key = line[..ind].Trim(); + var value = line[(ind + 1)..].Trim(); + // RFC 7230 §3.3.3: differing Content-Length values must be rejected (CL.CL request smuggling); + // identical repeated values are fine + if (string.Equals(key, "Content-Length", StringComparison.OrdinalIgnoreCase) && + task.Request.HeaderParameter.TryGetValue(key, out var existingLength) && + existingLength != value) + { + logger.LogError(HeaderEventId, "Bad Request, conflicting Content-Length headers"); + task.Response.StatusCode = HttpStateCode.BadRequest; + task.NextStage = ServerStage.CreateResponse; + // the client's framing of the body is now ambiguous - keeping the connection + // alive risks misparsing leftover bytes as the header of the next request + task.Request.FieldConnection = HttpConnectionType.Close; + return false; + } + // RFC 7230 §5.4: more than one Host header is always rejected, even with identical values + if (string.Equals(key, "Host", StringComparison.OrdinalIgnoreCase) && + task.Request.HeaderParameter.ContainsKey(key)) + { + logger.LogError(HeaderEventId, "Bad Request, duplicate Host header"); + task.Response.StatusCode = HttpStateCode.BadRequest; + task.NextStage = ServerStage.CreateResponse; + task.Request.FieldConnection = HttpConnectionType.Close; + return false; + } + // last-wins on any other repeated header name (Dictionary.Add would throw) + task.Request.HeaderParameter[key] = value; return true; } - protected virtual ValueTask LoadContent(WebProgressTask task, NetworkReader reader) + protected virtual async ValueTask LoadContent(WebProgressTask task, NetworkReader reader) { + ArgumentNullException.ThrowIfNull(task); + + // Transfer-Encoding request bodies are not supported (there is no chunked + // decoder), and honoring Content-Length while ignoring Transfer-Encoding (or + // vice versa) enables request smuggling against a front-end proxy that + // interprets the two differently (RFC 7230 §3.3.3). Reject outright until + // chunked request decoding is implemented; this also covers a request that + // sends both headers at once. + if (task.Request.HeaderParameter.ContainsKey("Transfer-Encoding")) + { + logger.LogError(HeaderEventId, "Transfer-Encoding is not supported"); + task.Response.StatusCode = HttpStateCode.NotImplemented; + task.NextStage = ServerStage.CreateResponse; + // the request's body (if any) is left unread on the socket; keeping the + // connection alive would let those bytes be parsed as the header of the + // next request, so force the connection closed after this response + task.Request.FieldConnection = HttpConnectionType.Close; + return false; + } + if (!task.Request.HeaderParameter.TryGetValue("Content-Length", out string? strLength)) - return new ValueTask(true); - - if (!int.TryParse(strLength, out int length) || length < 0) + return true; + + if (!long.TryParse(strLength, out long length) || length < 0) { - WebServerLog.Add(ServerLogType.Error, GetType(), "Header", "Bad Request, invalid content length"); + logger.LogError(HeaderEventId, "Bad Request, invalid content length"); task.Response.StatusCode = HttpStateCode.BadRequest; task.NextStage = ServerStage.CreateResponse; - return new ValueTask(false); + return false; } - var content = new IO.ContentStream(reader, length); + if (MaxContentLength >= 0 && length > MaxContentLength) + { + var allowedLength = ContentLengthLimitExceeded != null + ? await ContentLengthLimitExceeded(task, length).ConfigureAwait(false) + : MaxContentLength; + // allowedLength == null means the callback lifted the limit entirely + if (allowedLength != null && length > allowedLength.Value) + { + logger.LogError(HeaderEventId, "Request Entity Too Large"); + task.Response.StatusCode = HttpStateCode.RequestEntityTooLarge; + task.NextStage = ServerStage.CreateResponse; + // the client's body is never read, so leftover bytes would corrupt + // the next request on a reused connection + task.Request.FieldConnection = HttpConnectionType.Close; + return false; + } + } + + // bound how long this request's body is given to arrive: a fixed base + // component plus a size-dependent one, so a stalled client can't pin the + // reader (and later, the drain-on-dispose) forever, regardless of how large + // (but still accepted) its declared Content-Length is + var timeout = ContentReadBaseTimeout + (MinimumContentTransferRate > 0 + ? TimeSpan.FromSeconds(length / MinimumContentTransferRate) + : TimeSpan.Zero); + +#pragma warning disable CA2000 // ownership transfers via SetPost into HttpPost.Content, disposed by HttpPost.Dispose()/DisposeAsync() + var content = new IO.ContentStream(reader, length, timeout); task.Request.Post.SetPost( task, @@ -252,16 +410,25 @@ protected virtual ValueTask LoadContent(WebProgressTask task, NetworkReade task.Request.HeaderParameter.TryGetValue("Content-Type", out string? contentType) ? contentType : null ); +#pragma warning restore CA2000 - return new ValueTask(true); + return true; } public override async Task ProgressTask(WebProgressTask task) { _ = task ?? throw new ArgumentNullException(nameof(task)); - _ = task.NetworkStream ?? throw new ArgumentNullException(nameof(task.NetworkStream)); - - var reader = new NetworkReader(task.NetworkStream); + _ = task.NetworkStream ?? throw new ArgumentNullException(nameof(task)); + + // leaveOpen: true — this reader wraps the live connection stream, whose + // lifetime is owned by the Server/HttpConnection (it is reused across + // Keep-Alive requests). ContentStream now disposes the NetworkReader it + // is given once the request body has been drained; without leaveOpen + // that would close the connection stream after every request that had a + // body, defeating Keep-Alive. +#pragma warning disable CA2000 // must not dispose: reader is captured by a lazily-read ContentStream and consumed after this method returns + var reader = new NetworkReader(task.NetworkStream, leaveOpen: true); +#pragma warning restore CA2000 StringBuilder? debugBuilder = null; try @@ -269,21 +436,30 @@ public override async Task ProgressTask(WebProgressTask task) debugBuilder = await DebugStartRequest().ConfigureAwait(false); // wait until some data is received. - if (!await WaitForData(task)) + if (!await WaitForData(task).ConfigureAwait(false)) return; - + + // bound the entire request-line + header-reading phase as a whole (not + // per-line), so a client that trickles its request one byte at a time can't + // hold the connection open indefinitely just because it satisfied + // WaitForData's wait for the very first byte - see MaxHeaderReadTime + using var headerTimeoutSource = MaxHeaderReadTime > TimeSpan.Zero + ? new CancellationTokenSource(MaxHeaderReadTime) + : null; + var headerToken = headerTimeoutSource?.Token ?? CancellationToken.None; + // read first header line - var line = await ReadLine(task, reader, MaxUrlLength, HttpStateCode.RequestUrlTooLong) + var line = await ReadLine(task, reader, MaxUrlLength, HttpStateCode.RequestUrlTooLong, headerToken) .ConfigureAwait(false); if (line == null) return; debugBuilder?.AppendLine(line); if (!ParseFirstHeaderLine(task, line)) return; - + // read all other header lines var limit = MaxHeaderLength; - while (!string.IsNullOrWhiteSpace(line = await ReadLine(task, reader, limit, HttpStateCode.RequestHeaderFieldsTooLarge))) + while (!string.IsNullOrWhiteSpace(line = await ReadLine(task, reader, limit, HttpStateCode.RequestHeaderFieldsTooLarge, headerToken).ConfigureAwait(false))) { debugBuilder?.AppendLine(line); if (!ParseOtherHeaderLine(task, line)) @@ -299,9 +475,9 @@ public override async Task ProgressTask(WebProgressTask task) debugBuilder?.AppendLine(); // read content if possible - if (!await LoadContent(task, reader)) + if (!await LoadContent(task, reader).ConfigureAwait(false)) return; - + await DebugConnection(task).ConfigureAwait(false); } catch (IO.ReadLineOverflowException e) @@ -315,4 +491,4 @@ public override async Task ProgressTask(WebProgressTask task) } } } -} \ No newline at end of file +} diff --git a/MaxLib.WebServer/Services/HttpResponseCreator.cs b/MaxLib.WebServer/Services/HttpResponseCreator.cs index 6042683..5d8a570 100644 --- a/MaxLib.WebServer/Services/HttpResponseCreator.cs +++ b/MaxLib.WebServer/Services/HttpResponseCreator.cs @@ -1,4 +1,6 @@ -using System; +using Microsoft.Extensions.Logging; +using System; +using System.Globalization; using System.Linq; using System.Threading.Tasks; @@ -7,18 +9,25 @@ namespace MaxLib.WebServer.Services { /// - /// This service creates the response header and fill it with the necessary data. This will - /// also discard any unread POST data to make the network stream reader for sending data. + /// This service creates the response header and fill it with the necessary data. /// + /// + /// Any unread POST data is discarded later, once the response has actually been sent — see + /// . Doing it here instead, before the response is sent, would risk + /// the client never finding out about a response (e.g. a timeout status) if discarding that + /// data stalls or fails and the underlying connection has to be closed as a result. + /// public class HttpResponseCreator : WebService { + static readonly ILogger logger = WebServerLog.LoggerFactory.CreateLogger(); + static readonly EventId NoChunkedSenderEventId = new(0, "NoChunkedSender"); + /// - /// This service creates the response header and fill it with the necessary data. This will - /// also discard any unread POST data to make the network stream reader for sending data. + /// This service creates the response header and fill it with the necessary data. /// public HttpResponseCreator() : base(ServerStage.CreateResponse) { } - public override async Task ProgressTask(WebProgressTask task) + public override Task ProgressTask(WebProgressTask task) { _ = task ?? throw new ArgumentNullException(nameof(task)); @@ -27,23 +36,49 @@ public override async Task ProgressTask(WebProgressTask task) response.FieldContentType = task.Document.PrimaryMime; response.SetActualDate(); response.HttpProtocol = request.HttpProtocol; - response.SetHeader(new (string, string?)[] - { + response.SetHeader( + [ ("Connection", "keep-alive"), ("X-UA-Compatible", "IE=Edge"), - ("Content-Length", task.Document.DataSources.Sum((s) => s.Length()).ToString()), - }); + ]); if (task.Document.PrimaryEncoding != null) response.HeaderParameter["Content-Type"] += "; charset=" + task.Document.PrimaryEncoding; - - task.Request.Post.Dispose(); - await Task.CompletedTask.ConfigureAwait(false); + if (task.Document.DataSources.Any(s => s.Length() is null)) + { + // A null Length() means "unknown/streaming size" - Sum() over this would + // silently treat it as 0, undercounting Content-Length while the full body is + // still written to the wire (desyncing any client/proxy relying on that header + // for response framing). Only a genuinely chunked send (Chunked.ChunkedSender) + // expresses this correctly on the wire; if none is registered to do that, fail + // loudly instead of ever emitting a wrong Content-Length. + if (task.Server?.GetWebServices().Any() != true) + { + logger.LogError(NoChunkedSenderEventId, + "Rejecting a response containing a data source with an unknown length: " + + "no {Sender} is registered to send it correctly.", + nameof(Chunked.ChunkedSender)); + response.StatusCode = HttpStateCode.InternalServerError; + foreach (var source in task.Document.DataSources) + source.Dispose(); + task.Document.DataSources.Clear(); + response.HeaderParameter["Content-Length"] = "0"; + } + // else: a chunked sender is registered - leave Content-Length unset here and + // let it (and its paired Chunked.ChunkedResponseCreator, if also registered) + // take over framing for this response instead. + return Task.CompletedTask; + } + + response.HeaderParameter["Content-Length"] = + task.Document.DataSources.Sum((s) => s.Length())?.ToString(CultureInfo.InvariantCulture) ?? ""; + return Task.CompletedTask; } public override bool CanWorkWith(WebProgressTask task) { + ArgumentNullException.ThrowIfNull(task); return !task.Document.Information.ContainsKey($"block {nameof(HttpResponseCreator)}"); } } diff --git a/MaxLib.WebServer/Services/HttpSender.cs b/MaxLib.WebServer/Services/HttpSender.cs index b729fa3..7b9e71a 100644 --- a/MaxLib.WebServer/Services/HttpSender.cs +++ b/MaxLib.WebServer/Services/HttpSender.cs @@ -1,4 +1,6 @@ using System; +using Microsoft.Extensions.Logging; +using System.Globalization; using System.IO; using System.Linq; using System.Threading.Tasks; @@ -10,8 +12,18 @@ namespace MaxLib.WebServer.Services /// /// WebServiceType.SendResponse: Sendet Response und Dokument, wenn vorhanden, an den Clienten. /// + /// + /// Also discards any unread POST data once the response has been fully sent, readying the + /// connection for the next request. See for why this + /// happens here and not earlier. + /// public class HttpSender : WebService { + static readonly ILogger logger = WebServerLog.LoggerFactory.CreateLogger(); + static readonly EventId StatusCodeEventId = new(0, "StatusCode"); + static readonly EventId SendEventId = new(0, "Send"); + static readonly EventId DisposeEventId = new(0, "Dispose"); + /// /// WebServiceType.SendResponse: Sendet Response und Dokument, wenn vorhanden, an den Clienten. /// @@ -82,8 +94,8 @@ public virtual string StatusCodeText(HttpStateCode code) case 509: return "Bandwidth Limit Exceeded"; case 510: return "Not Extended"; default: - WebServerLog.Add(ServerLogType.Information, GetType(), "StatusCode", - "Cant get status string from {0} ({1}).", code, (int)code); + logger.LogInformation(StatusCodeEventId, + "Cant get status string from {StatusCode} ({StatusCodeNumber}).", code, (int)code); return ""; } } @@ -96,47 +108,98 @@ public override async Task ProgressTask(WebProgressTask task) var stream = task.NetworkStream; if (stream == null) return; - var writer = new StreamWriter(stream); - await writer.WriteAsync(header.HttpProtocol).ConfigureAwait(false); - await writer.WriteAsync(" ").ConfigureAwait(false); - await writer.WriteAsync(((int)header.StatusCode).ToString()).ConfigureAwait(false); - await writer.WriteAsync(" ").ConfigureAwait(false); - await writer.WriteLineAsync(StatusCodeText(header.StatusCode)).ConfigureAwait(false); - for (int i = 0; i < header.HeaderParameter.Count; ++i) //Parameter + try { - var e = header.HeaderParameter.ElementAt(i); - await writer.WriteAsync(e.Key).ConfigureAwait(false); - await writer.WriteAsync(": ").ConfigureAwait(false); - await writer.WriteLineAsync(e.Value).ConfigureAwait(false); +#pragma warning disable CA2000 // must not dispose: would close the still-needed connection stream, and StreamWriter's default no-BOM encoding must not be swapped just to add leaveOpen + var writer = new StreamWriter(stream); +#pragma warning restore CA2000 + await writer.WriteAsync(header.HttpProtocol).ConfigureAwait(false); + await writer.WriteAsync(" ").ConfigureAwait(false); + await writer.WriteAsync(((int)header.StatusCode).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false); + await writer.WriteAsync(" ").ConfigureAwait(false); + await writer.WriteLineAsync(StatusCodeText(header.StatusCode)).ConfigureAwait(false); + for (int i = 0; i < header.HeaderParameter.Count; ++i) //Parameter + { + var e = header.HeaderParameter.ElementAt(i); + await writer.WriteAsync(WebServerUtils.RemoveCrLf(e.Key)).ConfigureAwait(false); + await writer.WriteAsync(": ").ConfigureAwait(false); + await writer.WriteLineAsync(WebServerUtils.RemoveCrLf(e.Value)).ConfigureAwait(false); + } + foreach (var cookie in task.Request.Cookie.AddedCookies) //Cookies + { + await writer.WriteAsync("Set-Cookie: ").ConfigureAwait(false); + await writer.WriteLineAsync(cookie.Value.ToString()).ConfigureAwait(false); + } + await writer.WriteLineAsync().ConfigureAwait(false); + try { await writer.FlushAsync().ConfigureAwait(false); } + catch (ObjectDisposedException) + { + logger.LogInformation(SendEventId, "Connection closed by remote host."); + return; + } + catch (IOException) + { + logger.LogInformation(SendEventId, "Connection closed by remote host."); + return; + } + //Daten senden + try + { + if (!(task.Document.Information.ContainsKey("Only Header") && (bool)task.Document.Information["Only Header"]!)) + for (int i = 0; i < task.Document.DataSources.Count; ++i) + { + await task.Document.DataSources[i].WriteStream(stream).ConfigureAwait(false); + } + } + catch (ObjectDisposedException) + { + logger.LogInformation(SendEventId, "Connection closed by remote host."); + return; + } + catch (IOException) + { + logger.LogInformation(SendEventId, "Connection closed by remote host."); + return; + } + try { await stream.FlushAsync().ConfigureAwait(false); } + catch (IOException) + { + logger.LogInformation(SendEventId, "Connection closed by remote host."); + return; + } } - foreach (var cookie in task.Request.Cookie.AddedCookies) //Cookies + finally { - await writer.WriteAsync("Set-Cookie: ").ConfigureAwait(false); - await writer.WriteLineAsync(cookie.Value.ToString()).ConfigureAwait(false); + // must run however the try block above exits: this is the only place the request's POST data + // (and its temp files) is disposed + await DisposeRequestPostAsync(task).ConfigureAwait(false); } - await writer.WriteLineAsync().ConfigureAwait(false); - try { await writer.FlushAsync().ConfigureAwait(false); } - catch (ObjectDisposedException) + } + + /// + /// Disposes 's request POST data (temp files included), logging and marking the + /// connection for closure on failure. Every SendResponse-stage sender must call this exactly once, + /// from a finally block around its response transmission. + /// + protected static async Task DisposeRequestPostAsync(WebProgressTask task) + { + ArgumentNullException.ThrowIfNull(task); + try { - WebServerLog.Add(ServerLogType.Error, GetType(), "Send", "Connection closed by remote host."); - return; + await task.Request.Post.DisposeAsync().ConfigureAwait(false); } - catch (IOException) + catch (OperationCanceledException) { - WebServerLog.Add(ServerLogType.Error, GetType(), "Send", "Connection closed by remote host."); - return; + logger.LogWarning(DisposeEventId, + "Timed out while disposing request content; closing the connection"); + task.Request.FieldConnection = HttpConnectionType.Close; } - //Daten senden - if (!(task.Document.Information.ContainsKey("Only Header") && (bool)task.Document.Information["Only Header"]!)) - for (int i = 0; i < task.Document.DataSources.Count; ++i) - { - await task.Document.DataSources[i].WriteStream(stream).ConfigureAwait(false); - } - try { await stream.FlushAsync().ConfigureAwait(false); } catch (IOException) { - WebServerLog.Add(ServerLogType.Error, GetType(), "Send", "Connection closed by remote host."); - return; + // an ordinary connection reset while draining unread POST data: log it like the other + // broken-connection paths instead of letting it reach Server.ProcessTask's catch-all + logger.LogInformation(DisposeEventId, "Connection closed by remote host."); + task.Request.FieldConnection = HttpConnectionType.Close; } } diff --git a/MaxLib.WebServer/Services/LocalIOMapper.cs b/MaxLib.WebServer/Services/LocalIOMapper.cs index d84a8af..451861b 100644 --- a/MaxLib.WebServer/Services/LocalIOMapper.cs +++ b/MaxLib.WebServer/Services/LocalIOMapper.cs @@ -3,6 +3,7 @@ using System.IO; using System.Text; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; #nullable enable @@ -13,6 +14,10 @@ namespace MaxLib.WebServer.Services /// public class LocalIOMapper : WebService { + static readonly ILogger logger = WebServerLog.LoggerFactory.CreateLogger(); + static readonly EventId MapFileEventId = new(0, "map file"); + + /// /// A mapping rule that can produce a document for the requested path /// @@ -69,6 +74,7 @@ public FileMappingRule(ReadOnlyMemory urlPath, string localBasePath) public override bool MapRequest(ReadOnlySpan path, WebProgressTask task) { + ArgumentNullException.ThrowIfNull(task); var loc = task.Request.Location; if (loc.DocumentPath.EndsWith('/') || path.Length < UrlPath.Length) return false; @@ -83,7 +89,7 @@ public override bool MapRequest(ReadOnlySpan path, WebProgressTask task) try { fileInfo = new FileInfo(localPath); } catch (Exception e) { - WebServerLog.Add(ServerLogType.Error, GetType(), "map file", $"invalid path: {e}"); + logger.LogError(MapFileEventId, e, "Invalid path"); return false; } if (!fileInfo.Exists) @@ -139,7 +145,7 @@ public DirectoryMappingRule(ReadOnlyMemory urlPath, string localBasePath public override int Rank => UrlPath.Length; - private ReadOnlySpan EncodeUrl(ReadOnlySpan value) + private static ReadOnlySpan EncodeUrl(ReadOnlySpan value) { Span result = new string[value.Length]; for (int i = 0; i < value.Length; ++i) @@ -149,6 +155,7 @@ private ReadOnlySpan EncodeUrl(ReadOnlySpan value) public override bool MapRequest(ReadOnlySpan path, WebProgressTask task) { + ArgumentNullException.ThrowIfNull(task); var loc = task.Request.Location; if (path.Length < UrlPath.Length) return false; @@ -165,7 +172,7 @@ public override bool MapRequest(ReadOnlySpan path, WebProgressTask task) try { directoryInfo = new DirectoryInfo(localPath); } catch (Exception e) { - WebServerLog.Add(ServerLogType.Error, GetType(), "map file", $"invalid path: {e}"); + logger.LogError(MapFileEventId, e, "Invalid path"); return false; } if (!directoryInfo.Exists) @@ -228,7 +235,7 @@ public override bool MapRequest(ReadOnlySpan path, WebProgressTask task) /// /// Create a new local IO mapper that can map resources from the local io. /// - public LocalIOMapper() + public LocalIOMapper() : base(ServerStage.CreateDocument) { } @@ -257,7 +264,7 @@ public void AddFileMapping(string urlPath, string localBasePath) { _ = urlPath ?? throw new ArgumentNullException(nameof(urlPath)); Add(new FileMappingRule( - urlPath.Split('/', StringSplitOptions.RemoveEmptyEntries), + urlPath.Split('/', StringSplitOptions.RemoveEmptyEntries), localBasePath )); } @@ -286,6 +293,7 @@ public void AddDirectoryMapping(string urlPath, string localBasePath) public override bool CanWorkWith(WebProgressTask task) { + ArgumentNullException.ThrowIfNull(task); var path = ShortenPath(task.Request.Location.DocumentPathTiles); if (path == null) return false; @@ -307,7 +315,11 @@ public override Task ProgressTask(WebProgressTask task) /// the input path to shorten /// the shortened path or null if invalid input /// - /// Invalid paths are paths that starts with ".." like "../foo/bar". + /// Invalid paths are paths that starts with ".." like "../foo/bar", as well as any + /// tile that contains a path separator (/ or \) or that is itself rooted + /// (e.g. an absolute path or a drive reference smuggled into a single, decoded tile). + /// Such tiles could otherwise be used to escape the configured base directory when + /// combined with , so they are rejected outright. /// /// /// // always true @@ -330,6 +342,10 @@ public override Task ProgressTask(WebProgressTask task) offset--; continue; } + if (path[i].Contains('/', StringComparison.Ordinal) + || path[i].Contains('\\', StringComparison.Ordinal) + || Path.IsPathRooted(path[i])) + return null; output.Span[offset] = path[i]; offset++; } diff --git a/MaxLib.WebServer/Services/StandardDocumentLoader.cs b/MaxLib.WebServer/Services/StandardDocumentLoader.cs deleted file mode 100644 index c9eb835..0000000 --- a/MaxLib.WebServer/Services/StandardDocumentLoader.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System; -using System.Threading.Tasks; - -#nullable enable - -namespace MaxLib.WebServer.Services -{ - /// - /// WebServiceType.PreCreateDocument: Stellt ein festdefiniertes Dokument bereit. Dies ist unabhängig vom - /// angeforderten Pfad. - /// - [Obsolete("Define your own endpoint or use Http404Service")] - public class StandardDocumentLoader : WebService - { - /// - /// WebServiceType.PreCreateDocument: Stellt ein festdefiniertes Dokument bereit. Dies ist unabhängig vom - /// angeforderten Pfad. - /// - public StandardDocumentLoader() - : base(ServerStage.CreateDocument) - { - Priority = WebServicePriority.VeryLow; - Document = "Kein Dokument gefunden."; - } - - public string Document { get; set; } - - public override async Task ProgressTask(WebProgressTask task) - { - _ = task ?? throw new ArgumentNullException(nameof(task)); - - var source = new HttpStringDataSource(Document) - { - MimeType = MimeType.TextHtml - }; - task.Response.StatusCode = HttpStateCode.OK; - task.Document.DataSources.Add(source); - task.Document.PrimaryEncoding = "utf-8"; - - await Task.CompletedTask.ConfigureAwait(false); - } - - public override bool CanWorkWith(WebProgressTask task) - => true; - } -} diff --git a/MaxLib.WebServer/Sessions/MemorySessionService.cs b/MaxLib.WebServer/Sessions/MemorySessionService.cs index 7ea3014..bca6539 100644 --- a/MaxLib.WebServer/Sessions/MemorySessionService.cs +++ b/MaxLib.WebServer/Sessions/MemorySessionService.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Threading; using System.Threading.Tasks; #nullable enable @@ -8,19 +9,159 @@ namespace MaxLib.WebServer.Sessions { public class MemorySessionService : SessionServiceBase { + /// + /// This dictionary is not thread-safe and is modified concurrently by request processing and + /// the automatic sweep; do not read or modify it while the server is handling requests. + /// public Dictionary Sessions { get; } = new Dictionary(); + private readonly object sessionsLock = new(); + protected override ValueTask Get(string key) { _ = key ?? throw new ArgumentNullException(nameof(key)); - if (!Sessions.TryGetValue(key, out Session? value)) - Sessions.Add(key, value = new Session()); - value.LastUsed = DateTime.UtcNow; + Session? value; + lock (sessionsLock) + { + if (Sessions.TryGetValue(key, out value) && value.LastUsed + MaxAge < DateTime.UtcNow) + // expired: never resurrect stale data under an old id, and drop it here + // instead of paying for a full sweep on every single request + value = null; + if (value is null) + Sessions[key] = value = new Session { Key = key }; + value.LastUsed = DateTime.UtcNow; + } return new ValueTask(value); } protected override ValueTask IsKeyAvailable(string key) - => new ValueTask(!Sessions.ContainsKey(key)); + { + lock (sessionsLock) + // an expired entry counts as gone, consistent with Get(string); otherwise an expired but unswept key + // would be reused for a new session, reopening session fixation + return new ValueTask( + !Sessions.TryGetValue(key, out var value) || value.LastUsed + MaxAge < DateTime.UtcNow); + } + + protected override ValueTask Remove(string key) + { + lock (sessionsLock) + Sessions.Remove(key); + return default; + } + + /// + /// The margin adds after the oldest surviving + /// session's expiry when it schedules its next run, so a session isn't swept the + /// instant it expires and the timer isn't rescheduled to a near-immediate delay. + /// Default: one hour. + /// + public TimeSpan AutomaticSweepMargin { get; set; } = TimeSpan.FromHours(1); + + private Timer? sweepTimer; + + /// + /// Removes every session whose plus is in the past. This is the only way expired + /// sessions are ever evicted from in bulk - only ever discards the single expired entry it happens to + /// look up, to keep individual requests cheap. Call this yourself on whatever + /// schedule suits your application, or use to have + /// this service schedule it for you. + /// + /// + /// The of the least-recently-used session that + /// survived the sweep, or null if no session remains - so a caller scheduling the + /// next sweep doesn't need a second pass over to find it. + /// + public DateTime? Sweep() + { + var now = DateTime.UtcNow; + DateTime? oldestSurviving = null; + lock (sessionsLock) + { + List? expired = null; + foreach (var (key, session) in Sessions) + { + if (session.LastUsed + MaxAge < now) + (expired ??= new List()).Add(key); + else if (oldestSurviving is null || session.LastUsed < oldestSurviving) + oldestSurviving = session.LastUsed; + } + if (expired != null) + foreach (var key in expired) + Sessions.Remove(key); + } + return oldestSurviving; + } + + /// + /// Starts (or restarts) a background timer that calls for you, + /// so doesn't grow without bound. Entirely optional: is public specifically so you can drive it from your own + /// timer/background-job infrastructure instead, e.g. if your application already has + /// one and you'd rather not run a second. Each run reschedules itself for shortly + /// after the next session is due to expire (see ) + /// instead of polling on a fixed interval. Stop it with (also done by ). + /// + public void StartAutomaticSweep() + { + lock (sessionsLock) + { + sweepTimer?.Dispose(); + sweepTimer = new Timer(RunAutomaticSweep, null, TimeSpan.Zero, Timeout.InfiniteTimeSpan); + } + } + + /// + /// Stops the background timer started by , if + /// running. Does not remove any session already evicted. + /// + public void StopAutomaticSweep() + { + lock (sessionsLock) + { + sweepTimer?.Dispose(); + sweepTimer = null; + } + } + + /// + /// The longest delay hands to . + /// rejects due times over about 49.71 days, which a long + /// could exceed. Rescheduling earlier than necessary is harmless. + /// + private static readonly TimeSpan MaxAutomaticSweepDelay = TimeSpan.FromDays(45); + + /// + /// Runs one and reschedules the timer started for shortly after the next session is due to + /// expire, using the oldest surviving session reports back - + /// avoiding a second pass over just to find it. Exposed as + /// public so a host that prefers to drive its own scheduling can still reuse this + /// exact reschedule logic instead of reimplementing it. + /// + public void RunAutomaticSweep(object? state = null) + { + var oldestSurviving = Sweep(); + var delay = oldestSurviving is DateTime oldest + ? oldest + MaxAge + AutomaticSweepMargin - DateTime.UtcNow + : AutomaticSweepMargin; + if (delay < TimeSpan.Zero) + delay = TimeSpan.Zero; + else if (delay > MaxAutomaticSweepDelay) + delay = MaxAutomaticSweepDelay; + lock (sessionsLock) + sweepTimer?.Change(delay, Timeout.InfiniteTimeSpan); + } + + public override void Dispose() + { + StopAutomaticSweep(); + base.Dispose(); + GC.SuppressFinalize(this); + } } -} \ No newline at end of file +} diff --git a/MaxLib.WebServer/Sessions/Session.cs b/MaxLib.WebServer/Sessions/Session.cs index a8bc7da..a87bfc2 100644 --- a/MaxLib.WebServer/Sessions/Session.cs +++ b/MaxLib.WebServer/Sessions/Session.cs @@ -1,5 +1,6 @@ using System; using System.Collections; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -11,31 +12,40 @@ public class Session : IDictionary { public DateTime LastUsed { get; set; } = DateTime.UtcNow; - public object this[string key] - { - get => Data[key]; - set => Data[key] = value; + /// + /// The key this session is currently stored under. Maintained by the session service; do not set it directly. + /// + public string Key { get; internal set; } = ""; + + public object this[string key] + { + get => Data[key]; + set => Data[key] = value; } - public Dictionary Data { get; protected set; } - = new Dictionary(); + /// + /// The session's data. Thread-safe, so concurrent requests sharing a session id can use it at the same time. + /// Use the atomic methods for read-modify-write sequences. + /// + public ConcurrentDictionary Data { get; protected set; } + = new ConcurrentDictionary(); - public ICollection Keys + public ICollection Keys => Data.Keys; - public ICollection Values + public ICollection Values => Data.Values; - public int Count + public int Count => Data.Count; bool ICollection>.IsReadOnly => false; public void Add(string key, object value) - => Data.Add(key, value); + => ((IDictionary)Data).Add(key, value); void ICollection>.Add(KeyValuePair item) - => Data.Add(item.Key, item.Value); + => ((IDictionary)Data).Add(item.Key, item.Value); public void Clear() => Data.Clear(); @@ -57,7 +67,7 @@ public IEnumerator> GetEnumerator() => Data.GetEnumerator(); public bool Remove(string key) - => Data.Remove(key); + => Data.TryRemove(key, out _); bool ICollection>.Remove(KeyValuePair item) { @@ -74,7 +84,7 @@ bool IDictionary.TryGetValue(string key, out object value) IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - + public bool TryGetValue(string key, [MaybeNullWhen(false)] out T value) { if (TryGetValue(key, out object? rawValue) && rawValue is T realValue) @@ -96,4 +106,4 @@ public T Get(string key) else throw new KeyNotFoundException($"value from {key} cannot be transformed to {typeof(T)}"); } } -} \ No newline at end of file +} diff --git a/MaxLib.WebServer/Sessions/SessionServiceBase.cs b/MaxLib.WebServer/Sessions/SessionServiceBase.cs index 7dc01cd..d8fe288 100644 --- a/MaxLib.WebServer/Sessions/SessionServiceBase.cs +++ b/MaxLib.WebServer/Sessions/SessionServiceBase.cs @@ -1,16 +1,51 @@ using System; +using System.Net.Security; +using System.Security.Cryptography; using System.Threading.Tasks; #nullable enable namespace MaxLib.WebServer.Sessions { + /// + /// Controls the HttpOnly/Secure/SameSite attributes + /// issues its session cookie with. + /// + public enum CookieSecurityMode + { + /// + /// Detect per request whether the connection is encrypted ( is an ) and use + /// rules over it, rules otherwise. This is + /// only accurate if this server terminates TLS itself (SecureWebServer/ + /// DualSecureWebServer) - if a reverse proxy in front of it does instead, every + /// connection this library ever sees is plain HTTP, and should be + /// set explicitly. + /// + Auto, + /// + /// Always issue the session cookie with HttpOnly, Secure, and + /// SameSite=Strict, regardless of what this server itself observes. Use this if a + /// reverse proxy (e.g. nginx) terminates TLS in front of it, since + /// would otherwise never detect an HTTPS connection. + /// + Strict, + /// + /// Always issue the session cookie with just HttpOnly and + /// SameSite=Lax - no Secure flag, so it also works over plain HTTP. + /// + Lax, + } + + /// + /// Register at most one SessionServiceBase per server; every instance uses the "Session" cookie. + /// public abstract class SessionServiceBase : WebService { - public SessionServiceBase() + public SessionServiceBase() : base(ServerStage.ParseRequest) { - // HttpHeaderPostParser has a default priority of VeryHigh. This needs to be executed + // HttpHeaderPostParser has a default priority of VeryHigh. This needs to be executed // right after it but before others. Priority = (WebServicePriority)( ((int)WebServicePriority.VeryHigh + (int)WebServicePriority.High) / 2 @@ -20,34 +55,86 @@ public SessionServiceBase() public override bool CanWorkWith(WebProgressTask task) => true; - Random random = new Random(); - public string CookiePath { get; set; } = "/"; public TimeSpan MaxAge { get; set; } = TimeSpan.FromDays(30); + /// + /// Controls the security attributes of the issued session cookie. Defaults to + /// , which is only accurate if this server + /// terminates TLS itself; set if a reverse + /// proxy does that instead. See the "Sessions" section in README.md. + /// + public CookieSecurityMode CookieSecurity { get; set; } = CookieSecurityMode.Auto; + public override async Task ProgressTask(WebProgressTask task) { _ = task ?? throw new ArgumentNullException(nameof(task)); var cookie = task.Request?.Cookie.Get("Session"); - string key; - if (cookie == null) + var key = cookie?.ValueString; + if (key != null && await IsKeyAvailable(key).ConfigureAwait(false)) + // a client-supplied id that was never issued by this server must not be + // adopted, or any attacker could fix a victim's session id in advance + key = null; + if (key == null) { key = await GenerateSessionKey().ConfigureAwait(false); - task.Request?.Cookie.AddedCookies.Add("Session", - new HttpCookie.Cookie( - "Session", - key, - DateTime.UtcNow + MaxAge, - (int)MaxAge.TotalSeconds, - CookiePath - )); - } - else - { - key = cookie.Value.ValueString; + SetSessionCookie(task, key); } task.Session = await Get(key).ConfigureAwait(false); + task.Session.Key = key; + } + + /// + /// Issues a brand-new session id, migrates the current session's data to it, and + /// updates the "Session" cookie accordingly. Call this after any change in + /// privilege (most importantly right after a successful login), so that a session + /// id an attacker may have set on the client beforehand becomes worthless + /// afterwards. The old id is removed from storage once the new one is in place. + /// + /// the current progress task + /// the new session, already stored as task.Session + /// + /// RotateSessionKey copies the data into a new session, so writes made concurrently through the + /// old Session object by other in-flight requests may be lost. + /// + public async Task RotateSessionKey(WebProgressTask task) + { + ArgumentNullException.ThrowIfNull(task); + var oldKey = task.Session?.Key; + var newKey = await GenerateSessionKey().ConfigureAwait(false); + var newSession = await Get(newKey).ConfigureAwait(false); + newSession.Key = newKey; + if (task.Session != null) + foreach (var pair in task.Session) + newSession[pair.Key] = pair.Value; + task.Session = newSession; + SetSessionCookie(task, newKey); + if (!string.IsNullOrEmpty(oldKey)) + await Remove(oldKey).ConfigureAwait(false); + return newSession; + } + + private void SetSessionCookie(WebProgressTask task, string key) + { + _ = task ?? throw new ArgumentNullException(nameof(task)); + var strict = CookieSecurity switch + { + CookieSecurityMode.Strict => true, + CookieSecurityMode.Lax => false, + _ => task.NetworkStream is SslStream, + }; + task.Request.Cookie.AddedCookies["Session"] = + new HttpCookie.Cookie( + "Session", + key, + DateTime.UtcNow + MaxAge, + (int)MaxAge.TotalSeconds, + CookiePath, + httpOnly: true, + secure: strict, + sameSite: strict ? HttpCookie.SameSiteMode.Strict : HttpCookie.SameSiteMode.Lax + ); } /// @@ -58,16 +145,31 @@ public override async Task ProgressTask(WebProgressTask task) /// the session with its data protected abstract ValueTask Get(string key); + /// + /// Checks whether a session key is not yet used by any stored session, i.e. whether + /// it is safe to hand out as a freshly generated id. Also used to reject a + /// client-supplied id that does not correspond to a session this server ever + /// issued (see ). + /// + /// the key to check + /// true if no session is currently stored under this key protected abstract ValueTask IsKeyAvailable(string key); + /// + /// Removes the session stored under , if any. Used by + /// to retire the old session id. + /// + /// the key to remove + protected abstract ValueTask Remove(string key); + protected virtual async ValueTask GenerateSessionKey() { var key = new byte[16]; while (true) { - random.NextBytes(key); + RandomNumberGenerator.Fill(key); var stringKey = Convert.ToBase64String(key); - if (await IsKeyAvailable(stringKey)) + if (await IsKeyAvailable(stringKey).ConfigureAwait(false)) return stringKey; } } diff --git a/MaxLib.WebServer/Testing/TestWebServer.cs b/MaxLib.WebServer/Testing/TestWebServer.cs index e54ce0d..78cd685 100644 --- a/MaxLib.WebServer/Testing/TestWebServer.cs +++ b/MaxLib.WebServer/Testing/TestWebServer.cs @@ -55,6 +55,12 @@ public Task Execute(WebProgressTask task, ServerStage terminationState = ServerS return ExecuteTaskChain(task, terminationState); } + public Task RunProcessTask(WebProgressTask task, HttpConnection connection) + => ProcessTask(task, connection); + + public bool RunTryAdmitConnection(TcpClient client) + => TryAdmitConnection(client); + public new void RemoveConnection(HttpConnection connection) => base.RemoveConnection(connection); diff --git a/MaxLib.WebServer/WebProgressTask.cs b/MaxLib.WebServer/WebProgressTask.cs index 57d7145..205835c 100644 --- a/MaxLib.WebServer/WebProgressTask.cs +++ b/MaxLib.WebServer/WebProgressTask.cs @@ -1,5 +1,4 @@ -using System.Net; -using System; +using System; using System.Threading.Tasks; #nullable enable @@ -39,6 +38,7 @@ public class WebProgressTask : IDisposable public void Dispose() { Document?.Dispose(); + GC.SuppressFinalize(this); } public void EnableMonitoring() @@ -47,15 +47,18 @@ public void EnableMonitoring() Monitor = new Monitoring.Monitor(true); } - internal Func? SwitchProtocolHandler { get; private set; } = null; + internal Func? SwitchProtocolHandler { get; private set; } /// - /// A call to this method notify the web server that this connection will switch protocols - /// after all steps are finished. The web server will remove this connection from its + /// A call to this method notify the web server that this connection will switch protocols + /// after all steps are finished. The web server will remove this connection from its /// watch list and call after its finished. ///
- /// You as the caller are responsible to safely cleanup the connection it is no more - /// used. + /// You as the caller are responsible to safely cleanup the connection once it is no + /// longer used - already does this + /// automatically for its own connections once they close (see its + /// DisposeConnectionsOnClose), but any other protocol switch must handle this + /// itself. ///
/// /// This handler will be called after the server has no more control of this connection. diff --git a/MaxLib.WebServer/WebServerLog.cs b/MaxLib.WebServer/WebServerLog.cs index bbfc7cf..b48f1b1 100644 --- a/MaxLib.WebServer/WebServerLog.cs +++ b/MaxLib.WebServer/WebServerLog.cs @@ -1,5 +1,6 @@ -using System; -using System.Collections.Generic; +using System; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; #nullable enable @@ -7,46 +8,24 @@ namespace MaxLib.WebServer { public static class WebServerLog { - public static List ServerLog { get; } = new List(); - public static List IgnoreSenderEvents { get; } = new List(); + internal static ILoggerFactory LoggerFactory { get; set; } = NullLoggerFactory.Instance; - /// - /// This event fires if some log item should be added. The log item can now filtered and discarded. - /// - public static event ServerLogAddedHandler? LogPreAdded; + static bool factorySet; /// - /// This event fires after a log item is added. + /// Sets the this library uses for all of its internal logging. + /// Must be called before constructing anything else from this library - every class resolves + /// its logger once, at first use. Can only be called once; a second call throws. /// - public static event Action? LogAdded; - - static readonly object lockObject = new object(); - public static void Add(ServerLogItem logItem) - { - if (IgnoreSenderEvents.Exists((type) => type.FullName== logItem.SenderType)) - return; - var eventArgs = new ServerLogArgs(logItem); - LogPreAdded?.Invoke(eventArgs); - if (eventArgs.Discard) - return; - lock (lockObject) - ServerLog.Add(logItem); - LogAdded?.Invoke(logItem); - } - - public static void Add(ServerLogType type, Type sender, string infoType, string information) - { - Add(new ServerLogItem(type, sender, infoType, information)); - } - - public static void Add(ServerLogType type, Type sender, string infoType, string mask, params object?[] data) - { - Add(new ServerLogItem(type, sender, infoType, mask: mask, data: data)); - } - - public static void Clear() + public static void SetLoggerFactory(ILoggerFactory loggerFactory) { - ServerLog.Clear(); + ArgumentNullException.ThrowIfNull(loggerFactory); + if (factorySet) + throw new InvalidOperationException( + "The logger factory has already been set and cannot be changed afterwards." + ); + LoggerFactory = loggerFactory; + factorySet = true; } } } diff --git a/MaxLib.WebServer/WebServerSettings.cs b/MaxLib.WebServer/WebServerSettings.cs index 5ec0d79..b2cf9fd 100644 --- a/MaxLib.WebServer/WebServerSettings.cs +++ b/MaxLib.WebServer/WebServerSettings.cs @@ -43,16 +43,26 @@ public TimeSpan ConnectionDelay } } + /// + /// The maximum number of connections () accepted + /// at once. A new connection beyond this limit is rejected - its socket closed + /// immediately, without being processed at all - rather than left to exhaust + /// thread-pool/memory resources indefinitely (see also + /// and + /// , which bound what a + /// single already-admitted connection can do). Defaults to -1 (no limit). + /// + public int MaxConcurrentConnections { get; set; } = -1; + //Debug - public bool Debug_WriteRequests = false; - public bool Debug_LogConnections = false; + public bool Debug_WriteRequests; + public bool Debug_LogConnections; public WebServerSettings(int port, int connectionTimeout) { if (port <= 0 || port >= 0xffff) throw new ArgumentOutOfRangeException(nameof(port)); - if (connectionTimeout < 0) - throw new ArgumentOutOfRangeException(nameof(connectionTimeout)); + ArgumentOutOfRangeException.ThrowIfNegative(connectionTimeout); Port = port; ConnectionTimeout = connectionTimeout; } diff --git a/MaxLib.WebServer/WebServerTaskCreator.cs b/MaxLib.WebServer/WebServerTaskCreator.cs index b462439..bd3d2a2 100644 --- a/MaxLib.WebServer/WebServerTaskCreator.cs +++ b/MaxLib.WebServer/WebServerTaskCreator.cs @@ -29,6 +29,7 @@ public WebServerTaskCreator() public async Task Start(Server server) { + ArgumentNullException.ThrowIfNull(server); Task.Server = server; await server.ExecuteTaskChain(Task, TerminationStage).ConfigureAwait(false); Task.Server = null; @@ -48,14 +49,16 @@ public void SetHeaderParameter(string key, string value) else Task.Request.HeaderParameter.Add(key, value); } +#pragma warning disable CA2000 // ownership transfers via SetPost into HttpPost.Content, disposed by HttpPost.Dispose() public void SetPost(WebProgressTask task, ReadOnlyMemory post, string mime) { Task.Request.Post.SetPost( task, - new IO.ContentStream(new IO.NetworkReader(new IO.SpanStream(post)), post.Length), + new IO.ContentStream(new IO.NetworkReader(new IO.SpanStream(post)), post.Length), mime ); } +#pragma warning restore CA2000 public void SetAccept(string[]? acceptTypes = null, string[]? encoding = null) { @@ -93,6 +96,8 @@ public class BidirectionalStream : Stream public BidirectionalStream(Stream input, Stream output) { + ArgumentNullException.ThrowIfNull(input); + ArgumentNullException.ThrowIfNull(output); if (!input.CanRead) throw new ArgumentException("input is not readable"); if (!output.CanWrite) throw new ArgumentException("output is not writeable"); Input = input; diff --git a/MaxLib.WebServer/WebServerUtils.cs b/MaxLib.WebServer/WebServerUtils.cs index c7e1560..10aca28 100644 --- a/MaxLib.WebServer/WebServerUtils.cs +++ b/MaxLib.WebServer/WebServerUtils.cs @@ -14,30 +14,81 @@ public static string EncodeUri(string uri) public static string DecodeUri(string uri) => WebUtility.UrlDecode(uri); - public static string GetVolumeString(long byteCount, bool shortVersion, int digits) + /// + /// Removes every \r/\n from . Use this at a sink + /// that writes raw HTTP header names/values (or any other single-line wire text) built + /// from untrusted or application-supplied text, to prevent CRLF/header injection - + /// unlike , this leaves every other character (including + /// /) untouched, since header text generally isn't otherwise URI-encoded. + /// + public static string RemoveCrLf(string value) { - if (byteCount < 0) - throw new ArgumentOutOfRangeException(nameof(byteCount)); - var sn = new[] { "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" }; - var ln = new[] { "Byte", "Kilobyte", "Megabyte", "Gigabyte", "Terabyte", "Petabyte", "Exabyte", "Zettabyte", "Yottabyte" }; - var names = shortVersion ? sn : ln; + ArgumentNullException.ThrowIfNull(value); + return value.IndexOfAny(['\r', '\n']) == -1 + ? value + : value.Replace("\r", "", StringComparison.Ordinal) + .Replace("\n", "", StringComparison.Ordinal); + } + + private static readonly ReadOnlyMemory iecSn = new[] { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB", "RiB", "QiB" }; + private static readonly ReadOnlyMemory iecLn = new[] { "Byte", "Kibibyte", "Mebibyte", "Gibibyte", "Tebibyte", "Pebibyte", "Exbibyte", "Zebibyte", "Yobibyte", "Robibyte", "Quebibyte" }; + private static readonly ReadOnlyMemory siSn = new[] { "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB", "RB", "QB" }; + private static readonly ReadOnlyMemory siLn = new[] { "Byte", "Kilobyte", "Megabyte", "Gigabyte", "Terabyte", "Petabyte", "Exabyte", "Zettabyte", "Yottabyte", "Ronnabyte", "Quettabyte" }; + + /// + /// Formats a byte count into a human-readable string with the specified unit prefix system. + /// + /// The byte count to format. A byte count (e.g. + /// from ) can no longer reach the largest supported + /// prefixes (Ronna-/Quetta-), so this accepts a instead, which can. + /// If true, uses short unit names (e.g., "KB", "MB"), otherwise + /// uses long unit names (e.g., "Kilobyte", "Megabyte"). + /// The number of significant digits to include in the formatted + /// string. Using a value of 15 or larger is unreliable due to precision + /// limitations. + /// The unit prefix system to use (IEC or SI). + /// A human-readable string representing the byte count with the specified unit + /// prefix. + /// Thrown if is + /// negative or not finite + /// + /// The method calculates the appropriate unit prefix based on the byte count and formats + /// the number accordingly. It supports both binary (IEC) and decimal (SI) unit systems, + /// allowing for flexible representation of data sizes.
+ /// + /// Since a only has about 15-17 significant decimal digits of + /// precision, very large or very precise values may lose precision. However, it is + /// sufficient for most practical use cases. + ///
+ public static string GetVolumeString(double byteCount, bool shortVersion, int digits, + PrefixKind kind = PrefixKind.IEC) + { + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); + if(!double.IsFinite(byteCount)) + throw new ArgumentOutOfRangeException(nameof(byteCount), "Byte count must be a finite number."); + var names = kind == PrefixKind.SI + ? (shortVersion ? siSn.Span : siLn.Span) + : (shortVersion ? iecSn.Span : iecLn.Span); + var divisor = kind == PrefixKind.SI ? 1000 : 1024; + // select the appropriate unit prefix based on the byte count var step = 0; - var bc = (double)byteCount; - while (bc >= 1024) + while (byteCount >= divisor && step < names.Length - 1) { step++; - bc /= 1024; + byteCount /= divisor; } - if (step >= names.Length) - throw new ArgumentOutOfRangeException(nameof(byteCount)); - var vkd = bc >= 1000 ? 4 - : bc >= 100 ? 3 - : bc >= 10 ? 2 - : 1; - digits = Math.Max(Math.Min(digits, vkd + 3 * step), vkd); - var mask = vkd == 4 ? "0,000" : new string('0', vkd); - if (digits > vkd) mask += "." + new string('#', digits - vkd); - return $"{bc.ToString(mask)} {names[step]}"; + // count the leading (integer-part) digits of byteCount, e.g. 3 for 123.45 + var leadingDigits = 1; + for (var remaining = byteCount; remaining >= 10; remaining /= 10) + leadingDigits++; + // clamp digits to a reasonable range based on leading digits + digits = Math.Clamp(digits, leadingDigits, leadingDigits + 3 * step); + // generate format mask for the number of digits requested + var mask = "#,#0"; + if (digits > leadingDigits) // update mask to include decimal places if needed + mask += "." + new string('#', digits - leadingDigits); + // return formatted string with the appropriate unit prefix + return $"{byteCount.ToString(mask, CultureInfo.InvariantCulture)} {names[step]}"; } public static string GetDateString(DateTime date) @@ -48,20 +99,40 @@ public static DateTime GetDateFromString(string date) CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.AssumeUniversal | DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.RoundtripKind, out DateTime dateTime) - ? dateTime + ? dateTime : new DateTime(); - + + /// + /// Compares two byte sequences for equality. This short-circuits on the first + /// mismatching byte, so the time it takes can reveal how many leading bytes matched - + /// safe for ordinary content comparison, but not for comparing a secret, token, or + /// HMAC/signature value. Use for that instead. + /// public static bool BytesEqual(byte[] ba1, byte[] ba2) { _ = ba1 ?? throw new ArgumentNullException(nameof(ba1)); _ = ba2 ?? throw new ArgumentNullException(nameof(ba2)); - if (ba1.Length != ba2.Length) + if (ba1.Length != ba2.Length) return false; - for (int i = 0; i < ba1.Length; ++i) - if (ba1[i] != ba2[i]) + for (int i = 0; i < ba1.Length; ++i) + if (ba1[i] != ba2[i]) return false; return true; } + + /// + /// Compares two byte sequences for equality in constant time with respect to their + /// content, so the comparison itself cannot leak which byte (if any) first differed via + /// a timing side channel. Use this instead of whenever one of + /// the values is a secret, token, or HMAC/signature - e.g. checking a client-supplied + /// value against an expected one. + /// + public static bool BytesEqualConstantTime(byte[] ba1, byte[] ba2) + { + _ = ba1 ?? throw new ArgumentNullException(nameof(ba1)); + _ = ba2 ?? throw new ArgumentNullException(nameof(ba2)); + return System.Security.Cryptography.CryptographicOperations.FixedTimeEquals(ba1, ba2); + } } } diff --git a/MaxLib.WebServer/WebService.cs b/MaxLib.WebServer/WebService.cs index 96e0c32..d79b274 100644 --- a/MaxLib.WebServer/WebService.cs +++ b/MaxLib.WebServer/WebService.cs @@ -20,6 +20,7 @@ public WebService(ServerStage stage) public virtual void Dispose() { + GC.SuppressFinalize(this); } public event EventHandler? PriorityChanged; diff --git a/MaxLib.WebServer/WebService2.cs b/MaxLib.WebServer/WebService2.cs index f344873..46fb079 100644 --- a/MaxLib.WebServer/WebService2.cs +++ b/MaxLib.WebServer/WebService2.cs @@ -1,4 +1,5 @@ -using System.Threading.Tasks; +using System; +using System.Threading.Tasks; #nullable enable @@ -17,6 +18,7 @@ public WebService2(ServerStage stage) public override Task ProgressTask(WebProgressTask task) { + ArgumentNullException.ThrowIfNull(task); if (!task.Document.Information.TryGetValue(this, out object? data)) data = null; return ProgressTask(task, data); @@ -24,6 +26,7 @@ public override Task ProgressTask(WebProgressTask task) public override bool CanWorkWith(WebProgressTask task) { + ArgumentNullException.ThrowIfNull(task); if (!CanWorkWith(task, out object? data)) return false; task.Document[this] = data; diff --git a/MaxLib.WebServer/WebServiceCollection.cs b/MaxLib.WebServer/WebServiceCollection.cs index 276ef81..536d2f1 100644 --- a/MaxLib.WebServer/WebServiceCollection.cs +++ b/MaxLib.WebServer/WebServiceCollection.cs @@ -12,6 +12,11 @@ namespace MaxLib.WebServer /// them. Therefore this service collection is not suitable if you want to use multiple services /// in the same stage. ///
+ /// + /// Do not add or remove services while the collection is dispatching a request, including from + /// a contained service's CanWorkWith; the collection is not safe for concurrent + /// modification. + /// public class WebServiceCollection : WebService2, ICollection { @@ -71,6 +76,7 @@ public Task ProgressTask(WebProgressTask task) public override void Dispose() { base.Dispose(); + GC.SuppressFinalize(this); foreach (var service in Services) service.Dispose(); } @@ -81,6 +87,7 @@ public override void Dispose() public override Task ProgressTask(WebProgressTask task, CallInfo? data) { + ArgumentNullException.ThrowIfNull(task); if (data is null) return Task.CompletedTask; using (task.Monitor.Watch(data.Service, "ProgressTask()")) @@ -100,6 +107,7 @@ public virtual bool CheckPrecondition(WebProgressTask task) public override bool CanWorkWith(WebProgressTask task, out CallInfo? data) { + ArgumentNullException.ThrowIfNull(task); if (!CheckPrecondition(task)) { data = null; @@ -130,8 +138,15 @@ public override bool CanWorkWith(WebProgressTask task, out CallInfo? data) return false; } + /// + /// Do not add a collection to itself or to one of its descendants; the resulting cycle recurses + /// without bound on dispatch. + /// Adding the same service instance more than once registers it once per call, so it runs + /// once per registration, and each call removes only one registration. + /// public void Add(WebService item) { + ArgumentNullException.ThrowIfNull(item); if (item.Stage != Stage) throw new ArgumentException("invalid stage", nameof(item)); item.PriorityChanged += Service_PriorityChanged; @@ -163,6 +178,7 @@ public void CopyTo(WebService[] array, int arrayIndex) public bool Remove(WebService item) { + ArgumentNullException.ThrowIfNull(item); if (Services.Remove(item)) { item.PriorityChanged -= Service_PriorityChanged; diff --git a/MaxLib.WebServer/WebServiceGroup.cs b/MaxLib.WebServer/WebServiceGroup.cs index ac60e6d..5443e66 100644 --- a/MaxLib.WebServer/WebServiceGroup.cs +++ b/MaxLib.WebServer/WebServiceGroup.cs @@ -40,6 +40,12 @@ public virtual bool SingleExecution protected PriorityList Services { get; private set; } + /// + /// The service runs in this group's stage whatever its own Stage says; use + /// Server.AddWebService to register it in the stage it declares. + /// Adding the same service instance more than once registers it once per call, so it runs + /// once per registration, and each call removes only one registration. + /// public void Add(WebService service) { _ = service ?? throw new ArgumentNullException(nameof(service)); @@ -55,6 +61,7 @@ private void Service_PriorityChanged(object? sender, EventArgs e) public bool Remove(WebService service) { + ArgumentNullException.ThrowIfNull(service); if (Services.Remove(service)) { service.PriorityChanged -= Service_PriorityChanged; @@ -83,8 +90,20 @@ public IEnumerable GetAll() where T : WebService return Services.Where(x => x is T).Cast(); } + /// + /// Applies an caught from a service (either from its + /// CanWorkWith or its ProgressTask) to 's response. + /// + private static void ApplyHttpException(WebProgressTask task, HttpException e) + { + task.Response.StatusCode = e.StateCode; + if (e.DataSource != null) + task.Document.DataSources.Add(e.DataSource); + } + public virtual async Task Execute(WebProgressTask task) { + ArgumentNullException.ThrowIfNull(task); var se = SingleExecution; var set = false; var services = Services.ToArray(); @@ -94,63 +113,96 @@ public virtual async Task Execute(WebProgressTask task) if (service is WebService2 service2) { var watch = task.Monitor.Watch(service, "CanWorkWith()"); - if (service2.CanWorkWith(task, out object? data)) + bool matched; + object? data = null; + HttpException? bindingFailure = null; + try + { + matched = service2.CanWorkWith(task, out data); + } + catch (HttpException e) + { + matched = true; + bindingFailure = e; + } + finally { watch.Dispose(); + } + if (matched) + { if (task.Connection?.NetworkClient != null && !task.Connection.NetworkClient.Connected) return; - try + if (bindingFailure == null) { - watch = task.Monitor.Watch(service, "ProgressTask()"); - await service2.ProgressTask(task, data).ConfigureAwait(false); - } - catch (HttpException e) - { - task.Response.StatusCode = e.StateCode; - if (e.DataSource != null) - task.Document.DataSources.Add(e.DataSource); - } - finally - { - watch.Dispose(); + try + { + watch = task.Monitor.Watch(service, "ProgressTask()"); + await service2.ProgressTask(task, data).ConfigureAwait(false); + } + catch (HttpException e) + { + bindingFailure = e; + } + finally + { + watch.Dispose(); + } } + if (bindingFailure != null) + ApplyHttpException(task, bindingFailure); task.Document[Stage] = true; - if (se) + if (se) return; set = true; } - else watch.Dispose(); } - else + else { var watch = task.Monitor.Watch(service, "CanWorkWith()"); - if (service.CanWorkWith(task)) + bool matched; + HttpException? bindingFailure = null; + try + { + matched = service.CanWorkWith(task); + } + catch (HttpException e) + { + matched = true; + bindingFailure = e; + } + finally { watch.Dispose(); + } + if (matched) + { if (task.Connection?.NetworkClient != null && !task.Connection.NetworkClient.Connected) return; - try - { - watch = task.Monitor.Watch(service, "ProgressTask()"); - await service.ProgressTask(task).ConfigureAwait(false); - } - catch (HttpException e) - { - task.Response.StatusCode = e.StateCode; - if (e.DataSource != null) - task.Document.DataSources.Add(e.DataSource); - } - finally + if (bindingFailure == null) { - watch.Dispose(); + try + { + watch = task.Monitor.Watch(service, "ProgressTask()"); + await service.ProgressTask(task).ConfigureAwait(false); + } + catch (HttpException e) + { + bindingFailure = e; + } + finally + { + watch.Dispose(); + } } + if (bindingFailure != null) + ApplyHttpException(task, bindingFailure); task.Document[Stage] = true; - if (se) + if (se) return; set = true; } - else watch.Dispose(); } } - if (!set) + if (!set) task.Document[Stage] = false; } @@ -158,6 +210,7 @@ public void Dispose() { foreach (var service in Services) service.Dispose(); + GC.SuppressFinalize(this); } } } diff --git a/MaxLib.WebServer/WebSocket/EventBase.cs b/MaxLib.WebServer/WebSocket/EventBase.cs index 66dacde..93dd44e 100644 --- a/MaxLib.WebServer/WebSocket/EventBase.cs +++ b/MaxLib.WebServer/WebSocket/EventBase.cs @@ -1,92 +1,24 @@ -using System; -using System.Text.Json; -using System.Text.Json.Serialization; +using System.Text.Json.Serialization; #nullable enable namespace MaxLib.WebServer.WebSocket { /// - /// The base class for all events that can be sent or received from a WebSocket + /// The base class for all events that can be sent or received from a WebSocket. Subclasses + /// are plain classes with public properties, serialized and deserialized by + /// via the polymorphic type resolution built + /// by the owning — see + /// and . /// public abstract class EventBase { /// - /// The name of the event to identify + /// The default "$type" key used by . Only consulted + /// at registration time — once registered, the wire discriminator is whatever key was + /// passed to Add, independent of this property. /// [JsonIgnore] public virtual string TypeName => GetType().Name; - - /// - /// Tells if a new instance is generated during the - /// deserialization of the json data. If this property is false the current instance can be - /// updated. - /// - [JsonIgnore] - protected internal virtual bool DeserializeNew => false; - - /// - /// Write the content as a JSON to - /// - /// the to write into - public virtual void WriteJson(Utf8JsonWriter writer) - { - _ = writer ?? throw new ArgumentNullException(nameof(writer)); - writer.WriteStartObject(); - writer.WriteString("$type", TypeName); - WriteJsonContent(writer); - writer.WriteEndObject(); - } - - /// - /// Write the value content of this event into the - /// - /// the to write into - protected abstract void WriteJsonContent(Utf8JsonWriter writer); - - /// - /// Reads the value content from JSON and returns the object with updated information. If - /// is false this will return the current object. - /// - /// the to read from - /// the updated object - public virtual EventBase? ReadJson(JsonElement json) - { - try { ReadJsonContent(json); } - catch (JsonException e) - { - WebServerLog.Add(ServerLogType.Error, GetType(), "read json", "error: {0}", e); - return null; - } - return this; - } - - /// - /// Read the value content from JSON - /// - /// the to read from - public abstract void ReadJsonContent(JsonElement json); - - public virtual Frame? ToFrame() - { - using var m = new System.IO.MemoryStream(); - using var writer = new Utf8JsonWriter(m); - try { WriteJson(writer); } - catch (JsonException e) - { - WebServerLog.Add(ServerLogType.Error, GetType(), "write json", "error: {0}", e); - return null; - } - writer.Flush(); - - var frame = new Frame - { - OpCode = OpCode.Text, - Payload = m.ToArray(), - FinalFrame = true, - }; - - return frame; - } } } diff --git a/MaxLib.WebServer/WebSocket/EventConnection.cs b/MaxLib.WebServer/WebSocket/EventConnection.cs index de5c373..8e09271 100644 --- a/MaxLib.WebServer/WebSocket/EventConnection.cs +++ b/MaxLib.WebServer/WebSocket/EventConnection.cs @@ -1,5 +1,7 @@ -using System.IO; +using System; +using System.IO; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; #nullable enable @@ -7,25 +9,97 @@ namespace MaxLib.WebServer.WebSocket { public abstract class EventConnection : WebSocketConnection { + static readonly EventId EventParseErrorId = new(0, "event parse error"); + public EventFactory EventFactory { get; } - protected EventConnection(Stream networkStream, EventFactory factory) + protected EventConnection(Stream networkStream, EventFactory factory) : base(networkStream) { - EventFactory = factory; + EventFactory = factory ?? throw new ArgumentNullException(nameof(factory)); } protected override async Task ReceivedFrame(Frame frame) { - if (EventFactory.TryParse(frame, out EventBase? @event)) + EventBase? @event; + try + { + @event = EventFactory.Parse(frame); + } + catch (MalformedEventJsonException e) + { + await ReceivedMalformedEvent(frame, e).ConfigureAwait(false); + return; + } + catch (UnknownEventTypeException e) + { + await ReceivedUnknownEvent(frame, e).ConfigureAwait(false); + return; + } + catch (InvalidEventPayloadException e) + { + await ReceivedInvalidEventPayload(frame, e).ConfigureAwait(false); + return; + } + if (@event != null) await ReceivedFrame(@event).ConfigureAwait(false); } + /// + /// Overrides must not throw; an escaping exception leaves the ping loop running, so Closed never fires and the connection is never cleaned up. + /// protected abstract Task ReceivedFrame(EventBase @event); + /// + /// Called when an incoming frame's payload was not syntactically valid JSON. The default + /// implementation only logs the error; override to e.g. send an error event back to the + /// client or close the connection. + /// + protected virtual Task ReceivedMalformedEvent(Frame frame, MalformedEventJsonException exception) + { + _ = frame ?? throw new ArgumentNullException(nameof(frame)); + _ = exception ?? throw new ArgumentNullException(nameof(exception)); + WebServerLog.LoggerFactory.CreateLogger(GetType()) + .LogError(EventParseErrorId, exception, "Received a WebSocket frame with malformed JSON"); + return Task.CompletedTask; + } + + /// + /// Called when an incoming frame's "$type" discriminator is missing or does not match any + /// event type registered on . The default implementation only + /// logs the error; override to e.g. send an error event back to the client or close the + /// connection. + /// + protected virtual Task ReceivedUnknownEvent(Frame frame, UnknownEventTypeException exception) + { + _ = frame ?? throw new ArgumentNullException(nameof(frame)); + _ = exception ?? throw new ArgumentNullException(nameof(exception)); + WebServerLog.LoggerFactory.CreateLogger(GetType()) + .LogError(EventParseErrorId, exception, "Received a WebSocket frame for an unknown event type {EventTypeName}", + exception.EventTypeName); + return Task.CompletedTask; + } + + /// + /// Called when an incoming frame named a registered event type via its "$type" + /// discriminator, but its payload could not be mapped onto that type. The default + /// implementation only logs the error; override to e.g. send an error event back to the + /// client or close the connection. + /// + protected virtual Task ReceivedInvalidEventPayload(Frame frame, InvalidEventPayloadException exception) + { + _ = frame ?? throw new ArgumentNullException(nameof(frame)); + _ = exception ?? throw new ArgumentNullException(nameof(exception)); + WebServerLog.LoggerFactory.CreateLogger(GetType()) + .LogError(EventParseErrorId, exception, "Received an invalid payload for event type {EventTypeName}", + exception.EventTypeName); + return Task.CompletedTask; + } + protected virtual async Task SendFrame(EventBase @event) { - var frame = @event.ToFrame(); + ArgumentNullException.ThrowIfNull(@event); + var frame = EventFactory.ToFrame(@event); if (frame != null) await SendFrame(frame).ConfigureAwait(false); } diff --git a/MaxLib.WebServer/WebSocket/EventFactory.cs b/MaxLib.WebServer/WebSocket/EventFactory.cs index c52340e..4bf1459 100644 --- a/MaxLib.WebServer/WebSocket/EventFactory.cs +++ b/MaxLib.WebServer/WebSocket/EventFactory.cs @@ -1,48 +1,221 @@ using System; +using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; using System.Text.Json; +using System.Text.Json.Serialization; +using System.Text.Json.Serialization.Metadata; #nullable enable namespace MaxLib.WebServer.WebSocket { + /// + /// A registry of subclasses, keyed by their wire "$type" value, that + /// builds a using native + /// polymorphic serialization to (de)serialize payloads. Register every + /// event type via / before the first + /// call to / — the registry is + /// sealed on first use and further registrations throw. + /// public class EventFactory { - readonly Dictionary> registry - = new Dictionary>(); + static readonly ILogger logger = WebServerLog.LoggerFactory.CreateLogger(); + static readonly EventId WriteJsonEventId = new(0, "write json"); + readonly Dictionary registry = []; + readonly object sealLock = new(); + readonly JsonSerializerOptions? seedOptions; + JsonSerializerOptions? sealedOptions; + + public EventFactory() + : this(null) + { + } + + /// + /// A template to copy settings from (naming policy, + /// custom converters, etc.) before this factory layers its own polymorphic type + /// resolution on top. The instance you pass is never mutated or reused directly — its + /// settings are copied. + /// + public EventFactory(JsonSerializerOptions? seedOptions) + { + this.seedOptions = seedOptions; + } + + /// + /// Each event type may be registered under only one key; registering it twice makes the first + /// serialize/parse throw InvalidOperationException. + /// public void Add() where T : EventBase, new() => Add(new T().TypeName); + /// + /// Each event type may be registered under only one key; registering it twice makes the first + /// serialize/parse throw InvalidOperationException. + /// public void Add(string key) where T : EventBase, new() - => registry.Add(key ?? throw new ArgumentNullException(nameof(key)), () => new T()); + => AddCore(key, typeof(T)); + /// + /// Each event type may be registered under only one key; registering it twice makes the first + /// serialize/parse throw InvalidOperationException. + /// public void Add(string key, Type type) { - _ = key ?? throw new ArgumentNullException(nameof(key)); _ = type ?? throw new ArgumentNullException(nameof(type)); if (!type.IsSubclassOf(typeof(EventBase))) throw new ArgumentException("invalid type", nameof(type)); - var constructor = type.GetConstructor(Type.EmptyTypes); - if (constructor == null) + if (type.GetConstructor(Type.EmptyTypes) == null) throw new ArgumentException("type has no parameterless constructor", nameof(type)); - registry.Add(key, () => (EventBase)constructor.Invoke(Array.Empty())); + AddCore(key, type); + } + + void AddCore(string key, Type type) + { + _ = key ?? throw new ArgumentNullException(nameof(key)); + lock (sealLock) + { + if (sealedOptions != null) + throw new InvalidOperationException( + "This EventFactory has already been used to serialize or deserialize " + + "an event; its type registry is sealed. Register all event types before " + + $"first use. (Attempted to add '{key}' -> {type}.)"); + registry.Add(key, type); + } } + /// + /// The used for all serialization and + /// deserialization operations of this factory. Lazily built (and sealed) on first + /// access. + /// + public JsonSerializerOptions Options + { + get + { + if (sealedOptions != null) + return sealedOptions; + lock (sealLock) + { + return sealedOptions ??= BuildOptions(); + } + } + } + + JsonSerializerOptions BuildOptions() + { + var snapshot = registry.ToArray(); + // Copy (never reuse-in-place) the seed so the caller's own options object is + // untouched and can still be used/locked elsewhere. + var options = seedOptions != null + ? new JsonSerializerOptions(seedOptions) + : new JsonSerializerOptions(); + IJsonTypeInfoResolver baseResolver = options.TypeInfoResolver + ?? new DefaultJsonTypeInfoResolver(); + options.TypeInfoResolver = baseResolver.WithAddedModifier(typeInfo => + { + if (typeInfo.Type != typeof(EventBase)) + return; + var poly = new JsonPolymorphismOptions + { + TypeDiscriminatorPropertyName = "$type", + UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FailSerialization, + }; + foreach (var (key, type) in snapshot) + poly.DerivedTypes.Add(new JsonDerivedType(type, key)); + typeInfo.PolymorphismOptions = poly; + }); + return options; + } + + /// + /// Parses a payload into the its "$type" + /// discriminator names. + /// + /// + /// The payload is not syntactically valid JSON. + /// + /// + /// The payload's "$type" discriminator is missing or does not match any event type + /// registered via /. + /// + /// + /// The "$type" discriminator names a registered event type, but the payload could not be + /// mapped onto it. + /// public EventBase? Parse(Frame frame) { _ = frame ?? throw new ArgumentNullException(nameof(frame)); - var doc = JsonDocument.Parse(frame.Payload); - var key = doc.RootElement.GetProperty("$type").GetString(); - if (key == null || !registry.TryGetValue(key, out Func? caller)) - throw new KeyNotFoundException($"type {{{key}}} not registered"); - var @event = caller(); - return @event.ReadJson(doc.RootElement); + // Accessing Options seals the type registry; do this on every call, even for a frame that fails to parse. + var options = Options; + + // System.Text.Json's polymorphic deserialization needs "$type" to be the first property, but JSON is + // unordered. Resolve "$type" with an order-independent JsonDocument pre-scan and deserialize onto the + // concrete type instead. + JsonDocument doc; + try + { + // mirror the caller's JsonSerializerOptions leniency; JsonDocumentOptions has its own defaults + var docOptions = new JsonDocumentOptions + { + AllowTrailingCommas = options.AllowTrailingCommas, + CommentHandling = options.ReadCommentHandling, + MaxDepth = options.MaxDepth, +#if NET10_0_OR_GREATER + // only exists on net10.0; JsonSerializerOptions has no such member on net8.0 + AllowDuplicateProperties = options.AllowDuplicateProperties, +#endif + }; + doc = JsonDocument.Parse(frame.Payload, docOptions); + } + catch (JsonException e) + { + throw new MalformedEventJsonException(e); + } + + using (doc) + { + // a literal JSON "null" payload yields a null EventBase, regardless of "$type" resolution + if (doc.RootElement.ValueKind == JsonValueKind.Null) + return null; + + var typeName = doc.RootElement.ValueKind == JsonValueKind.Object && + doc.RootElement.TryGetProperty("$type", out var typeProp) && + typeProp.ValueKind == JsonValueKind.String + ? typeProp.GetString() + : null; + + if (typeName == null || !registry.TryGetValue(typeName, out var resolvedType)) + throw new UnknownEventTypeException(typeName); + + try + { + // "$type" first is the shape the polymorphic reader handles natively, and it + // consumes "$type" as metadata instead of an unmapped member + using var props = doc.RootElement.EnumerateObject(); + if (props.MoveNext() && props.Current.NameEquals("$type")) + return JsonSerializer.Deserialize(frame.Payload.Span, options); + return (EventBase?)JsonSerializer.Deserialize(frame.Payload.Span, resolvedType, options); + } + catch (Exception e) when (e is JsonException or NotSupportedException) + { + throw new InvalidEventPayloadException(typeName, e); + } + } } + /// + /// Like , but reports a parse failure as a + /// return instead of a thrown . Use + /// directly (or override the handlers on ) when the reason for + /// the failure matters. + /// public bool TryParse(Frame frame, [NotNullWhen(true)] out EventBase? @event) { _ = frame ?? throw new ArgumentNullException(nameof(frame)); @@ -51,12 +224,41 @@ public bool TryParse(Frame frame, [NotNullWhen(true)] out EventBase? @event) @event = Parse(frame); return @event != null; } - catch (Exception e) + catch (EventParseException) { - WebServerLog.Add(new ServerLogItem(ServerLogType.Error, GetType(), "parse error", e.ToString())); @event = null; return false; } } + + /// + /// Serializes an event into a using this factory's + /// . + /// + /// + /// Every event type passed to ToFrame must be registered via Add first; an unregistered type + /// throws NotSupportedException. + /// + public Frame? ToFrame(EventBase @event) + { + _ = @event ?? throw new ArgumentNullException(nameof(@event)); + try + { + using var m = new MemoryStream(); + using (var writer = new Utf8JsonWriter(m)) + JsonSerializer.Serialize(writer, @event, typeof(EventBase), Options); + return new Frame + { + OpCode = OpCode.Text, + Payload = m.ToArray(), + FinalFrame = true, + }; + } + catch (JsonException e) + { + logger.LogError(WriteJsonEventId, e, "Error writing JSON content"); + return null; + } + } } } diff --git a/MaxLib.WebServer/WebSocket/EventParseException.cs b/MaxLib.WebServer/WebSocket/EventParseException.cs new file mode 100644 index 0000000..6aa8e9d --- /dev/null +++ b/MaxLib.WebServer/WebSocket/EventParseException.cs @@ -0,0 +1,120 @@ +using System; +using System.Text.Json; + +#nullable enable + +namespace MaxLib.WebServer.WebSocket +{ + /// + /// Base class for the reasons can fail to turn an + /// incoming into an . + /// catches each concrete subclass separately and routes it to a matching overridable handler, + /// so a subclass can react to (and recover from) client-supplied garbage instead of the + /// connection silently dropping the frame. + /// + [Serializable] + public abstract class EventParseException : Exception + { + protected EventParseException() + { + } + + protected EventParseException(string message) + : base(message) + { + } + + protected EventParseException(string message, Exception? innerException) + : base(message, innerException) + { + } + } + + /// + /// The frame payload is not syntactically valid JSON. + /// + [Serializable] + public sealed class MalformedEventJsonException : EventParseException + { + public MalformedEventJsonException() + { + } + + public MalformedEventJsonException(string message) + : base(message) + { + } + + public MalformedEventJsonException(string message, Exception innerException) + : base(message, innerException) + { + } + + public MalformedEventJsonException(JsonException innerException) + : base("The WebSocket frame payload is not valid JSON.", + innerException ?? throw new ArgumentNullException(nameof(innerException))) + { + } + } + + /// + /// The frame payload is valid JSON, but its "$type" discriminator is missing, not a string, + /// or does not match any event type registered on the owning . + /// + [Serializable] + public sealed class UnknownEventTypeException : EventParseException + { + /// + /// The "$type" value found on the wire, or if the payload had no + /// usable "$type" discriminator at all. + /// + public string? EventTypeName { get; } + + public UnknownEventTypeException() + { + } + + public UnknownEventTypeException(string message, Exception innerException) + : base(message, innerException) + { + } + + public UnknownEventTypeException(string? eventTypeName) + : base(eventTypeName == null + ? "The event payload has no '$type' discriminator." + : $"No event type is registered for \"$type\" = \"{eventTypeName}\".") + { + EventTypeName = eventTypeName; + } + } + + /// + /// The frame payload's "$type" discriminator matched a registered event type, but the + /// payload could not be mapped onto that type (e.g. a property has the wrong shape). + /// + [Serializable] + public sealed class InvalidEventPayloadException : EventParseException + { + /// + /// The registered "$type" value the payload named, or if this + /// exception was constructed without one. + /// + public string? EventTypeName { get; } + + public InvalidEventPayloadException() + { + } + + public InvalidEventPayloadException(string message) + : base(message) + { + } + + public InvalidEventPayloadException(string eventTypeName, Exception innerException) + : base($"The event payload for \"$type\" = \"{eventTypeName}\" could not be deserialized.", + innerException ?? throw new ArgumentNullException(nameof(innerException))) + { + EventTypeName = eventTypeName ?? throw new ArgumentNullException(nameof(eventTypeName)); + } + } +} diff --git a/MaxLib.WebServer/WebSocket/Frame.cs b/MaxLib.WebServer/WebSocket/Frame.cs index c6e4f3e..9569c74 100644 --- a/MaxLib.WebServer/WebSocket/Frame.cs +++ b/MaxLib.WebServer/WebSocket/Frame.cs @@ -1,5 +1,7 @@ using System; +using Microsoft.Extensions.Logging; using System.IO; +using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; @@ -9,6 +11,9 @@ namespace MaxLib.WebServer.WebSocket { public class Frame { + static readonly ILogger logger = WebServerLog.LoggerFactory.CreateLogger(); + static readonly EventId WebSocketEventId = new(0, "WebSocket"); + public bool FinalFrame { get; set; } = true; public OpCode OpCode { get; set; } @@ -27,11 +32,12 @@ public string TextPayload public async Task Write(Stream output) { + ArgumentNullException.ThrowIfNull(output); Memory buffer = new byte[8]; buffer.Span[0] = (byte)((byte)OpCode | (FinalFrame ? 0x80 : 0x00)); - buffer.Span[1] = (byte)(Payload.Length < 126 ? Payload.Length : + buffer.Span[1] = (byte)((HasMaskingKey ? 0x80 : 0x00) | (Payload.Length < 126 ? Payload.Length : (Payload.Length <= ushort.MaxValue ? 126 : 127) - ); + )); await output.WriteAsync(buffer[ .. 2]).ConfigureAwait(false); if (Payload.Length >= 126 && Payload.Length <= ushort.MaxValue) { @@ -49,13 +55,26 @@ public async Task Write(Stream output) await output.WriteAsync(Payload).ConfigureAwait(false); } - public static async Task TryRead(Stream input, bool throwLargePayload = false) + /// the stream to read the frame from + /// + /// throw instead of returning null when the declared payload + /// length exceeds or + /// + /// + /// reject the frame before allocating or reading its payload once its declared length exceeds this value; + /// a negative value (the default) only enforces the cap. Pass + /// here too, as unfragmented frames bypass reassembly. + /// + public static async Task TryRead(Stream input, bool throwLargePayload = false, + long maxPayloadSize = -1) { + ArgumentNullException.ThrowIfNull(input); try { + // ReadAsync may return fewer bytes than requested; ReadExactlyAsync loops until the buffer is full + // (or throws EndOfStreamException) Memory buffer = new byte[8]; - if (await input.ReadAsync(buffer[0..2]).ConfigureAwait(false) != 2) - return null; + await input.ReadExactlyAsync(buffer[0..2]).ConfigureAwait(false); var frame = new Frame { FinalFrame = (buffer.Span[0] & 0x80) == 0x80, @@ -66,35 +85,31 @@ public async Task Write(Stream output) ulong length = (ulong)lengthIndicator; if (lengthIndicator == 126) { - if (await input.ReadAsync(buffer[0..2]).ConfigureAwait(false) != 2) - return null; + await input.ReadExactlyAsync(buffer[0..2]).ConfigureAwait(false); ToLocalByteOrder(buffer.Span[..2]); length = BitConverter.ToUInt16(buffer.Span[..2]); } if (lengthIndicator == 127) { - if (await input.ReadAsync(buffer).ConfigureAwait(false) != 8) - return null; + await input.ReadExactlyAsync(buffer).ConfigureAwait(false); ToLocalByteOrder(buffer.Span); length = BitConverter.ToUInt64(buffer.Span); } - if (length > int.MaxValue) + if (length > int.MaxValue || (maxPayloadSize >= 0 && length > (ulong)maxPayloadSize)) { if (throwLargePayload) throw new TooLargePayloadException(); else return null; } - + if (frame.HasMaskingKey) { - if (await input.ReadAsync(buffer[..4]).ConfigureAwait(false) != 4) - return null; + await input.ReadExactlyAsync(buffer[..4]).ConfigureAwait(false); buffer[..4].CopyTo(frame.MaskingKey); } frame.Payload = new byte[(int)length]; - if (await input.ReadAsync(frame.Payload).ConfigureAwait(false) != frame.Payload.Length) - return null; + await input.ReadExactlyAsync(frame.Payload).ConfigureAwait(false); return frame; } @@ -104,7 +119,7 @@ public async Task Write(Stream output) } catch (Exception e) { - WebServerLog.Add(ServerLogType.Information, typeof(Frame), "WebSocket", $"cannot read frame: {e}"); + logger.LogInformation(WebSocketEventId, e, "Cannot read frame"); return null; } } @@ -125,7 +140,7 @@ public static void ToLocalByteOrder(Span buffer) buffer.Reverse(); } - protected void ToBytes(ushort value, Span buffer) + protected static void ToBytes(ushort value, Span buffer) { var result = BitConverter.GetBytes(value); if (result.Length > buffer.Length) @@ -140,6 +155,8 @@ public void ApplyMask() { if (HasMaskingKey) return; + // RFC 6455 §5.3: the masking key must be unpredictable and differ per frame + RandomNumberGenerator.Fill(MaskingKey.Span); var span = Payload.Span; var mask = MaskingKey.Span; for (int i = 0; i < span.Length; ++i) diff --git a/MaxLib.WebServer/WebSocket/SerializedEventBase.cs b/MaxLib.WebServer/WebSocket/SerializedEventBase.cs deleted file mode 100644 index 581046e..0000000 --- a/MaxLib.WebServer/WebSocket/SerializedEventBase.cs +++ /dev/null @@ -1,80 +0,0 @@ -using System; -using System.ComponentModel; -using System.Text.Json; -using System.Text.Json.Serialization; - -#nullable enable - -namespace MaxLib.WebServer.WebSocket -{ - /// - /// The base class for all websocket events that are serialized and deserialized using - /// . - /// - public abstract class SerializedEventBase : EventBase - { - /// - /// The that are used for all serialization and - /// deserialization operations. - /// - public static JsonSerializerOptions JsonSerializerOptions { get; set; } - = new JsonSerializerOptions(); - - /// - /// Tells if a new instance is generated during the - /// deserialization of the json data. If this property is false the current instance can be - /// updated. - [JsonIgnore] - protected internal override bool DeserializeNew => true; - - /// - /// This tells the the type name of this event. Do not use - /// this property in your custom code. Any changes to this are ignored. - /// - [JsonPropertyName("$type")] - [EditorBrowsable(EditorBrowsableState.Never)] - public string JsonTypeName - { - get => TypeName; - set {} - } - - /// - /// Write the content as a JSON to - /// - /// the to write into - public override void WriteJson(Utf8JsonWriter writer) - { - _ = writer ?? throw new ArgumentNullException(nameof(writer)); - JsonSerializer.Serialize(writer, this, JsonSerializerOptions); - } - - /// - /// Not supported - /// - /// - protected override void WriteJsonContent(Utf8JsonWriter writer) - { - throw new NotSupportedException(); - } - - /// - /// Reads the value content from JSON and returns the object with updated information. - /// - /// the to read from - /// the updated object - public override EventBase ReadJson(JsonElement json) - { - return (EventBase)JsonSerializer.Deserialize(json, GetType(), JsonSerializerOptions)!; - } - - /// - /// Not supported - /// - /// - public override void ReadJsonContent(JsonElement json) - { - throw new NotSupportedException(); - } - } -} \ No newline at end of file diff --git a/MaxLib.WebServer/WebSocket/WebSocketCloserEndpoint.cs b/MaxLib.WebServer/WebSocket/WebSocketCloserEndpoint.cs index 351bb94..1ca909a 100644 --- a/MaxLib.WebServer/WebSocket/WebSocketCloserEndpoint.cs +++ b/MaxLib.WebServer/WebSocket/WebSocketCloserEndpoint.cs @@ -1,5 +1,6 @@ #nullable enable +using System; using System.IO; using System.Threading.Tasks; @@ -26,9 +27,10 @@ public WebSocketCloserEndpoint(CloseReason closeReason, string? info) public class WebSocketCloseConnection : WebSocketConnection { - public WebSocketCloseConnection(Stream networkStream, WebSocketCloserEndpoint endpoint) + public WebSocketCloseConnection(Stream networkStream, WebSocketCloserEndpoint endpoint) : base(networkStream) { + ArgumentNullException.ThrowIfNull(endpoint); _ = Close(endpoint.CloseReason, endpoint.Info); } diff --git a/MaxLib.WebServer/WebSocket/WebSocketConnection.cs b/MaxLib.WebServer/WebSocket/WebSocketConnection.cs index fe452ed..1a176d1 100644 --- a/MaxLib.WebServer/WebSocket/WebSocketConnection.cs +++ b/MaxLib.WebServer/WebSocket/WebSocketConnection.cs @@ -1,4 +1,5 @@ using System; +using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; @@ -10,8 +11,25 @@ namespace MaxLib.WebServer.WebSocket { + /// + /// Exceptions thrown from ReceivedFrame/ReceiveClose overrides must have a non-throwing ToString(); + /// they are passed to the logger as-is. Streams and custom JsonConverters used with WebSockets must + /// throw exceptions with a non-throwing ToString(); they are passed to the logger as-is. + /// public abstract class WebSocketConnection : IDisposable, IAsyncDisposable { + // Not cached per-type: this class is an arbitrary-subclass extension point, and this + // logger lookup only happens on the (rare) network-error path below, so resolving the + // concrete subclass's own logger category here costs nothing in practice. + static readonly EventId WebSocketEventId = new(0, "WebSocket"); + + /// + /// RFC 6455 §5.5: control frames (// + /// ) MUST have a payload of at most this many bytes, and MUST + /// NOT be fragmented. + /// + private const int MaxControlFramePayloadSize = 125; + public Stream NetworkStream { get; } private readonly SemaphoreSlim lockStream = new SemaphoreSlim(0, 1); @@ -21,6 +39,27 @@ public abstract class WebSocketConnection : IDisposable, IAsyncDisposable public DateTime LastPong { get; private set; } + /// + /// The maximum total size, in bytes, of the fragments accumulated so far while + /// reassembling a fragmented message. Checked after every fragment - not only once the + /// message is complete - so a client that never finalizes a message (or does so very + /// slowly) can't grow the accumulation queue indefinitely. Exceeding it closes the + /// connection with immediately. Defaults to + /// 100 MB; a negative value disables this check (not recommended - see also + /// ). + /// + public long MaxMessageSize { get; set; } = 100_000_000; + + /// + /// The maximum number of fragments accumulated while reassembling a message, checked + /// alongside . A size limit alone doesn't bound the + /// per-fragment bookkeeping overhead itself - many empty or near-empty fragments still + /// cost one queued entry each. Defaults to 10,000; a negative value disables this check. + /// An unfragmented message counts as one fragment, so 0 rejects every data message; use 1 + /// to allow only unfragmented messages. + /// + public int MaxMessageFragments { get; set; } = 10_000; + public event EventHandler? Closed; public event EventHandler? PongReceived; @@ -30,14 +69,24 @@ public WebSocketConnection(Stream networkStream) NetworkStream = networkStream ?? throw new ArgumentNullException(nameof(networkStream)); } + /// + /// Disposing while a SendFrame call is waiting for the send lock leaves that call pending + /// forever; stop sending on the connection before disposing it. + /// public virtual void Dispose() { NetworkStream.Dispose(); lockStream.Dispose(); + GC.SuppressFinalize(this); } + /// + /// Disposing while a SendFrame call is waiting for the send lock leaves that call pending + /// forever; stop sending on the connection before disposing it. + /// public virtual async ValueTask DisposeAsync() { + GC.SuppressFinalize(this); await NetworkStream.DisposeAsync().ConfigureAwait(false); lockStream.Dispose(); } @@ -49,6 +98,10 @@ public async Task Close(CloseReason reason = CloseReason.NormalClose, string? in int size = payload.Length; if (info != null) size = 2 + Encoding.UTF8.GetBytes(info, payload.Span[2..]); + // RFC 6455 §5.5: control frame payloads (Close included) must not exceed 125 bytes; + // truncate rather than send a non-compliant frame. + if (size > MaxControlFramePayloadSize) + size = MaxControlFramePayloadSize; await SendFrame(new Frame { OpCode = OpCode.Close, @@ -60,140 +113,298 @@ await SendFrame(new Frame /// This function is called after the handshake is finished /// public async Task HandshakeFinished() + { + var receiver = Task.Run(ReceiveLoop); + + // ping + var pinger = Task.Run(async () => + { + while (!SendCloseSignal) + { + await Task.Delay(TimeSpan.FromSeconds(10)).ConfigureAwait(false); + if (SendCloseSignal) + break; + await SendFrame(new Frame + { + OpCode = OpCode.Ping + }).ConfigureAwait(false); + } + }); + + await Task.WhenAll(receiver, pinger).ConfigureAwait(false); + Closed?.Invoke(this, EventArgs.Empty); + } + + /// + /// Reads and dispatches frames from until the connection + /// closes or the stream ends. Releases the send-side lock as its first action, since + /// sending is only meant to be possible once this loop is actually about to service the + /// connection - call this at most once per connection, exactly what + /// does. Exposed (internal) so tests can drive it + /// directly without also running the (10-second-interval) ping loop. + /// + internal async Task ReceiveLoop() { lockStream.Release(); - // receiving end - var receiver = Task.Run(async () => + var payloadQueue = new Queue>(); + OpCode code = OpCode.Binary; + long accumulatedSize = 0; + while (!ReceivedCloseSignal) { - var payloadQueue = new Queue>(); - OpCode code = OpCode.Binary; - while (!ReceivedCloseSignal) + Frame? frame; + try + { + // MaxMessageSize also bounds a single unfragmented frame, which never reaches payloadQueue below. + // Not clamped below MaxControlFramePayloadSize: control frames have their own fixed limit. + var maxDataPayloadSize = MaxMessageSize >= 0 + ? Math.Max(MaxMessageSize, MaxControlFramePayloadSize) + : MaxMessageSize; + frame = await Frame.TryRead(NetworkStream, throwLargePayload: true, maxPayloadSize: maxDataPayloadSize) + .ConfigureAwait(false); + } + catch (TooLargePayloadException) + { + var limit = MaxMessageSize >= 0 ? MaxMessageSize : (long)int.MaxValue; + await Close(CloseReason.TooBigMessage, $"Payload is larger then the allowed {limit} bytes") + .ConfigureAwait(false); + return; + } + if (frame == null) + return; + + if (!frame.HasMaskingKey) + { + // RFC 6455 §5.1: "A server MUST close the connection upon receiving a + // frame that is not masked." + await Close(CloseReason.ProtocolError, "Client frames must be masked") + .ConfigureAwait(false); + return; + } + frame.UnapplyMask(); + + if (!IsKnownOpCode(frame.OpCode)) + { + // RFC 6455 §5.2: an unknown opcode must fail the connection + await Close(CloseReason.ProtocolError, $"Unknown opcode {(byte)frame.OpCode:X}") + .ConfigureAwait(false); + return; + } + + if (IsControlFrame(frame.OpCode) && + (!frame.FinalFrame || frame.Payload.Length > MaxControlFramePayloadSize)) + { + // RFC 6455 §5.4/§5.5: control frames must not be fragmented and their + // payload must not exceed 125 bytes. + await Close(CloseReason.ProtocolError, + "Control frames must not be fragmented and must not exceed 125 bytes" + ).ConfigureAwait(false); + return; + } + + if (!frame.FinalFrame) { - Frame? frame; - try + // Per RFC 6455, only the first fragment of a message carries the real + // opcode; every later fragment is a Continuation, so only latch it once. + if (payloadQueue.Count == 0) { - frame = await Frame.TryRead(NetworkStream).ConfigureAwait(false); + if (frame.OpCode == OpCode.Continuation) + { + // RFC 6455 §5.4: the first frame of a message must carry its real data opcode + await Close(CloseReason.ProtocolError, + "The first fragment of a message must not use the Continuation opcode" + ).ConfigureAwait(false); + return; + } + code = frame.OpCode; + accumulatedSize = 0; } - catch (TooLargePayloadException) + else if (frame.OpCode != OpCode.Continuation) { - await Close(CloseReason.TooBigMessage, $"Payload is larger then the allowed {int.MaxValue} bytes") - .ConfigureAwait(false); + await Close(CloseReason.ProtocolError, + "A non-initial fragment must use the Continuation opcode" + ).ConfigureAwait(false); return; } - if (frame == null) + payloadQueue.Enqueue(frame.Payload); + accumulatedSize += frame.Payload.Length; + if (await ExceedsConfiguredMessageLimits(payloadQueue.Count, accumulatedSize).ConfigureAwait(false)) return; + continue; + } - frame.UnapplyMask(); - - if (!frame.FinalFrame) - { - code = frame.OpCode; - payloadQueue.Enqueue(frame.Payload); - continue; - } - - switch (frame.OpCode) - { - case OpCode.Close: - CloseReason? reason = null; - string? info = null; - if (frame.Payload.Length >= 2) + switch (frame.OpCode) + { + case OpCode.Close: + CloseReason? reason = null; + string? info = null; + if (frame.Payload.Length >= 2) + { + Frame.ToLocalByteOrder(frame.Payload.Span[0..2]); + reason = (CloseReason)BitConverter.ToUInt16(frame.Payload.Span[0..2]); + } + if (frame.Payload.Length > 2) + { + info = Encoding.UTF8.GetString(frame.Payload.Span[2..]); + } + ReceivedCloseSignal = true; + await ReceiveClose(reason, info).ConfigureAwait(false); + break; + case OpCode.Ping: + frame.OpCode = OpCode.Pong; + await SendFrame(frame).ConfigureAwait(false); + break; + case OpCode.Pong: + LastPong = DateTime.UtcNow; + _ = Task.Run(() => PongReceived?.Invoke(this, EventArgs.Empty)); + break; + default: + if (payloadQueue.Count == 0) + { + if (frame.OpCode == OpCode.Continuation) { - Frame.ToLocalByteOrder(frame.Payload.Span[0..2]); - reason = (CloseReason)BitConverter.ToUInt16(frame.Payload.Span[0..2]); + // RFC 6455 §5.4: an unfragmented message must not use the Continuation opcode + await Close(CloseReason.ProtocolError, + "A complete message must not use the Continuation opcode" + ).ConfigureAwait(false); + return; } - if (frame.Payload.Length > 2) + // Frame.TryRead's cap is at least MaxControlFramePayloadSize, so enforce MaxMessageSize + // for a single complete data frame here as well + if (await ExceedsConfiguredMessageLimits(1, frame.Payload.Length).ConfigureAwait(false)) + return; + await ReceivedFrame(frame).ConfigureAwait(false); + } + else + { + if (frame.OpCode != OpCode.Continuation) { - info = Encoding.UTF8.GetString(frame.Payload.Span[2..]); + await Close(CloseReason.ProtocolError, + "The final fragment of a message must use the Continuation opcode" + ).ConfigureAwait(false); + return; } - ReceivedCloseSignal = true; - await ReceiveClose(reason, info).ConfigureAwait(false); - break; - case OpCode.Ping: - frame.OpCode = OpCode.Pong; - await SendFrame(frame).ConfigureAwait(false); - break; - case OpCode.Pong: - LastPong = DateTime.UtcNow; - _ = Task.Run(() => PongReceived?.Invoke(this, EventArgs.Empty)); - break; - default: - if (payloadQueue.Count == 0) - await ReceivedFrame(frame).ConfigureAwait(false); - else + payloadQueue.Enqueue(frame.Payload); + accumulatedSize += frame.Payload.Length; + if (await ExceedsConfiguredMessageLimits(payloadQueue.Count, accumulatedSize).ConfigureAwait(false)) + return; + var payload = TryReassembleFragmentedPayload(payloadQueue); + if (payload == null) { - payloadQueue.Enqueue(frame.Payload); long maxSize = payloadQueue.Sum(x => (long)x.Length); - if (maxSize > int.MaxValue) - { - await Close(CloseReason.TooBigMessage, - $"the payload of all frames add up to {maxSize}. Only {int.MaxValue} is allowed." - ).ConfigureAwait(false); - } - Memory payload = new byte[maxSize]; - int start = 0; - while (payloadQueue.Count > 0) - { - var item = payloadQueue.Dequeue(); - item.CopyTo(payload.Slice(start, item.Length)); - start += item.Length; - } - frame.Payload = payload; - frame.OpCode = code; - await ReceivedFrame(frame).ConfigureAwait(false); + await Close(CloseReason.TooBigMessage, + $"the payload of all frames add up to {maxSize}. Only {int.MaxValue} is allowed." + ).ConfigureAwait(false); + return; } - break; - } + frame.Payload = payload.Value; + frame.OpCode = code; + await ReceivedFrame(frame).ConfigureAwait(false); + } + break; } - }); + } + } - // ping - var pinger = Task.Run(async () => + // RFC 6455 §5.2: the whole 0x8-0xF range is control opcodes, including unassigned ones + private static bool IsControlFrame(OpCode opCode) + => (byte)opCode >= 0x8; + + // only 0x0-0x2 (data) and 0x8-0xA (control) are assigned; every other opcode + // must fail the connection (RFC 6455 §5.2) + private static bool IsKnownOpCode(OpCode opCode) + => opCode is OpCode.Continuation or OpCode.Text or OpCode.Binary + or OpCode.Close or OpCode.Ping or OpCode.Pong; + + /// + /// Checks the running fragment count/size accumulated so far for the message currently + /// being reassembled against /, sending a close + /// frame and returning true if either is exceeded - the caller must stop + /// processing this connection in that case, rather than continuing to buffer an + /// unbounded amount of data until (or unless) the client ever finalizes the message. + /// + private async Task ExceedsConfiguredMessageLimits(int fragmentCount, long accumulatedSize) + { + if ((MaxMessageFragments >= 0 && fragmentCount > MaxMessageFragments) || + (MaxMessageSize >= 0 && accumulatedSize > MaxMessageSize)) { - while (!SendCloseSignal) - { - await Task.Delay(TimeSpan.FromSeconds(10)).ConfigureAwait(false); - if (SendCloseSignal) - break; - await SendFrame(new Frame - { - OpCode = OpCode.Ping - }).ConfigureAwait(false); - } - }); + await Close(CloseReason.TooBigMessage, + $"the message being reassembled exceeds the configured limit " + + $"({MaxMessageFragments} fragments / {MaxMessageSize} bytes)." + ).ConfigureAwait(false); + return true; + } + return false; + } - await Task.WhenAll(receiver, pinger).ConfigureAwait(false); - Closed?.Invoke(this, EventArgs.Empty); + /// + /// Reassembles the queued fragments of the current message into one contiguous buffer. A + /// can never represent more than + /// bytes, so if the queued payloads add up to more than that, this returns null. The + /// queue is left untouched in that case, so the caller can still inspect it (e.g. to report + /// the total size back to the client) before discarding it. + /// + internal static Memory? TryReassembleFragmentedPayload(Queue> payloadQueue) + { + _ = payloadQueue ?? throw new ArgumentNullException(nameof(payloadQueue)); + long maxSize = payloadQueue.Sum(x => (long)x.Length); + if (maxSize > int.MaxValue) + return null; + Memory payload = new byte[maxSize]; + int start = 0; + while (payloadQueue.Count > 0) + { + var item = payloadQueue.Dequeue(); + item.CopyTo(payload.Slice(start, item.Length)); + start += item.Length; + } + return payload; } protected virtual async Task SendFrame(Frame frame) { + ArgumentNullException.ThrowIfNull(frame); if (SendCloseSignal) return; await lockStream.WaitAsync().ConfigureAwait(false); - if (frame.OpCode == OpCode.Close) - SendCloseSignal = true; - try + try { - await frame.Write(NetworkStream).ConfigureAwait(false); - lockStream.Release(); + // re-check under the lock: a concurrent call may have sent a Close frame already, + // and RFC 6455 §5.5.1 forbids sending after it + if (SendCloseSignal) + return; + if (frame.OpCode == OpCode.Close) + SendCloseSignal = true; + try + { + await frame.Write(NetworkStream).ConfigureAwait(false); + } + catch (IOException e) + { + if (frame.OpCode != OpCode.Ping && frame.OpCode != OpCode.Pong) + WebServerLog.LoggerFactory.CreateLogger(GetType()) + .LogInformation(WebSocketEventId, e, "Unexpected network error: frame={OpCode}", frame.OpCode); + var alreadyReceived = ReceivedCloseSignal; + ReceivedCloseSignal = true; + SendCloseSignal = true; + if (!alreadyReceived) + await ReceiveClose(null, null).ConfigureAwait(false); + } } - catch (IOException e) + finally { - if (frame.OpCode != OpCode.Ping && frame.OpCode != OpCode.Pong) - WebServerLog.Add(ServerLogType.Information, GetType(), "WebSocket", - $"Unexpected network error: frame={frame.OpCode} error={e}" - ); - var alreadyReceived = ReceivedCloseSignal; - ReceivedCloseSignal = true; - SendCloseSignal = true; - if (!alreadyReceived) - await ReceiveClose(null, null).ConfigureAwait(false); + lockStream.Release(); } } + /// + /// Overrides must not throw; an escaping exception leaves the ping loop running, so Closed never fires and the connection is never cleaned up. + /// protected abstract Task ReceiveClose(CloseReason? reason, string? info); + /// + /// Overrides must not throw; an escaping exception leaves the ping loop running, so Closed never fires and the connection is never cleaned up. + /// protected abstract Task ReceivedFrame(Frame frame); } } diff --git a/MaxLib.WebServer/WebSocket/WebSocketEndpoint.cs b/MaxLib.WebServer/WebSocket/WebSocketEndpoint.cs index 2d75c57..70cba33 100644 --- a/MaxLib.WebServer/WebSocket/WebSocketEndpoint.cs +++ b/MaxLib.WebServer/WebSocket/WebSocketEndpoint.cs @@ -37,10 +37,12 @@ public void Dispose() connection.Dispose(); connections.Clear(); connectionLock.Dispose(); + GC.SuppressFinalize(this); } public async ValueTask DisposeAsync() { + GC.SuppressFinalize(this); await connectionLock.WaitAsync().ConfigureAwait(false); foreach (var connection in connections) await connection.DisposeAsync().ConfigureAwait(false); @@ -64,14 +66,38 @@ private void Connection_Closed(object? sender, EventArgs eventArgs) { if (sender is T connection) { - _ = RemoveConnection(connection); + _ = HandleConnectionClosed(connection); } } + /// + /// Removes from this endpoint's bookkeeping and, unless + /// opts out, disposes it. Runs whenever a + /// connection's event fires. Exposed + /// (internal) so tests can drive it directly, without needing a real handshake + /// and ping loop just to make that event fire. + /// + internal async Task HandleConnectionClosed(T connection) + { + await RemoveConnection(connection).ConfigureAwait(false); + if (DisposeConnectionsOnClose) + await connection.DisposeAsync().ConfigureAwait(false); + } + + /// + /// If true (the default), a connection is automatically disposed once its + /// event fires and it has been removed from + /// this endpoint's bookkeeping. Override to return false if you need to keep + /// using the connection object afterwards (e.g. to inspect its final state) and will + /// dispose it yourself. + /// + protected virtual bool DisposeConnectionsOnClose => true; + protected abstract T? CreateConnection(Stream stream, HttpRequestHeader header); public async Task RemoveConnection(T connection) { + ArgumentNullException.ThrowIfNull(connection); await connectionLock.WaitAsync().ConfigureAwait(false); connections.Remove(connection); connectionLock.Release(); diff --git a/MaxLib.WebServer/WebSocket/WebSocketService.cs b/MaxLib.WebServer/WebSocket/WebSocketService.cs index 1c02d0a..0450d23 100644 --- a/MaxLib.WebServer/WebSocket/WebSocketService.cs +++ b/MaxLib.WebServer/WebSocket/WebSocketService.cs @@ -1,4 +1,5 @@ using System; +using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.Linq; using System.Text; @@ -10,12 +11,17 @@ namespace MaxLib.WebServer.WebSocket { public class WebSocketService : WebService, IDisposable, IAsyncDisposable { - public WebSocketService() + static readonly ILogger logger = WebServerLog.LoggerFactory.CreateLogger(); + static readonly EventId HandshakeEventId = new(0, "handshake"); + + private static readonly char[] ProtocolSeparators = [' ', ',']; + + public WebSocketService() : base(ServerStage.ParseRequest) { } - public ICollection Endpoints { get; } + public ICollection Endpoints { get; } = new List(); public WebSocketCloserEndpoint? CloseEndpoint { get; set; } @@ -28,19 +34,22 @@ public void Add(WebSocketEndpoint endpoint) public override bool CanWorkWith(WebProgressTask task) { - return task.Request.GetHeader("Upgrade") == "websocket" && - (task.Request.GetHeader("Connection")?.ToLower().Contains("upgrade") ?? false); + ArgumentNullException.ThrowIfNull(task); + return task.Request.GetHeader("Upgrade") == "websocket" && + (task.Request.GetHeader("Connection")?.Contains("upgrade", StringComparison.OrdinalIgnoreCase) ?? false); } public override void Dispose() { base.Dispose(); + GC.SuppressFinalize(this); foreach (var endpoint in Endpoints) endpoint.Dispose(); } public async ValueTask DisposeAsync() { + GC.SuppressFinalize(this); await Task.WhenAll( Endpoints.Select(async x => await x.DisposeAsync().ConfigureAwait(false)) ).ConfigureAwait(false); @@ -48,11 +57,13 @@ await Task.WhenAll( public override async Task ProgressTask(WebProgressTask task) { + ArgumentNullException.ThrowIfNull(task); if (task.NetworkStream == null) return; - var protocols = (task.Request.GetHeader("Sec-WebSocket-Protocol")?.ToLower() ?? "") - .Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries); + var rawProtocols = (task.Request.GetHeader("Sec-WebSocket-Protocol") ?? "") + .Split(ProtocolSeparators, StringSplitOptions.RemoveEmptyEntries); + var protocols = Array.ConvertAll(rawProtocols, p => p.ToLowerInvariant()); var key = task.Request.GetHeader("Sec-WebSocket-Key"); var version = task.Request.GetHeader("Sec-WebSocket-Version"); // MUST be 13 according RFC 6455 @@ -66,7 +77,7 @@ public override async Task ProgressTask(WebProgressTask task) } var responseKey = Convert.ToBase64String( - System.Security.Cryptography.SHA1.Create().ComputeHash( + System.Security.Cryptography.SHA1.HashData( Encoding.UTF8.GetBytes( $"{key.Trim()}258EAFA5-E914-47DA-95CA-C5AB0DC85B11" ) @@ -76,16 +87,30 @@ public override async Task ProgressTask(WebProgressTask task) foreach (var endpoint in Endpoints) { - if (protocols.Length > 0 && (endpoint.Protocol == null || !protocols.Contains(endpoint.Protocol))) + // symmetric with IWebSocketEndpoint.Protocol: a non-null Protocol requires the client to ask for it, + // a null Protocol requires the client to ask for none + string? matchedProtocol; + if (endpoint.Protocol == null) { - continue; + if (protocols.Length > 0) + continue; + matchedProtocol = null; + } + else + { + var idx = Array.IndexOf(protocols, endpoint.Protocol.ToLowerInvariant()); + if (idx < 0) + continue; + // RFC 6455 §4.2.2: the response must be one of the client's offered tokens verbatim, + // not the endpoint's casing + matchedProtocol = rawProtocols[idx]; } var connection = await endpoint.Create(task.NetworkStream, task.Request).ConfigureAwait(false); if (connection == null) continue; - HandleCreateConnection(task, responseKey, endpoint, connection); + HandleCreateConnection(task, responseKey, matchedProtocol, connection); return; } @@ -94,12 +119,12 @@ public override async Task ProgressTask(WebProgressTask task) var connection = await ep.Create(task.NetworkStream, task.Request).ConfigureAwait(false); if (connection == null) return; - HandleCreateConnection(task, responseKey, ep, connection); + HandleCreateConnection(task, responseKey, ep.Protocol, connection); } } - private void HandleCreateConnection(WebProgressTask task, string responseKey, - IWebSocketEndpoint endpoint, WebSocketConnection connection) + private static void HandleCreateConnection(WebProgressTask task, string responseKey, + string? protocol, WebSocketConnection connection) { task.Response.StatusCode = HttpStateCode.SwitchingProtocols; task.Response.SetHeader( @@ -107,7 +132,7 @@ private void HandleCreateConnection(WebProgressTask task, string responseKey, ("Upgrade", "websocket"), ("Connection", "Upgrade"), ("Sec-WebSocket-Accept", responseKey), - ("Sec-WebSocket-Protocol", endpoint.Protocol) + ("Sec-WebSocket-Protocol", protocol) ); task.SwitchProtocols(async () => @@ -121,7 +146,7 @@ private void HandleCreateConnection(WebProgressTask task, string responseKey, } catch (Exception e) { - WebServerLog.Add(ServerLogType.Error, GetType(), "handshake", $"handshake error: {e}"); + logger.LogError(HandshakeEventId, e, "Handshake error"); } }); task.NextStage = ServerStage.SendResponse; diff --git a/README.md b/README.md index 098b7db..d7c732a 100644 --- a/README.md +++ b/README.md @@ -25,10 +25,10 @@ Some of the current features of the web server are: to use. - Asynchronous handling of requests. Every part of the pipeline works with awaitable Tasks. - REST Api builder. You can directly bind your methods to the handlers. -- Chunked transport. The server understands chunked data streams and can produce these. +- Chunked transport. The server understands chunked data streams and can produce these on + responses. Chunked **request** bodies are not supported yet. - Lazy handling of requests. The server allows you to produce the content while you are sending the response. No need to wait. -- Work with components that belongs to another AppDomain with Marshaling. - Deliver contents from your local drive (e.g. HDD) - Session keeping. You can identify the user later. - ... @@ -65,7 +65,7 @@ using var server = new Server(new WebServerSettings( server.InitDefault(); // the server can now be started. A basic set of services is defined so a new -// request will be handled and the user gets a response. Right now its a +// request will be handled and the user gets a response. Right now its a // 404 NOT FOUND but we will add more. server.Start(); @@ -112,10 +112,298 @@ After that you can run your programm and open the page > More information about the new builder system can be found [here](https://github.com/Garados007/MaxLib.WebServer/wiki/Builder-System) +## Advanced usage + +### Logging + +`MaxLib.WebServer` logs exclusively through the standard +[`Microsoft.Extensions.Logging.ILogger`](https://learn.microsoft.com/en-us/dotnet/core/extensions/logging) +abstraction. There is no MaxLib-specific logging API to learn: point it at whatever +logging backend your application already uses (Serilog, NLog, log4net, the built-in +console/debug providers, ...) via that backend's own standard `ILoggerFactory` setup, +and every log call made inside this library flows into it. + +> **The one-line contract:** call `WebServerLog.SetLoggerFactory(...)` **exactly once**, +> **before** constructing anything else from this library. Each class resolves its +> logger once, at first use, so a factory set afterwards will not be picked up by +> classes that already ran. A second call to `SetLoggerFactory` throws +> `InvalidOperationException` rather than silently changing anything. + +```csharp +using Microsoft.Extensions.Logging; + +// Wire this library's logging to whatever backend you already use - here plain +// console output, but AddSerilog(), AddNLog(), AddDebug(), etc. work the same way. +WebServerLog.SetLoggerFactory(LoggerFactory.Create(builder => builder.AddSimpleConsole())); + +using var server = new Server(new WebServerSettings(8000, 5000)); +// ... +``` + +### Sessions + +`MaxLib.WebServer.Sessions` identifies returning users via a `Session` cookie, without you +having to manage that cookie yourself. Add a session service - `MemorySessionService` for a +simple in-process store, or subclass `SessionServiceBase` for your own backing store - and read +or write per-user data through `task.Session`: + +```csharp +using MaxLib.WebServer.Sessions; + +server.AddWebService(new MemorySessionService()); +``` + +```csharp +// inside any WebService that runs after the session service (ServerStage.ParseRequest or later) +var session = task.Session!; +var visits = session.TryGetValue("visits", out var v) ? (int)v! : 0; +session["visits"] = visits + 1; +``` + +The service issues a fresh session id (and its cookie) the first time a client is seen, and +reuses it on every later request that presents that same cookie back. + +**Hardening:** call `RotateSessionKey(task)` right after any change in privilege - most +importantly, right after a successful login - so that a session id an attacker may have set on +the client beforehand (before the user authenticated) becomes worthless afterwards. The session +cookie itself already defaults to `HttpOnly`, and to `Secure`/`SameSite=Strict` whenever this +server observes the connection as encrypted (`SameSite=Lax` and no `Secure` otherwise) - if a +reverse proxy (e.g. nginx) terminates TLS in front of this server instead, that auto-detection +never sees an HTTPS connection, so set `CookieSecurity = CookieSecurityMode.Strict` on your +session service explicitly to still get the stricter, HTTPS-only cookie attributes. + +**Expiry:** `MaxAge` (default 30 days) already governs the cookie's `Expires`/`Max-Age` +attributes; `MemorySessionService` also enforces it server-side. A session that's expired by +the time it's next looked up is discarded and replaced with a fresh, empty one instead of being +served - so a session id leaked long ago stops giving access to whatever data it used to hold. +This alone doesn't stop `Sessions` from otherwise growing unboundedly (e.g. from many distinct +or absent cookie values), so call `Sweep()` periodically to evict every session that's expired +but hasn't been looked up since, or call `StartAutomaticSweep()` once to have the service run it +for you on its own background timer (stop it with `StopAutomaticSweep()`, also done by +`Dispose()`): + +```csharp +var sessions = new MemorySessionService(); +sessions.StartAutomaticSweep(); +server.AddWebService(sessions); +``` + +### Chunked responses + +Most `HttpDataSource` implementations know their length up front, and `HttpResponseCreator` +computes `Content-Length` from that. A source that doesn't (e.g. `Chunked.HttpChunkedStream`, +wrapping a stream whose size isn't known ahead of time) reports `Length() == null` instead - if +`HttpResponseCreator` computed `Content-Length` from that the same way, it would silently +undercount it while still writing the full body, desyncing the connection for any client or +proxy relying on that header for framing. + +To actually send such a response correctly, register `Chunked.ChunkedResponseCreator` and +`Chunked.ChunkedSender` alongside the default services - typically with `onlyWithLazy: true`, so +they only take over responses that need it (unknown-length or lazy data sources) and leave +ordinary responses to the default `Content-Length` path: + +```csharp +using MaxLib.WebServer.Chunked; + +server.AddWebService(new ChunkedResponseCreator(onlyWithLazy: true)); +server.AddWebService(new ChunkedSender(onlyWithLazy: true)); +``` + +Without a `ChunkedSender` registered, a response containing an unknown-length data source is +rejected with `500 Internal Server Error` (logged) instead of being sent with a wrong +`Content-Length`. + +### Reading POST data + +`task.Request.Post.Data` (or the awaitable `DataAsync`) gives you a parsed `IPostData` for the +request body, chosen by `Content-Type`: + +- `application/x-www-form-urlencoded` → `Post.UrlEncodedData` (`.Parameter`, a `Dictionary`). + A body larger than `UrlEncodedData.MaximumCacheSize` (default 50 MB) is parsed into `.Overflow` + instead - a `Post.MultipartFormData` with one entry per key, individually eligible for the same + in-memory-vs-temp-file decision a multipart part gets - so `Parameter` is left empty in that case. +- `multipart/form-data` → `Post.MultipartFormData` (`.Entries`, a list of parts - each with `.Content` + or, once uploaded files get large enough, a `.TempFile` instead) +- `application/json`, `application/octet-stream`, anything else unrecognized, or a missing + `Content-Type` entirely → `Post.RawPostData`, storing the whole body as one nameless entry + (`.Entry.Content` or `.Entry.TempFile`, on the same size threshold as a multipart part) + +Every one of these actually reads and stores the body - none of them leave it as an unread +reference to the live connection. If you're building a Builder endpoint (see "Create own +service" above), `[TextPost]` binds a `string` parameter to a `RawPostData` body decoded as UTF-8, +without you having to touch `Post.Data` yourself: + +```csharp +[Path("/echo"), Method("POST")] +public string Echo([TextPost] string body) => body; +``` + +### Request body size and read timeout + +`HttpRequestParser` bounds both how large a request body it accepts and how long it waits for +one to arrive, so that an unbounded `Content-Length` combined with a client that stalls +mid-upload can't pin a thread-pool thread forever (draining an unconsumed body on dispose is +fully asynchronous - see `HttpPost.DisposeAsync()` - and bounded by the same timeout). It also +bounds how long a client is given to actually send its request in the first place: + +- **`MaxConnectionDelay`** (default 5 s) is how long the parser waits for the very first byte of + a request to arrive before giving up. Set it to zero or negative to disable this wait. +- **`MaxHeaderReadTime`** (default 10 s) bounds the *rest* of the request-line-and-header phase + as a whole, once that first byte has arrived - not a per-line timeout. Without it, a client + that trickles its request one byte (or one header line) at a time - the classic "Slowloris" + attack - could hold the connection open indefinitely just by satisfying + `MaxConnectionDelay`'s wait first. Set it to zero or negative to disable it. + +- **`MaxContentLength`** (default 100 MB) is the body size every request is accepted under + without further checks. A request whose `Content-Length` exceeds it is rejected with + `413 Request Entity Too Large` - unless you set `ContentLengthLimitExceeded`. +- **`ContentLengthLimitExceeded`** is an optional callback invoked with the current request and + its declared `Content-Length` whenever `MaxContentLength` is exceeded. Return a higher limit to + apply for just that request (e.g. based on the route or authenticated user), or `null` to allow + any size. If the callback isn't set, or the limit it returns is still exceeded, the request is + rejected the same way. +- **`ContentReadBaseTimeout`** (default 5 s) and **`MinimumContentTransferRate`** (default + 16 000 byte/s) together bound how long a request's body is given to arrive: the full timeout is + `ContentReadBaseTimeout + Content-Length / MinimumContentTransferRate`, so larger (but still + accepted) bodies get proportionally more time, while a stalled client is still bounded rather + than blocking the reader indefinitely. Unlike the size limit, this always applies uniformly - + there is no per-request override. + +Whenever a request is rejected for being too large, the connection is closed instead of kept +alive, since the client's bytes are left completely unread. A body read that instead times out +mid-request never closes the connection by itself - that could pre-empt a response the server was +about to send on it, e.g. one reporting that very timeout - it only ever does once the response +has actually been transmitted and any leftover POST data is being discarded to ready the +connection for reuse (in `HttpSender`, right after sending); if that final drain times out, the +connection is closed there instead of kept alive, since its position in the byte stream is by then +unknown. + +### Connection limits + +`WebServerSettings.MaxConcurrentConnections` bounds how many connections (`Server.AllConnections`) +the server accepts at once - a new connection beyond that limit is rejected outright (its socket +closed immediately, without being processed at all) instead of being left to compete for +thread-pool/memory resources indefinitely alongside every other admitted connection. Defaults to +`-1` (no limit, the previous behavior); applies to both the plain and TLS-terminating listeners +(`SecureWebServer`, `DualSecureWebServer`), since they share the same connection bookkeeping. + +```csharp +using var server = new Server(new WebServerSettings(8000, 5000) +{ + MaxConcurrentConnections = 1000, +}); +``` + +### WebSocket Events + +`MaxLib.WebServer.WebSocket` includes `EventBase`/`EventFactory`, a small typed-message +layer on top of raw WebSocket frames. Events are plain classes, and +`System.Text.Json`'s native polymorphic serialization takes care of reading/writing +the `"$type"` discriminator and the rest of the payload - no custom converters needed. + +#### Registering events + +Subclass `EventBase` with public properties, create an `EventFactory`, and register +your event types before using it: + +```csharp +using MaxLib.WebServer.WebSocket; + +public class ChatMessage : EventBase +{ + public string Text { get; set; } = ""; +} + +var factory = new EventFactory(); +factory.Add(); // wire "$type" defaults to the class name +// factory.Add("chat.msg"); // or pick an explicit wire name + +// pass `factory` into your EventConnection subclass, then: +// await SendFrame(new ChatMessage { Text = "hi" }); +``` + +All event types must be registered before the factory's first use (its registry is +sealed on first serialize/deserialize) - register everything once at startup. + +#### Automatic registration + +There is no attribute-scanning or assembly discovery: declaring an `EventBase` +subclass alone does not register it. Every event type must be added explicitly via +`Add()`/`Add(string)`/`Add(string, Type)`. + +#### Customizing the wire format + +Use standard `System.Text.Json` attributes directly on your event's properties: + +```csharp +public class ChatMessage : EventBase +{ + [JsonPropertyName("text")] + public string Text { get; set; } = ""; + + [JsonIgnore] + public DateTime ReceivedAt { get; set; } +} +``` + +For settings that should apply to every event on a factory (a naming policy, a +converter for a shared type), pass a `JsonSerializerOptions` into the constructor: + +```csharp +var factory = new EventFactory(new JsonSerializerOptions +{ + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, +}); +``` + +See Microsoft's [System.Text.Json property customization documentation](https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/customize-properties) +for the full set of supported attributes and options. + +#### Multiple factories + +Each `EventFactory` instance has its own independent type registry and +`JsonSerializerOptions` - nothing is shared statically between instances. Create one +factory per protocol/endpoint that needs a different set of event types (or different +wire settings), and give each `EventConnection` subclass the factory instance +appropriate to it. + +#### Handling invalid incoming events + +A client can send a frame that isn't a valid event: malformed JSON, an +unregistered `"$type"`, or JSON that doesn't match the shape of the type it +names. `EventFactory.Parse(Frame)` reports these as one of three exception types +(`MalformedEventJsonException`, `UnknownEventTypeException`, +`InvalidEventPayloadException`, all deriving from `EventParseException`), and +`EventConnection` routes each to its own overridable handler instead of dropping +the frame silently: + +```csharp +public class Connection : EventConnection +{ + // ... + + protected override Task ReceivedUnknownEvent(Frame frame, UnknownEventTypeException exception) + { + // e.g. tell the client what went wrong instead of just logging it + return SendFrame(new ErrorEvent { Message = exception.Message }); + } +} +``` + +The default implementation of each handler (`ReceivedMalformedEvent`, +`ReceivedUnknownEvent`, `ReceivedInvalidEventPayload`) just logs the error, so +overriding only the ones you care about is safe - the rest keep their previous +behavior. + ## Example - [example/MaxLib.WebServer.Example](example/MaxLib.WebServer.Example) - create a basic webserver +- [example/MaxLib.WebServer.Builder.Debugger.Example](example/MaxLib.WebServer.Builder.Debugger.Example) + - a mix of working and deliberately misconfigured `Builder.Service` types, an index + page linking to every endpoint, and the `Builder.Debugger.DebuggerService` wired up + to explain what got built (or skipped/failed) and why a given request would or + wouldn't reach a service ## Contributing diff --git a/example/MaxLib.WebServer.Builder.Debugger.Example/BrokenEndpoints.cs b/example/MaxLib.WebServer.Builder.Debugger.Example/BrokenEndpoints.cs new file mode 100644 index 0000000..073691d --- /dev/null +++ b/example/MaxLib.WebServer.Builder.Debugger.Example/BrokenEndpoints.cs @@ -0,0 +1,106 @@ +using System; +using System.Text; + +namespace MaxLib.WebServer.Builder.Debugger.Example +{ + /// + /// Deliberately excluded from the builder via [Ignore] - open the debugger and search for + /// "IgnoredDemoService" to see it listed as Ignored/TypeIgnoredByAttribute. + /// + [Ignore] + public class IgnoredDemoService : Service + { + [Path("/broken/ignored")] + public HttpDataSource M() => new HttpStringDataSource("you should never see this"); + } + + /// + /// Abstract types can never be instantiated by the generator, so this whole type is skipped. + /// + public abstract class AbstractDemoService : Service + { + [Path("/broken/abstract")] + public abstract HttpDataSource M(); + } + + /// + /// A common real-world mistake: adding a constructor parameter (e.g. for dependency + /// injection) without also providing a parameterless one. The generator can only construct + /// types via `new()`, so this type is skipped entirely - none of its methods are ever built, + /// even the ones that look otherwise fine. + /// + public class NoConstructorDemoService : Service + { + private readonly string config; + + public NoConstructorDemoService(string config) + { + this.config = config; + } + + [Path("/broken/no-constructor")] + public HttpDataSource M() => new HttpStringDataSource(config); + } + + /// + /// The constructor throws once the generator tries to create an instance to bind methods to. + /// The exception is caught and attributed to exactly this method - every other service in + /// the same scan still builds fine. Open the debugger and search for + /// "ThrowingConstructorDemoService" to see it reported as Failed/MethodConstructorThrew. + /// + public class ThrowingConstructorDemoService : Service + { + public ThrowingConstructorDemoService() + => throw new InvalidOperationException("simulated misconfiguration in the constructor"); + + [Path("/broken/throwing-constructor")] + public HttpDataSource M() => new HttpStringDataSource("you should never see this"); + } + + /// + /// A very common gotcha: the class-level [Path] restricts the URL to that exact path unless + /// you also set Prefix = true. Without it, no method below can ever be reached, because the + /// class-level rule already rejects any longer URL before the method rules are even checked. + /// This is a REAL, live endpoint that 404s - click it, then use the debugger's request + /// simulator on "/broken/forgot-prefix/detail" to see exactly why. + /// + [Path("/broken/forgot-prefix")] + public class ForgotPrefixDemoService : Service + { + [Path("/broken/forgot-prefix/detail")] + public HttpDataSource M() => new HttpStringDataSource("you should never see this either"); + } + + /// + /// A grab-bag of per-method issues inside an otherwise healthy class. + /// + public class MixedMethodIssuesDemoService : Service + { + [Path("/broken/mixed/ok")] + public HttpDataSource Ok() => new HttpStringDataSource("this one works fine"); + + [Ignore] + [Path("/broken/mixed/ignored-method")] + public HttpDataSource IgnoredMethod() => new HttpStringDataSource("you should never see this"); + + // Not public - the generator only ever binds public methods. + [Path("/broken/mixed/not-public")] + internal HttpDataSource NotPublicMethod() => new HttpStringDataSource("you should never see this"); + + // [Var] is present, but the built-in converters have no way to turn a string into a + // StringBuilder -> ParamNoConverterFound. + [Path("/broken/mixed/bad-param-converter")] + public HttpDataSource BadParamConverter([Var] StringBuilder value) => new HttpStringDataSource(value.ToString()); + + // No attribute at all, and StringBuilder isn't one of the injectable core types either + // -> ParamNoCoreConverterFound. + [Path("/broken/mixed/unsupported-param-type")] + public HttpDataSource UnsupportedParamType(StringBuilder value) => new HttpStringDataSource(value.ToString()); + + // Nothing in the default converters knows how to turn a plain int into an HttpDataSource + // -> ResultNoConverter. Use [return: JsonDataConverter] or return an HttpDataSource + // yourself instead, like MathService.AddJson() does. + [Path("/broken/mixed/unsupported-return-type")] + public int UnsupportedReturnType() => 42; + } +} diff --git a/example/MaxLib.WebServer.Builder.Debugger.Example/Endpoints.cs b/example/MaxLib.WebServer.Builder.Debugger.Example/Endpoints.cs new file mode 100644 index 0000000..719d430 --- /dev/null +++ b/example/MaxLib.WebServer.Builder.Debugger.Example/Endpoints.cs @@ -0,0 +1,74 @@ +namespace MaxLib.WebServer.Builder.Debugger.Example +{ + /// + /// A path variable and a class-level path prefix, done correctly. + /// + [Path("/greet", Prefix = true)] + public class GreetingService : Service + { + [Path("/greet/{name}")] + public HttpDataSource Hello([Var] string name) + => new HttpStringDataSource($"Hello, {name}!"); + } + + public record MathResult(int A, int B, int Sum); + + /// + /// GET query parameters with automatic string-to-int conversion, and a JSON API endpoint. + /// + [Path("/math", Prefix = true)] + public class MathService : Service + { + [Path("/math/add")] + public HttpDataSource Add([Get] int a, [Get] int b) + => new HttpStringDataSource($"{a} + {b} = {a + b}"); + + [Path("/math/add-json")] + [return: JsonDataConverter] + public MathResult AddJson([Get] int a, [Get] int b) + => new(a, b, a + b); + } + + /// + /// A POST endpoint reading an "application/x-www-form-urlencoded" body. + /// + public class EchoPostService : Service + { + [Path("/echo-post")] + [Method("POST")] + public HttpDataSource Echo([UrlEncodedPost] string message) + => new HttpStringDataSource($"You said: {message}"); + } + + /// + /// Framework types (here: the raw request header) can be injected into a method parameter + /// without any attribute - the generator resolves them as "core parameters". + /// + public class RequestInfoService : Service + { + [Path("/request-info")] + public HttpDataSource Info(HttpRequestHeader request) + => new HttpStringDataSource( + $"{request.ProtocolMethod} {request.Location.Url} from {request.Host}" + ); + } + + /// + /// Two unrelated services both claim the same path. Whichever has the higher priority always + /// wins, and the other one never runs - open the debugger's request simulator on + /// "/priority-demo" to see this play out and which candidate was never reached. + /// + public class PriorityDemoHighService : Service + { + [Path("/priority-demo")] + [Priority(WebServicePriority.High)] + public HttpDataSource M() => new HttpStringDataSource("Handled by the HIGH priority service."); + } + + public class PriorityDemoLowService : Service + { + [Path("/priority-demo")] + [Priority(WebServicePriority.Low)] + public HttpDataSource M() => new HttpStringDataSource("Handled by the LOW priority service."); + } +} diff --git a/example/MaxLib.WebServer.Builder.Debugger.Example/IndexService.cs b/example/MaxLib.WebServer.Builder.Debugger.Example/IndexService.cs new file mode 100644 index 0000000..9eac5d6 --- /dev/null +++ b/example/MaxLib.WebServer.Builder.Debugger.Example/IndexService.cs @@ -0,0 +1,31 @@ +using System.Threading.Tasks; + +namespace MaxLib.WebServer.Builder.Debugger.Example +{ + /// + /// A small, hand-written landing page at "/" that links to every demo endpoint in this + /// example, plus the debugger itself, so you don't have to remember any of the URLs while + /// exploring. Some links intentionally 404 - each of those has a matching "explain in + /// debugger" link that deep-links straight into the request-routing simulator for that exact + /// path. + /// + public class IndexService : WebService + { + public IndexService() : base(ServerStage.CreateDocument) + { + } + + public override bool CanWorkWith(WebProgressTask task) + => task.Request.Location.DocumentPath == "/"; + + public override Task ProgressTask(WebProgressTask task) + { + task.Document.DataSources.Add(new HttpStringDataSource(Properties.Resources.Debugger_IndexShell) + { + MimeType = MimeType.TextHtml, + TextEncoding = "utf-8", + }); + return Task.CompletedTask; + } + } +} diff --git a/example/MaxLib.WebServer.Builder.Debugger.Example/MaxLib.WebServer.Builder.Debugger.Example.csproj b/example/MaxLib.WebServer.Builder.Debugger.Example/MaxLib.WebServer.Builder.Debugger.Example.csproj new file mode 100644 index 0000000..506618a --- /dev/null +++ b/example/MaxLib.WebServer.Builder.Debugger.Example/MaxLib.WebServer.Builder.Debugger.Example.csproj @@ -0,0 +1,23 @@ + + + + Exe + net10.0 + enable + + + + + + + + + + + + + + + + + diff --git a/example/MaxLib.WebServer.Builder.Debugger.Example/Program.cs b/example/MaxLib.WebServer.Builder.Debugger.Example/Program.cs new file mode 100644 index 0000000..63d6002 --- /dev/null +++ b/example/MaxLib.WebServer.Builder.Debugger.Example/Program.cs @@ -0,0 +1,40 @@ +using System; +using System.Reflection; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; + +namespace MaxLib.WebServer.Builder.Debugger.Example +{ + class Program + { + static async Task Main() + { + WebServerLog.SetLoggerFactory(LoggerFactory.Create(builder => builder.AddSimpleConsole())); + using var server = new Server(new WebServerSettings(8000, 5000)); + server.InitialDefault(); + server.AddWebService(new IndexService()); + + // Scan this whole assembly for Service subclasses at once - GreetingService, + // MathService, ... alongside every deliberately broken one in BrokenEndpoints.cs. + // The report below shows every scanned type/method, whether it was built, and why + // not for the ones that weren't. + var built = Service.Build(Assembly.GetExecutingAssembly(), out var report); + if (built != null) + server.AddWebService(built); + + Console.WriteLine( + $"Build report: {report.CountByStatus(BuildReportStatus.Accepted)} accepted, " + + $"{report.CountByStatus(BuildReportStatus.Ignored)} ignored, " + + $"{report.CountByStatus(BuildReportStatus.Failed)} failed." + ); + + server.AddWebService(new DebuggerService(server, report)); + + Console.WriteLine("Listening on http://localhost:8000/ - open it in a browser."); + Console.WriteLine("Debugger: http://localhost:8000/_debugger/"); + + // run server until cancel received + await server.RunAsync(); + } + } +} diff --git a/example/MaxLib.WebServer.Builder.Debugger.Example/Properties/Resources.cs b/example/MaxLib.WebServer.Builder.Debugger.Example/Properties/Resources.cs new file mode 100644 index 0000000..f3d0378 --- /dev/null +++ b/example/MaxLib.WebServer.Builder.Debugger.Example/Properties/Resources.cs @@ -0,0 +1,27 @@ +using System.IO; + +namespace MaxLib.WebServer.Builder.Debugger.Example.Properties +{ + public static class Resources + { + private static string? debugger_IndexShell; + + /// + /// The self-contained HTML page serves at "/". + /// + public static string Debugger_IndexShell + { + get + { + if (debugger_IndexShell != null) + return debugger_IndexShell; + var assembly = typeof(Resources).Assembly; + using var stream = assembly.GetManifestResourceStream( + "MaxLib.WebServer.Builder.Debugger.Example.Resources.Debugger.IndexShell.html" + )!; + using var reader = new StreamReader(stream); + return debugger_IndexShell = reader.ReadToEnd(); + } + } + } +} diff --git a/example/MaxLib.WebServer.Builder.Debugger.Example/Resources/Debugger.IndexShell.html b/example/MaxLib.WebServer.Builder.Debugger.Example/Resources/Debugger.IndexShell.html new file mode 100644 index 0000000..a2524b1 --- /dev/null +++ b/example/MaxLib.WebServer.Builder.Debugger.Example/Resources/Debugger.IndexShell.html @@ -0,0 +1,70 @@ + + + + +MaxLib.WebServer.Builder.Debugger Example + + + +

MaxLib.WebServer — Builder Debugger example

+

+ This example registers a mix of working and deliberately misconfigured + MaxLib.WebServer.Builder.Service types. Click around, then open the debugger to + see why each one behaves the way it does. +

+ + Open the Builder Debugger → + +

Working endpoints

+ + +

Intentionally broken endpoints

+

These 404 (or were never even built) on purpose - use the debugger to find out why.

+ + + diff --git a/example/MaxLib.WebServer.Example/MaxLib.WebServer.Example.csproj b/example/MaxLib.WebServer.Example/MaxLib.WebServer.Example.csproj index 5c7ceec..12b4127 100644 --- a/example/MaxLib.WebServer.Example/MaxLib.WebServer.Example.csproj +++ b/example/MaxLib.WebServer.Example/MaxLib.WebServer.Example.csproj @@ -2,11 +2,16 @@ Exe - net8.0 + net10.0 + + + + + diff --git a/example/MaxLib.WebServer.Example/Program.cs b/example/MaxLib.WebServer.Example/Program.cs index 143aa0f..2376d0e 100644 --- a/example/MaxLib.WebServer.Example/Program.cs +++ b/example/MaxLib.WebServer.Example/Program.cs @@ -1,5 +1,5 @@ -using System; -using System.Threading.Tasks; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using MaxLib.WebServer.Services; namespace MaxLib.WebServer.Example @@ -8,7 +8,7 @@ class Program { static async Task Main(string[] args) { - WebServerLog.LogAdded += WebServerLog_LogAdded; + WebServerLog.SetLoggerFactory(LoggerFactory.Create(builder => builder.AddSimpleConsole())); using var server = new Server(new WebServerSettings(8000, 5000)); // add services server.AddWebService(new HttpRequestParser()); @@ -19,10 +19,5 @@ static async Task Main(string[] args) // run server until cancel received await server.RunAsync(); } - - private static void WebServerLog_LogAdded(ServerLogItem item) - { - Console.WriteLine($"[{item.Date}] [{item.Type}] ({item.InfoType}) {item.SenderType}: {item.Information}"); - } } } diff --git a/example/MaxLib.WebServer.WebSocket.Echo/EchoConnection.cs b/example/MaxLib.WebServer.WebSocket.Echo/EchoConnection.cs index a5857d4..2bb2abe 100644 --- a/example/MaxLib.WebServer.WebSocket.Echo/EchoConnection.cs +++ b/example/MaxLib.WebServer.WebSocket.Echo/EchoConnection.cs @@ -1,4 +1,5 @@ -using System.IO; +using System; +using System.IO; using System.Threading.Tasks; #nullable enable @@ -7,14 +8,14 @@ namespace MaxLib.WebServer.WebSocket.Echo { public class EchoConnection : WebSocketConnection { - public EchoConnection(Stream networkStream) + public EchoConnection(Stream networkStream) : base(networkStream) { } protected override async Task ReceiveClose(CloseReason? reason, string? info) { - WebServerLog.Add(ServerLogType.Information, GetType(), "WebSocket", $"client close websocket ({reason}): {info}"); + Console.WriteLine($"client close websocket ({reason}): {info}"); if (!SendCloseSignal) await Close().ConfigureAwait(false); } diff --git a/example/MaxLib.WebServer.WebSocket.Echo/MaxLib.WebServer.WebSocket.Echo.csproj b/example/MaxLib.WebServer.WebSocket.Echo/MaxLib.WebServer.WebSocket.Echo.csproj index 5c7ceec..12b4127 100644 --- a/example/MaxLib.WebServer.WebSocket.Echo/MaxLib.WebServer.WebSocket.Echo.csproj +++ b/example/MaxLib.WebServer.WebSocket.Echo/MaxLib.WebServer.WebSocket.Echo.csproj @@ -2,11 +2,16 @@ Exe - net8.0 + net10.0 + + + + + diff --git a/example/MaxLib.WebServer.WebSocket.Echo/Program.cs b/example/MaxLib.WebServer.WebSocket.Echo/Program.cs index 95184d1..55f28a2 100644 --- a/example/MaxLib.WebServer.WebSocket.Echo/Program.cs +++ b/example/MaxLib.WebServer.WebSocket.Echo/Program.cs @@ -1,5 +1,5 @@ using MaxLib.WebServer.Services; -using System; +using Microsoft.Extensions.Logging; using System.Threading.Tasks; #nullable enable @@ -10,7 +10,7 @@ class Program { static async Task Main() { - WebServerLog.LogAdded += WebServerLog_LogAdded; + WebServerLog.SetLoggerFactory(LoggerFactory.Create(builder => builder.AddSimpleConsole())); using var server = new Server(new WebServerSettings(8000, 5000)); // add services server.AddWebService(new HttpRequestParser()); @@ -24,10 +24,5 @@ static async Task Main() // run server until cancel received await server.RunAsync(); } - - private static void WebServerLog_LogAdded(ServerLogItem item) - { - Console.WriteLine($"[{item.Date}] [{item.Type}] ({item.InfoType}) {item.SenderType}: {item.Information}"); - } } } diff --git a/tests/MaxLib.WebServer.Test/Api/Rest/TestRestActionEndpoint.cs b/tests/MaxLib.WebServer.Test/Api/Rest/TestRestActionEndpoint.cs deleted file mode 100644 index 33b738b..0000000 --- a/tests/MaxLib.WebServer.Test/Api/Rest/TestRestActionEndpoint.cs +++ /dev/null @@ -1,136 +0,0 @@ -using MaxLib.WebServer.Api.Rest; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; -using System.Collections.Generic; -using System.Threading.Tasks; - -namespace MaxLib.WebServer.Test.Api.Rest -{ - [Obsolete] - [TestClass] - public class TestRestActionEndpoint - { - class Methods - { - public static Task HandleDicSource(Dictionary args) - { - Assert.IsNotNull(args); - return Task.FromResult( - new HttpStringDataSource("handle-dic-source")); - } - - public static Task HandleFunc0Source() - { - return Task.FromResult( - new HttpStringDataSource("handle-func-0-source")); - } - - public static Task HandleFunc1Source(string arg1) - { - Assert.AreEqual("value-1", arg1); - return Task.FromResult( - new HttpStringDataSource("handle-func-1-source")); - } - - public static Task HandleFunc2Source(string arg1, string arg2) - { - Assert.AreEqual("value-1", arg1); - Assert.AreEqual("value-2", arg2); - return Task.FromResult( - new HttpStringDataSource("handle-func-2-source")); - } - - public static Task HandleFunc3Source(string arg1, string arg2, string arg3) - { - Assert.AreEqual("value-1", arg1); - Assert.AreEqual("value-2", arg2); - Assert.AreEqual("value-3", arg3); - return Task.FromResult( - new HttpStringDataSource("handle-func-3-source")); - } - - public static Task HandleFunc4Source(string arg1, string arg2, string arg3, string arg4) - { - Assert.AreEqual("value-1", arg1); - Assert.AreEqual("value-2", arg2); - Assert.AreEqual("value-3", arg3); - Assert.AreEqual("value-4", arg4); - return Task.FromResult( - new HttpStringDataSource("handle-func-4-source")); - } - } - - private async Task GetResult(RestActionEndpoint endpoint, string check, params (string, object)[] values) - { - var args = new Dictionary(); - foreach (var (key, value) in values) - args[key] = value; - var source = await endpoint.GetSource(args).ConfigureAwait(false); - Assert.IsTrue(source is HttpStringDataSource, "source is not a string source"); - var ds = (HttpStringDataSource)source; - Assert.AreEqual(check, ds.Data); - } - - [TestMethod] - public async Task TestDicSource() - { - var ep = RestActionEndpoint.Create(Methods.HandleDicSource); - await GetResult(ep, "handle-dic-source").ConfigureAwait(false); - } - - [TestMethod] - public async Task TestFunc0Source() - { - var ep = RestActionEndpoint.Create(Methods.HandleFunc0Source); - await GetResult(ep, "handle-func-0-source").ConfigureAwait(false); - } - - [TestMethod] - public async Task TestFunc1Source() - { - var ep = RestActionEndpoint.Create(Methods.HandleFunc1Source, "arg1"); - await GetResult(ep, "handle-func-1-source", - ("arg1", "value-1")); - } - - [TestMethod] - public async Task TestFunc2Source() - { - var ep = RestActionEndpoint.Create(Methods.HandleFunc2Source, "arg1", "arg2"); - await GetResult(ep, "handle-func-2-source", - ("arg2", "value-2"), - ("arg1", "value-1")); - } - - [TestMethod] - public async Task TestFunc3Source() - { - var ep = RestActionEndpoint.Create( - Methods.HandleFunc3Source, "arg1", "arg2", "arg3"); - await GetResult(ep, "handle-func-3-source", - ("arg2", "value-2"), - ("arg3", "value-3"), - ("arg1", "value-1")); - } - - [TestMethod] - public async Task TestFunc4Source() - { - var ep = RestActionEndpoint.Create( - new Func>( - Methods.HandleFunc4Source), - new string[] - { - "arg1", - "arg2", - "arg3", - "arg4", - }); - await GetResult(ep, "handle-func-4-source", - ("arg4", "value-4"), - ("arg2", "value-2"), - ("arg3", "value-3"), - ("arg1", "value-1")); - } - } -} diff --git a/tests/MaxLib.WebServer.Test/Api/Rest/TestRestApiFactory.cs b/tests/MaxLib.WebServer.Test/Api/Rest/TestRestApiFactory.cs deleted file mode 100644 index 46003a8..0000000 --- a/tests/MaxLib.WebServer.Test/Api/Rest/TestRestApiFactory.cs +++ /dev/null @@ -1,209 +0,0 @@ -using System.Text; -using MaxLib.WebServer.Api.Rest; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System.Collections.Generic; -using System; - -namespace MaxLib.WebServer.Test.Api.Rest -{ - [Obsolete] - [TestClass] - public class TestRestApiFactory - { - ApiRuleFactory fact; - RestQueryArgs args; - - [TestInitialize] - public void Init() - { - fact = new ApiRuleFactory(); - args = new RestQueryArgs( - "localhost", - new[] { "foo", "bar", "0", "1" }, - new Dictionary - { - { "foo", "bar" }, - { "baz", "7" }, - }, - new HttpPost( - new WebProgressTask(), - Encoding.UTF8.GetBytes("a=1&b=2"), - MimeType.ApplicationXWwwFromUrlencoded), - null - ); - } - - [TestMethod] - public void TestUrlConstant() - { - var rule = fact.UrlConstant("foo"); - Assert.IsTrue(rule.Check(args), "test: foo"); - - rule = fact.UrlConstant("Bar", true, 1); - Assert.IsTrue(rule.Check(args), "test: bar"); - - rule = fact.UrlConstant("baz"); - Assert.IsFalse(rule.Check(args), "test: baz"); - } - - [TestMethod] - public void TestUrlArgument() - { - var rule = fact.UrlArgument("num0", int.TryParse, 2); - Assert.IsTrue(rule.Check(args), "test:num0"); - Assert.AreEqual(0, args.ParsedArguments["num0"]); - - rule = fact.UrlArgument("num1", int.TryParse, 3); - Assert.IsTrue(rule.Check(args), "test:num1"); - Assert.AreEqual(1, args.ParsedArguments["num1"]); - - rule = fact.UrlArgument("num2", int.TryParse, 1); - Assert.IsFalse(rule.Check(args), "test:num2"); - Assert.IsFalse(args.ParsedArguments.ContainsKey("num2"), "check:num2"); - - var rule2 = fact.UrlArgument("arg", 1); - Assert.IsTrue(rule2.Check(args), "test:arg"); - Assert.AreEqual("bar", args.ParsedArguments["arg"]); - } - - [TestMethod] - public void TestMaxLength() - { - var rule = fact.MaxLength(4); - Assert.IsTrue(rule.Check(args), "test:4"); - - rule = fact.MaxLength(3); - Assert.IsFalse(rule.Check(args), "test:3"); - - rule = fact.MaxLength(5); - Assert.IsTrue(rule.Check(args), "test:5"); - } - - [TestMethod] - public void TestKeyExists() - { - var rule = fact.KeyExists("foo"); - Assert.IsTrue(rule.Check(args), "test:1"); - - rule = fact.KeyExists("bar"); - Assert.IsFalse(rule.Check(args), "test:2"); - } - - [TestMethod] - public void TestGetArgument() - { - var rule = fact.GetArgument("baz", int.TryParse); - Assert.IsTrue(rule.Check(args), "test:1"); - Assert.AreEqual(7, args.ParsedArguments["baz"]); - - rule = fact.GetArgument("foo", int.TryParse); - Assert.IsFalse(rule.Check(args), "test:2"); - Assert.IsFalse(args.ParsedArguments.ContainsKey("foo")); - - var rule2 = fact.GetArgument("foo"); - Assert.IsTrue(rule2.Check(args), "test:3"); - Assert.AreEqual("bar", args.ParsedArguments["foo"]); - } - - [TestMethod] - public void TestGroup() - { - var rule = fact.Group( - fact.UrlConstant("foo"), - fact.KeyExists("baz")); - Assert.IsTrue(rule.Check(args), "test:1"); - - rule = fact.Group( - fact.Optional(fact.UrlConstant("bar")), - fact.KeyExists("baz")); - Assert.IsTrue(rule.Check(args), "test:2"); - - rule = fact.Group( - fact.UrlConstant("foo"), - fact.Optional(fact.KeyExists("bar"))); - Assert.IsTrue(rule.Check(args), "test:3"); - - rule = fact.Group( - fact.UrlConstant("bar"), - fact.KeyExists("baz")); - Assert.IsFalse(rule.Check(args), "test:4"); - - rule = fact.Group( - fact.UrlConstant("foo"), - fact.KeyExists("bar")); - Assert.IsFalse(rule.Check(args), "test:5"); - } - - [TestMethod] - public void TestLocation() - { - var rule = fact.Location( - fact.UrlConstant("foo"), - fact.UrlConstant("bar")); - Assert.IsTrue(rule.Check(args), "test:1"); - - rule = fact.Location( - fact.UrlConstant("foo"), - fact.UrlConstant("bar"), - fact.UrlConstant("0"), - fact.UrlArgument("var", int.TryParse)); - Assert.IsTrue(rule.Check(args), "test:2"); - Assert.AreEqual(1, args.ParsedArguments["var"]); - - args.ParsedArguments.Clear(); - rule = fact.Location( - fact.UrlConstant("foo"), - fact.UrlConstant("bar"), - fact.UrlConstant("0"), - fact.UrlArgument("var", int.TryParse), - fact.MaxLength()); - Assert.IsTrue(rule.Check(args), "test:2"); - Assert.AreEqual(1, args.ParsedArguments["var"]); - } - - [TestMethod] - public void TestOptional() - { - var rule = fact.Optional(fact.UrlConstant("foo")); - Assert.IsTrue(rule.Check(args), "test:1"); - - rule = fact.Optional(fact.UrlConstant("baz")); - Assert.IsFalse(rule.Check(args), "test:2"); - } - - [TestMethod] - public void TestConditional() - { - var rule = fact.Conditional( - fact.UrlConstant("foo"), - fact.UrlArgument("var", int.TryParse, 2), - fact.UrlArgument("var", int.TryParse, 3)); - Assert.IsTrue(rule.Check(args), "test:1"); - Assert.AreEqual(0, args.ParsedArguments["var"], "check:1"); - - args.ParsedArguments.Clear(); - rule = fact.Conditional( - fact.UrlConstant("bar"), - fact.UrlArgument("var", int.TryParse, 2), - fact.UrlArgument("var", int.TryParse, 3)); - Assert.IsTrue(rule.Check(args), "test:2"); - Assert.AreEqual(1, args.ParsedArguments["var"], "check:2"); - - args.ParsedArguments.Clear(); - rule = fact.Conditional( - fact.UrlConstant("foo"), - fact.UrlArgument("var", int.TryParse, 1), - fact.UrlArgument("var", int.TryParse, 3)); - Assert.IsFalse(rule.Check(args), "test:3"); - Assert.IsFalse(args.ParsedArguments.ContainsKey("var"), "check:3"); - - args.ParsedArguments.Clear(); - rule = fact.Conditional( - fact.UrlConstant("bar"), - fact.UrlArgument("var", int.TryParse, 2), - fact.UrlArgument("var", int.TryParse, 1)); - Assert.IsFalse(rule.Check(args), "test:4"); - Assert.IsFalse(args.ParsedArguments.ContainsKey("var"), "check:4"); - } - } -} diff --git a/tests/MaxLib.WebServer.Test/Builder/Debugger/ReportFixtures.cs b/tests/MaxLib.WebServer.Test/Builder/Debugger/ReportFixtures.cs new file mode 100644 index 0000000..80abb2e --- /dev/null +++ b/tests/MaxLib.WebServer.Test/Builder/Debugger/ReportFixtures.cs @@ -0,0 +1,188 @@ +using System; +using MaxLib.WebServer.Builder; +using MaxLib.WebServer.Builder.Tools; + +#nullable enable + +namespace MaxLib.WebServer.Test.Builder.Debugger +{ + [Ignore] + public class IgnoredTypeFixture : Service + { + [Path("/ignored")] + public void M() { } + } + + public abstract class AbstractTypeFixture : Service + { + [Path("/abstract-type")] + public void M() { } + } + + public class GenericTypeFixture : Service + { + [Path("/generic-type")] + public void M() { } + } + + public class NoConstructorTypeFixture : Service + { + public NoConstructorTypeFixture(int _) { } + + [Path("/no-ctor")] + public void M() { } + } + + public class ThrowingConstructorFixture : Service + { + public ThrowingConstructorFixture() => throw new InvalidOperationException("boom"); + + [Path("/throwing")] + public void M() { } + } + + public class HealthyFixture : Service + { + [Path("/healthy")] + public HttpDataSource M() => new HttpStringDataSource("ok"); + } + + public class NestedTypeFixture : Service + { + [Path("/nested-outer")] + public void Outer() { } + + public class Inner : Service + { + [Path("/nested-inner")] + public HttpDataSource M() => new HttpStringDataSource("inner"); + } + } + + public abstract class AbstractMethodFixture : Service + { + [Path("/abstract-method")] + public abstract void M(); + } + + public class NoParameterlessCtorConverter : IDataConverter + { + public NoParameterlessCtorConverter(int _) { } + + public Func? GetConverter(Type data) => null; + } + + public class MethodFixtures : Service + { + [Ignore] + public void IgnoredMethod() { } + + internal void NotPublicMethod() { } + + public void GenericMethod() { } + + public void ParamNoConverterMethod([Var] System.Text.StringBuilder sb) { } + + public void WorkingParamMethod([Var] string x) { } + + public void ParamNoCoreConverterMethod(string plain) { } + + public void ParamMissingConverterInstanceMethod( + [Converter(typeof(IConverter))][Var] string x + ) + { } + + [return: DataConverter(typeof(string))] + public string ResultInvalidConverterTypeMethod() => "x"; + + [return: DataConverter(typeof(NoParameterlessCtorConverter))] + public string ResultCannotCreateConverterInstanceMethod() => "x"; + + public int ResultNoConverterMethod() => 1; + } + + public class DupHighFixture : Service + { + [Path("/dup")] + [Priority(WebServicePriority.High)] + public HttpDataSource M() => new HttpStringDataSource("high"); + } + + public class DupLowFixture : Service + { + [Path("/dup")] + [Priority(WebServicePriority.Low)] + public HttpDataSource M() => new HttpStringDataSource("low"); + } + + public class GetOnlyFixture : Service + { + [Path("/only-get")] + [Method("GET")] + public HttpDataSource M() => new HttpStringDataSource("got"); + } + + [Path("/grouped", Prefix = true)] + public class GroupedFixture : Service + { + [Path("/grouped/only")] + public HttpDataSource M() => new HttpStringDataSource("grouped"); + } + + [Path("/inner-dup", Prefix = true)] + public class InnerDupFixture : Service + { + [Path("/inner-dup/x")] + [Priority(WebServicePriority.High)] + public HttpDataSource A() => new HttpStringDataSource("a"); + + [Path("/inner-dup/x")] + [Priority(WebServicePriority.Low)] + public HttpDataSource B() => new HttpStringDataSource("b"); + } + + [Path("/none-matches", Prefix = true)] + public class NoMatchingChildFixture : Service + { + [Path("/none-matches/only")] + [Method("POST")] + public HttpDataSource M() => new HttpStringDataSource("x"); + } + + public class CoreParamFixture : Service + { + [Path("/core-param")] + public HttpDataSource M(System.Net.IPEndPoint endpoint) => new HttpStringDataSource(endpoint.ToString()); + } + + public class ConversionFailureFixture : Service + { + [Path("/conv-fail")] + public HttpDataSource M([Get] int id) => new HttpStringDataSource(id.ToString(System.Globalization.CultureInfo.InvariantCulture)); + } + + public sealed class AlwaysFailRuleAttribute : RuleAttributeBase + { + public override bool CanWorkWith(WebProgressTask task, System.Collections.Generic.Dictionary vars) + => false; + + public override string ToString() => "AlwaysFail"; + } + + public class NonExplainableRuleFixture : Service + { + [AlwaysFailRule] + [Path("/non-explainable")] + public HttpDataSource M() => new HttpStringDataSource("x"); + } + + public class AlwaysRejectService : WebService + { + public AlwaysRejectService() : base(ServerStage.CreateDocument) { } + + public override bool CanWorkWith(WebProgressTask task) => false; + + public override System.Threading.Tasks.Task ProgressTask(WebProgressTask task) + => System.Threading.Tasks.Task.CompletedTask; + } +} diff --git a/tests/MaxLib.WebServer.Test/Builder/Debugger/TestBuildReport.cs b/tests/MaxLib.WebServer.Test/Builder/Debugger/TestBuildReport.cs new file mode 100644 index 0000000..cda7caa --- /dev/null +++ b/tests/MaxLib.WebServer.Test/Builder/Debugger/TestBuildReport.cs @@ -0,0 +1,241 @@ +using System.Linq; +using System.Reflection; +using MaxLib.WebServer.Builder; +using MaxLib.WebServer.Builder.Debugger; +using MaxLib.WebServer.Builder.Tools; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +#nullable enable + +namespace MaxLib.WebServer.Test.Builder.Debugger +{ + [TestClass] + public class TestBuildReport + { + [TestMethod] + public void TestTypeIgnoredByAttribute() + { + var group = Generator.GenerateClass(typeof(IgnoredTypeFixture), out var report); + Assert.IsNull(group); + Assert.AreEqual(BuildReportStatus.Ignored, report.Status); + Assert.AreEqual(BuildReasonCode.TypeIgnoredByAttribute, report.Reason); + + // the plain (no-report) overload keeps behaving identically. + Assert.IsNull(Generator.GenerateClass(typeof(IgnoredTypeFixture))); + } + + [TestMethod] + public void TestTypeAbstract() + { + var group = Generator.GenerateClass(typeof(AbstractTypeFixture), out var report); + Assert.IsNull(group); + Assert.AreEqual(BuildReportStatus.Ignored, report.Status); + Assert.AreEqual(BuildReasonCode.TypeAbstract, report.Reason); + } + + [TestMethod] + public void TestTypeGeneric() + { + var group = Generator.GenerateClass(typeof(GenericTypeFixture), out var report); + Assert.IsNull(group); + Assert.AreEqual(BuildReportStatus.Ignored, report.Status); + Assert.AreEqual(BuildReasonCode.TypeGeneric, report.Reason); + } + + [TestMethod] + public void TestTypeNoConstructor() + { + var group = Generator.GenerateClass(typeof(NoConstructorTypeFixture), out var report); + Assert.IsNull(group); + Assert.AreEqual(BuildReportStatus.Ignored, report.Status); + Assert.AreEqual(BuildReasonCode.TypeNoConstructor, report.Reason); + } + + [TestMethod] + public void TestTypeAccepted() + { + var group = Generator.GenerateClass(typeof(HealthyFixture), out var report); + Assert.IsNotNull(group); + Assert.AreEqual(BuildReportStatus.Accepted, report.Status); + Assert.AreEqual(BuildReasonCode.Accepted, report.Reason); + Assert.AreEqual(1, report.Methods.Count(m => m.Name == "M")); + var methodReport = report.Methods.Single(m => m.Name == "M"); + Assert.AreEqual(BuildReportStatus.Accepted, methodReport.Status); + Assert.IsNotNull(methodReport.Result); + } + + [TestMethod] + public void TestMethodIgnoredByAttribute() + { + var method = Generator.GenerateMethod( + typeof(MethodFixtures).GetMethod("IgnoredMethod")!, out var report + ); + Assert.IsNull(method); + Assert.AreEqual(BuildReportStatus.Ignored, report.Status); + Assert.AreEqual(BuildReasonCode.MethodIgnoredByAttribute, report.Reason); + } + + [TestMethod] + public void TestMethodNotPublic() + { + var methodInfo = typeof(MethodFixtures).GetMethod("NotPublicMethod", + BindingFlags.NonPublic | BindingFlags.Instance + )!; + var method = Generator.GenerateMethod(methodInfo, out var report); + Assert.IsNull(method); + Assert.AreEqual(BuildReportStatus.Ignored, report.Status); + Assert.AreEqual(BuildReasonCode.MethodNotPublic, report.Reason); + } + + [TestMethod] + public void TestMethodGeneric() + { + var method = Generator.GenerateMethod( + typeof(MethodFixtures).GetMethod("GenericMethod")!, out var report + ); + Assert.IsNull(method); + Assert.AreEqual(BuildReportStatus.Ignored, report.Status); + Assert.AreEqual(BuildReasonCode.MethodGeneric, report.Reason); + } + + [TestMethod] + public void TestMethodAbstract() + { + var method = Generator.GenerateMethod( + typeof(AbstractMethodFixture).GetMethod("M")!, out var report + ); + Assert.IsNull(method); + Assert.AreEqual(BuildReportStatus.Ignored, report.Status); + Assert.AreEqual(BuildReasonCode.MethodAbstract, report.Reason); + } + + [TestMethod] + public void TestMethodDeclaredInObject() + { + var method = Generator.GenerateMethod( + typeof(HealthyFixture).GetMethod("ToString")!, out var report + ); + Assert.IsNull(method); + Assert.AreEqual(BuildReportStatus.Ignored, report.Status); + Assert.AreEqual(BuildReasonCode.MethodDeclaredInObject, report.Reason); + } + + [TestMethod] + public void TestParamNoConverterFound() + { + var method = Generator.GenerateMethod( + typeof(MethodFixtures).GetMethod("ParamNoConverterMethod")!, out var report + ); + Assert.IsNull(method); + Assert.AreEqual(BuildReportStatus.Failed, report.Status); + Assert.AreEqual(BuildReasonCode.ParamNoConverterFound, report.Reason); + Assert.AreEqual(1, report.Parameters.Count); + Assert.AreEqual(BuildReasonCode.ParamNoConverterFound, report.Parameters[0].Reason); + } + + [TestMethod] + public void TestParamNoCoreConverterFound() + { + var method = Generator.GenerateMethod( + typeof(MethodFixtures).GetMethod("ParamNoCoreConverterMethod")!, out var report + ); + Assert.IsNull(method); + Assert.AreEqual(BuildReportStatus.Failed, report.Status); + Assert.AreEqual(BuildReasonCode.ParamNoCoreConverterFound, report.Reason); + } + + [TestMethod] + public void TestParamMissingConverterInstance() + { + var method = Generator.GenerateMethod( + typeof(MethodFixtures).GetMethod("ParamMissingConverterInstanceMethod")!, out var report + ); + Assert.IsNull(method); + Assert.AreEqual(BuildReportStatus.Failed, report.Status); + Assert.AreEqual(BuildReasonCode.ParamMissingConverterInstance, report.Reason); + } + + [TestMethod] + public void TestResultInvalidConverterType() + { + var method = Generator.GenerateMethod( + typeof(MethodFixtures).GetMethod("ResultInvalidConverterTypeMethod")!, out var report + ); + Assert.IsNull(method); + Assert.AreEqual(BuildReportStatus.Failed, report.Status); + Assert.AreEqual(BuildReasonCode.ResultInvalidConverterType, report.Reason); + Assert.IsNotNull(report.Result); + Assert.AreEqual(BuildReasonCode.ResultInvalidConverterType, report.Result!.Reason); + } + + [TestMethod] + public void TestResultCannotCreateConverterInstance() + { + var method = Generator.GenerateMethod( + typeof(MethodFixtures).GetMethod("ResultCannotCreateConverterInstanceMethod")!, out var report + ); + Assert.IsNull(method); + Assert.AreEqual(BuildReportStatus.Failed, report.Status); + Assert.AreEqual(BuildReasonCode.ResultCannotCreateConverterInstance, report.Reason); + } + + [TestMethod] + public void TestResultNoConverter() + { + var method = Generator.GenerateMethod( + typeof(MethodFixtures).GetMethod("ResultNoConverterMethod")!, out var report + ); + Assert.IsNull(method); + Assert.AreEqual(BuildReportStatus.Failed, report.Status); + Assert.AreEqual(BuildReasonCode.ResultNoConverter, report.Reason); + } + + [TestMethod] + public void TestGenerateParameterDirectOutOverload() + { + var method = typeof(MethodFixtures).GetMethod("WorkingParamMethod")!; + var parameter = Generator.GenerateParameter(method, method.GetParameters()[0], out var report); + Assert.IsNotNull(parameter); + Assert.AreEqual(BuildReportStatus.Accepted, report.Status); + Assert.AreEqual("x", report.Name); + } + + [TestMethod] + public void TestGenerateResultDirectOutOverload() + { + var method = typeof(HealthyFixture).GetMethod("M")!; + var result = Generator.GenerateResult(method, out var report); + Assert.IsNotNull(result); + Assert.AreEqual(BuildReportStatus.Accepted, report.Status); + } + + [TestMethod] + public void TestNestedTypeIsReported() + { + var group = Generator.GenerateClass(typeof(NestedTypeFixture), out var report); + Assert.IsNotNull(group); + var nested = report.NestedTypes.Single(n => n.Name == nameof(NestedTypeFixture.Inner)); + Assert.AreEqual(BuildReportStatus.Accepted, nested.Status); + Assert.IsTrue(nested.Methods.Any(m => m.Name == "M" && m.Status == BuildReportStatus.Accepted)); + } + + [TestMethod] + public void TestBuildReportWalkAndCount() + { + // HealthyFixture.M() succeeds, but GetMethods() also picks up inherited public + // methods like ToString()/Dispose() which are ignored as MethodDeclaredInObject. + Service.Build(typeof(HealthyFixture), out var buildReport); + var report = buildReport.Roots.Single(); + var walked = buildReport.Walk().ToList(); + var methodNode = report.Methods.Single(m => m.Name == "M"); + Assert.AreEqual(BuildReportStatus.Accepted, methodNode.Status); + CollectionAssert.Contains(walked, methodNode); + CollectionAssert.Contains(walked, methodNode.Result); + // type node + M itself are Accepted + Assert.IsTrue(buildReport.CountByStatus(BuildReportStatus.Accepted) >= 2); + // inherited object/Service methods are ignored as MethodDeclaredInObject + Assert.IsTrue(buildReport.CountByStatus(BuildReportStatus.Ignored) >= 1); + Assert.AreEqual(0, buildReport.CountByStatus(BuildReportStatus.Failed)); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/Builder/Debugger/TestBuildReportGapFixes.cs b/tests/MaxLib.WebServer.Test/Builder/Debugger/TestBuildReportGapFixes.cs new file mode 100644 index 0000000..13c2d3f --- /dev/null +++ b/tests/MaxLib.WebServer.Test/Builder/Debugger/TestBuildReportGapFixes.cs @@ -0,0 +1,98 @@ +using System.Linq; +using System.Reflection; +using MaxLib.WebServer.Builder; +using MaxLib.WebServer.Builder.Debugger; +using MaxLib.WebServer.Builder.Tools; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +#nullable enable + +namespace MaxLib.WebServer.Test.Builder.Debugger +{ + /// + /// Verifies that an -only skip, a constructor exception, and a + /// non- type are each attributed correctly in , and that a constructor exception in one type does not abort the rest of the scan. + /// + [TestClass] + public class TestBuildReportGapFixes + { + [TestMethod] + public void TestIgnoredSkipIsAttributedEvenWhenNotLogged() + { + // the default GeneratorLogFlag configuration doesn't include the "ignored by + // attribute" flags (they are considered intentional) - the report must still surface + // the reason regardless of the log-gating configuration. + Assert.AreNotEqual( + GeneratorLogFlag.TypeIgnoredByAttribute, + Generator.LogBuildWarnings & GeneratorLogFlag.TypeIgnoredByAttribute + ); + + var group = Generator.GenerateClass(typeof(IgnoredTypeFixture), out var typeReport); + Assert.IsNull(group); + Assert.AreEqual(BuildReasonCode.TypeIgnoredByAttribute, typeReport.Reason); + + var method = Generator.GenerateMethod( + typeof(MethodFixtures).GetMethod("IgnoredMethod")!, out var methodReport + ); + Assert.IsNull(method); + Assert.AreEqual(BuildReasonCode.MethodIgnoredByAttribute, methodReport.Reason); + } + + [TestMethod] + public void TestConstructorExceptionIsCaughtAndAttributed() + { + var group = Generator.GenerateClass(typeof(ThrowingConstructorFixture), out var report); + + // the type itself is still a valid (empty) service group - only the one broken + // method failed, it didn't abort the whole type. + Assert.IsNotNull(group); + Assert.AreEqual(0, group!.Count); + Assert.AreEqual(BuildReportStatus.Accepted, report.Status); + + var methodReport = report.Methods.Single(m => m.Name == "M"); + Assert.AreEqual(BuildReportStatus.Failed, methodReport.Status); + Assert.AreEqual(BuildReasonCode.MethodConstructorThrew, methodReport.Reason); + Assert.AreEqual("boom", methodReport.ExceptionMessage); + Assert.IsNotNull(methodReport.Exception); + } + + [TestMethod] + public void TestConstructorExceptionDoesNotAbortAssemblyScan() + { + var result = Service.Build(Assembly.GetExecutingAssembly(), out var report); + Assert.IsNotNull(result); + + var throwingNode = report.Roots.Single(r => r.TypeFullName == typeof(ThrowingConstructorFixture).FullName); + Assert.AreEqual(BuildReportStatus.Accepted, throwingNode.Status); + var throwingMethod = throwingNode.Methods.Single(m => m.Name == "M"); + Assert.AreEqual(BuildReasonCode.MethodConstructorThrew, throwingMethod.Reason); + + // a healthy, unrelated service in the same assembly still builds successfully. + var healthyNode = report.Roots.Single(r => r.TypeFullName == typeof(HealthyFixture).FullName); + Assert.AreEqual(BuildReportStatus.Accepted, healthyNode.Status); + Assert.IsTrue(healthyNode.Methods.Any(m => m.Name == "M" && m.Status == BuildReportStatus.Accepted)); + } + + [TestMethod] + public void TestNonServiceTypeIsAttributedForSingleTypeBuild() + { + var result = Service.Build(typeof(string), out var report); + Assert.IsNull(result); + Assert.AreEqual(1, report.Roots.Count); + Assert.AreEqual(BuildReportStatus.Failed, report.Roots[0].Status); + Assert.AreEqual(BuildReasonCode.TypeNotService, report.Roots[0].Reason); + } + + [TestMethod] + public void TestNonServiceTypesAreOnlyCountedForBulkScans() + { + Service.Build(Assembly.GetExecutingAssembly(), out var report); + + // the test assembly contains many non-Service classes (test classes, fixtures, ...) + // - they must not flood Roots with a TypeNotService node each. + Assert.IsTrue(report.SkippedNonServiceTypeCount > 0); + Assert.IsFalse(report.Roots.Any(r => r.Reason == BuildReasonCode.TypeNotService)); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/Builder/Debugger/TestDebuggerService.cs b/tests/MaxLib.WebServer.Test/Builder/Debugger/TestDebuggerService.cs new file mode 100644 index 0000000..3d356a9 --- /dev/null +++ b/tests/MaxLib.WebServer.Test/Builder/Debugger/TestDebuggerService.cs @@ -0,0 +1,131 @@ +using System.Linq; +using System.Text.Json; +using MaxLib.WebServer.Builder; +using MaxLib.WebServer.Builder.Debugger; +using MaxLib.WebServer.Builder.Tools; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +#nullable enable + +namespace MaxLib.WebServer.Test.Builder.Debugger +{ + [TestClass] + public class TestDebuggerService + { + private static (Server server, DebuggerService debugger) CreateServer() + { + var server = new Server(new WebServerSettings(12345, 0)); + server.AddWebService(Generator.GenerateMethod(typeof(GetOnlyFixture).GetMethod("M")!)!); + Service.Build(typeof(HealthyFixture), out var report); + var debugger = new DebuggerService(server, report); + server.AddWebService(debugger); + return (server, debugger); + } + + private static WebProgressTask MakeTask(string url) + { + var task = new WebProgressTask(); + task.Request.Url = url; + return task; + } + + private static string GetBody(WebProgressTask task) + { + Assert.AreEqual(1, task.Document.DataSources.Count); + return Assert.IsInstanceOfType(task.Document.DataSources[0]).Data; + } + + [TestMethod] + public void TestCanWorkWithMatchesOnlyOwnSubTree() + { + var (_, debugger) = CreateServer(); + + Assert.IsTrue(debugger.CanWorkWith(MakeTask("/_debugger"))); + Assert.IsTrue(debugger.CanWorkWith(MakeTask("/_debugger/"))); + Assert.IsTrue(debugger.CanWorkWith(MakeTask("/_debugger/api/build-report"))); + Assert.IsFalse(debugger.CanWorkWith(MakeTask("/_debuggerother"))); + Assert.IsFalse(debugger.CanWorkWith(MakeTask("/other"))); + } + + [TestMethod] + public async System.Threading.Tasks.Task TestHtmlShellIsServed() + { + var (_, debugger) = CreateServer(); + var task = MakeTask("/_debugger/"); + await debugger.ProgressTask(task); + + Assert.AreEqual(HttpStateCode.OK, task.Response.StatusCode); + Assert.AreEqual(MimeType.TextHtml, task.Document.DataSources[0].MimeType); + var body = GetBody(task); + StringAssert.Contains(body, "__debuggerBasePath"); + StringAssert.Contains(body, "/api/build-report"); + } + + [TestMethod] + public async System.Threading.Tasks.Task TestBuildReportJsonIsServed() + { + var (_, debugger) = CreateServer(); + var task = MakeTask("/_debugger/api/build-report"); + await debugger.ProgressTask(task); + + Assert.AreEqual(MimeType.ApplicationJson, task.Document.DataSources[0].MimeType); + var body = GetBody(task); + using var doc = JsonDocument.Parse(body); + var roots = doc.RootElement.GetProperty("roots"); + Assert.AreEqual(1, roots.GetArrayLength()); + Assert.AreEqual(nameof(HealthyFixture), roots[0].GetProperty("name").GetString()); + } + + [TestMethod] + public async System.Threading.Tasks.Task TestRouteJsonIsServedForOneStage() + { + var (_, debugger) = CreateServer(); + var task = MakeTask("/_debugger/api/route?method=GET&path=/only-get&stage=CreateDocument"); + await debugger.ProgressTask(task); + + var body = GetBody(task); + using var doc = JsonDocument.Parse(body); + Assert.AreEqual(1, doc.RootElement.GetArrayLength()); + Assert.AreEqual("createDocument", doc.RootElement[0].GetProperty("stage").GetString()); + Assert.AreEqual("GetOnlyFixture.M()", doc.RootElement[0].GetProperty("matchedLabel").GetString()); + } + + [TestMethod] + public async System.Threading.Tasks.Task TestRouteJsonSimulatesAllStagesByDefault() + { + var (_, debugger) = CreateServer(); + var task = MakeTask("/_debugger/api/route?method=GET&path=/only-get"); + await debugger.ProgressTask(task); + + var body = GetBody(task); + using var doc = JsonDocument.Parse(body); + Assert.AreEqual(7, doc.RootElement.GetArrayLength()); + var createDocument = doc.RootElement.EnumerateArray() + .Single(e => e.GetProperty("stage").GetString() == "createDocument"); + Assert.AreEqual("GetOnlyFixture.M()", createDocument.GetProperty("matchedLabel").GetString()); + } + + [TestMethod] + public async System.Threading.Tasks.Task TestUnknownSubPathIsNotFound() + { + var (_, debugger) = CreateServer(); + var task = MakeTask("/_debugger/api/does-not-exist"); + await debugger.ProgressTask(task); + + Assert.AreEqual(HttpStateCode.NotFound, task.Response.StatusCode); + } + + [TestMethod] + public async System.Threading.Tasks.Task TestMissingBuildReportServesEmptyReport() + { + var server = new Server(new WebServerSettings(12346, 0)); + var debugger = new DebuggerService(server); + var task = MakeTask("/_debugger/api/build-report"); + await debugger.ProgressTask(task); + + var body = GetBody(task); + using var doc = JsonDocument.Parse(body); + Assert.AreEqual(0, doc.RootElement.GetProperty("roots").GetArrayLength()); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/Builder/Debugger/TestRoutingDryRun.cs b/tests/MaxLib.WebServer.Test/Builder/Debugger/TestRoutingDryRun.cs new file mode 100644 index 0000000..8781341 --- /dev/null +++ b/tests/MaxLib.WebServer.Test/Builder/Debugger/TestRoutingDryRun.cs @@ -0,0 +1,198 @@ +using System.Linq; +using MaxLib.WebServer.Builder.Debugger; +using MaxLib.WebServer.Builder.Tools; +using MaxLib.WebServer.Services; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +#nullable enable + +namespace MaxLib.WebServer.Test.Builder.Debugger +{ + [TestClass] + public class TestRoutingDryRun + { + [TestMethod] + public void TestHigherPriorityWinsAndLowerIsNotReached() + { + var group = new WebServiceGroup(ServerStage.CreateDocument); + // added in reverse-priority order to make sure the dry run relies on the group's + // own priority ordering, not insertion order. + group.Add(Generator.GenerateMethod(typeof(DupLowFixture).GetMethod("M")!)!); + group.Add(Generator.GenerateMethod(typeof(DupHighFixture).GetMethod("M")!)!); + + var report = RoutingDryRun.Run(group, "GET", "/dup"); + + Assert.AreEqual(2, report.Services.Count); + Assert.AreEqual(RoutingOutcome.Accepted, report.Services[0].Outcome); + Assert.AreEqual(RoutingOutcome.NotReached, report.Services[1].Outcome); + Assert.AreEqual("DupHighFixture.M()", report.MatchedLabel); + } + + [TestMethod] + public void TestMethodMismatchIsExplained() + { + var group = new WebServiceGroup(ServerStage.CreateDocument); + group.Add(Generator.GenerateMethod(typeof(GetOnlyFixture).GetMethod("M")!)!); + + var report = RoutingDryRun.Run(group, "POST", "/only-get"); + + Assert.AreEqual(RoutingOutcome.Rejected, report.Services[0].Outcome); + Assert.IsTrue(report.Services[0].Reasons.Any(r => r.Contains("GET") && r.Contains("POST"))); + Assert.IsNull(report.MatchedLabel); + } + + [TestMethod] + public void TestPathMismatchIsExplained() + { + var group = new WebServiceGroup(ServerStage.CreateDocument); + group.Add(Generator.GenerateMethod(typeof(GetOnlyFixture).GetMethod("M")!)!); + + var report = RoutingDryRun.Run(group, "GET", "/does-not-exist"); + + Assert.AreEqual(RoutingOutcome.Rejected, report.Services[0].Outcome); + Assert.IsTrue(report.Services[0].Reasons.Count > 0); + } + + [TestMethod] + public void TestUnresolvableParameterIsExplained() + { + var group = new WebServiceGroup(ServerStage.CreateDocument); + group.Add(Generator.GenerateMethod(typeof(MethodFixtures).GetMethod("WorkingParamMethod")!)!); + + // nothing provides the "x" variable the [Var] parameter needs. + var report = RoutingDryRun.Run(group, "GET", "/"); + + Assert.AreEqual(RoutingOutcome.Rejected, report.Services[0].Outcome); + Assert.IsTrue(report.Services[0].Reasons.Any(r => r.Contains("'x'"))); + } + + [TestMethod] + public void TestServiceGroupTraversal() + { + var group = new WebServiceGroup(ServerStage.CreateDocument); + group.Add(Generator.GenerateClass(typeof(GroupedFixture))!); + + var accepted = RoutingDryRun.Run(group, "GET", "/grouped/only"); + Assert.AreEqual(RoutingOutcome.Accepted, accepted.Services[0].Outcome); + Assert.AreEqual(1, accepted.Services[0].Children.Count); + Assert.AreEqual(RoutingOutcome.Accepted, accepted.Services[0].Children[0].Outcome); + Assert.AreEqual("GroupedFixture.M()", accepted.MatchedLabel); + + var rejected = RoutingDryRun.Run(group, "GET", "/elsewhere"); + Assert.AreEqual(RoutingOutcome.Rejected, rejected.Services[0].Outcome); + // the class-level rule already failed, so the nested method was never evaluated. + Assert.AreEqual(0, rejected.Services[0].Children.Count); + Assert.IsTrue(rejected.Services[0].Reasons.Count > 0); + } + + [TestMethod] + public void TestGenericFallbackService() + { + var group = new WebServiceGroup(ServerStage.CreateDocument); + group.Add(Generator.GenerateMethod(typeof(GetOnlyFixture).GetMethod("M")!)!); + group.Add(new Http404Service()); + + var report = RoutingDryRun.Run(group, "POST", "/only-get"); + + Assert.AreEqual(RoutingOutcome.Rejected, report.Services[0].Outcome); + Assert.AreEqual(RoutingOutcome.Accepted, report.Services[1].Outcome); + Assert.AreEqual(nameof(Http404Service), report.MatchedLabel); + } + + [TestMethod] + public void TestGenericFallbackServiceRejection() + { + var group = new WebServiceGroup(ServerStage.CreateDocument); + group.Add(new AlwaysRejectService()); + + var report = RoutingDryRun.Run(group, "GET", "/"); + + Assert.AreEqual(RoutingOutcome.Rejected, report.Services[0].Outcome); + Assert.IsTrue(report.Services[0].Reasons.Contains("CanWorkWith() returned false")); + } + + [TestMethod] + public void TestHeadersArePassedToTheSyntheticRequest() + { + var group = new WebServiceGroup(ServerStage.CreateDocument); + group.Add(new Http404Service()); + + var report = RoutingDryRun.Run(group, "GET", "/", new System.Collections.Generic.Dictionary + { + ["X-Test"] = "value", + }); + + Assert.AreEqual(RoutingOutcome.Accepted, report.Services[0].Outcome); + } + + [TestMethod] + public void TestSecondMatchingChildInServiceGroupIsNotReached() + { + var group = new WebServiceGroup(ServerStage.CreateDocument); + group.Add(Generator.GenerateClass(typeof(InnerDupFixture))!); + + var report = RoutingDryRun.Run(group, "GET", "/inner-dup/x"); + + Assert.AreEqual(RoutingOutcome.Accepted, report.Services[0].Outcome); + Assert.AreEqual(2, report.Services[0].Children.Count); + Assert.AreEqual(RoutingOutcome.Accepted, report.Services[0].Children[0].Outcome); + Assert.AreEqual(RoutingOutcome.NotReached, report.Services[0].Children[1].Outcome); + Assert.AreEqual("InnerDupFixture.A()", report.MatchedLabel); + } + + [TestMethod] + public void TestNoChildMatchesInsideServiceGroup() + { + var group = new WebServiceGroup(ServerStage.CreateDocument); + group.Add(Generator.GenerateClass(typeof(NoMatchingChildFixture))!); + + // matches the group's class-level prefix, but no child accepts GET (only POST is + // registered for the sub-path). + var report = RoutingDryRun.Run(group, "GET", "/none-matches/only"); + + Assert.AreEqual(RoutingOutcome.Rejected, report.Services[0].Outcome); + Assert.AreEqual(1, report.Services[0].Children.Count); + Assert.AreEqual(RoutingOutcome.Rejected, report.Services[0].Children[0].Outcome); + Assert.IsTrue(report.Services[0].Reasons.Contains("none of the contained services matched the request")); + } + + [TestMethod] + public void TestUnresolvableCoreParameterIsExplainedByReflectedName() + { + var group = new WebServiceGroup(ServerStage.CreateDocument); + group.Add(Generator.GenerateMethod(typeof(CoreParamFixture).GetMethod("M")!)!); + + // no Connection is set on the synthetic task, so the IPEndPoint core parameter can + // never resolve. + var report = RoutingDryRun.Run(group, "GET", "/core-param"); + + Assert.AreEqual(RoutingOutcome.Rejected, report.Services[0].Outcome); + Assert.IsTrue(report.Services[0].Reasons.Any(r => r.Contains("'endpoint'"))); + } + + [TestMethod] + public void TestParameterConversionFailureIsExplainedInsteadOfThrowing() + { + var group = new WebServiceGroup(ServerStage.CreateDocument); + group.Add(Generator.GenerateMethod(typeof(ConversionFailureFixture).GetMethod("M")!)!); + + // a non-numeric value for an int parameter must show up as a rejection reason, not as an uncaught HttpException + var report = RoutingDryRun.Run(group, "GET", "/conv-fail?id=notanumber"); + + Assert.AreEqual(RoutingOutcome.Rejected, report.Services[0].Outcome); + Assert.IsTrue(report.Services[0].Reasons.Any(r => r.Contains("failed to convert"))); + } + + [TestMethod] + public void TestNonExplainableRuleFallsBackToGenericReason() + { + var group = new WebServiceGroup(ServerStage.CreateDocument); + group.Add(Generator.GenerateMethod(typeof(NonExplainableRuleFixture).GetMethod("M")!)!); + + var report = RoutingDryRun.Run(group, "GET", "/non-explainable"); + + Assert.AreEqual(RoutingOutcome.Rejected, report.Services[0].Outcome); + Assert.IsTrue(report.Services[0].Reasons.Any(r => r.Contains("AlwaysFail") && r.Contains("rejected the request"))); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/Builder/ExceptionHandlingFixtures.cs b/tests/MaxLib.WebServer.Test/Builder/ExceptionHandlingFixtures.cs new file mode 100644 index 0000000..ed5a826 --- /dev/null +++ b/tests/MaxLib.WebServer.Test/Builder/ExceptionHandlingFixtures.cs @@ -0,0 +1,32 @@ +using MaxLib.WebServer; +using MaxLib.WebServer.Builder; + +#nullable enable + +namespace MaxLib.WebServer.Test.Builder +{ + // A synchronous (non-Task) handler that throws HttpException - the documented pattern for + // cancelling a request with a specific status code. MethodBase.Invoke wraps this in a + // TargetInvocationException unless the caller passes BindingFlags.DoNotWrapExceptions. + [Path("/sync-throw")] + public class SyncHttpExceptionService + { + [Path("/sync-throw")] + public HttpDataSource Foo() + { + throw new HttpException(HttpStateCode.Forbidden); + } + } + + // A handler with a typed parameter, used to exercise a conversion failure (e.g. a + // non-numeric query value bound to an int) at the parameter-binding layer. + [Path("/conv-fail")] + public class ConversionFailureService + { + [Path("/conv-fail")] + public HttpDataSource Foo([Get] int id) + { + return new HttpStringDataSource($"id={id}"); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/Builder/SpecificityFixtures.cs b/tests/MaxLib.WebServer.Test/Builder/SpecificityFixtures.cs new file mode 100644 index 0000000..09b8e2a --- /dev/null +++ b/tests/MaxLib.WebServer.Test/Builder/SpecificityFixtures.cs @@ -0,0 +1,29 @@ +using MaxLib.WebServer; +using MaxLib.WebServer.Builder; + +#nullable enable + +namespace MaxLib.WebServer.Test.Builder +{ + // Two overlapping routes with equal (default) priority: a catch-all {var} segment and a + // literal segment matching the same URL. Declared in the order least-specific-first, so a + // fix that just preserved Type.GetMethods() order would happen to "work" here by accident + // - the companion fixture below declares them in the opposite order to rule that out. + public class SpecificityVarFirstFixture + { + [Path("/spec/{id}")] + public HttpDataSource ByVar([Var("id")] string id) => new HttpStringDataSource($"var:{id}"); + + [Path("/spec/literal")] + public HttpDataSource ByLiteral() => new HttpStringDataSource("literal"); + } + + public class SpecificityLiteralFirstFixture + { + [Path("/spec/literal")] + public HttpDataSource ByLiteral() => new HttpStringDataSource("literal"); + + [Path("/spec/{id}")] + public HttpDataSource ByVar([Var("id")] string id) => new HttpStringDataSource($"var:{id}"); + } +} diff --git a/tests/MaxLib.WebServer.Test/Builder/TestExceptionHandling.cs b/tests/MaxLib.WebServer.Test/Builder/TestExceptionHandling.cs new file mode 100644 index 0000000..b6cbe22 --- /dev/null +++ b/tests/MaxLib.WebServer.Test/Builder/TestExceptionHandling.cs @@ -0,0 +1,45 @@ +using System.Linq; +using MaxLib.WebServer.Builder.Tools; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +#nullable enable + +namespace MaxLib.WebServer.Test.Builder +{ + [TestClass] + public class TestExceptionHandling + { + [TestMethod] + public async System.Threading.Tasks.Task TestSyncHandlerHttpExceptionProducesTheExpectedStatusCode() + { + var group = new WebServiceGroup(ServerStage.CreateDocument); + group.Add(Generator.GenerateMethod(typeof(SyncHttpExceptionService).GetMethod("Foo")!)!); + + var task = new WebProgressTask(); + task.Request.Url = "/sync-throw"; + + await group.Execute(task); + + Assert.AreEqual(HttpStateCode.Forbidden, task.Response.StatusCode); + } + + [TestMethod] + public async System.Threading.Tasks.Task TestParameterConversionFailureProducesABadRequestWithAnExplanation() + { + var group = new WebServiceGroup(ServerStage.CreateDocument); + group.Add(Generator.GenerateMethod(typeof(ConversionFailureService).GetMethod("Foo")!)!); + + var task = new WebProgressTask(); + task.Request.Url = "/conv-fail?id=abc"; + + await group.Execute(task); + + Assert.AreEqual(HttpStateCode.BadRequest, task.Response.StatusCode); + Assert.AreEqual(1, task.Document.DataSources.Count); + Assert.IsTrue(task.Document.DataSources[0] is HttpStringDataSource); + var body = ((HttpStringDataSource)task.Document.DataSources[0]).Data; + StringAssert.Contains(body, "id"); + StringAssert.Contains(body, "abc"); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/Builder/TestJsonConverterAttribute.cs b/tests/MaxLib.WebServer.Test/Builder/TestJsonConverterAttribute.cs new file mode 100644 index 0000000..d1edec8 --- /dev/null +++ b/tests/MaxLib.WebServer.Test/Builder/TestJsonConverterAttribute.cs @@ -0,0 +1,73 @@ +using System; +using System.Text.Json; +using MaxLib.WebServer.Builder; +using MaxLib.WebServer.Builder.Converter; +using MaxLib.WebServer.Builder.Tools; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +#nullable enable + +namespace MaxLib.WebServer.Test.Builder +{ + [TestClass] + public class TestJsonConverterAttribute + { + private sealed class Dto + { + public string? Name { get; set; } + } + + // a converter targeting JsonElement naturally returns the element it was handed, unmodified + public sealed class PassthroughConverter : ICustomJsonConverter + { + public object Convert(JsonElement value, Type target) => value; + } + + [TestMethod] + public void TestConvertsWellFormedJsonFromAString() + { + var attr = new JsonConverterAttribute(); + var converter = ((IConverter)attr).GetConverter(typeof(string), typeof(Dto)); + + Assert.IsNotNull(converter); + var result = converter!("{\"Name\":\"hello\"}"); + + Assert.IsInstanceOfType(result, typeof(Dto)); + Assert.AreEqual("hello", ((Dto)result!).Name); + } + + [TestMethod] + public void TestMalformedJsonThrowsInsteadOfSilentlyConvertingToNull() + { + // a parse error must propagate so Parameter.GetValue can turn it into a 400 + var attr = new JsonConverterAttribute(); + var converter = ((IConverter)attr).GetConverter(typeof(string), typeof(Dto)); + + Assert.IsNotNull(converter); + try + { + converter!("{\"Name\":"); + Assert.Fail("expected a JsonException to be thrown"); + } + catch (JsonException) + { + // expected - any subclass (e.g. the internal JsonReaderException) is fine + } + } + + [TestMethod] + public void TestCustomConverterReturningTheElementItselfStaysUsableAfterConversion() + { + // the returned element must stay valid after the backing JsonDocument is disposed + var attr = new JsonConverterAttribute { CustomConverter = typeof(PassthroughConverter) }; + var converter = ((IConverter)attr).GetConverter(typeof(string), typeof(JsonElement)); + + Assert.IsNotNull(converter); + var result = converter!("{\"a\":1}"); + + Assert.IsInstanceOfType(result, typeof(JsonElement)); + var element = (JsonElement)result!; + Assert.AreEqual(1, element.GetProperty("a").GetInt32()); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/Builder/TestJsonDataConverterAttribute.cs b/tests/MaxLib.WebServer.Test/Builder/TestJsonDataConverterAttribute.cs new file mode 100644 index 0000000..fb1ad14 --- /dev/null +++ b/tests/MaxLib.WebServer.Test/Builder/TestJsonDataConverterAttribute.cs @@ -0,0 +1,43 @@ +using System.IO; +using System.Text; +using System.Threading.Tasks; +using MaxLib.WebServer.Builder; +using MaxLib.WebServer.Builder.Tools; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +#nullable enable + +namespace MaxLib.WebServer.Test.Builder +{ + [TestClass] + public class TestJsonDataConverterAttribute + { + private static async Task Serialize(object? value) + { + var attr = new JsonDataConverterAttribute(); + var converter = ((IDataConverter)attr).GetConverter(typeof(object)); + Assert.IsNotNull(converter); + var source = converter!(value!); + Assert.IsNotNull(source); + using var stream = new MemoryStream(); + await source!.WriteStream(stream).ConfigureAwait(false); + return Encoding.UTF8.GetString(stream.ToArray()); + } + + [TestMethod] + public async Task TestGetConverterSerializesNullAsJsonNull() + { + // the null token must not be followed by a second root-level value, which makes the writer throw + var json = await Serialize(null).ConfigureAwait(false); + Assert.AreEqual("null", json); + } + + [TestMethod] + public async Task TestGetConverterSerializesAnOrdinaryValue() + { + var json = await Serialize(new { hello = "world" }).ConfigureAwait(false); + StringAssert.Contains(json, "\"hello\""); + StringAssert.Contains(json, "\"world\""); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/Builder/TestPathAttribute.cs b/tests/MaxLib.WebServer.Test/Builder/TestPathAttribute.cs new file mode 100644 index 0000000..9c32b8b --- /dev/null +++ b/tests/MaxLib.WebServer.Test/Builder/TestPathAttribute.cs @@ -0,0 +1,79 @@ +using System.Collections.Generic; +using MaxLib.WebServer.Builder; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +#nullable enable + +namespace MaxLib.WebServer.Test.Builder +{ + [TestClass] + public class TestPathAttribute + { + [TestMethod] + public void TestPrefixModeRejectsAUrlShorterThanTheTemplate() + { + // a URL shorter than the template must never match, even in Prefix mode + var attr = new PathAttribute("/admin/secret/{token}") { Prefix = true }; + var task = new WebProgressTask(); + task.Request.Url = "/admin/secret"; + var vars = new Dictionary(); + + var matched = attr.CanWorkWith(task, vars); + + Assert.IsFalse(matched, "a URL missing the template's final {token} segment must not match"); + Assert.AreEqual(0, vars.Count); + } + + [TestMethod] + public void TestPrefixModeRejectsTheRootUrlAgainstAMultiSegmentTemplate() + { + var attr = new PathAttribute("/admin/secret/{token}") { Prefix = true }; + var task = new WebProgressTask(); + task.Request.Url = "/"; + var vars = new Dictionary(); + + Assert.IsFalse(attr.CanWorkWith(task, vars)); + } + + [TestMethod] + public void TestPrefixModeStillMatchesAUrlAtLeastAsLongAsTheTemplate() + { + var attr = new PathAttribute("/admin/secret/{token}") { Prefix = true }; + var task = new WebProgressTask(); + task.Request.Url = "/admin/secret/abc123/extra"; + var vars = new Dictionary(); + + var matched = attr.CanWorkWith(task, vars); + + Assert.IsTrue(matched); + Assert.AreEqual("abc123", vars["token"]); + } + + [TestMethod] + public void TestNonPrefixModeStillRequiresAnExactLengthMatch() + { + var attr = new PathAttribute("/admin/secret/{token}") { Prefix = false }; + var task = new WebProgressTask(); + task.Request.Url = "/admin/secret"; + var vars = new Dictionary(); + + Assert.IsFalse(attr.CanWorkWith(task, vars)); + } + + [TestMethod] + public void TestExplainableRulePrefixModeAlsoRejectsAUrlShorterThanTheTemplate() + { + // the IExplainableRule copy used by RoutingDryRun must agree with CanWorkWith above + var attr = new PathAttribute("/admin/secret/{token}") { Prefix = true }; + var task = new WebProgressTask(); + task.Request.Url = "/admin/secret"; + var vars = new Dictionary(); + + var matched = ((MaxLib.WebServer.Builder.Debugger.IExplainableRule)attr).CanWorkWith(task, vars, out var reason); + + Assert.IsFalse(matched); + Assert.IsNotNull(reason); + Assert.AreEqual(0, vars.Count); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/Builder/TestRouteSpecificity.cs b/tests/MaxLib.WebServer.Test/Builder/TestRouteSpecificity.cs new file mode 100644 index 0000000..2ae069b --- /dev/null +++ b/tests/MaxLib.WebServer.Test/Builder/TestRouteSpecificity.cs @@ -0,0 +1,38 @@ +using System.Threading.Tasks; +using MaxLib.WebServer.Builder.Runtime; +using MaxLib.WebServer.Builder.Tools; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +#nullable enable + +namespace MaxLib.WebServer.Test.Builder +{ + [TestClass] + public class TestRouteSpecificity + { + private static async Task Resolve(System.Type fixtureType) + { + var group = Generator.GenerateClass(fixtureType)!; + var task = new WebProgressTask(); + task.Request.Url = "/spec/literal"; + Assert.IsTrue(group.CanWorkWith(task, out ServiceGroup.CallInfo? data), + "no method matched the request at all"); + await group.ProgressTask(task, data); + Assert.AreEqual(1, task.Document.DataSources.Count); + Assert.IsTrue(task.Document.DataSources[0] is HttpStringDataSource); + return ((HttpStringDataSource)task.Document.DataSources[0]).Data; + } + + [TestMethod] + public async Task TestLiteralRouteWinsOverVarRouteWhenVarIsDeclaredFirst() + { + Assert.AreEqual("literal", await Resolve(typeof(SpecificityVarFirstFixture))); + } + + [TestMethod] + public async Task TestLiteralRouteWinsOverVarRouteWhenLiteralIsDeclaredFirst() + { + Assert.AreEqual("literal", await Resolve(typeof(SpecificityLiteralFirstFixture))); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/Builder/TestSystemConverter.cs b/tests/MaxLib.WebServer.Test/Builder/TestSystemConverter.cs new file mode 100644 index 0000000..133c9c7 --- /dev/null +++ b/tests/MaxLib.WebServer.Test/Builder/TestSystemConverter.cs @@ -0,0 +1,96 @@ +using System; +using MaxLib.WebServer.Builder.Converter; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +#nullable enable + +namespace MaxLib.WebServer.Test.Builder +{ + [TestClass] + public class TestSystemConverter + { + private enum Color { Red, Green, Blue } + + [Flags] + private enum Perm : byte { None = 0, Read = 1, Write = 2, Execute = 4 } + + [TestMethod] + public void TestConvertsAStringToAnEnumByMemberName() + { + // Convert.ChangeType throws InvalidCastException for enums; they must be parsed by name instead + var converter = new SystemConverter().GetConverter(typeof(string), typeof(Color)); + + Assert.IsNotNull(converter); + Assert.AreEqual(Color.Green, converter!("Green")); + } + + [TestMethod] + public void TestConvertsAStringToAnEnumCaseInsensitively() + { + var converter = new SystemConverter().GetConverter(typeof(string), typeof(Color)); + + Assert.IsNotNull(converter); + Assert.AreEqual(Color.Blue, converter!("blue")); + } + + [TestMethod] + public void TestInvalidEnumMemberNameThrows() + { + var converter = new SystemConverter().GetConverter(typeof(string), typeof(Color)); + + Assert.IsNotNull(converter); + Assert.ThrowsExactly(() => converter!("Purple")); + } + + [TestMethod] + public void TestOutOfRangeNumericStringIsRejectedNotSilentlyBound() + { + // Enum.Parse accepts any numeric string, so a value like "99" must not bind an undefined member + var converter = new SystemConverter().GetConverter(typeof(string), typeof(Color)); + + Assert.IsNotNull(converter); + Assert.ThrowsExactly(() => converter!("99")); + } + + [TestMethod] + public void TestInRangeNumericStringMatchingADefinedMemberStillConverts() + { + var converter = new SystemConverter().GetConverter(typeof(string), typeof(Color)); + + Assert.IsNotNull(converter); + Assert.AreEqual(Color.Green, converter!("1")); + } + + [TestMethod] + public void TestFlagsEnumCombinationNotSeparatelyNamedStillConverts() + { + // the comma-separated flags syntax ("Read,Write") is valid for a [Flags] enum + // even when the combination is not a named member + var converter = new SystemConverter().GetConverter(typeof(string), typeof(Perm)); + + Assert.IsNotNull(converter); + Assert.AreEqual(Perm.Read | Perm.Write, converter!("Read,Write")); + } + + [TestMethod] + public void TestFlagsEnumOutOfRangeCombinationStillRejected() + { + // a bit outside the union of all named flags must still be rejected + var converter = new SystemConverter().GetConverter(typeof(string), typeof(Perm)); + + Assert.IsNotNull(converter); + Assert.ThrowsExactly(() => converter!("99")); + } + + [TestMethod] + public void TestNonFlagsEnumCommaSeparatedCombinationStillRejected() + { + // Enum.Parse accepts the comma-separated syntax for any enum; the flags carve-out + // must only apply to [Flags] enums + var converter = new SystemConverter().GetConverter(typeof(string), typeof(Color)); + + Assert.IsNotNull(converter); + Assert.ThrowsExactly(() => converter!("Green,Blue")); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/Builder/TestTextPostAttribute.cs b/tests/MaxLib.WebServer.Test/Builder/TestTextPostAttribute.cs new file mode 100644 index 0000000..4eed352 --- /dev/null +++ b/tests/MaxLib.WebServer.Test/Builder/TestTextPostAttribute.cs @@ -0,0 +1,92 @@ +using System.Collections.Generic; +using System.IO; +using System.Text; +using MaxLib.WebServer.Builder; +using MaxLib.WebServer.IO; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +#nullable enable + +namespace MaxLib.WebServer.Test.Builder +{ + [TestClass] + public class TestTextPostAttribute + { + [TestMethod] + public void TestGetValueReadsAnInMemoryRawPostDataAsText() + { + var task = new WebProgressTask(); + var body = Encoding.UTF8.GetBytes("hello raw body"); + task.Request.Post.SetPost( + task, + new ContentStream(new NetworkReader(new MemoryStream(body)), body.Length), + MimeType.ApplicationOctetStream + ); + + var result = new TextPostAttribute().GetValue(task, "", new Dictionary()); + + Assert.IsTrue(result.HasValue); + Assert.AreEqual("hello raw body", result.Value); + } + + [TestMethod] + public void TestGetValueReadsAFileBackedRawPostDataAsText() + { + var originalLimit = Post.RawPostData.MaximumCacheSize; + try + { + Post.RawPostData.MaximumCacheSize = 1; + var task = new WebProgressTask(); + var body = Encoding.UTF8.GetBytes("a body larger than the 1-byte limit"); + task.Request.Post.SetPost( + task, + new ContentStream(new NetworkReader(new MemoryStream(body)), body.Length), + MimeType.ApplicationOctetStream + ); + + var result = new TextPostAttribute().GetValue(task, "", new Dictionary()); + + Assert.IsTrue(result.HasValue); + Assert.AreEqual("a body larger than the 1-byte limit", result.Value); + } + finally + { + Post.RawPostData.MaximumCacheSize = originalLimit; + } + } + + [TestMethod] + public void TestGetValueDecodesUsingTheDeclaredCharset() + { + // "café" in ISO-8859-1: decoding as UTF-8 would mangle the 0xE9 byte + var task = new WebProgressTask(); + var body = new byte[] { (byte)'c', (byte)'a', (byte)'f', 0xE9 }; + task.Request.Post.SetPost( + task, + new ContentStream(new NetworkReader(new MemoryStream(body)), body.Length), + "text/plain; charset=iso-8859-1" + ); + + var result = new TextPostAttribute().GetValue(task, "", new Dictionary()); + + Assert.IsTrue(result.HasValue); + Assert.AreEqual("café", result.Value); + } + + [TestMethod] + public void TestGetValueReturnsNoValueForAKnownPostDataType() + { + var task = new WebProgressTask(); + var body = Encoding.UTF8.GetBytes("foo=bar"); + task.Request.Post.SetPost( + task, + new ContentStream(new NetworkReader(new MemoryStream(body)), body.Length), + MimeType.ApplicationXWwwFromUrlencoded + ); + + var result = new TextPostAttribute().GetValue(task, "", new Dictionary()); + + Assert.IsFalse(result.HasValue); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/Builder/TestUrlEncodedPostAttribute.cs b/tests/MaxLib.WebServer.Test/Builder/TestUrlEncodedPostAttribute.cs new file mode 100644 index 0000000..83977fc --- /dev/null +++ b/tests/MaxLib.WebServer.Test/Builder/TestUrlEncodedPostAttribute.cs @@ -0,0 +1,113 @@ +using System.Collections.Generic; +using System.IO; +using System.Text; +using MaxLib.WebServer.Builder; +using MaxLib.WebServer.IO; +using MaxLib.WebServer.Post; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +#nullable enable + +namespace MaxLib.WebServer.Test.Builder +{ + [TestClass] + public class TestUrlEncodedPostAttribute + { + [TestMethod] + public void TestGetValueReadsAnInMemoryParameterBelowTheOverflowThreshold() + { + var task = new WebProgressTask(); + var body = Encoding.UTF8.GetBytes("name=world"); + task.Request.Post.SetPost( + task, + new ContentStream(new NetworkReader(new MemoryStream(body)), body.Length), + MimeType.ApplicationXWwwFromUrlencoded + ); + + var result = new UrlEncodedPostAttribute("name").GetValue(task, "", new Dictionary()); + + Assert.IsTrue(result.HasValue); + Assert.AreEqual("world", result.Value); + } + + [TestMethod] + public void TestGetValueReadsAnInMemoryOverflowEntry() + { + // once the body exceeds MaximumCacheSize, fields are in Overflow rather than Parameter + var originalLimit = UrlEncodedData.MaximumCacheSize; + try + { + UrlEncodedData.MaximumCacheSize = 1; + var task = new WebProgressTask(); + var body = Encoding.UTF8.GetBytes("name=x"); + task.Request.Post.SetPost( + task, + new ContentStream(new NetworkReader(new MemoryStream(body)), body.Length), + MimeType.ApplicationXWwwFromUrlencoded + ); + + var result = new UrlEncodedPostAttribute("name").GetValue(task, "", new Dictionary()); + + Assert.IsTrue(result.HasValue, + "the field must still resolve via Overflow once the body exceeds MaximumCacheSize"); + Assert.AreEqual("x", result.Value); + } + finally + { + UrlEncodedData.MaximumCacheSize = originalLimit; + } + } + + [TestMethod] + public void TestGetValueReadsAFileBackedOverflowEntry() + { + // a value that itself exceeds MaximumCacheSize is spilled to a temp file in Overflow; GetValue must read it too + var originalLimit = UrlEncodedData.MaximumCacheSize; + try + { + UrlEncodedData.MaximumCacheSize = 1; + var task = new WebProgressTask(); + var body = Encoding.UTF8.GetBytes("name=a-value-longer-than-the-limit"); + task.Request.Post.SetPost( + task, + new ContentStream(new NetworkReader(new MemoryStream(body)), body.Length), + MimeType.ApplicationXWwwFromUrlencoded + ); + + var result = new UrlEncodedPostAttribute("name").GetValue(task, "", new Dictionary()); + + Assert.IsTrue(result.HasValue); + Assert.AreEqual("a-value-longer-than-the-limit", result.Value); + } + finally + { + UrlEncodedData.MaximumCacheSize = originalLimit; + } + } + + [TestMethod] + public void TestGetValueReturnsNoValueForAnUnknownFieldPastTheOverflowThreshold() + { + var originalLimit = UrlEncodedData.MaximumCacheSize; + try + { + UrlEncodedData.MaximumCacheSize = 1; + var task = new WebProgressTask(); + var body = Encoding.UTF8.GetBytes("name=x"); + task.Request.Post.SetPost( + task, + new ContentStream(new NetworkReader(new MemoryStream(body)), body.Length), + MimeType.ApplicationXWwwFromUrlencoded + ); + + var result = new UrlEncodedPostAttribute("missing").GetValue(task, "", new Dictionary()); + + Assert.IsFalse(result.HasValue); + } + finally + { + UrlEncodedData.MaximumCacheSize = originalLimit; + } + } + } +} diff --git a/tests/MaxLib.WebServer.Test/Chunked/TestChunkedSender.cs b/tests/MaxLib.WebServer.Test/Chunked/TestChunkedSender.cs new file mode 100644 index 0000000..97182f5 --- /dev/null +++ b/tests/MaxLib.WebServer.Test/Chunked/TestChunkedSender.cs @@ -0,0 +1,224 @@ +using MaxLib.WebServer.Chunked; +using MaxLib.WebServer.IO; +using MaxLib.WebServer.Post; +using MaxLib.WebServer.Testing; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.IO; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace MaxLib.WebServer.Test.Chunked +{ + [TestClass] + public class TestChunkedSender + { + TestWebServer server; + TestTask test; + + [TestInitialize] + public void Init() + { + server = new TestWebServer(); + server.AddWebService(new ChunkedSender()); + test = new TestTask(server) + { + CurrentStage = ServerStage.SendResponse, + TerminationStage = ServerStage.SendResponse, + }; + } + + [TestMethod] + public async Task TestSendingStripsCrLfFromHeaderNamesAndValues() + { + // A header value built from attacker-influenced text must never let a raw CRLF + // split it into extra header/response lines - see http-header-crlf-injection.md + test.Response.HttpProtocol = HttpProtocolDefinition.HttpVersion1_1; + test.Response.StatusCode = HttpStateCode.OK; + test.Response.HeaderParameter["X-Custom"] = "evil\r\nX-Injected: 1"; + + using (var response = test.SetStream()) + using (var r = new StreamReader(response)) + { + await new ChunkedSender().ProgressTask(test.Task).ConfigureAwait(false); + + response.Position = 0; + + Assert.AreEqual("HTTP/1.1 200 OK", r.ReadLine()); + Assert.AreEqual("X-Custom: evilX-Injected: 1", r.ReadLine()); + } + } + + [TestMethod] + public async Task TestSendingEmitsAWellFormedSetCookieHeader() + { + // AddedCookies yields KeyValuePairs; the header must use cookie.Value.ToString(), not the pair's "[Key, Value]" + test.Response.HttpProtocol = HttpProtocolDefinition.HttpVersion1_1; + test.Response.StatusCode = HttpStateCode.OK; + test.Request.Cookie.AddedCookies["session"] = new HttpCookie.Cookie("session", "abc123"); + + using (var response = test.SetStream()) + using (var r = new StreamReader(response)) + { + await new ChunkedSender().ProgressTask(test.Task).ConfigureAwait(false); + + response.Position = 0; + var lines = new System.Collections.Generic.List(); + for (var line = r.ReadLine(); line != null; line = r.ReadLine()) + lines.Add(line); + + var expected = "Set-Cookie: " + new HttpCookie.Cookie("session", "abc123").ToString(); + CollectionAssert.Contains(lines, expected); + Assert.IsFalse(lines.Exists(l => l.Contains('[') || l.Contains(']')), + "the emitted Set-Cookie line must not contain the KeyValuePair wrapper brackets"); + } + } + + [TestMethod] + public async Task TestPostTempFileIsDisposedAfterAChunkedResponse() + { + // ChunkedSender replaces HttpSender.ProgressTask, so it must dispose the POST data itself + // or its temp files leak + var originalMapper = MultipartFormData.StorageMapper; + string tempFilePath = ""; + try + { + MultipartFormData.StorageMapper = (task, file) => + { + tempFilePath = ((FileStream)file).Name; + return file; + }; + + var content = + "-----1234\r\n" + + "Content-Type: text/plain\r\n" + + "Content-Disposition: form-data; name=\"f\"; filename=\"x\"\r\n" + + "\r\n" + + "Hello World\r\n" + + "-----1234--\r\n"; + var contentBytes = Encoding.UTF8.GetBytes(content); + var contentStream = new ContentStream( + new NetworkReader(new MemoryStream(contentBytes)), contentBytes.Length); + test.Request.Post.SetPost(test.Task, contentStream, "multipart/form-data; boundary=---1234"); + // force the lazy IPostData to actually resolve, as if some handler had + // already read it - this is what creates the temp file in the first place + Assert.IsNotNull(await test.Request.Post.DataAsync!.ConfigureAwait(false)); + + test.Response.HttpProtocol = HttpProtocolDefinition.HttpVersion1_1; + test.Response.StatusCode = HttpStateCode.OK; + + using var response = test.SetStream(); + await new ChunkedSender().ProgressTask(test.Task).ConfigureAwait(false); + + Assert.AreNotEqual("", tempFilePath, "the StorageMapper hook was never invoked"); + Assert.IsFalse(File.Exists(tempFilePath), + "the POST temp file must not be orphaned once a chunked response has been sent"); + } + finally + { + MultipartFormData.StorageMapper = originalMapper; + } + } + + // Never touches the stream it's given, like a source whose underlying I/O fails before producing any bytes. + private sealed class ThrowingDataSource : HttpDataSource + { + public override void Dispose() => GC.SuppressFinalize(this); + public override long? Length() => null; + protected override Task WriteStreamInternal(Stream stream) + => throw new InvalidOperationException("boom from WriteStreamInternal"); + } + + // TestTask's BidirectionalStream only overrides the synchronous Flush()/Write(), so every awaited flush + // runs it on a background thread. Slowing it gives SendChunk's background task a head start over the + // recursive read of the same sink; without it the read hits a BufferedSinkStream quirk (FinishWrite() + // does not wake a waiting reader) and hangs. + private sealed class SlowFlushStream(Stream inner) : Stream + { + public override bool CanRead => inner.CanRead; + public override bool CanSeek => inner.CanSeek; + public override bool CanWrite => inner.CanWrite; + public override long Length => inner.Length; + public override long Position { get => inner.Position; set => inner.Position = value; } + + public override void Flush() + { + Thread.Sleep(100); + inner.Flush(); + } + + public override int Read(byte[] buffer, int offset, int count) => inner.Read(buffer, offset, count); + public override long Seek(long offset, SeekOrigin origin) => inner.Seek(offset, origin); + public override void SetLength(long value) => inner.SetLength(value); + public override void Write(byte[] buffer, int offset, int count) => inner.Write(buffer, offset, count); + } + + [TestMethod] + public async Task TestSendingAnUnboundedLengthSourceThatThrowsFaultsInsteadOfHangingOrLookingLikeSuccess() + { + // if WriteStream throws, the reader of the sink must still see completion instead of blocking forever, + // and ProgressTask must fault instead of completing as an empty, successful response + test.Response.HttpProtocol = HttpProtocolDefinition.HttpVersion1_1; + test.Response.StatusCode = HttpStateCode.OK; + test.GetDataSources().Add(new ThrowingDataSource()); + + using var response = new MemoryStream(); + test.SetStream(new MemoryStream(), new SlowFlushStream(response)); + + var sendTask = new ChunkedSender().ProgressTask(test.Task); + var winner = await Task.WhenAny(sendTask, Task.Delay(TimeSpan.FromSeconds(4))).ConfigureAwait(false); + + Assert.AreSame(sendTask, winner, + "ChunkedSender.ProgressTask must not hang forever when an unbounded-length source's WriteStream throws"); + var ex = await Assert.ThrowsExactlyAsync(() => sendTask) + .ConfigureAwait(false); + Assert.IsInstanceOfType(ex.InnerException, typeof(InvalidOperationException)); + } + + // Writes some bytes before throwing, like a source whose underlying I/O fails partway through. + private sealed class PartialThenThrowDataSource : HttpDataSource + { + public override void Dispose() => GC.SuppressFinalize(this); + public override long? Length() => null; + protected override async Task WriteStreamInternal(Stream stream) + { + var data = Encoding.ASCII.GetBytes("PARTIAL-DATA-BEFORE-FAILURE"); + await stream.WriteAsync(data).ConfigureAwait(false); + await stream.FlushAsync().ConfigureAwait(false); + throw new InvalidOperationException("boom after writing partial data"); + } + } + + [TestMethod] + public async Task TestSendingAnUnboundedLengthSourceThatThrowsAfterPartialDataNeverSendsTheTerminatingChunk() + { + // once WriteStream failed after writing bytes, the terminating chunk must not be written, + // so a chunked-transfer-aware client can detect the truncated response + test.Response.HttpProtocol = HttpProtocolDefinition.HttpVersion1_1; + test.Response.StatusCode = HttpStateCode.OK; + test.GetDataSources().Add(new PartialThenThrowDataSource()); + + using var response = new MemoryStream(); + test.SetStream(new MemoryStream(), new SlowFlushStream(response)); + + var sendTask = new ChunkedSender().ProgressTask(test.Task); + var winner = await Task.WhenAny(sendTask, Task.Delay(TimeSpan.FromSeconds(4))).ConfigureAwait(false); + Assert.AreSame(sendTask, winner, + "ChunkedSender.ProgressTask must not hang forever when an unbounded-length source's WriteStream throws after partial data"); + + var ex = await Assert.ThrowsExactlyAsync(() => sendTask) + .ConfigureAwait(false); + Assert.IsInstanceOfType(ex.InnerException, typeof(InvalidOperationException)); + + response.Position = 0; + using var r = new StreamReader(response); + var wire = r.ReadToEnd(); + + StringAssert.Contains(wire, "PARTIAL-DATA-BEFORE-FAILURE", + "the bytes written before the failure must still reach the client"); + Assert.IsFalse(wire.Contains("\r\n0\r\n\r\n", StringComparison.Ordinal), + "the response must never be closed off with a valid terminating 0-chunk once WriteStream has failed"); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/IO/TestContentStream.cs b/tests/MaxLib.WebServer.Test/IO/TestContentStream.cs new file mode 100644 index 0000000..309297c --- /dev/null +++ b/tests/MaxLib.WebServer.Test/IO/TestContentStream.cs @@ -0,0 +1,229 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using MaxLib.WebServer.IO; + +namespace MaxLib.WebServer.Test.IO +{ + [TestClass] + public class TestContentStream + { + // Simulates a client that stalls mid-upload: every read blocks forever unless the + // caller's cancellation token fires. Tracks whether it was ever closed, so tests can + // verify the underlying connection is (or isn't) torn down as expected. + private sealed class StallingStream : Stream + { + public bool Disposed { get; private set; } + + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => throw new NotSupportedException(); + public override long Position + { + get => 0; + set => throw new NotSupportedException(); + } + public override void Flush() { } + public override int Read(byte[] buffer, int offset, int count) + => throw new NotSupportedException("only the async read paths are exercised here"); + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + => ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + await Task.Delay(Timeout.Infinite, cancellationToken).ConfigureAwait(false); + throw new InvalidOperationException("unreachable: Task.Delay(Infinite) only ever completes by cancellation"); + } + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + protected override void Dispose(bool disposing) + { + if (disposing) + Disposed = true; + base.Dispose(disposing); + } + } + + // Tracks whether it was ever closed, so a test can verify a keep-alive connection is + // left open after a normal (non-cancelled) drain. + private sealed class TrackingMemoryStream(byte[] data) : MemoryStream(data) + { + public bool Disposed { get; private set; } + protected override void Dispose(bool disposing) + { + if (disposing) + Disposed = true; + base.Dispose(disposing); + } + } + + private static async Task AssertCancelsQuickly(Func action) + { + var stopwatch = Stopwatch.StartNew(); + try + { + await action().ConfigureAwait(false); + Assert.Fail("expected an OperationCanceledException"); + } + catch (OperationCanceledException) + { + // expected - any subclass (e.g. TaskCanceledException) is fine too + } + stopwatch.Stop(); + Assert.IsTrue(stopwatch.Elapsed < TimeSpan.FromSeconds(5), + $"expected cancellation well within the configured timeout, took {stopwatch.Elapsed}"); + } + + [TestMethod] + public async Task TestDiscardAsyncRespectsConfiguredTimeout() + { + var reader = new NetworkReader(new StallingStream(), null, true); + var content = new ContentStream(reader, 1024, TimeSpan.FromMilliseconds(50)); + + await AssertCancelsQuickly(() => content.DiscardAsync()).ConfigureAwait(false); + } + + [TestMethod] + public async Task TestReadAsyncRespectsConfiguredTimeout() + { + var reader = new NetworkReader(new StallingStream(), null, true); + var content = new ContentStream(reader, 1024, TimeSpan.FromMilliseconds(50)); + + await AssertCancelsQuickly(async () => + { + var buffer = new byte[16]; + await content.ReadAsync(buffer.AsMemory()).ConfigureAwait(false); + }).ConfigureAwait(false); + } + + [TestMethod] + public async Task TestDisposeAsyncRespectsConfiguredTimeout() + { + var reader = new NetworkReader(new StallingStream(), null, true); + var content = new ContentStream(reader, 1024, TimeSpan.FromMilliseconds(50)); + + // DisposeAsync tries to drain the remaining bytes first; on a stalled stream + // that never arrives, so the cancellation must surface here rather than block + await AssertCancelsQuickly(() => content.DisposeAsync().AsTask()).ConfigureAwait(false); + } + + [TestMethod] + public async Task TestNoTimeoutConfiguredStillWorks() + { + // sanity check: the original two-argument constructor (no timeout) behaves + // exactly as before against a normal, non-stalling source + var bytes = new byte[] { 1, 2, 3, 4 }; + using var reader = new NetworkReader(new MemoryStream(bytes)); + using var content = new ContentStream(reader, bytes.Length); + + var buffer = new byte[4]; + var read = await content.ReadAsync(buffer.AsMemory()).ConfigureAwait(false); + + Assert.AreEqual(4, read); + CollectionAssert.AreEqual(bytes, buffer); + Assert.AreEqual(CancellationToken.None, content.TimeoutToken); + } + + [TestMethod] + public async Task TestDiscardAsyncNeverClosesTheUnderlyingStreamEvenOnCancellation() + { + // DiscardAsync can be called mid-pipeline, before any response has been sent on + // this connection (e.g. MultipartFormData drains trailing bytes while still + // parsing the request) - it must never close the connection itself, or a later + // stage could lose the ability to send a response (e.g. a timeout status) + var stream = new StallingStream(); + var reader = new NetworkReader(stream, null, false); // leaveOpen: false + var content = new ContentStream(reader, 1024, TimeSpan.FromMilliseconds(50)); + + await AssertCancelsQuickly(() => content.DiscardAsync()).ConfigureAwait(false); + + Assert.IsFalse(stream.Disposed, + "a plain discard must never close the underlying connection, even when cancelled"); + } + + [TestMethod] + public async Task TestReadAsyncNeverClosesTheUnderlyingStreamEvenOnCancellation() + { + var stream = new StallingStream(); + var reader = new NetworkReader(stream, null, false); + var content = new ContentStream(reader, 1024, TimeSpan.FromMilliseconds(50)); + + await AssertCancelsQuickly(async () => + { + var buffer = new byte[16]; + await content.ReadAsync(buffer.AsMemory()).ConfigureAwait(false); + }).ConfigureAwait(false); + + Assert.IsFalse(stream.Disposed, + "a plain read must never close the underlying connection, even when cancelled"); + } + + [TestMethod] + public async Task TestDisposeAsyncClosesTheUnderlyingStreamOnCancellation() + { + // DisposeAsync, unlike a plain read/discard, is the terminal operation on this + // stream - callers must only invoke it once nothing further needs the + // connection (e.g. after a response has already been sent), so it is safe (and + // necessary) for it to close the connection immediately if its drain is + // cancelled, rather than leaving that to whichever code further up the stack + // happens to notice the resulting exception + var stream = new StallingStream(); + var reader = new NetworkReader(stream, null, false); + var content = new ContentStream(reader, 1024, TimeSpan.FromMilliseconds(50)); + + await AssertCancelsQuickly(() => content.DisposeAsync().AsTask()).ConfigureAwait(false); + + Assert.IsTrue(stream.Disposed, + "expected the underlying stream to be closed after a cancelled disposal"); + } + + [TestMethod] + public async Task TestDiscardAsyncStopsAtEarlyEofInsteadOfBusyLooping() + { + // DiscardAsync must stop when the connection ends before the declared length instead of spinning. + // No timeout is configured on purpose; the bound below turns a spin into a test failure. + var reader = new NetworkReader(new MemoryStream(new byte[] { 1, 2, 3, 4 }), null, true); + using var content = new ContentStream(reader, 1000); + + var discardTask = content.DiscardAsync(); + var completed = await Task.WhenAny(discardTask, Task.Delay(TimeSpan.FromSeconds(5))).ConfigureAwait(false); + + Assert.AreSame(discardTask, completed, + "DiscardAsync should stop at genuine EOF instead of busy-looping"); + await discardTask.ConfigureAwait(false); + } + + [TestMethod] + public async Task TestDiscardStopsAtEarlyEofInsteadOfBusyLooping() + { + var reader = new NetworkReader(new MemoryStream(new byte[] { 1, 2, 3, 4 }), null, true); + using var content = new ContentStream(reader, 1000); + + var discardTask = Task.Run(content.Discard); + var completed = await Task.WhenAny(discardTask, Task.Delay(TimeSpan.FromSeconds(5))).ConfigureAwait(false); + + Assert.AreSame(discardTask, completed, + "Discard should stop at genuine EOF instead of busy-looping"); + await discardTask.ConfigureAwait(false); + } + + [TestMethod] + public async Task TestDiscardAsyncLeavesTheUnderlyingStreamOpenOnNormalCompletion() + { + // a keep-alive connection must survive an ordinary (non-cancelled) drain, since + // it is reused for the next request on the same connection + var stream = new TrackingMemoryStream(new byte[] { 1, 2, 3, 4 }); + var reader = new NetworkReader(stream, null, false); + var content = new ContentStream(reader, 4, TimeSpan.FromSeconds(30)); + + await content.DiscardAsync().ConfigureAwait(false); + + Assert.IsFalse(stream.Disposed, + "a normal drain must not close the underlying connection"); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/IO/TestNetworkReader.cs b/tests/MaxLib.WebServer.Test/IO/TestNetworkReader.cs index b44bb74..e63800e 100644 --- a/tests/MaxLib.WebServer.Test/IO/TestNetworkReader.cs +++ b/tests/MaxLib.WebServer.Test/IO/TestNetworkReader.cs @@ -2,6 +2,7 @@ using System.Linq; using System.Text; using System.IO; +using System.Threading; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Threading.Tasks; using MaxLib.WebServer.IO; @@ -11,6 +12,32 @@ namespace MaxLib.WebServer.Test.IO [TestClass] public class TestNetworkReader { + // Simulates a hostile/slow peer that never delivers more than one byte per + // socket read, regardless of how much buffer space or data is available. + // Used to force multi-byte UTF-8 sequences to split across many refills. + private sealed class OneByteAtATimeStream(byte[] data) : MemoryStream(data) + { + public override ValueTask ReadAsync(Memory buffer, + CancellationToken cancellationToken = default) + => base.ReadAsync(buffer.Length > 1 ? buffer[..1] : buffer, cancellationToken); + } + + // Used to exercise the constructor's "stream is not readable" guard, which a + // plain MemoryStream (always readable) can never trigger on its own. + private sealed class NonReadableStream : Stream + { + public override bool CanRead => false; + public override bool CanSeek => false; + public override bool CanWrite => true; + public override long Length => 0; + public override long Position { get => 0; set => throw new NotSupportedException(); } + public override void Flush() { } + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } + Stream baseStream; [TestInitialize] @@ -57,6 +84,21 @@ public async Task TestReadBytes() ); } + [TestMethod] + public async Task TestReadIntoStream() + { + var reader = new NetworkReader(baseStream); + await reader.ReadLineAsync().ConfigureAwait(false); + await reader.ReadLineAsync().ConfigureAwait(false); + using var output = new MemoryStream(); + var read = await reader.ReadAsync(output, 8).ConfigureAwait(false); + Assert.AreEqual(8, read); + Assert.AreEqual( + BitConverter.ToString(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 }), + BitConverter.ToString(output.ToArray()) + ); + } + [TestMethod] public async Task TestPeekAndReadBytes() { @@ -105,5 +147,608 @@ public async Task TestReadUntil() Assert.AreEqual("00-01-02-03", BitConverter.ToString(readed.ToArray())); Assert.AreEqual("04-05-06-07-08-09", BitConverter.ToString(await reader.ReadBytesAsync(6).ConfigureAwait(false))); } + + [TestMethod] + public async Task TestReadUntilAsync_MarkingSplitAcrossARefillIsStillFound() + { + // a marker straddling two refills (one byte per socket read here) must still be found + using var stream = new OneByteAtATimeStream(Encoding.UTF8.GetBytes("XXBOUNDYY")); + using var reader = new NetworkReader(stream); + + var readed = await reader.ReadUntilAsync(Encoding.UTF8.GetBytes("BOUND")).ConfigureAwait(false); + + Assert.AreEqual("XX", Encoding.UTF8.GetString(readed.ToArray())); + // the marker itself must remain unconsumed, ready for the caller to read next + var markerAndRemainder = await reader.ReadBytesAsync(7).ConfigureAwait(false); + Assert.AreEqual("BOUNDYY", Encoding.UTF8.GetString(markerAndRemainder)); + } + + // Regression test for https://github.com/Garados007/MaxLib.WebServer/issues/18 + // A "\r\n" line ending advances past the '\n' without decrementing the pending + // char count. That drift accumulates with every CRLF-terminated line and, once + // it overruns the actually-decoded data, the scan reads stale characters left + // over from a previous decode pass into the returned line (here: a spurious + // trailing '\0' instead of a clean "BC"). + [TestMethod] + public async Task TestReadLine_DoesNotDriftPastDecodedData() + { + // buffer size 8 forces exactly one decode pass to hold "A\r\nBC" (5 bytes), + // leaving the rest of the char buffer at its default '\0'. + var data = Encoding.ASCII.GetBytes("A\r\nBC"); + using var stream = new MemoryStream(data); + var reader = new NetworkReader(stream, Encoding.ASCII, false, 8); + Assert.AreEqual("A", await reader.ReadLineAsync().ConfigureAwait(false)); + Assert.AreEqual("BC", await reader.ReadLineAsync().ConfigureAwait(false)); + } + + // Regression test for https://github.com/Garados007/MaxLib.WebServer/issues/18 + // When the byte buffer is fully drained exactly as its read offset reaches the + // buffer's end, the buffer-compaction is skipped, so the following read targets + // a zero-length slice. That read returns 0 and is misread as "stream closed", + // even though more data is still available - silently truncating the stream. + [TestMethod] + public async Task TestReadLine_RefillsAfterBufferExactlyDrained() + { + // buffer size 8: the first line exactly fills the buffer with no line + // terminator, so the next line's data only arrives on a later refill. + var data = Encoding.ASCII.GetBytes("AAAAAAAA\r\nBBBB\r\n"); + using var stream = new MemoryStream(data); + var reader = new NetworkReader(stream, Encoding.ASCII, false, 8); + Assert.AreEqual("AAAAAAAA", await reader.ReadLineAsync().ConfigureAwait(false)); + Assert.AreEqual("BBBB", await reader.ReadLineAsync().ConfigureAwait(false)); + } + + // A malicious or merely unlucky peer can have its "\r\n" split exactly across + // two socket reads (the '\r' arrives at the very end of one chunk, the '\n' at + // the start of the next). The line must still be reassembled as one clean line. + [TestMethod] + public async Task TestReadLine_CrLfSplitAcrossRefillBoundary() + { + // buffer size 3: the first refill reads exactly "AB\r", stopping right on + // the '\r'; the '\n' only becomes available on the following refill. + var data = Encoding.ASCII.GetBytes("AB\r\nCD"); + using var stream = new MemoryStream(data); + var reader = new NetworkReader(stream, Encoding.ASCII, false, 3); + Assert.AreEqual("AB", await reader.ReadLineAsync().ConfigureAwait(false)); + Assert.AreEqual("CD", await reader.ReadLineAsync().ConfigureAwait(false)); + } + + // A client can send a bare '\r' that is not followed by '\n' (old Mac-style + // line ending, or just malformed/hostile input). It must still be treated as + // a line break without swallowing the character that follows it. + [TestMethod] + public async Task TestReadLine_BareCrWithoutLfIsTreatedAsLineBreak() + { + var data = Encoding.ASCII.GetBytes("A\rB\rC"); + using var stream = new MemoryStream(data); + var reader = new NetworkReader(stream, Encoding.ASCII, false, 8); + Assert.AreEqual("A", await reader.ReadLineAsync().ConfigureAwait(false)); + Assert.AreEqual("B", await reader.ReadLineAsync().ConfigureAwait(false)); + Assert.AreEqual("C", await reader.ReadLineAsync().ConfigureAwait(false)); + Assert.IsNull(await reader.ReadLineAsync().ConfigureAwait(false)); + } + + // A request whose header block is immediately terminated ("\r\n\r\n" with no + // headers at all) must yield two empty lines rather than being merged, dropped, + // or corrupted. buffer size 4 also forces the terminating refill to happen + // exactly when the byte buffer's read offset reaches its capacity. + [TestMethod] + public async Task TestReadLine_ConsecutiveBlankLines() + { + var data = Encoding.ASCII.GetBytes("\r\n\r\n"); + using var stream = new MemoryStream(data); + var reader = new NetworkReader(stream, Encoding.ASCII, false, 4); + Assert.AreEqual("", await reader.ReadLineAsync().ConfigureAwait(false)); + Assert.AreEqual("", await reader.ReadLineAsync().ConfigureAwait(false)); + Assert.IsNull(await reader.ReadLineAsync().ConfigureAwait(false)); + } + + // A client sending a byte that is not valid UTF-8 (here a lone 0xFF, which is + // never a legal lead byte) must not throw or desynchronize the reader. It + // should decode to the replacement character and parsing of subsequent, + // well-formed lines must continue normally. + [TestMethod] + public async Task TestReadLine_InvalidUtf8ByteDoesNotThrowAndKeepsSync() + { + var data = new byte[] { 0x41, 0xFF, 0x42, 0x0D, 0x0A, 0x43, 0x0D, 0x0A }; // "A" 0xFF "B\r\nC\r\n" + using var stream = new MemoryStream(data); + var reader = new NetworkReader(stream); + Assert.AreEqual("A�B", await reader.ReadLineAsync().ConfigureAwait(false)); + Assert.AreEqual("C", await reader.ReadLineAsync().ConfigureAwait(false)); + } + + // A hostile peer could dribble a multi-byte UTF-8 character one byte per + // socket read on purpose, hoping to desynchronize the decoder across many + // refills. The character must still be reconstructed correctly as part of a + // single line. + [TestMethod] + public async Task TestReadLine_MultiByteCharacterSplitByteByByteAcrossReads() + { + // "A" + U+1F600 (F0 9F 98 80, a 4-byte sequence) + "B\r\n" + var data = new byte[] { 0x41, 0xF0, 0x9F, 0x98, 0x80, 0x42, 0x0D, 0x0A }; + using var stream = new OneByteAtATimeStream(data); + var reader = new NetworkReader(stream); + var expected = "A" + char.ConvertFromUtf32(0x1F600) + "B"; + Assert.AreEqual(expected, await reader.ReadLineAsync().ConfigureAwait(false)); + } + + // A peer that connects and immediately closes without sending anything must + // be reported as a clean "no data", not throw or hang. + [TestMethod] + public async Task TestReadLine_EmptyStreamReturnsNull() + { + using var stream = new MemoryStream(Array.Empty()); + var reader = new NetworkReader(stream); + Assert.IsNull(await reader.ReadLineAsync().ConfigureAwait(false)); + } + + // A malformed multipart body whose boundary marker never actually appears + // must not hang forever or throw. All bytes up to the (never reached) EOF + // must be returned instead. + [TestMethod] + public async Task TestReadUntilAsync_MarkingNeverFoundReturnsAllBytes() + { + var data = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + using var stream = new MemoryStream(data); + var reader = new NetworkReader(stream); + var readed = await reader.ReadUntilAsync(new byte[] { 0xAA, 0xBB, 0xCC }).ConfigureAwait(false); + Assert.AreEqual(BitConverter.ToString(data), BitConverter.ToString(readed.ToArray())); + } + + // An empty marking must be a safe no-op: nothing is consumed from the stream + // and a subsequent real read still observes the untouched data. + [TestMethod] + public async Task TestReadUntilAsync_EmptyMarkingReadsNothing() + { + var data = new byte[] { 1, 2, 3 }; + using var stream = new MemoryStream(data); + var reader = new NetworkReader(stream); + var readed = await reader.ReadUntilAsync(Array.Empty()).ConfigureAwait(false); + Assert.AreEqual(0, readed.Length); + Assert.AreEqual( + BitConverter.ToString(data), + BitConverter.ToString(await reader.ReadBytesAsync(3).ConfigureAwait(false)) + ); + } + + // --- coverage: synchronous API mirrors --- + // The synchronous PeekChar/ReadChar/ReadLine methods (and the RefillCharBuffer/ + // RefillBuffer helpers behind them) are a fully separate code path from their + // async counterparts and were entirely untested. + + [TestMethod] + public void TestPeek_Sync() + { + var reader = new NetworkReader(baseStream); + Assert.AreEqual('♡', reader.PeekChar()); + Assert.AreEqual('♡', reader.PeekChar()); + Assert.AreEqual('♡', reader.ReadChar()); + } + + [TestMethod] + public void TestReadLine_Sync() + { + var reader = new NetworkReader(baseStream); + Assert.AreEqual("♡", reader.ReadLine()); + Assert.AreEqual("foo", reader.ReadLine()); + } + + [TestMethod] + public void TestReadChar_Sync_ReplacesInvalidByteWithReplacementChar() + { + var reader = new NetworkReader(baseStream); + // remove the first byte to kill the char, same trick as TestBrokenRead + var buffer = new byte[1]; + Assert.AreEqual(1, reader.Read(buffer, 0, 1)); + Assert.AreEqual(0xe2, buffer[0]); + Assert.AreEqual(65533, (int)reader.ReadChar()!); + } + + [TestMethod] + public void TestReadLine_Sync_BareCrWithoutLfIsTreatedAsLineBreak() + { + var data = Encoding.ASCII.GetBytes("A\rB"); + using var stream = new MemoryStream(data); + var reader = new NetworkReader(stream, Encoding.ASCII); + Assert.AreEqual("A", reader.ReadLine()); + Assert.AreEqual("B", reader.ReadLine()); + Assert.IsNull(reader.ReadLine()); + } + + [TestMethod] + public void TestReadLine_Sync_LineSpanningMultipleRefills() + { + // mirrors TestReadLine_RefillsAfterBufferExactlyDrained, but via the sync + // API: the terminator is only found after the partial line has already + // been buffered into a StringBuilder from an earlier refill. + var data = Encoding.ASCII.GetBytes("AAAAAAAA\r\nBBBB\r\n"); + using var stream = new MemoryStream(data); + var reader = new NetworkReader(stream, Encoding.ASCII, false, 8); + Assert.AreEqual("AAAAAAAA", reader.ReadLine()); + Assert.AreEqual("BBBB", reader.ReadLine()); + } + + [TestMethod] + public void TestReadLine_Sync_LineSpanningManyRefills() + { + // three refills happen before the terminator ever shows up, so the + // StringBuilder is already non-null on the second and third append - + // exercising the "already have a StringBuilder" side of `sb ??= ...`. + var data = Encoding.ASCII.GetBytes("AABBCC\r\n"); + using var stream = new MemoryStream(data); + var reader = new NetworkReader(stream, Encoding.ASCII, false, 2); + Assert.AreEqual("AABBCC", reader.ReadLine()); + } + + [TestMethod] + public void TestReadLine_Sync_BareCrAtEndOfStreamIsTreatedAsLineBreak() + { + // the '\r' is the very last byte in the stream, so the lookahead for a + // paired '\n' hits a genuine EOF rather than more buffered data. + var data = Encoding.ASCII.GetBytes("A\r"); + using var stream = new MemoryStream(data); + var reader = new NetworkReader(stream, Encoding.ASCII); + Assert.AreEqual("A", reader.ReadLine()); + Assert.IsNull(reader.ReadLine()); + } + + [TestMethod] + public void TestPeekAndReadChar_Sync_EmptyStreamReturnsNull() + { + using var stream = new MemoryStream(Array.Empty()); + var reader = new NetworkReader(stream); + Assert.IsNull(reader.PeekChar()); + Assert.IsNull(reader.ReadChar()); + } + + [TestMethod] + public async Task TestPeekAndReadChar_EmptyStreamReturnsNull() + { + using var stream = new MemoryStream(Array.Empty()); + var reader = new NetworkReader(stream); + Assert.IsNull(await reader.PeekCharAsync().ConfigureAwait(false)); + Assert.IsNull(await reader.ReadCharAsync().ConfigureAwait(false)); + } + + // --- coverage: Dispose / DisposeAsync lifecycle --- + + [TestMethod] + public void TestDispose_ClosesUnderlyingStreamAndBlocksFurtherUse() + { + var stream = new MemoryStream(new byte[] { 1, 2, 3 }); + var reader = new NetworkReader(stream); + reader.Dispose(); + Assert.ThrowsExactly(() => stream.ReadByte()); + Assert.ThrowsExactly(() => reader.ReadChar()); + } + + [TestMethod] + public void TestDispose_LeaveOpenTrue_DoesNotDisposeStream() + { + var stream = new MemoryStream(new byte[] { 1, 2, 3 }); + var reader = new NetworkReader(stream, Encoding.UTF8, leaveOpen: true); + reader.Dispose(); + Assert.AreEqual(1, stream.ReadByte()); + } + + [TestMethod] + public async Task TestDisposeAsync_ClosesUnderlyingStream() + { + var stream = new MemoryStream(new byte[] { 1, 2, 3 }); + var reader = new NetworkReader(stream); + await reader.DisposeAsync().ConfigureAwait(false); + Assert.ThrowsExactly(() => stream.ReadByte()); + } + + // --- coverage: constructor validation --- + + [TestMethod] + public void TestConstructor_NullStreamThrows() + { + Assert.ThrowsExactly(() => new NetworkReader(null!)); + } + + [TestMethod] + public void TestConstructor_NonReadableStreamThrows() + { + using var stream = new NonReadableStream(); + Assert.ThrowsExactly(() => new NetworkReader(stream)); + } + + [TestMethod] + public async Task TestConstructor_TwoArgOverload_UsesGivenEncoding() + { + var data = Encoding.ASCII.GetBytes("hi\r\n"); + using var stream = new MemoryStream(data); + var reader = new NetworkReader(stream, Encoding.ASCII); + Assert.AreEqual("hi", await reader.ReadLineAsync().ConfigureAwait(false)); + } + + // --- coverage: Encoding property --- + + [TestMethod] + public async Task TestEncodingSetter_ChangesDecoder() + { + var data = Encoding.ASCII.GetBytes("hi\r\n"); + using var stream = new MemoryStream(data); + var reader = new NetworkReader(stream, Encoding.UTF8); + Assert.AreEqual(Encoding.UTF8, reader.Encoding); + reader.Encoding = Encoding.ASCII; + Assert.AreEqual(Encoding.ASCII, reader.Encoding); + Assert.AreEqual("hi", await reader.ReadLineAsync().ConfigureAwait(false)); + } + + [TestMethod] + public void TestEncodingSetter_NullThrows() + { + using var stream = new MemoryStream(); + var reader = new NetworkReader(stream); + Assert.ThrowsExactly(() => reader.Encoding = null!); + } + + // --- coverage: raw byte-read overloads --- + // Read(byte[],offset,count) (the plain synchronous overload) was entirely + // untested, and several argument-validation branches on the async byte[] + // and Memory overloads were never exercised from the "throws" side. + + [TestMethod] + public void TestRead_Sync_ReadsBufferedAndRemainingBytes() + { + var reader = new NetworkReader(baseStream); + // ReadChar (unlike PeekChar) actually advances past the decoded char, so + // Read() must discard it from the pending char buffer before reading raw + // bytes, rather than silently re-serving already-consumed data. + Assert.AreEqual('♡', reader.ReadChar()); + var buffer = new byte[5]; + var read = reader.Read(buffer, 0, 5); + Assert.AreEqual(5, read); + Assert.AreEqual("0D-0A-66-6F-6F", BitConverter.ToString(buffer)); + } + + [TestMethod] + public void TestRead_Sync_ArgumentValidation() + { + var reader = new NetworkReader(baseStream); + var buffer = new byte[4]; + Assert.ThrowsExactly(() => reader.Read(null!, 0, 1)); + Assert.ThrowsExactly(() => reader.Read(buffer, -1, 1)); + Assert.ThrowsExactly(() => reader.Read(buffer, 5, 0)); + Assert.ThrowsExactly(() => reader.Read(buffer, 0, -1)); + Assert.ThrowsExactly(() => reader.Read(buffer, 2, 3)); + } + + [TestMethod] + public async Task TestReadAsync_ByteArray_ArgumentValidation() + { + var reader = new NetworkReader(baseStream); + var buffer = new byte[4]; + await Assert.ThrowsExactlyAsync( + () => reader.ReadAsync(null!, 0, 1).AsTask()); + await Assert.ThrowsExactlyAsync( + () => reader.ReadAsync(buffer, -1, 1).AsTask()); + await Assert.ThrowsExactlyAsync( + () => reader.ReadAsync(buffer, 5, 0).AsTask()); + await Assert.ThrowsExactlyAsync( + () => reader.ReadAsync(buffer, 0, -1).AsTask()); + await Assert.ThrowsExactlyAsync( + () => reader.ReadAsync(buffer, 2, 3).AsTask()); + } + + [TestMethod] + public async Task TestReadAsync_Memory_ReadsBufferedAndRemainingBytes() + { + var reader = new NetworkReader(baseStream); + // force everything into the internal byte buffer without consuming it + Assert.IsNotNull(await reader.PeekCharAsync().ConfigureAwait(false)); + + // fully satisfied from the pre-buffered bytes - no further stream read needed + var small = new byte[3]; + Assert.AreEqual(3, await reader.ReadAsync(small.AsMemory()).ConfigureAwait(false)); + Assert.AreEqual("E2-99-A1", BitConverter.ToString(small)); + + // requesting more than what's left pre-buffered must also pull from BaseStream + var rest = new byte[20]; + var read = await reader.ReadAsync(rest.AsMemory()).ConfigureAwait(false); + Assert.AreEqual(14, read); // 17 bytes total in the fixture, 3 already consumed + } + + [TestMethod] + public async Task TestReadMemoryAsync_ReturnsCorrectSlice() + { + var reader = new NetworkReader(baseStream); + var mem = await reader.ReadMemoryAsync(3).ConfigureAwait(false); + Assert.AreEqual(3, mem.Length); + Assert.AreEqual("E2-99-A1", BitConverter.ToString(mem.ToArray())); + } + + [TestMethod] + public async Task TestReadBytesAsync_ShortReadTrimsResultToActualLength() + { + // a client that promises more data (e.g. via Content-Length) than it + // actually sends must not get its short read padded with zero bytes. + using var stream = new MemoryStream(new byte[] { 1, 2, 3 }); + var reader = new NetworkReader(stream); + var result = await reader.ReadBytesAsync(10).ConfigureAwait(false); + Assert.AreEqual(3, result.Length); + Assert.AreEqual("01-02-03", BitConverter.ToString(result)); + } + + // --- coverage: ReadAsync(Stream, count) --- + + [TestMethod] + public async Task TestReadAsync_IntoStream_ArgumentValidation() + { + var reader = new NetworkReader(baseStream); + await Assert.ThrowsExactlyAsync( + () => reader.ReadAsync((Stream)null!, 1).AsTask()); + using var readOnlyTarget = new MemoryStream(new byte[] { 1, 2, 3 }, writable: false); + await Assert.ThrowsExactlyAsync( + () => reader.ReadAsync(readOnlyTarget, 1).AsTask()); + using var target = new MemoryStream(); + await Assert.ThrowsExactlyAsync( + () => reader.ReadAsync(target, -1).AsTask()); + } + + [TestMethod] + public async Task TestReadAsync_IntoStream_StopsEarlyWhenSourceExhausted() + { + // a malicious/broken peer can close the connection before delivering as + // many bytes as requested; the copy must stop cleanly instead of hanging. + using var stream = new MemoryStream(new byte[] { 1, 2, 3 }); + var reader = new NetworkReader(stream); + using var target = new MemoryStream(); + var read = await reader.ReadAsync(target, 100).ConfigureAwait(false); + Assert.AreEqual(3, read); + Assert.AreEqual("01-02-03", BitConverter.ToString(target.ToArray())); + } + + // --- coverage: synchronous ReadUntil, and the marking-too-large guard --- + + [TestMethod] + public void TestReadUntil_Sync_FindsMarking() + { + using var stream = new MemoryStream(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }); + var reader = new NetworkReader(stream); + var readed = reader.ReadUntil(new byte[] { 4, 5, 6 }); + Assert.AreEqual("00-01-02-03", BitConverter.ToString(readed.ToArray())); + var remainder = new byte[6]; + Assert.AreEqual(6, reader.Read(remainder, 0, 6)); + Assert.AreEqual("04-05-06-07-08-09", BitConverter.ToString(remainder)); + } + + [TestMethod] + public void TestReadUntil_Sync_MarkingSplitAcrossARefillIsStillFound() + { + using var stream = new OneByteAtATimeStream(Encoding.UTF8.GetBytes("XXBOUNDYY")); + var reader = new NetworkReader(stream); + + var readed = reader.ReadUntil(Encoding.UTF8.GetBytes("BOUND")); + + Assert.AreEqual("XX", Encoding.UTF8.GetString(readed.ToArray())); + var markerAndRemainder = new byte[7]; + Assert.AreEqual(7, reader.Read(markerAndRemainder, 0, 7)); + Assert.AreEqual("BOUNDYY", Encoding.UTF8.GetString(markerAndRemainder)); + } + + [TestMethod] + public void TestReadUntil_Sync_MarkingNeverFoundReturnsAllBytes() + { + var data = new byte[] { 1, 2, 3, 4, 5 }; + using var stream = new MemoryStream(data); + var reader = new NetworkReader(stream); + var readed = reader.ReadUntil(new byte[] { 0xAA, 0xBB }); + Assert.AreEqual(BitConverter.ToString(data), BitConverter.ToString(readed.ToArray())); + } + + [TestMethod] + public void TestReadUntil_Sync_EmptyMarkingReadsNothing() + { + var data = new byte[] { 1, 2, 3 }; + using var stream = new MemoryStream(data); + var reader = new NetworkReader(stream); + var readed = reader.ReadUntil(Array.Empty()); + Assert.AreEqual(0, readed.Length); + var remainder = new byte[3]; + Assert.AreEqual(3, reader.Read(remainder, 0, 3)); + Assert.AreEqual(BitConverter.ToString(data), BitConverter.ToString(remainder)); + } + + [TestMethod] + public void TestReadUntil_Sync_DiscardsPendingCharBufferBeforeSearching() + { + // ReadChar buffers ahead into the char buffer; ReadUntil operates on raw + // bytes and must discard that pending, already-decoded-but-unread data + // rather than re-serving it or losing the byte it corresponds to. + using var stream = new MemoryStream(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }); + var reader = new NetworkReader(stream); + Assert.IsNotNull(reader.ReadChar()); + var readed = reader.ReadUntil(new byte[] { 4, 5, 6 }); + Assert.AreEqual("01-02-03", BitConverter.ToString(readed.ToArray())); + } + + [TestMethod] + public void TestReadUntil_Sync_MarkingTooLargeForBufferThrows() + { + // a marking that (doubled, to guarantee room to slide the match window) + // does not fit in the read buffer must be rejected rather than silently + // producing wrong matches. + using var stream = new MemoryStream(new byte[] { 1, 2, 3, 4 }); + var reader = new NetworkReader(stream, Encoding.ASCII, false, 4); + Assert.ThrowsExactly(() => reader.ReadUntil(new byte[] { 1, 2, 3 })); + } + + [TestMethod] + public async Task TestReadUntilAsync_MarkingTooLargeForBufferThrows() + { + using var stream = new MemoryStream(new byte[] { 1, 2, 3, 4 }); + var reader = new NetworkReader(stream, Encoding.ASCII, false, 4); + await Assert.ThrowsExactlyAsync( + () => reader.ReadUntilAsync(new byte[] { 1, 2, 3 }).AsTask()); + } + + // --- coverage: ReadLineAsync(limit, ...) edge branches --- + // The happy path is already exercised indirectly via HttpRequestParser's + // tests; these cover the limit-specific branches that aren't. + + [TestMethod] + public async Task TestReadLineAsync_WithLimit_EmptyStreamReturnsNull() + { + using var stream = new MemoryStream(Array.Empty()); + var reader = new NetworkReader(stream); + Assert.IsNull(await reader.ReadLineAsync(10).ConfigureAwait(false)); + } + + [TestMethod] + public async Task TestReadLineAsync_NegativeLimitDelegatesToUnlimitedOverload() + { + var data = Encoding.ASCII.GetBytes("hello\r\n"); + using var stream = new MemoryStream(data); + var reader = new NetworkReader(stream, Encoding.ASCII); + Assert.AreEqual("hello", await reader.ReadLineAsync(-1).ConfigureAwait(false)); + } + + [TestMethod] + public async Task TestReadLineAsync_LineExceedingLimitThrowsWithinSingleRefill() + { + var data = Encoding.ASCII.GetBytes("abcdef\r\n"); + using var stream = new MemoryStream(data); + var reader = new NetworkReader(stream, Encoding.ASCII); + await Assert.ThrowsExactlyAsync( + () => reader.ReadLineAsync(3).AsTask()); + } + + [TestMethod] + public async Task TestReadLineAsync_LineExceedingLimitThrowsAcrossRefills() + { + // buffer size 4: neither "AAAA" nor "BBBB" contains a terminator on its + // own, so the overflow can only be detected once the accumulated partial + // line is checked against the limit between refills. + var data = Encoding.ASCII.GetBytes("AAAABBBB\r\n"); + using var stream = new MemoryStream(data); + var reader = new NetworkReader(stream, Encoding.ASCII, false, 4); + await Assert.ThrowsExactlyAsync( + () => reader.ReadLineAsync(6).AsTask()); + } + + [TestMethod] + public async Task TestReadLineAsync_WithLimit_LineSpanningMultipleRefillsSucceeds() + { + // the terminator is only found after a partial line already accumulated + // in a StringBuilder from an earlier refill - and the completed line + // still fits under the limit. + var data = Encoding.ASCII.GetBytes("AAAABB\r\n"); + using var stream = new MemoryStream(data); + var reader = new NetworkReader(stream, Encoding.ASCII, false, 4); + Assert.AreEqual("AAAABB", await reader.ReadLineAsync(10).ConfigureAwait(false)); + } + + [TestMethod] + public async Task TestReadLineAsync_ReturnsPartialLineOnEofWithinLimit() + { + var data = Encoding.ASCII.GetBytes("AB"); // no terminator, stream just ends + using var stream = new MemoryStream(data); + var reader = new NetworkReader(stream, Encoding.ASCII); + Assert.AreEqual("AB", await reader.ReadLineAsync(10).ConfigureAwait(false)); + } } } \ No newline at end of file diff --git a/tests/MaxLib.WebServer.Test/MaxLib.WebServer.Test.csproj b/tests/MaxLib.WebServer.Test/MaxLib.WebServer.Test.csproj index ff5d126..e366bdf 100644 --- a/tests/MaxLib.WebServer.Test/MaxLib.WebServer.Test.csproj +++ b/tests/MaxLib.WebServer.Test/MaxLib.WebServer.Test.csproj @@ -3,16 +3,16 @@ - net8.0 + net10.0;net8.0 false - - - - + + + + diff --git a/tests/MaxLib.WebServer.Test/PostData/TestMultipartFormData.cs b/tests/MaxLib.WebServer.Test/PostData/TestMultipartFormData.cs new file mode 100644 index 0000000..3f3d594 --- /dev/null +++ b/tests/MaxLib.WebServer.Test/PostData/TestMultipartFormData.cs @@ -0,0 +1,101 @@ +using System; +using System.IO; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using MaxLib.WebServer.IO; +using MaxLib.WebServer.Post; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +#nullable enable + +namespace MaxLib.WebServer.Test.PostData +{ + [TestClass] + public class TestMultipartFormData + { + // Delivers allowedBytes successfully, then throws on every further read + // (a client that stalls mid-upload). + private sealed class ThrowsAfterNBytesStream(byte[] data, int allowedBytes) : MemoryStream(data) + { + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + if (Position >= allowedBytes) + throw new IOException("simulated stalled upload"); + var maxLength = (int)Math.Min(buffer.Length, allowedBytes - Position); + return base.ReadAsync(buffer[..maxLength], cancellationToken); + } + } + + [TestMethod] + public async Task TestSetAsyncDeletesTheOrphanedTempFileWhenTheContentReadThrowsPartway() + { + var originalMapper = MultipartFormData.StorageMapper; + string? tempFilePath = null; + try + { + // AlwaysStoreFiles defaults to true, so a part with a filename always goes + // through the temp-file branch regardless of MaximumCacheSize. + var headerPart = + "-----1234\r\n" + + "Content-Type: text/plain\r\n" + + "Content-Disposition: form-data; name=\"f\"; filename=\"x\"\r\n" + + "\r\n"; + var bodyPart = "Hello World\r\n-----1234--\r\n"; + var content = headerPart + bodyPart; + var contentBytes = Encoding.UTF8.GetBytes(content); + var allowedBytes = Encoding.UTF8.GetByteCount(headerPart); + + MultipartFormData.StorageMapper = (task, file) => + { + tempFilePath = ((FileStream)file).Name; + return file; + }; + var reader = new NetworkReader(new ThrowsAfterNBytesStream(contentBytes, allowedBytes)); + var contentStream = new ContentStream(reader, contentBytes.Length); + var data = new MultipartFormData(); + + await Assert.ThrowsExactlyAsync( + () => data.SetAsync(new WebProgressTask(), contentStream, "boundary=---1234") + ).ConfigureAwait(false); + + Assert.IsNotNull(tempFilePath); + Assert.IsFalse(File.Exists(tempFilePath), + "the temp file must not be orphaned when reading the part's content fails partway through"); + } + finally + { + MultipartFormData.StorageMapper = originalMapper; + } + } + + [TestMethod] + public async Task TestSetAsyncRejectsAPartHeaderLineExceedingTheLengthLimit() + { + // a part header line without a CRLF must be rejected instead of buffering the whole remaining body + var originalLimit = MultipartFormData.MaxPartHeaderLineLength; + try + { + MultipartFormData.MaxPartHeaderLineLength = 16; + var content = + "-----1234\r\n" + + "X-Very-Long-Header-Name-That-Is-Way-Too-Long: value\r\n" + + "\r\n" + + "content\r\n" + + "-----1234--\r\n"; + var contentBytes = Encoding.UTF8.GetBytes(content); + var contentStream = new ContentStream(new NetworkReader(new MemoryStream(contentBytes)), contentBytes.Length); + var data = new MultipartFormData(); + var task = new WebProgressTask(); + + await data.SetAsync(task, contentStream, "boundary=---1234").ConfigureAwait(false); + + Assert.AreEqual(HttpStateCode.RequestHeaderFieldsTooLarge, task.Response.StatusCode); + } + finally + { + MultipartFormData.MaxPartHeaderLineLength = originalLimit; + } + } + } +} diff --git a/tests/MaxLib.WebServer.Test/PostData/TestRawPostData.cs b/tests/MaxLib.WebServer.Test/PostData/TestRawPostData.cs new file mode 100644 index 0000000..d0f8a6f --- /dev/null +++ b/tests/MaxLib.WebServer.Test/PostData/TestRawPostData.cs @@ -0,0 +1,125 @@ +using System; +using System.IO; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using MaxLib.WebServer.IO; +using MaxLib.WebServer.Post; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +#nullable enable + +namespace MaxLib.WebServer.Test.PostData +{ + [TestClass] + public class TestRawPostData + { + // Stream.ReadAsync may return fewer bytes than requested; deliver one byte at a time to make sure + // SetAsync doesn't truncate the body. + private sealed class OneByteAtATimeStream(byte[] data) : MemoryStream(data) + { + public override ValueTask ReadAsync(System.Memory buffer, + CancellationToken cancellationToken = default) + => base.ReadAsync(buffer.Length > 1 ? buffer[..1] : buffer, cancellationToken); + } + + [TestMethod] + public async Task TestSetAsyncReadsTheWholeBodyEvenWhenItArrivesOneByteAtATime() + { + var body = Encoding.UTF8.GetBytes("{\"hello\":\"world, this is a longer body than one byte\"}"); + using var content = new ContentStream(new NetworkReader(new OneByteAtATimeStream(body)), body.Length); + var data = new RawPostData(MimeType.ApplicationJson); + + await data.SetAsync(new WebProgressTask(), content, "").ConfigureAwait(false); + + Assert.IsNotNull(data.Entry.Content); + var stored = data.Entry.Content!.Value.ToArray(); + CollectionAssert.AreEqual(body, stored); + } + + // Reads one byte (so the temp file gets created), then throws on every further read. + private sealed class ThrowsAfterFirstReadStream(byte[] data) : MemoryStream(data) + { + public override async ValueTask ReadAsync(System.Memory buffer, + CancellationToken cancellationToken = default) + { + if (Position == 0) + return await base.ReadAsync(buffer.Length > 1 ? buffer[..1] : buffer, cancellationToken) + .ConfigureAwait(false); + throw new IOException("simulated stalled upload"); + } + } + + [TestMethod] + public async Task TestSetAsyncDeletesTheOrphanedTempFileWhenTheCopyThrowsPartway() + { + var originalLimit = RawPostData.MaximumCacheSize; + var originalMapper = MultipartFormData.StorageMapper; + string? tempFilePath = null; + try + { + RawPostData.MaximumCacheSize = 1; // force the temp-file branch regardless of body size + MultipartFormData.StorageMapper = (task, file) => + { + tempFilePath = ((FileStream)file).Name; + return file; + }; + var body = Encoding.UTF8.GetBytes("this body is definitely larger than one byte"); + var content = new ContentStream(new NetworkReader(new ThrowsAfterFirstReadStream(body)), body.Length); + var data = new RawPostData(MimeType.ApplicationOctetStream); + + await Assert.ThrowsExactlyAsync( + () => data.SetAsync(new WebProgressTask(), content, "") + ).ConfigureAwait(false); + + Assert.IsNotNull(tempFilePath); + Assert.IsFalse(File.Exists(tempFilePath), + "the temp file must not be orphaned when the copy into it fails partway through"); + } + finally + { + RawPostData.MaximumCacheSize = originalLimit; + MultipartFormData.StorageMapper = originalMapper; + } + } + + [TestMethod] + public async Task TestSetAsyncResolvesADeclaredNonUtf8Charset() + { + // "café" in ISO-8859-1: decoding as UTF-8 would mangle the 0xE9 byte + var body = new byte[] { (byte)'c', (byte)'a', (byte)'f', 0xE9 }; + var content = new ContentStream(new NetworkReader(new MemoryStream(body)), body.Length); + var data = new RawPostData(MimeType.TextPlain); + + await data.SetAsync(new WebProgressTask(), content, "charset=iso-8859-1").ConfigureAwait(false); + + Assert.AreEqual("café", data.Encoding.GetString(data.Entry.Content!.Value.Span)); + } + + [TestMethod] + public async Task TestSetAsyncResolvesAQuotedNonUtf8Charset() + { + // a quoted charset value (RFC 9110 §5.6.6) must be unwrapped, not fall back to UTF-8 + var body = new byte[] { (byte)'c', (byte)'a', (byte)'f', 0xE9 }; + var content = new ContentStream(new NetworkReader(new MemoryStream(body)), body.Length); + var data = new RawPostData(MimeType.TextPlain); + + await data.SetAsync(new WebProgressTask(), content, "charset=\"iso-8859-1\"").ConfigureAwait(false); + + Assert.AreEqual("iso-8859-1", data.Encoding.WebName); + Assert.AreEqual("café", data.Encoding.GetString(data.Entry.Content!.Value.Span)); + } + + [TestMethod] + public async Task TestSetAsyncDefaultsToUtf8WhenNoCharsetIsDeclared() + { + var body = Encoding.UTF8.GetBytes("café"); + var content = new ContentStream(new NetworkReader(new MemoryStream(body)), body.Length); + var data = new RawPostData(MimeType.TextPlain); + + await data.SetAsync(new WebProgressTask(), content, "").ConfigureAwait(false); + + Assert.AreEqual(Encoding.UTF8, data.Encoding); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/PostData/TestUrlEncodedData.cs b/tests/MaxLib.WebServer.Test/PostData/TestUrlEncodedData.cs new file mode 100644 index 0000000..1043b12 --- /dev/null +++ b/tests/MaxLib.WebServer.Test/PostData/TestUrlEncodedData.cs @@ -0,0 +1,110 @@ +using System; +using System.IO; +using System.Reflection; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using MaxLib.WebServer.IO; +using MaxLib.WebServer.Post; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +#nullable enable + +namespace MaxLib.WebServer.Test.PostData +{ + [TestClass] + public class TestUrlEncodedData + { + // Stream.ReadAsync may return fewer bytes than requested; deliver one byte at a time to make sure + // SetAsync doesn't truncate the body. + private sealed class OneByteAtATimeStream(byte[] data) : MemoryStream(data) + { + public override ValueTask ReadAsync(System.Memory buffer, + CancellationToken cancellationToken = default) + => base.ReadAsync(buffer.Length > 1 ? buffer[..1] : buffer, cancellationToken); + } + + [TestMethod] + public async Task TestSetAsyncReadsTheWholeBodyEvenWhenItArrivesOneByteAtATime() + { + var body = Encoding.UTF8.GetBytes("firstKey=firstValue&secondKey=secondValueThatIsLonger"); + using var content = new ContentStream(new NetworkReader(new OneByteAtATimeStream(body)), body.Length); + var data = new UrlEncodedData(); + + await data.SetAsync(new WebProgressTask(), content, "").ConfigureAwait(false); + + Assert.AreEqual("firstValue", data.Parameter["firstKey"]); + Assert.AreEqual("secondValueThatIsLonger", data.Parameter["secondKey"]); + } + + [TestMethod] + public void TestResolveEncodingResolvesAQuotedNonUtf8Charset() + { + // a quoted charset value must be unwrapped, not fall back to UTF-8; invoked via reflection + // because ResolveEncoding is private + var resolveEncoding = typeof(UrlEncodedData).GetMethod("ResolveEncoding", BindingFlags.NonPublic | BindingFlags.Static) + ?? throw new InvalidOperationException("UrlEncodedData.ResolveEncoding method not found - test needs updating to match the current method name"); + + var unquoted = (Encoding?)resolveEncoding.Invoke(null, ["charset=iso-8859-1"]); + var quoted = (Encoding?)resolveEncoding.Invoke(null, ["charset=\"iso-8859-1\""]); + + Assert.AreEqual("iso-8859-1", unquoted?.WebName); + Assert.AreEqual("iso-8859-1", quoted?.WebName); + } + + // Forwards everything to the wrapped stream except writing, which always fails - + // simulating a mid-write fault while spilling one oversized overflow value to disk. + private sealed class ThrowsOnWriteStream(Stream inner) : Stream + { + public override bool CanRead => inner.CanRead; + public override bool CanSeek => inner.CanSeek; + public override bool CanWrite => inner.CanWrite; + public override long Length => inner.Length; + public override long Position { get => inner.Position; set => inner.Position = value; } + public override void Flush() => inner.Flush(); + public override int Read(byte[] buffer, int offset, int count) => inner.Read(buffer, offset, count); + public override long Seek(long offset, SeekOrigin origin) => inner.Seek(offset, origin); + public override void SetLength(long value) => inner.SetLength(value); + public override void Write(byte[] buffer, int offset, int count) + => throw new IOException("simulated write failure"); + public override ValueTask WriteAsync(ReadOnlyMemory buffer, + CancellationToken cancellationToken = default) + => throw new IOException("simulated write failure"); + } + + [TestMethod] + public async Task TestAddTokenAsyncDeletesTheOrphanedTempFileWhenTheWriteThrowsPartway() + { + var originalLimit = UrlEncodedData.MaximumCacheSize; + var originalMapper = MultipartFormData.StorageMapper; + string? tempFilePath = null; + try + { + // forces both the raw-body overflow spool and, since the single value alone + // exceeds it too, the per-value temp-file branch in AddTokenAsync + UrlEncodedData.MaximumCacheSize = 1; + MultipartFormData.StorageMapper = (task, file) => + { + tempFilePath = ((FileStream)file).Name; + return new ThrowsOnWriteStream(file); + }; + var body = Encoding.UTF8.GetBytes("key=thisvalueislongerthanonebyte"); + var content = new ContentStream(new NetworkReader(new MemoryStream(body)), body.Length); + var data = new UrlEncodedData(); + + await Assert.ThrowsExactlyAsync( + () => data.SetAsync(new WebProgressTask(), content, "") + ).ConfigureAwait(false); + + Assert.IsNotNull(tempFilePath); + Assert.IsFalse(File.Exists(tempFilePath), + "the temp file must not be orphaned when the write into it fails partway through"); + } + finally + { + UrlEncodedData.MaximumCacheSize = originalLimit; + MultipartFormData.StorageMapper = originalMapper; + } + } + } +} diff --git a/tests/MaxLib.WebServer.Test/SSL/TestDualSecureWebServerSettings.cs b/tests/MaxLib.WebServer.Test/SSL/TestDualSecureWebServerSettings.cs new file mode 100644 index 0000000..e17cb30 --- /dev/null +++ b/tests/MaxLib.WebServer.Test/SSL/TestDualSecureWebServerSettings.cs @@ -0,0 +1,27 @@ +using System; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using MaxLib.WebServer.SSL; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace MaxLib.WebServer.Test.SSL +{ + [TestClass] + public class TestDualSecureWebServerSettings + { + [TestMethod] + public void TestHandshakeTimeoutDefaultsToTenSeconds() + { + using var rsa = RSA.Create(2048); + var request = new CertificateRequest( + "CN=maxlib-webserver-test", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1 + ); + using var certificate = request.CreateSelfSigned( + DateTimeOffset.UtcNow.AddMinutes(-5), DateTimeOffset.UtcNow.AddMinutes(5)); + + var settings = new DualSecureWebServerSettings(443, 5000, certificate); + + Assert.AreEqual(TimeSpan.FromSeconds(10), settings.HandshakeTimeout); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/SSL/TestSecureHandshakeFailure.cs b/tests/MaxLib.WebServer.Test/SSL/TestSecureHandshakeFailure.cs new file mode 100644 index 0000000..35589d7 --- /dev/null +++ b/tests/MaxLib.WebServer.Test/SSL/TestSecureHandshakeFailure.cs @@ -0,0 +1,213 @@ +using System; +using System.Net; +using System.Net.Sockets; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using MaxLib.WebServer.SSL; + +namespace MaxLib.WebServer.Test.SSL +{ + [TestClass] + public class TestSecureHandshakeFailure + { + private static X509Certificate2 CreateSelfSignedCertificate() + { + using var rsa = RSA.Create(2048); + var request = new CertificateRequest( + "CN=maxlib-webserver-test", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1 + ); + return request.CreateSelfSigned(DateTimeOffset.UtcNow.AddMinutes(-5), DateTimeOffset.UtcNow.AddMinutes(5)); + } + + private static int GetFreePort() + { + var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var port = ((IPEndPoint)listener.LocalEndpoint).Port; + listener.Stop(); + return port; + } + + private static async Task WaitUntilAsync(Func condition, TimeSpan timeout) + { + var deadline = DateTime.UtcNow + timeout; + while (!condition() && DateTime.UtcNow < deadline) + await Task.Delay(20).ConfigureAwait(false); + } + + [TestMethod] + public async Task TestSecureWebServerRemovesTheConnectionWhenTheHandshakeThrows() + { + using var cert = CreateSelfSignedCertificate(); + var port = GetFreePort(); + var settings = new SecureWebServerSettings(port, connectionTimeout: 5000) + { + Certificate = cert, + }; + var server = new SecureWebServer(settings); + server.Start(); + try + { + using (var client = new TcpClient()) + { + await client.ConnectAsync(IPAddress.Loopback, port).ConfigureAwait(false); + // garbage instead of a TLS ClientHello - makes AuthenticateAsServerAsync throw + var garbage = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + await client.GetStream().WriteAsync(garbage).ConfigureAwait(false); + } + + await WaitUntilAsync(() => server.AllConnections.Count == 0, TimeSpan.FromSeconds(5)) + .ConfigureAwait(false); + + Assert.AreEqual(0, server.AllConnections.Count, + "the connection must be removed even though the TLS handshake threw"); + } + finally + { + server.Stop(); + } + } + + [TestMethod] + public async Task TestSecureWebServerDropsAStalledConnectionThatNeverSendsAnything() + { + using var cert = CreateSelfSignedCertificate(); + var port = GetFreePort(); + var settings = new SecureWebServerSettings(port, connectionTimeout: 5000) + { + Certificate = cert, + HandshakeTimeout = TimeSpan.FromMilliseconds(300), + }; + var server = new SecureWebServer(settings); + server.Start(); + try + { + using var client = new TcpClient(); + await client.ConnectAsync(IPAddress.Loopback, port).ConfigureAwait(false); + // send nothing at all: only HandshakeTimeout ends this connection + + // confirm the connection was registered first, or the wait below could pass + // before the server accepted it + await WaitUntilAsync(() => server.AllConnections.Count == 1, TimeSpan.FromSeconds(5)) + .ConfigureAwait(false); + Assert.AreEqual(1, server.AllConnections.Count, + "the connection was never registered - test setup is broken"); + + await WaitUntilAsync(() => server.AllConnections.Count == 0, TimeSpan.FromSeconds(5)) + .ConfigureAwait(false); + + Assert.AreEqual(0, server.AllConnections.Count, + "a stalled handshake that never receives any data must eventually be dropped"); + } + finally + { + server.Stop(); + } + } + + [TestMethod] + public async Task TestDualSecureWebServerDropsAStalledConnectionThatNeverSendsAnything() + { + using var cert = CreateSelfSignedCertificate(); + var port = GetFreePort(); + var settings = new DualSecureWebServerSettings(port, 5000, cert) + { + HandshakeTimeout = TimeSpan.FromMilliseconds(300), + }; + var server = new DualSecureWebServer(settings); + server.Start(); + try + { + using var client = new TcpClient(); + await client.ConnectAsync(IPAddress.Loopback, port).ConfigureAwait(false); + // send nothing at all: only HandshakeTimeout ends the initial protocol peek + + // confirm the connection was registered first, or the wait below could pass + // before the server accepted it + await WaitUntilAsync(() => server.AllConnections.Count == 1, TimeSpan.FromSeconds(5)) + .ConfigureAwait(false); + Assert.AreEqual(1, server.AllConnections.Count, + "the connection was never registered - test setup is broken"); + + await WaitUntilAsync(() => server.AllConnections.Count == 0, TimeSpan.FromSeconds(5)) + .ConfigureAwait(false); + + Assert.AreEqual(0, server.AllConnections.Count, + "a stalled connection that never sends its first byte must eventually be dropped"); + } + finally + { + server.Stop(); + } + } + + [TestMethod] + public async Task TestDualSecureWebServerRemovesTheConnectionWhenTheHandshakeThrows() + { + using var cert = CreateSelfSignedCertificate(); + var port = GetFreePort(); + var settings = new DualSecureWebServerSettings(port, 5000, cert); + var server = new DualSecureWebServer(settings); + server.Start(); + try + { + using (var client = new TcpClient()) + { + await client.ConnectAsync(IPAddress.Loopback, port).ConfigureAwait(false); + // a non-ASCII first byte routes this down DualSecureWebServer's SSL branch; + // the rest is garbage instead of a real TLS ClientHello + var garbage = new byte[] { 0xFF, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + await client.GetStream().WriteAsync(garbage).ConfigureAwait(false); + } + + await WaitUntilAsync(() => server.AllConnections.Count == 0, TimeSpan.FromSeconds(5)) + .ConfigureAwait(false); + + Assert.AreEqual(0, server.AllConnections.Count, + "the connection must be removed even though the TLS handshake threw"); + } + finally + { + server.Stop(); + } + } + + [TestMethod] + public async Task TestDualSecureWebServerRemovesTheConnectionWhenResetBeforeTheFirstByte() + { + using var cert = CreateSelfSignedCertificate(); + var port = GetFreePort(); + var settings = new DualSecureWebServerSettings(port, 5000, cert); + var server = new DualSecureWebServer(settings); + server.Start(); + try + { + using (var client = new TcpClient()) + { + await client.ConnectAsync(IPAddress.Loopback, port).ConfigureAwait(false); + // confirm the connection was registered first, so the abortive close races the server's read + await WaitUntilAsync(() => server.AllConnections.Count == 1, TimeSpan.FromSeconds(5)) + .ConfigureAwait(false); + Assert.AreEqual(1, server.AllConnections.Count, + "the connection was never registered - test setup is broken"); + + // abortive close (RST) before sending any byte; Socket.Close(0) forces this instead of a graceful FIN + client.Client.Close(0); + } + + await WaitUntilAsync(() => server.AllConnections.Count == 0, TimeSpan.FromSeconds(5)) + .ConfigureAwait(false); + + Assert.AreEqual(0, server.AllConnections.Count, + "a connection reset before the first byte must not leak the connection"); + } + finally + { + server.Stop(); + } + } + } +} diff --git a/tests/MaxLib.WebServer.Test/SSL/TestSecureWebServerAcceptLoopExceptionSafety.cs b/tests/MaxLib.WebServer.Test/SSL/TestSecureWebServerAcceptLoopExceptionSafety.cs new file mode 100644 index 0000000..6ea69f9 --- /dev/null +++ b/tests/MaxLib.WebServer.Test/SSL/TestSecureWebServerAcceptLoopExceptionSafety.cs @@ -0,0 +1,120 @@ +using System; +using System.Net; +using System.Net.Sockets; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using System.Threading; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using MaxLib.WebServer.SSL; + +namespace MaxLib.WebServer.Test.SSL +{ + [TestClass] + public class TestSecureWebServerAcceptLoopExceptionSafety + { + private static X509Certificate2 CreateSelfSignedCertificate() + { + using var rsa = RSA.Create(2048); + var request = new CertificateRequest( + "CN=maxlib-webserver-test", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1 + ); + return request.CreateSelfSigned(DateTimeOffset.UtcNow.AddMinutes(-5), DateTimeOffset.UtcNow.AddMinutes(5)); + } + + // Mirrors TestServerAcceptLoopExceptionSafety's ThrowingAcceptServer for SecureWebServer.SecureMainTask's accept loop. + private sealed class ThrowingSecureAcceptServer : SecureWebServer + { + public int SecureClientConnectedCalls; + + public ThrowingSecureAcceptServer(SecureWebServerSettings settings) : base(settings) { } + + public void SetSecureListener(TcpListener listener) => SecureListener = listener; + + protected override void SecureClientConnected(TcpClient client) + { + Interlocked.Increment(ref SecureClientConnectedCalls); + client.Dispose(); + if (SecureClientConnectedCalls == 1) + throw new InvalidOperationException("simulated accept-time failure"); + ServerExecution = false; + } + + public void RunSecureMainTaskOnceSynchronously() + { + ServerExecution = true; + SecureMainTask(); + } + } + + [TestMethod] + public void TestSecureMainTaskSurvivesAnExceptionFromSecureClientConnected() + { + using var cert = CreateSelfSignedCertificate(); + using var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + using var client1 = new TcpClient(); + client1.Connect((IPEndPoint)listener.LocalEndpoint); + using var client2 = new TcpClient(); + client2.Connect((IPEndPoint)listener.LocalEndpoint); + var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(5); + while (!listener.Pending() && DateTime.UtcNow < deadline) + Thread.Sleep(5); + + var settings = new SecureWebServerSettings(1, 1, 5000) { Certificate = cert }; + var server = new ThrowingSecureAcceptServer(settings); + server.SetSecureListener(listener); + + server.RunSecureMainTaskOnceSynchronously(); + + Assert.AreEqual(2, server.SecureClientConnectedCalls, + "the accept loop must keep accepting further pending connections even after SecureClientConnected throws for an earlier one"); + } + + // Throws without ever touching (or disposing) the accepted client itself. + private sealed class ThrowingAfterSecureAcceptServer : SecureWebServer + { + public ThrowingAfterSecureAcceptServer(SecureWebServerSettings settings) : base(settings) { } + + public void SetSecureListener(TcpListener listener) => SecureListener = listener; + + protected override void SecureClientConnected(TcpClient client) + { + ServerExecution = false; + throw new InvalidOperationException("simulated post-accept failure"); + } + + public void RunSecureMainTaskOnceSynchronously() + { + ServerExecution = true; + SecureMainTask(); + } + } + + [TestMethod] + public void TestSecureMainTaskClosesTheAcceptedClientWhenSecureClientConnectedThrows() + { + using var cert = CreateSelfSignedCertificate(); + using var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + using var client = new TcpClient(); + client.Connect((IPEndPoint)listener.LocalEndpoint); + var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(5); + while (!listener.Pending() && DateTime.UtcNow < deadline) + Thread.Sleep(5); + + var settings = new SecureWebServerSettings(1, 1, 5000) { Certificate = cert }; + var server = new ThrowingAfterSecureAcceptServer(settings); + server.SetSecureListener(listener); + + server.RunSecureMainTaskOnceSynchronously(); + + // if the server never closes the accepted client, this blocks until the receive + // timeout instead of observing a graceful EOF (read returning 0) + client.ReceiveTimeout = 2000; + var buffer = new byte[1]; + var read = client.GetStream().Read(buffer, 0, 1); + Assert.AreEqual(0, read, + "the server must close the accepted client if SecureClientConnected throws, or its socket leaks forever"); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/SSL/TestSecureWebServerSettings.cs b/tests/MaxLib.WebServer.Test/SSL/TestSecureWebServerSettings.cs new file mode 100644 index 0000000..678864b --- /dev/null +++ b/tests/MaxLib.WebServer.Test/SSL/TestSecureWebServerSettings.cs @@ -0,0 +1,17 @@ +using System; +using MaxLib.WebServer.SSL; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace MaxLib.WebServer.Test.SSL +{ + [TestClass] + public class TestSecureWebServerSettings + { + [TestMethod] + public void TestHandshakeTimeoutDefaultsToTenSeconds() + { + var settings = new SecureWebServerSettings(443, 5000); + Assert.AreEqual(TimeSpan.FromSeconds(10), settings.HandshakeTimeout); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/SSL/TestStreamPeaker.cs b/tests/MaxLib.WebServer.Test/SSL/TestStreamPeaker.cs new file mode 100644 index 0000000..0fe4a0b --- /dev/null +++ b/tests/MaxLib.WebServer.Test/SSL/TestStreamPeaker.cs @@ -0,0 +1,243 @@ +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using MaxLib.WebServer.SSL; + +namespace MaxLib.WebServer.Test.SSL +{ + [TestClass] + public class TestStreamPeaker + { + // A stream whose ReadAsync never completes on its own - simulates a client that + // opened the connection but never sends anything at all. + class NeverRespondingStream : Stream + { + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => throw new NotSupportedException(); + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + // only ends when the token is cancelled, which propagates out of this call + await Task.Delay(Timeout.Infinite, cancellationToken).ConfigureAwait(false); + return 0; + } + + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + public override void Flush() { } + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } + + // Delivers exactly one byte successfully, then never completes again - simulates a + // client that sends enough to pass the initial peek and then stalls mid-handshake. + class FirstByteThenStallsStream : Stream + { + bool firstByteGiven; + + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => throw new NotSupportedException(); + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + if (!firstByteGiven) + { + firstByteGiven = true; + buffer.Span[0] = 0x16; + return 1; + } + await Task.Delay(Timeout.Infinite, cancellationToken).ConfigureAwait(false); + return 0; + } + + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + public override void Flush() { } + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } + + // Simulates a socket that delivers its payload in small fragments instead of + // handing back everything in one Read() call, and reports a graceful close + // (Read() returning 0) once the payload is exhausted. + class FragmentedStream : Stream + { + readonly byte[] data; + readonly int maxChunk; + int position; + + public FragmentedStream(byte[] data, int maxChunk) + { + this.data = data; + this.maxChunk = maxChunk; + } + + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => throw new NotSupportedException(); + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + public override int Read(byte[] buffer, int offset, int count) + { + var remaining = data.Length - position; + if (remaining == 0) + return 0; + var length = Math.Min(Math.Min(count, maxChunk), remaining); + Array.Copy(data, position, buffer, offset, length); + position += length; + return length; + } + + public override void Flush() { } + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } + + [TestMethod] + public void TestFirstByteIsPeekedNotConsumed() + { + var peaker = new DualSecureWebServer.StreamPeaker(new FragmentedStream(new byte[] { 0x16, 0x03, 0x01 }, 16)); + Assert.IsTrue(peaker.HasFirstByte); + Assert.AreEqual((byte)0x16, peaker.FirstByte); + // reading FirstByte again must not advance the underlying stream + Assert.AreEqual((byte)0x16, peaker.FirstByte); + + var buffer = new byte[3]; + var read = peaker.Read(buffer, 0, buffer.Length); + Assert.AreEqual(3, read); + CollectionAssert.AreEqual(new byte[] { 0x16, 0x03, 0x01 }, buffer); + } + + [TestMethod] + public void TestReadForwardsFragmentedUnderlyingReads() + { + var payload = new byte[] { 0x47, 0x45, 0x54, 0x20, 0x2f, 0x20, 0x48, 0x54, 0x54, 0x50 }; // "GET / HTTP" + // force the underlying stream to hand back at most 2 bytes per Read() call + var peaker = new DualSecureWebServer.StreamPeaker(new FragmentedStream(payload, 2)); + + Assert.AreEqual((byte)'G', peaker.FirstByte); + + var result = new byte[payload.Length]; + var total = 0; + while (total < result.Length) + { + var read = peaker.Read(result, total, result.Length - total); + Assert.IsTrue(read > 0, "Read() returned 0 before all data was consumed"); + total += read; + } + + CollectionAssert.AreEqual(payload, result); + } + + [TestMethod] + public void TestEmptyStreamDoesNotFakeAZeroByte() + { + var peaker = new DualSecureWebServer.StreamPeaker(new FragmentedStream(Array.Empty(), 16)); + + // Before the fix, an immediately-closed connection was indistinguishable from + // one whose first byte genuinely is 0x00 - FirstByte would silently report 0. + Assert.IsFalse(peaker.HasFirstByte); + Assert.AreEqual((byte)0, peaker.FirstByte); + + var buffer = new byte[4]; + var read = peaker.Read(buffer, 0, buffer.Length); + Assert.AreEqual(0, read, "Read() must report end-of-stream instead of hanging or fabricating data"); + } + + [TestMethod] + public void TestLiteralZeroFirstByteIsStillReadCorrectly() + { + // a peer that legitimately sends 0x00 as its first byte must still round-trip + // correctly and must be distinguishable from the empty-stream case above. + var peaker = new DualSecureWebServer.StreamPeaker(new FragmentedStream(new byte[] { 0x00, 0x01 }, 16)); + + Assert.IsTrue(peaker.HasFirstByte); + Assert.AreEqual((byte)0, peaker.FirstByte); + + var buffer = new byte[2]; + var read = peaker.Read(buffer, 0, buffer.Length); + Assert.AreEqual(2, read); + CollectionAssert.AreEqual(new byte[] { 0x00, 0x01 }, buffer); + } + + [TestMethod] + public async Task TestEnsureFirstByteAsyncCachesTheByteForLaterSynchronousAccess() + { + var peaker = new DualSecureWebServer.StreamPeaker(new FragmentedStream(new byte[] { 0x16, 0x03 }, 16)); + + await peaker.EnsureFirstByteAsync(CancellationToken.None).ConfigureAwait(false); + + // FirstByte must return the already-cached value without reading again + Assert.AreEqual((byte)0x16, peaker.FirstByte); + var buffer = new byte[2]; + Assert.AreEqual(2, peaker.Read(buffer, 0, 2)); + CollectionAssert.AreEqual(new byte[] { 0x16, 0x03 }, buffer); + } + + [TestMethod] + public async Task TestEnsureFirstByteAsyncRespectsCancellation() + { + // a timeout must be able to cancel the peek for a client that never sends anything + var peaker = new DualSecureWebServer.StreamPeaker(new NeverRespondingStream()); + using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(50)); + + await Assert.ThrowsExactlyAsync( + () => peaker.EnsureFirstByteAsync(cts.Token).AsTask() + ).ConfigureAwait(false); + } + + [TestMethod] + public async Task TestReadAsyncPastTheFirstByteRespectsCancellation() + { + // SslStream reads the rest of the handshake through the peaker; those reads must stay cancellable + var peaker = new DualSecureWebServer.StreamPeaker(new FirstByteThenStallsStream()); + await peaker.EnsureFirstByteAsync(CancellationToken.None).ConfigureAwait(false); + Assert.AreEqual((byte)0x16, peaker.FirstByte); + + using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(50)); + var buffer = new byte[16]; + + await Assert.ThrowsExactlyAsync( + () => peaker.ReadAsync(buffer.AsMemory(), cts.Token).AsTask() + ).ConfigureAwait(false); + } + + [TestMethod] + public void TestSingleByteReadAfterPeek() + { + var peaker = new DualSecureWebServer.StreamPeaker(new FragmentedStream(new byte[] { 0xAA, 0xBB }, 16)); + Assert.AreEqual((byte)0xAA, peaker.FirstByte); + + var buffer = new byte[1]; + Assert.AreEqual(1, peaker.Read(buffer, 0, 1)); + Assert.AreEqual((byte)0xAA, buffer[0]); + + Assert.AreEqual(1, peaker.Read(buffer, 0, 1)); + Assert.AreEqual((byte)0xBB, buffer[0]); + + Assert.AreEqual(0, peaker.Read(buffer, 0, 1)); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/Services/TestHttp404Service.cs b/tests/MaxLib.WebServer.Test/Services/TestHttp404Service.cs new file mode 100644 index 0000000..289551a --- /dev/null +++ b/tests/MaxLib.WebServer.Test/Services/TestHttp404Service.cs @@ -0,0 +1,68 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using MaxLib.WebServer.IO; +using MaxLib.WebServer.Services; +using MaxLib.WebServer.Testing; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +#nullable enable + +namespace MaxLib.WebServer.Test.Services +{ + [TestClass] + public class TestHttp404Service + { + // Simulates a client that stalls mid-upload: every async read blocks forever unless the + // caller's cancellation token fires - mirrors TestHttpSender.StallingStream. + private sealed class StallingStream : Stream + { + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => throw new NotSupportedException(); + public override long Position + { + get => 0; + set => throw new NotSupportedException(); + } + public override void Flush() { } + public override int Read(byte[] buffer, int offset, int count) + => throw new NotSupportedException("only the async read paths are exercised here"); + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + => ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + await Task.Delay(Timeout.Infinite, cancellationToken).ConfigureAwait(false); + throw new InvalidOperationException("unreachable: Task.Delay(Infinite) only ever completes by cancellation"); + } + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } + + [TestMethod] + public void TestProgressTaskDoesNotBlockOnAStalledBody() + { + // the 404 response must neither block on nor fail because of a stalled request body + var server = new TestWebServer(); + var task = new TestTask(server) { CurrentStage = ServerStage.CreateDocument }.Task; + var reader = new NetworkReader(new StallingStream(), null, true); + var content = new ContentStream(reader, 1024, TimeSpan.FromMilliseconds(50)); + task.Request.Post.SetPost(task, content, "text/plain"); + + var stopwatch = Stopwatch.StartNew(); + new Http404Service().ProgressTask(task).GetAwaiter().GetResult(); + stopwatch.Stop(); + + Assert.IsTrue(stopwatch.Elapsed < TimeSpan.FromSeconds(2), + $"ProgressTask must not block on the request body at all, took {stopwatch.Elapsed}"); + Assert.AreEqual(HttpStateCode.NotFound, task.Response.StatusCode); + var body = ((HttpStringDataSource)task.Document.DataSources.Single()).Data; + StringAssert.Contains(body, "[text/plain]"); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/Services/TestHttpRequestParser.cs b/tests/MaxLib.WebServer.Test/Services/TestHttpRequestParser.cs index e7141b3..2cf1a14 100644 --- a/tests/MaxLib.WebServer.Test/Services/TestHttpRequestParser.cs +++ b/tests/MaxLib.WebServer.Test/Services/TestHttpRequestParser.cs @@ -1,4 +1,5 @@ using System; +using System.IO; using System.Text; using System.Threading.Tasks; using MaxLib.WebServer.Services; @@ -42,6 +43,24 @@ public async Task TestRequestParser_SimpleGet() } } + [TestMethod] + public async Task TestRequestParser_DuplicatedHeaderNameDoesNotCrashAndLastValueWins() + { + // a repeated header name must not crash parsing + var sb = new StringBuilder(); + sb.AppendLine("GET /test.html HTTP/1.1"); + sb.AppendLine("Host: testdomain.local"); + sb.AppendLine("X-Custom: first"); + sb.AppendLine("X-Custom: second"); + sb.AppendLine(); + using (var output = test.SetStream(sb.ToString())) + { + await new HttpRequestParser().ProgressTask(test.Task).ConfigureAwait(false); + Assert.AreEqual(HttpProtocolMethod.Get, test.Request.ProtocolMethod); + Assert.AreEqual("second", test.GetRequestHeader("X-Custom")); + } + } + [TestMethod] public async Task TestRequestParser_SimplePost() { @@ -71,16 +90,258 @@ public async Task TestRequestParser_SimplePost() } [TestMethod] - public async Task TestRequestParser_MultipartPost() + public async Task TestRequestParser_LargeUrlEncodedBodyUsesOverflowInsteadOfParameter() { + var originalLimit = Post.UrlEncodedData.MaximumCacheSize; + try + { + Post.UrlEncodedData.MaximumCacheSize = 10; + var content = "foo=bar&baz=foobar"; + var sb = new StringBuilder(); + sb.AppendLine("POST /test.html HTTP/1.1"); + sb.AppendLine("Host: testdomain.local"); + sb.AppendLine($"Content-Length: {content.Length}"); + sb.AppendLine("Content-Type: application/x-www-form-urlencoded"); + sb.AppendLine(); + sb.Append(content); + using (var output = test.SetStream(sb.ToString())) + { + await new HttpRequestParser().ProgressTask(test.Task).ConfigureAwait(false); + Assert.IsTrue(test.Request.Post.Data is Post.UrlEncodedData); + var data = (Post.UrlEncodedData)test.Request.Post.Data; + Assert.AreEqual(0, data.Parameter.Count); + Assert.IsNotNull(data.Overflow); + Assert.AreEqual(2, data.Overflow!.Entries.Count); + var foo = (Post.MultipartFormData.FormData)data.Overflow.Entries[0]; + var baz = (Post.MultipartFormData.FormData)data.Overflow.Entries[1]; + Assert.AreEqual("foo", foo.Name); + Assert.AreEqual("bar", Encoding.UTF8.GetString(foo.Content!.Value.Span)); + Assert.AreEqual("baz", baz.Name); + Assert.AreEqual("foobar", Encoding.UTF8.GetString(baz.Content!.Value.Span)); + } + } + finally + { + Post.UrlEncodedData.MaximumCacheSize = originalLimit; + } + } + + [TestMethod] + public async Task TestRequestParser_LargeUrlEncodedBodyOverflowFirstValueWinsForDuplicateKeys() + { + var originalLimit = Post.UrlEncodedData.MaximumCacheSize; + try + { + Post.UrlEncodedData.MaximumCacheSize = 10; + var content = "foo=first&foo=second"; + var sb = new StringBuilder(); + sb.AppendLine("POST /test.html HTTP/1.1"); + sb.AppendLine("Host: testdomain.local"); + sb.AppendLine($"Content-Length: {content.Length}"); + sb.AppendLine("Content-Type: application/x-www-form-urlencoded"); + sb.AppendLine(); + sb.Append(content); + using (var output = test.SetStream(sb.ToString())) + { + await new HttpRequestParser().ProgressTask(test.Task).ConfigureAwait(false); + var data = (Post.UrlEncodedData)test.Request.Post.Data; + Assert.AreEqual(1, data.Overflow!.Entries.Count); + var entry = (Post.MultipartFormData.FormData)data.Overflow.Entries[0]; + Assert.AreEqual("first", Encoding.UTF8.GetString(entry.Content!.Value.Span)); + } + } + finally + { + Post.UrlEncodedData.MaximumCacheSize = originalLimit; + } + } + + [TestMethod] + public async Task TestRequestParser_LargeUrlEncodedBodyOverflowHandlesAKeyWithNoValue() + { + var originalLimit = Post.UrlEncodedData.MaximumCacheSize; + try + { + Post.UrlEncodedData.MaximumCacheSize = 10; + var content = "loneKey&foo=bar"; + var sb = new StringBuilder(); + sb.AppendLine("POST /test.html HTTP/1.1"); + sb.AppendLine("Host: testdomain.local"); + sb.AppendLine($"Content-Length: {content.Length}"); + sb.AppendLine("Content-Type: application/x-www-form-urlencoded"); + sb.AppendLine(); + sb.Append(content); + using (var output = test.SetStream(sb.ToString())) + { + await new HttpRequestParser().ProgressTask(test.Task).ConfigureAwait(false); + var data = (Post.UrlEncodedData)test.Request.Post.Data; + Assert.AreEqual(2, data.Overflow!.Entries.Count); + var loneKey = (Post.MultipartFormData.FormData)data.Overflow.Entries[0]; + Assert.AreEqual("loneKey", loneKey.Name); + Assert.AreEqual("", Encoding.UTF8.GetString(loneKey.Content!.Value.Span)); + } + } + finally + { + Post.UrlEncodedData.MaximumCacheSize = originalLimit; + } + } + + [TestMethod] + public async Task TestRequestParser_UrlEncodedOverflowEntrySpillsToATempFileWhenIndividuallyLarge() + { + var originalLimit = Post.UrlEncodedData.MaximumCacheSize; + try + { + Post.UrlEncodedData.MaximumCacheSize = 10; + var content = "small=ok&big=this-value-is-longer-than-ten-bytes"; + var sb = new StringBuilder(); + sb.AppendLine("POST /test.html HTTP/1.1"); + sb.AppendLine("Host: testdomain.local"); + sb.AppendLine($"Content-Length: {content.Length}"); + sb.AppendLine("Content-Type: application/x-www-form-urlencoded"); + sb.AppendLine(); + sb.Append(content); + using (var output = test.SetStream(sb.ToString())) + { + await new HttpRequestParser().ProgressTask(test.Task).ConfigureAwait(false); + var data = (Post.UrlEncodedData)test.Request.Post.Data; + var small = (Post.MultipartFormData.FormData)data.Overflow!.Entries[0]; + var big = (Post.MultipartFormData.FormData)data.Overflow.Entries[1]; + Assert.IsTrue(small.Content.HasValue); + Assert.IsNull(small.TempFile); + Assert.IsFalse(big.Content.HasValue); + Assert.IsNotNull(big.TempFile); + Assert.IsTrue(big.TempFile!.Exists); + Assert.AreEqual("this-value-is-longer-than-ten-bytes", File.ReadAllText(big.TempFile.FullName)); + + var path = big.TempFile.FullName; + data.Dispose(); + Assert.IsFalse(File.Exists(path)); + } + } + finally + { + Post.UrlEncodedData.MaximumCacheSize = originalLimit; + } + } + + [TestMethod] + public async Task TestRequestParser_OctetStreamPostIsReadIntoARawPostData() + { + var content = "arbitrary binary-ish content"; var sb = new StringBuilder(); - sb.AppendLine("-----1234"); - sb.AppendLine("Content-Type: text/plain"); + sb.AppendLine("POST /test.html HTTP/1.1"); + sb.AppendLine("Host: testdomain.local"); + sb.AppendLine($"Content-Length: {content.Length}"); + sb.AppendLine("Content-Type: application/octet-stream"); sb.AppendLine(); - sb.Append("Hello World"); - sb.AppendLine("-----1234--"); - var content = sb.ToString(); - sb.Clear(); + sb.Append(content); + using (var output = test.SetStream(sb.ToString())) + { + await new HttpRequestParser().ProgressTask(test.Task).ConfigureAwait(false); + Assert.AreEqual(MimeType.ApplicationOctetStream, test.Request.Post.MimeType); + Assert.IsTrue(test.Request.Post.Data is Post.RawPostData); + var data = (Post.RawPostData)test.Request.Post.Data; + Assert.IsTrue(data.Entry.Content.HasValue); + Assert.AreEqual(content, Encoding.UTF8.GetString(data.Entry.Content.Value.Span)); + Assert.IsNull(data.Entry.TempFile); + } + } + + [TestMethod] + public async Task TestRequestParser_JsonPostIsReadIntoARawPostData() + { + var content = "{\"hello\":\"world\"}"; + var sb = new StringBuilder(); + sb.AppendLine("POST /test.html HTTP/1.1"); + sb.AppendLine("Host: testdomain.local"); + sb.AppendLine($"Content-Length: {content.Length}"); + sb.AppendLine("Content-Type: application/json"); + sb.AppendLine(); + sb.Append(content); + using (var output = test.SetStream(sb.ToString())) + { + await new HttpRequestParser().ProgressTask(test.Task).ConfigureAwait(false); + Assert.AreEqual(MimeType.ApplicationJson, test.Request.Post.MimeType); + Assert.IsTrue(test.Request.Post.Data is Post.RawPostData); + var data = (Post.RawPostData)test.Request.Post.Data; + Assert.AreEqual(content, Encoding.UTF8.GetString(data.Entry.Content!.Value.Span)); + } + } + + [TestMethod] + public async Task TestRequestParser_UnrecognizedContentTypeIsReadIntoARawPostData() + { + // the framework used to leave a body with no dedicated IPostData entirely unread + // (see post-unknownpostdata-dispose-race.md) - it must now actually be consumed + var content = "whatever-this-is"; + var sb = new StringBuilder(); + sb.AppendLine("POST /test.html HTTP/1.1"); + sb.AppendLine("Host: testdomain.local"); + sb.AppendLine($"Content-Length: {content.Length}"); + sb.AppendLine("Content-Type: application/x-something-unknown"); + sb.AppendLine(); + sb.Append(content); + using (var output = test.SetStream(sb.ToString())) + { + await new HttpRequestParser().ProgressTask(test.Task).ConfigureAwait(false); + Assert.IsTrue(test.Request.Post.Data is Post.RawPostData); + var data = (Post.RawPostData)test.Request.Post.Data; + Assert.AreEqual(content, Encoding.UTF8.GetString(data.Entry.Content!.Value.Span)); + } + } + + [TestMethod] + public async Task TestRequestParser_LargeRawBodySpillsToATempFileAndIsDeletedOnDispose() + { + var originalLimit = Post.RawPostData.MaximumCacheSize; + try + { + Post.RawPostData.MaximumCacheSize = 10; + var content = "this content is longer than the configured 10-byte limit"; + var sb = new StringBuilder(); + sb.AppendLine("POST /test.html HTTP/1.1"); + sb.AppendLine("Host: testdomain.local"); + sb.AppendLine($"Content-Length: {content.Length}"); + sb.AppendLine("Content-Type: application/octet-stream"); + sb.AppendLine(); + sb.Append(content); + using (var output = test.SetStream(sb.ToString())) + { + await new HttpRequestParser().ProgressTask(test.Task).ConfigureAwait(false); + Assert.IsTrue(test.Request.Post.Data is Post.RawPostData); + var data = (Post.RawPostData)test.Request.Post.Data; + Assert.IsFalse(data.Entry.Content.HasValue); + Assert.IsNotNull(data.Entry.TempFile); + Assert.IsTrue(data.Entry.TempFile!.Exists); + Assert.AreEqual(content, File.ReadAllText(data.Entry.TempFile.FullName)); + + var path = data.Entry.TempFile.FullName; + data.Dispose(); + Assert.IsFalse(File.Exists(path)); + } + } + finally + { + Post.RawPostData.MaximumCacheSize = originalLimit; + } + } + + [TestMethod] + public async Task TestRequestParser_MultipartPost() + { + // a real HTTP client always terminates every line - including the last one + // before a boundary - with a literal CRLF; that CRLF belongs to the boundary + // delimiter per RFC 2046 §5.1.1, not to the part's content, and must not show + // up in the parsed content + var content = + "-----1234\r\n" + + "Content-Type: text/plain\r\n" + + "\r\n" + + "Hello World\r\n" + + "-----1234--\r\n"; + var sb = new StringBuilder(); sb.AppendLine("POST /test.html HTTP/1.1"); sb.AppendLine("Host: testdomain.local"); sb.AppendLine($"Content-Length: {content.Length}"); @@ -109,5 +370,605 @@ public async Task TestRequestParser_MultipartPost() ); } } + + [TestMethod] + public async Task TestRequestParser_MultipartBoundaryFollowedByAnotherParameterIsParsedCorrectly() + { + // boundary= may be unquoted and need not be the last Content-Type parameter + var content = + "-----1234\r\n" + + "Content-Type: text/plain\r\n" + + "\r\n" + + "Hello World\r\n" + + "-----1234--\r\n"; + var sb = new StringBuilder(); + sb.AppendLine("POST /test.html HTTP/1.1"); + sb.AppendLine("Host: testdomain.local"); + sb.AppendLine($"Content-Length: {content.Length}"); + sb.AppendLine("Content-Type: multipart/form-data; boundary=---1234; charset=utf-8"); + sb.AppendLine(); + sb.Append(content); + using (var output = test.SetStream(sb.ToString())) + { + await new HttpRequestParser().ProgressTask(test.Task).ConfigureAwait(false); + Assert.IsTrue(test.Request.Post.Data is Post.MultipartFormData); + var data = (Post.MultipartFormData)test.Request.Post.Data; + Assert.AreEqual(1, data.Entries.Count); + Assert.AreEqual("Hello World", + Encoding.UTF8.GetString(data.Entries[0].Content!.Value.ToArray()) + ); + } + } + + [TestMethod] + public async Task TestRequestParser_MultipartDuplicateHeaderWithinAPartDoesNotCrash() + { + // a repeated header name within one part must not crash SetAsync + var content = + "-----1234\r\n" + + "Content-Type: text/plain\r\n" + + "Content-Type: text/html\r\n" + + "\r\n" + + "Hello World\r\n" + + "-----1234--\r\n"; + var sb = new StringBuilder(); + sb.AppendLine("POST /test.html HTTP/1.1"); + sb.AppendLine("Host: testdomain.local"); + sb.AppendLine($"Content-Length: {content.Length}"); + sb.AppendLine("Content-Type: multipart/form-data; boundary=---1234"); + sb.AppendLine(); + sb.Append(content); + using (var output = test.SetStream(sb.ToString())) + { + await new HttpRequestParser().ProgressTask(test.Task).ConfigureAwait(false); + Assert.IsTrue(test.Request.Post.Data is Post.MultipartFormData); + var data = (Post.MultipartFormData)test.Request.Post.Data; + Assert.AreEqual(1, data.Entries.Count); + Assert.AreEqual("text/html", data.Entries[0].Header["Content-Type"]); + } + } + + [TestMethod] + public async Task TestRequestParser_MultipartWithNoBoundaryIsRejected() + { + var content = "irrelevant -- content -- here"; + var sb = new StringBuilder(); + sb.AppendLine("POST /test.html HTTP/1.1"); + sb.AppendLine("Host: testdomain.local"); + sb.AppendLine($"Content-Length: {content.Length}"); + sb.AppendLine("Content-Type: multipart/form-data"); + sb.AppendLine(); + sb.Append(content); + using (var output = test.SetStream(sb.ToString())) + { + await new HttpRequestParser().ProgressTask(test.Task).ConfigureAwait(false); + Assert.IsTrue(test.Request.Post.Data is Post.MultipartFormData); + var data = (Post.MultipartFormData)test.Request.Post.Data; + Assert.AreEqual(0, data.Entries.Count); + Assert.AreEqual(HttpStateCode.BadRequest, test.GetStatusCode()); + // skip CreateDocument/ProcessDocument - there is no content to generate for a + // request that was already rejected + Assert.AreEqual(ServerStage.CreateResponse, test.Task.NextStage); + } + } + + [TestMethod] + public async Task TestRequestParser_MultipartWithEmptyBoundaryIsRejected() + { + var content = "irrelevant -- content -- here"; + var sb = new StringBuilder(); + sb.AppendLine("POST /test.html HTTP/1.1"); + sb.AppendLine("Host: testdomain.local"); + sb.AppendLine($"Content-Length: {content.Length}"); + sb.AppendLine("Content-Type: multipart/form-data; boundary="); + sb.AppendLine(); + sb.Append(content); + using (var output = test.SetStream(sb.ToString())) + { + await new HttpRequestParser().ProgressTask(test.Task).ConfigureAwait(false); + Assert.IsTrue(test.Request.Post.Data is Post.MultipartFormData); + var data = (Post.MultipartFormData)test.Request.Post.Data; + Assert.AreEqual(0, data.Entries.Count); + Assert.AreEqual(HttpStateCode.BadRequest, test.GetStatusCode()); + Assert.AreEqual(ServerStage.CreateResponse, test.Task.NextStage); + } + } + + [TestMethod] + public async Task TestRequestParser_MultipartWithTooManyPartsIsRejected() + { + var originalLimit = Post.MultipartFormData.MaximumPartCount; + try + { + Post.MultipartFormData.MaximumPartCount = 2; + + var content = new StringBuilder(); + for (var i = 0; i < 4; ++i) + content.Append("--B\r\n\r\nx\r\n"); + content.Append("--B--\r\n"); + + var sb = new StringBuilder(); + sb.AppendLine("POST /test.html HTTP/1.1"); + sb.AppendLine("Host: testdomain.local"); + sb.AppendLine($"Content-Length: {content.Length}"); + sb.AppendLine("Content-Type: multipart/form-data; boundary=B"); + sb.AppendLine(); + sb.Append(content); + using (var output = test.SetStream(sb.ToString())) + { + await new HttpRequestParser().ProgressTask(test.Task).ConfigureAwait(false); + Assert.IsTrue(test.Request.Post.Data is Post.MultipartFormData); + var data = (Post.MultipartFormData)test.Request.Post.Data; + // rejected as soon as the 3rd part's boundary is seen, before its + // headers/content are parsed at all + Assert.AreEqual(2, data.Entries.Count); + Assert.AreEqual(HttpStateCode.RequestEntityTooLarge, test.GetStatusCode()); + Assert.AreEqual(ServerStage.CreateResponse, test.Task.NextStage); + } + } + finally + { + Post.MultipartFormData.MaximumPartCount = originalLimit; + } + } + + [TestMethod] + public async Task TestRequestParser_MultipartPost_BinaryContentIsNotCorrupted() + { + // every byte value 0x00-0x7F, including embedded CR/LF bytes that are not part + // of a boundary delimiter - the parser must not stop early on those, and must + // return the content byte-for-byte with no trailing CRLF appended or stripped + var contentBytes = new byte[128]; + for (var i = 0; i < contentBytes.Length; ++i) + contentBytes[i] = (byte)i; + var binaryPart = new string(Array.ConvertAll(contentBytes, b => (char)b)); + + var content = + "-----1234\r\n" + + "Content-Type: application/octet-stream\r\n" + + "\r\n" + + binaryPart + "\r\n" + + "-----1234--\r\n"; + var sb = new StringBuilder(); + sb.AppendLine("POST /test.html HTTP/1.1"); + sb.AppendLine("Host: testdomain.local"); + sb.AppendLine($"Content-Length: {content.Length}"); + sb.AppendLine("Content-Type: multipart/form-data; boundary=---1234"); + sb.AppendLine(); + sb.Append(content); + using (var output = test.SetStream(sb.ToString())) + { + await new HttpRequestParser().ProgressTask(test.Task).ConfigureAwait(false); + Assert.IsTrue(test.Request.Post.Data is Post.MultipartFormData); + var data = (Post.MultipartFormData)test.Request.Post.Data; + Assert.AreEqual(1, data.Entries.Count); + Assert.IsTrue(data.Entries[0].Content.HasValue); + CollectionAssert.AreEqual(contentBytes, data.Entries[0].Content.Value.ToArray()); + } + } + + [TestMethod] + public async Task TestRequestParser_MultipartPost_TempFileIsDeletedOnDispose() + { + var content = + "-----1234\r\n" + + "Content-Disposition: form-data; name=\"file\"; filename=\"test.txt\"\r\n" + + "Content-Type: text/plain\r\n" + + "\r\n" + + "Hello World\r\n" + + "-----1234--\r\n"; + var sb = new StringBuilder(); + sb.AppendLine("POST /test.html HTTP/1.1"); + sb.AppendLine("Host: testdomain.local"); + sb.AppendLine($"Content-Length: {content.Length}"); + sb.AppendLine("Content-Type: multipart/form-data; boundary=---1234"); + sb.AppendLine(); + sb.Append(content); + using (var output = test.SetStream(sb.ToString())) + { + await new HttpRequestParser().ProgressTask(test.Task).ConfigureAwait(false); + Assert.IsTrue(test.Request.Post.Data is Post.MultipartFormData); + var data = (Post.MultipartFormData)test.Request.Post.Data; + Assert.AreEqual(1, data.Entries.Count); + var entry = data.Entries[0]; + Assert.IsTrue(entry is Post.MultipartFormData.FormDataFile); + Assert.IsNotNull(entry.TempFile); + Assert.IsTrue(entry.TempFile!.Exists); + var path = entry.TempFile.FullName; + + // this is what HttpResponseCreator triggers (via HttpPost.Dispose()) once + // the response has been fully sent - the temp file must not be left behind + data.Dispose(); + + Assert.IsFalse(File.Exists(path)); + } + } + + [TestMethod] + public async Task TestRequestParser_TransferEncodingIsRejected() + { + var sb = new StringBuilder(); + sb.AppendLine("POST /test.html HTTP/1.1"); + sb.AppendLine("Host: testdomain.local"); + sb.AppendLine("Transfer-Encoding: chunked"); + sb.AppendLine(); + sb.Append("0\r\n\r\n"); + using (var output = test.SetStream(sb.ToString())) + { + await new HttpRequestParser().ProgressTask(test.Task).ConfigureAwait(false); + Assert.AreEqual(HttpStateCode.NotImplemented, test.GetStatusCode()); + // the chunked body was never read off the socket; the connection must not + // be kept alive, or those bytes would be parsed as the next request's header + Assert.AreEqual(HttpConnectionType.Close, test.Request.FieldConnection); + } + } + + [TestMethod] + public async Task TestRequestParser_TransferEncodingWithContentLengthIsRejected() + { + var content = "foo=bar"; + var sb = new StringBuilder(); + sb.AppendLine("POST /test.html HTTP/1.1"); + sb.AppendLine("Host: testdomain.local"); + sb.AppendLine($"Content-Length: {content.Length}"); + sb.AppendLine("Transfer-Encoding: chunked"); + sb.AppendLine("Content-Type: application/x-www-form-urlencoded"); + sb.AppendLine(); + sb.Append(content); + using (var output = test.SetStream(sb.ToString())) + { + await new HttpRequestParser().ProgressTask(test.Task).ConfigureAwait(false); + Assert.AreEqual(HttpStateCode.NotImplemented, test.GetStatusCode()); + Assert.AreEqual(HttpConnectionType.Close, test.Request.FieldConnection); + } + } + + [TestMethod] + public async Task TestRequestParser_ConflictingContentLengthHeadersAreRejected() + { + // RFC 7230 §3.3.3: Content-Length headers with differing values must be rejected + var sb = new StringBuilder(); + sb.AppendLine("POST /test.html HTTP/1.1"); + sb.AppendLine("Host: testdomain.local"); + sb.AppendLine("Content-Length: 3"); + sb.AppendLine("Content-Length: 7"); + sb.AppendLine("Content-Type: application/x-www-form-urlencoded"); + sb.AppendLine(); + sb.Append("foo=bar"); + using (var output = test.SetStream(sb.ToString())) + { + await new HttpRequestParser().ProgressTask(test.Task).ConfigureAwait(false); + Assert.AreEqual(HttpStateCode.BadRequest, test.GetStatusCode()); + // the client's framing is now ambiguous - the connection must not be kept alive + Assert.AreEqual(HttpConnectionType.Close, test.Request.FieldConnection); + } + } + + [TestMethod] + public async Task TestRequestParser_IdenticalRepeatedContentLengthHeadersAreAccepted() + { + // a naive header-duplicating proxy repeating the same value verbatim is still + // fine - only a genuine conflict must be rejected + var content = "foo=bar"; + var sb = new StringBuilder(); + sb.AppendLine("POST /test.html HTTP/1.1"); + sb.AppendLine("Host: testdomain.local"); + sb.AppendLine($"Content-Length: {content.Length}"); + sb.AppendLine($"Content-Length: {content.Length}"); + sb.AppendLine("Content-Type: application/x-www-form-urlencoded"); + sb.AppendLine(); + sb.Append(content); + using (var output = test.SetStream(sb.ToString())) + { + await new HttpRequestParser().ProgressTask(test.Task).ConfigureAwait(false); + Assert.AreNotEqual(HttpStateCode.BadRequest, test.GetStatusCode()); + Assert.IsTrue(test.Request.Post.Data is Post.UrlEncodedData); + } + } + + [TestMethod] + public async Task TestRequestParser_DuplicateHostHeaderIsRejected() + { + // RFC 7230 §5.4: more than one Host header is rejected unconditionally + var sb = new StringBuilder(); + sb.AppendLine("GET /test.html HTTP/1.1"); + sb.AppendLine("Host: victim.example"); + sb.AppendLine("Host: attacker.example"); + sb.AppendLine(); + using (var output = test.SetStream(sb.ToString())) + { + await new HttpRequestParser().ProgressTask(test.Task).ConfigureAwait(false); + Assert.AreEqual(HttpStateCode.BadRequest, test.GetStatusCode()); + Assert.AreEqual(HttpConnectionType.Close, test.Request.FieldConnection); + } + } + + [TestMethod] + public async Task TestRequestParser_DuplicateIdenticalHostHeaderIsAlsoRejected() + { + // unlike Content-Length, identical repeated Host values are still rejected - the + // RFC gives no carve-out for this header + var sb = new StringBuilder(); + sb.AppendLine("GET /test.html HTTP/1.1"); + sb.AppendLine("Host: testdomain.local"); + sb.AppendLine("Host: testdomain.local"); + sb.AppendLine(); + using (var output = test.SetStream(sb.ToString())) + { + await new HttpRequestParser().ProgressTask(test.Task).ConfigureAwait(false); + Assert.AreEqual(HttpStateCode.BadRequest, test.GetStatusCode()); + } + } + + [TestMethod] + public async Task TestRequestParser_ContentLengthExceedingMaxIsRejectedWithoutCallback() + { + var parser = new HttpRequestParser { MaxContentLength = 10 }; + var sb = new StringBuilder(); + sb.AppendLine("POST /test.html HTTP/1.1"); + sb.AppendLine("Host: testdomain.local"); + sb.AppendLine("Content-Length: 1000"); + sb.AppendLine("Content-Type: application/x-www-form-urlencoded"); + sb.AppendLine(); + using (var output = test.SetStream(sb.ToString())) + { + await parser.ProgressTask(test.Task).ConfigureAwait(false); + Assert.AreEqual(HttpStateCode.RequestEntityTooLarge, test.GetStatusCode()); + // the body was never read, so the connection can't be reused + Assert.AreEqual(HttpConnectionType.Close, test.Request.FieldConnection); + } + } + + [TestMethod] + public async Task TestRequestParser_ContentLengthCallbackCanRaiseTheLimit() + { + long? observedLength = null; + var parser = new HttpRequestParser + { + MaxContentLength = 3, + ContentLengthLimitExceeded = (_, declaredLength) => + { + observedLength = declaredLength; + return new ValueTask(100L); + }, + }; + var content = "foo=bar"; + var sb = new StringBuilder(); + sb.AppendLine("POST /test.html HTTP/1.1"); + sb.AppendLine("Host: testdomain.local"); + sb.AppendLine($"Content-Length: {content.Length}"); + sb.AppendLine("Content-Type: application/x-www-form-urlencoded"); + sb.AppendLine(); + sb.Append(content); + using (var output = test.SetStream(sb.ToString())) + { + await parser.ProgressTask(test.Task).ConfigureAwait(false); + Assert.AreEqual(content.Length, observedLength); + Assert.AreNotEqual(HttpStateCode.RequestEntityTooLarge, test.GetStatusCode()); + Assert.IsTrue(test.Request.Post.Data is Post.UrlEncodedData); + var data = (Post.UrlEncodedData)test.Request.Post.Data; + Assert.AreEqual("bar", data.Parameter["foo"]); + } + } + + [TestMethod] + public async Task TestRequestParser_ContentLengthCallbackCanStillRejectAfterRaisingTheLimit() + { + var parser = new HttpRequestParser + { + MaxContentLength = 3, + // still below the declared Content-Length of 7 + ContentLengthLimitExceeded = (_, _) => new ValueTask(5L), + }; + var content = "foo=bar"; + var sb = new StringBuilder(); + sb.AppendLine("POST /test.html HTTP/1.1"); + sb.AppendLine("Host: testdomain.local"); + sb.AppendLine($"Content-Length: {content.Length}"); + sb.AppendLine("Content-Type: application/x-www-form-urlencoded"); + sb.AppendLine(); + sb.Append(content); + using (var output = test.SetStream(sb.ToString())) + { + await parser.ProgressTask(test.Task).ConfigureAwait(false); + Assert.AreEqual(HttpStateCode.RequestEntityTooLarge, test.GetStatusCode()); + Assert.AreEqual(HttpConnectionType.Close, test.Request.FieldConnection); + } + } + + [TestMethod] + public async Task TestRequestParser_ContentLengthCallbackReturningNullMeansUnlimited() + { + var parser = new HttpRequestParser + { + MaxContentLength = 3, + ContentLengthLimitExceeded = (_, _) => new ValueTask((long?)null), + }; + var content = "foo=bar"; + var sb = new StringBuilder(); + sb.AppendLine("POST /test.html HTTP/1.1"); + sb.AppendLine("Host: testdomain.local"); + sb.AppendLine($"Content-Length: {content.Length}"); + sb.AppendLine("Content-Type: application/x-www-form-urlencoded"); + sb.AppendLine(); + sb.Append(content); + using (var output = test.SetStream(sb.ToString())) + { + await parser.ProgressTask(test.Task).ConfigureAwait(false); + Assert.AreNotEqual(HttpStateCode.RequestEntityTooLarge, test.GetStatusCode()); + Assert.IsTrue(test.Request.Post.Data is Post.UrlEncodedData); + } + } + + [TestMethod] + public async Task TestRequestParser_NegativeMaxContentLengthDisablesTheLimit() + { + var parser = new HttpRequestParser { MaxContentLength = -1 }; + var content = "foo=bar"; + var sb = new StringBuilder(); + sb.AppendLine("POST /test.html HTTP/1.1"); + sb.AppendLine("Host: testdomain.local"); + sb.AppendLine($"Content-Length: {content.Length}"); + sb.AppendLine("Content-Type: application/x-www-form-urlencoded"); + sb.AppendLine(); + sb.Append(content); + using (var output = test.SetStream(sb.ToString())) + { + await parser.ProgressTask(test.Task).ConfigureAwait(false); + Assert.AreNotEqual(HttpStateCode.RequestEntityTooLarge, test.GetStatusCode()); + Assert.IsTrue(test.Request.Post.Data is Post.UrlEncodedData); + } + } + + // Simulates a client that fully sends its headers, then stalls forever partway + // through its declared body - every read past the header bytes blocks until + // cancelled. + private sealed class HeaderThenStallStream : Stream + { + private readonly MemoryStream header; + + public HeaderThenStallStream(byte[] headerBytes) + => header = new MemoryStream(headerBytes); + + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => throw new NotSupportedException(); + public override long Position + { + get => 0; + set => throw new NotSupportedException(); + } + public override void Flush() { } + public override int Read(byte[] buffer, int offset, int count) + => throw new NotSupportedException("only the async read paths are exercised here"); + public override Task ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) + => ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + public override async ValueTask ReadAsync(Memory buffer, System.Threading.CancellationToken cancellationToken = default) + { + if (header.Position < header.Length) + return await header.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); + await Task.Delay(System.Threading.Timeout.Infinite, cancellationToken).ConfigureAwait(false); + throw new InvalidOperationException("unreachable: Task.Delay(Infinite) only ever completes by cancellation"); + } + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } + + [TestMethod] + public async Task TestRequestParser_StalledBodyIsCancelledWithinTheConfiguredTimeout() + { + var content = "foo=bar"; + var sb = new StringBuilder(); + sb.AppendLine("POST /test.html HTTP/1.1"); + sb.AppendLine("Host: testdomain.local"); + sb.AppendLine($"Content-Length: {content.Length}"); + sb.AppendLine("Content-Type: application/x-www-form-urlencoded"); + sb.AppendLine(); + // the header ends here; the declared body never actually arrives + var headerBytes = Encoding.UTF8.GetBytes(sb.ToString()); + + var parser = new HttpRequestParser + { + ContentReadBaseTimeout = TimeSpan.FromMilliseconds(50), + MinimumContentTransferRate = 1_000_000, // keeps the size-dependent part negligible + }; + test.SetStream(new HeaderThenStallStream(headerBytes)); + + await parser.ProgressTask(test.Task).ConfigureAwait(false); + // header parsing itself succeeds; the stall only happens once the body is + // actually read (i.e. once a handler consumes Post.Data) + Assert.AreNotEqual(HttpStateCode.RequestEntityTooLarge, test.GetStatusCode()); + + var stopwatch = System.Diagnostics.Stopwatch.StartNew(); + try + { + await test.Request.Post.DataAsync!.ConfigureAwait(false); + Assert.Fail("expected an OperationCanceledException"); + } + catch (OperationCanceledException) + { + // expected - the stalled body never satisfies UrlEncodedData.SetAsync + } + stopwatch.Stop(); + + Assert.IsTrue(stopwatch.Elapsed < TimeSpan.FromSeconds(5), + $"expected cancellation well within the configured timeout, took {stopwatch.Elapsed}"); + } + + // Simulates a client that sends its request line, then trickles the rest of the + // request (the classic "Slowloris" attack) - every read past the request line + // blocks until cancelled. + private sealed class RequestLineThenStallStream : Stream + { + private readonly MemoryStream requestLine; + + public RequestLineThenStallStream(byte[] requestLineBytes) + => requestLine = new MemoryStream(requestLineBytes); + + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => throw new NotSupportedException(); + public override long Position + { + get => 0; + set => throw new NotSupportedException(); + } + public override void Flush() { } + public override int Read(byte[] buffer, int offset, int count) + => throw new NotSupportedException("only the async read paths are exercised here"); + public override Task ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) + => ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + public override async ValueTask ReadAsync(Memory buffer, System.Threading.CancellationToken cancellationToken = default) + { + if (requestLine.Position < requestLine.Length) + return await requestLine.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); + await Task.Delay(System.Threading.Timeout.Infinite, cancellationToken).ConfigureAwait(false); + throw new InvalidOperationException("unreachable: Task.Delay(Infinite) only ever completes by cancellation"); + } + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } + + [TestMethod] + public async Task TestRequestParser_StalledHeaderReadIsCancelledWithinTheConfiguredTimeout() + { + // the request line arrives, but the client then trickles nothing further - the + // classic Slowloris attack, which used to hold the connection open indefinitely + // once WaitForData's wait for the very first byte was already satisfied + var requestLineBytes = Encoding.UTF8.GetBytes("GET /test.html HTTP/1.1\r\n"); + var parser = new HttpRequestParser { MaxHeaderReadTime = TimeSpan.FromMilliseconds(50) }; + test.SetStream(new RequestLineThenStallStream(requestLineBytes)); + + var stopwatch = System.Diagnostics.Stopwatch.StartNew(); + await parser.ProgressTask(test.Task).ConfigureAwait(false); + stopwatch.Stop(); + + Assert.IsTrue(stopwatch.Elapsed < TimeSpan.FromSeconds(5), + $"expected the header read to be cancelled well within the configured timeout, took {stopwatch.Elapsed}"); + Assert.AreEqual(HttpStateCode.RequestTimeOut, test.GetStatusCode()); + // the connection's position in the byte stream is unknown once a mid-header + // read is abandoned, so it can't safely be reused for a further request + Assert.AreEqual(HttpConnectionType.Close, test.Request.FieldConnection); + } + + [TestMethod] + public async Task TestRequestParser_ZeroMaxHeaderReadTimeDisablesTheTimeout() + { + var parser = new HttpRequestParser { MaxHeaderReadTime = TimeSpan.Zero }; + var sb = new StringBuilder(); + sb.AppendLine("GET /test.html HTTP/1.1"); + sb.AppendLine("Host: testdomain.local"); + sb.AppendLine(); + using (var output = test.SetStream(sb.ToString())) + { + await parser.ProgressTask(test.Task).ConfigureAwait(false); + Assert.AreEqual(HttpProtocolMethod.Get, test.Request.ProtocolMethod); + Assert.AreEqual("/test.html", test.Request.Location.DocumentPath); + } + } } } \ No newline at end of file diff --git a/tests/MaxLib.WebServer.Test/Services/TestHttpResponseCreator.cs b/tests/MaxLib.WebServer.Test/Services/TestHttpResponseCreator.cs index 4f09eeb..7abf394 100644 --- a/tests/MaxLib.WebServer.Test/Services/TestHttpResponseCreator.cs +++ b/tests/MaxLib.WebServer.Test/Services/TestHttpResponseCreator.cs @@ -1,6 +1,8 @@ -using MaxLib.WebServer.Services; +using MaxLib.WebServer.Chunked; +using MaxLib.WebServer.Services; using MaxLib.WebServer.Testing; using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.IO; using System.Threading.Tasks; namespace MaxLib.WebServer.Test.Services @@ -41,5 +43,35 @@ public async Task TestHeader() Assert.AreEqual("IE=Edge", test.GetResponseHeader("X-UA-Compatible")); Assert.AreEqual("4", test.GetResponseHeader("Content-Length")); } + + [TestMethod] + public async Task TestUnknownLengthDataSourceRejectsWithoutARegisteredChunkedSender() + { + // Content-Length can never be computed correctly for an unknown-length data source + // (Sum() would silently treat it as 0) - with no chunked sender registered to send + // it correctly instead, this must fail loudly rather than desync the connection. + test.Response.StatusCode = HttpStateCode.OK; + test.Task.Document.DataSources.Add(new HttpChunkedStream(new MemoryStream())); + + await new HttpResponseCreator().ProgressTask(test.Task).ConfigureAwait(false); + + Assert.AreEqual(HttpStateCode.InternalServerError, test.GetStatusCode()); + Assert.AreEqual(0, test.GetDataSources().Count); + Assert.AreEqual("0", test.GetResponseHeader("Content-Length")); + } + + [TestMethod] + public async Task TestUnknownLengthDataSourceDefersToARegisteredChunkedSender() + { + server.AddWebService(new ChunkedSender()); + test.Response.StatusCode = HttpStateCode.OK; + test.Task.Document.DataSources.Add(new HttpChunkedStream(new MemoryStream())); + + await new HttpResponseCreator().ProgressTask(test.Task).ConfigureAwait(false); + + Assert.AreEqual(HttpStateCode.OK, test.GetStatusCode()); + Assert.AreEqual(1, test.GetDataSources().Count); + Assert.IsNull(test.GetResponseHeader("Content-Length")); + } } } diff --git a/tests/MaxLib.WebServer.Test/Services/TestHttpSender.cs b/tests/MaxLib.WebServer.Test/Services/TestHttpSender.cs index a88725c..ce43e31 100644 --- a/tests/MaxLib.WebServer.Test/Services/TestHttpSender.cs +++ b/tests/MaxLib.WebServer.Test/Services/TestHttpSender.cs @@ -1,7 +1,12 @@ -using MaxLib.WebServer.Services; +using MaxLib.WebServer.IO; +using MaxLib.WebServer.Post; +using MaxLib.WebServer.Services; using MaxLib.WebServer.Testing; using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; using System.IO; +using System.Text; +using System.Threading; using System.Threading.Tasks; namespace MaxLib.WebServer.Test.Services @@ -49,5 +54,294 @@ public async Task TestSending() Assert.AreEqual("foobarbaz", r.ReadLine()); } } + + [TestMethod] + public async Task TestSendingStripsCrLfFromHeaderNamesAndValues() + { + // A header value built from attacker-influenced text (e.g. a redirect Location) + // must never let a raw CRLF split it into extra header/response lines - + // see http-header-crlf-injection.md + test.Response.HttpProtocol = HttpProtocolDefinition.HttpVersion1_1; + test.Response.StatusCode = HttpStateCode.OK; + test.Response.HeaderParameter["X-Custom"] = "evil\r\nX-Injected: 1"; + + using (var response = test.SetStream()) + using (var r = new StreamReader(response)) + { + await new HttpSender().ProgressTask(test.Task).ConfigureAwait(false); + + response.Position = 0; + + Assert.AreEqual("HTTP/1.1 200 OK", r.ReadLine()); + Assert.AreEqual("X-Custom: evilX-Injected: 1", r.ReadLine()); + Assert.AreEqual("", r.ReadLine()); + Assert.AreEqual(null, r.ReadLine()); + } + } + + [TestMethod] + public async Task TestUnconsumedPostBodyIsDrainedAfterTheResponseIsSent() + { + // e.g. a request that routes to a 404 or GET-style handler that never reads + // task.Request.Post.Data at all + var body = Encoding.UTF8.GetBytes("foo=bar"); + var content = new ContentStream(new NetworkReader(new MemoryStream(body)), body.Length); + test.Request.Post.SetPost(test.Task, content, MimeType.ApplicationXWwwFromUrlencoded); + test.Request.FieldConnection = HttpConnectionType.KeepAlive; + + test.Response.HttpProtocol = HttpProtocolDefinition.HttpVersion1_1; + test.Response.StatusCode = HttpStateCode.OK; + + using (var response = test.SetStream()) + { + await new HttpSender().ProgressTask(test.Task).ConfigureAwait(false); + + Assert.AreEqual(0, content.UnreadData); + // disposal succeeded without hitting the configured timeout, so the + // connection must be left exactly as the caller set it up + Assert.AreEqual(HttpConnectionType.KeepAlive, test.Request.FieldConnection); + } + } + + [TestMethod] + public async Task TestKeepAliveConnectionStreamSurvivesDisposalOfARequestWithABody() + { + // HttpRequestParser wraps the *actual, shared* connection stream in the + // NetworkReader that ends up owned by the request's ContentStream. Disposing + // that ContentStream after the response is sent (see above) must not take the + // connection stream down with it, or every Keep-Alive connection would die + // after its first request with a body. + var body = "foo=bar"; + var requestBytes = Encoding.UTF8.GetBytes( + "POST /test.html HTTP/1.1\r\n" + + $"Content-Length: {body.Length}\r\n" + + "\r\n" + + body + ); + using var stream = new MemoryStream(); + stream.Write(requestBytes, 0, requestBytes.Length); + stream.Position = 0; + test.SetStream(stream); + + test.CurrentStage = ServerStage.ReadRequest; + await new HttpRequestParser().ProgressTask(test.Task).ConfigureAwait(false); + + test.Request.FieldConnection = HttpConnectionType.KeepAlive; + test.Response.HttpProtocol = HttpProtocolDefinition.HttpVersion1_1; + test.Response.StatusCode = HttpStateCode.OK; + + await new HttpSender().ProgressTask(test.Task).ConfigureAwait(false); + + Assert.AreEqual(HttpConnectionType.KeepAlive, test.Request.FieldConnection); + Assert.IsTrue(stream.CanRead, + "the connection stream must stay open for further requests on a Keep-Alive connection"); + } + + // Simulates a client that stalls mid-upload: every read blocks forever unless the + // caller's cancellation token fires. + private sealed class StallingStream : Stream + { + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => throw new NotSupportedException(); + public override long Position + { + get => 0; + set => throw new NotSupportedException(); + } + public override void Flush() { } + public override int Read(byte[] buffer, int offset, int count) + => throw new NotSupportedException("only the async read paths are exercised here"); + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + => ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + await Task.Delay(Timeout.Infinite, cancellationToken).ConfigureAwait(false); + throw new InvalidOperationException("unreachable: Task.Delay(Infinite) only ever completes by cancellation"); + } + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } + + [TestMethod] + public async Task TestResponseIsSentEvenWhenPostBodyDisposalTimesOut() + { + // this is the crux of the fix: a stalled, still-unread POST body must never + // prevent (or race with) transmitting the response that was already prepared + // for this request - only after that response is fully sent is it safe to + // drain the leftover body and, if that stalls, close the connection + test.Response.HttpProtocol = HttpProtocolDefinition.HttpVersion1_1; + test.Response.StatusCode = HttpStateCode.OK; + test.Response.FieldContentType = MimeType.TextPlain; + test.Task.Document.DataSources.Add(new HttpStringDataSource("hello")); + + var content = new ContentStream( + new NetworkReader(new StallingStream(), null, true), + 1024, + TimeSpan.FromMilliseconds(50) + ); + test.Request.Post.SetPost(test.Task, content, MimeType.ApplicationOctetStream); + + using (var response = test.SetStream()) + using (var r = new StreamReader(response)) + { + var stopwatch = System.Diagnostics.Stopwatch.StartNew(); + await new HttpSender().ProgressTask(test.Task).ConfigureAwait(false); + stopwatch.Stop(); + + Assert.IsTrue(stopwatch.Elapsed < TimeSpan.FromSeconds(5), + $"expected disposal to give up well within the configured timeout, took {stopwatch.Elapsed}"); + + response.Position = 0; + var text = r.ReadToEnd(); + StringAssert.Contains(text, "HTTP/1.1 200 OK"); + StringAssert.Contains(text, "hello"); + + // the socket is now at an unknown position in the byte stream and must not + // be reused for a further request + Assert.AreEqual(HttpConnectionType.Close, test.Request.FieldConnection); + } + } + + // Simulates a connection reset while draining the leftover, unread POST body. + private sealed class ResetsWhileReadingStream : Stream + { + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => throw new NotSupportedException(); + public override long Position + { + get => 0; + set => throw new NotSupportedException(); + } + public override void Flush() { } + public override int Read(byte[] buffer, int offset, int count) + => throw new NotSupportedException("only the async read paths are exercised here"); + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + => ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + => throw new IOException("simulated connection reset"); + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } + + [TestMethod] + public async Task TestResponseIsSentEvenWhenPostBodyDrainHitsAConnectionReset() + { + // a connection reset while draining the leftover POST body must be logged, not propagate + test.Response.HttpProtocol = HttpProtocolDefinition.HttpVersion1_1; + test.Response.StatusCode = HttpStateCode.OK; + test.Response.FieldContentType = MimeType.TextPlain; + test.Task.Document.DataSources.Add(new HttpStringDataSource("hello")); + + var content = new ContentStream( + new NetworkReader(new ResetsWhileReadingStream()), + 1024 + ); + test.Request.Post.SetPost(test.Task, content, MimeType.ApplicationOctetStream); + + using (var response = test.SetStream()) + using (var r = new StreamReader(response)) + { + await new HttpSender().ProgressTask(test.Task).ConfigureAwait(false); + + response.Position = 0; + var text = r.ReadToEnd(); + StringAssert.Contains(text, "HTTP/1.1 200 OK"); + StringAssert.Contains(text, "hello"); + + Assert.AreEqual(HttpConnectionType.Close, test.Request.FieldConnection); + } + } + + // Writes through to a MemoryStream normally, but FlushAsync always fails - + // simulating a client that disconnects while the response is being sent. + private sealed class ThrowsOnFlushStream : MemoryStream + { + public override Task FlushAsync(CancellationToken cancellationToken) + => throw new IOException("simulated broken connection"); + } + + // Simulates a client that disconnects while the response body is being written - + // e.g. HttpDataSource.WriteStream itself surfacing the broken connection, as + // HttpStreamDataSource/HttpChunkedStream do when the underlying stream throws. + private sealed class ThrowsOnWriteStreamDataSource : HttpDataSource + { + public override void Dispose() { } + public override long? Length() => null; + protected override Task WriteStreamInternal(Stream stream) + => throw new IOException("simulated broken connection"); + } + + [TestMethod] + public async Task TestBodyWriteDisconnectIsLoggedGracefullyInsteadOfPropagatingUnhandled() + { + // a client disconnect mid-body-write must be logged like the header/footer flush disconnects, + // not propagate out of ProgressTask + test.Response.HttpProtocol = HttpProtocolDefinition.HttpVersion1_1; + test.Response.StatusCode = HttpStateCode.OK; + test.Task.Document.DataSources.Add(new ThrowsOnWriteStreamDataSource()); + + using (var response = test.SetStream()) + using (var r = new StreamReader(response)) + { + // must not throw: the IOException from WriteStream is caught inside + // ProgressTask, not propagated to the caller + await new HttpSender().ProgressTask(test.Task).ConfigureAwait(false); + + response.Position = 0; + var text = r.ReadToEnd(); + StringAssert.Contains(text, "HTTP/1.1 200 OK"); + } + } + + [TestMethod] + public async Task TestPostTempFileIsDisposedEvenWhenSendingTheResponseFails() + { + // the POST temp file must be cleaned up even when the connection breaks while sending the response + var originalMapper = MultipartFormData.StorageMapper; + string tempFilePath = ""; + try + { + MultipartFormData.StorageMapper = (task, file) => + { + tempFilePath = ((FileStream)file).Name; + return file; + }; + + var content = + "-----1234\r\n" + + "Content-Type: text/plain\r\n" + + "Content-Disposition: form-data; name=\"f\"; filename=\"x\"\r\n" + + "\r\n" + + "Hello World\r\n" + + "-----1234--\r\n"; + var contentBytes = Encoding.UTF8.GetBytes(content); + var contentStream = new ContentStream( + new NetworkReader(new MemoryStream(contentBytes)), contentBytes.Length); + test.Request.Post.SetPost(test.Task, contentStream, "multipart/form-data; boundary=---1234"); + // force the lazy IPostData to actually resolve, as if some handler had + // already read it - this is what creates the temp file in the first place + Assert.IsNotNull(await test.Request.Post.DataAsync!.ConfigureAwait(false)); + + test.Response.HttpProtocol = HttpProtocolDefinition.HttpVersion1_1; + test.Response.StatusCode = HttpStateCode.OK; + test.Task.NetworkStream = new ThrowsOnFlushStream(); + + await new HttpSender().ProgressTask(test.Task).ConfigureAwait(false); + + Assert.AreNotEqual("", tempFilePath, "the StorageMapper hook was never invoked"); + Assert.IsFalse(File.Exists(tempFilePath), + "the POST temp file must not be orphaned when sending the response fails"); + } + finally + { + MultipartFormData.StorageMapper = originalMapper; + } + } } } diff --git a/tests/MaxLib.WebServer.Test/Services/TestLocalIOMapper.cs b/tests/MaxLib.WebServer.Test/Services/TestLocalIOMapper.cs new file mode 100644 index 0000000..0e3f769 --- /dev/null +++ b/tests/MaxLib.WebServer.Test/Services/TestLocalIOMapper.cs @@ -0,0 +1,208 @@ +using MaxLib.WebServer.Services; +using MaxLib.WebServer.Testing; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.IO; + +namespace MaxLib.WebServer.Test.Services +{ + [TestClass] + public class TestLocalIOMapperShortenPath + { + [TestMethod] + public void TestNormalPathIsUnchanged() + { + var result = LocalIOMapper.ShortenPath(new[] { "foo", "bar" }); + Assert.IsNotNull(result); + CollectionAssert.AreEqual(new[] { "foo", "bar" }, result.Value.ToArray()); + } + + [TestMethod] + public void TestDotSegmentIsRemoved() + { + var result = LocalIOMapper.ShortenPath(new[] { "foo", ".", "bar" }); + Assert.IsNotNull(result); + CollectionAssert.AreEqual(new[] { "foo", "bar" }, result.Value.ToArray()); + } + + [TestMethod] + public void TestParentSegmentGoesUpOneLevel() + { + var result = LocalIOMapper.ShortenPath(new[] { "foo", "bar", "..", "baz" }); + Assert.IsNotNull(result); + CollectionAssert.AreEqual(new[] { "foo", "baz" }, result.Value.ToArray()); + } + + [TestMethod] + public void TestLeadingParentSegmentIsRejected() + { + var result = LocalIOMapper.ShortenPath(new[] { "..", "foo" }); + Assert.IsNull(result); + } + + [TestMethod] + public void TestTileWithEmbeddedForwardSlashIsRejected() + { + // Simulates a %2f-encoded tile that decodes to "../../../etc/passwd" as a single, + // opaque path segment after splitting on literal '/'. Since it never equals ".." + // exactly, the plain segment-based guard would let it through. + var result = LocalIOMapper.ShortenPath(new[] { "static", "../../../etc/passwd" }); + Assert.IsNull(result); + } + + [TestMethod] + public void TestTileWithEmbeddedBackslashIsRejected() + { + var result = LocalIOMapper.ShortenPath(new[] { "static", "foo\\..\\bar" }); + Assert.IsNull(result); + } + + [TestMethod] + public void TestRootedTileIsRejected() + { + var result = LocalIOMapper.ShortenPath(new[] { "static", "/etc/passwd" }); + Assert.IsNull(result); + } + + [TestMethod] + public void TestWindowsDriveRelativeTileIsRejected() + { + if (!OperatingSystem.IsWindows()) + Assert.Inconclusive("drive-relative paths are only considered rooted on Windows"); + var result = LocalIOMapper.ShortenPath(new[] { "static", "C:" }); + Assert.IsNull(result); + } + } + + [TestClass] + public class TestLocalIOMapperFileMappingRule + { + TestWebServer server; + TestTask test; + string baseDir; + string publicDir; + string secretFile; + + [TestInitialize] + public void Init() + { + baseDir = Path.Combine(Path.GetTempPath(), "MaxLibWebServerTest_" + Guid.NewGuid().ToString("N")); + publicDir = Path.Combine(baseDir, "public"); + Directory.CreateDirectory(publicDir); + File.WriteAllText(Path.Combine(publicDir, "hello.txt"), "hi"); + secretFile = Path.Combine(baseDir, "secret.txt"); + File.WriteAllText(secretFile, "top secret"); + + server = new TestWebServer(); + var mapper = new LocalIOMapper(); + mapper.AddFileMapping("static", publicDir); + server.AddWebService(mapper); + test = new TestTask(server) + { + CurrentStage = ServerStage.CreateDocument, + TerminationStage = ServerStage.CreateDocument, + }; + } + + [TestCleanup] + public void Cleanup() + { + foreach (var source in test.GetDataSources()) + source.Dispose(); + Directory.Delete(baseDir, true); + } + + [TestMethod] + public void TestValidFileIsServed() + { + test.Request.Url = "/static/hello.txt"; + var mapper = server.WebServiceGroups[ServerStage.CreateDocument] + .Get(); + Assert.IsTrue(mapper.CanWorkWith(test.Task)); + Assert.AreEqual(1, test.GetDataSources().Count); + var source = Assert.IsInstanceOfType(test.GetDataSources()[0]); + Assert.AreEqual(Path.Combine(publicDir, "hello.txt"), source.Path); + } + + [TestMethod] + public void TestEncodedSlashTraversalIsRejected() + { + // %2f is decoded only after the URL is split on literal '/', so this whole + // segment survives the split as a single tile that decodes to "../secret.txt". + test.Request.Url = "/static/..%2fsecret.txt"; + var mapper = server.WebServiceGroups[ServerStage.CreateDocument] + .Get(); + Assert.IsFalse(mapper.CanWorkWith(test.Task)); + Assert.AreEqual(0, test.GetDataSources().Count); + } + + [TestMethod] + public void TestEncodedAbsolutePathOverrideIsRejected() + { + // decodes to a single, rooted tile "/etc/passwd" which Path.Combine would + // otherwise return verbatim, discarding the configured base directory. + test.Request.Url = "/static/%2fetc%2fpasswd"; + var mapper = server.WebServiceGroups[ServerStage.CreateDocument] + .Get(); + Assert.IsFalse(mapper.CanWorkWith(test.Task)); + Assert.AreEqual(0, test.GetDataSources().Count); + } + } + + [TestClass] + public class TestLocalIOMapperDirectoryMappingRule + { + TestWebServer server; + TestTask test; + string baseDir; + string publicDir; + + [TestInitialize] + public void Init() + { + baseDir = Path.Combine(Path.GetTempPath(), "MaxLibWebServerTest_" + Guid.NewGuid().ToString("N")); + publicDir = Path.Combine(baseDir, "public"); + Directory.CreateDirectory(publicDir); + File.WriteAllText(Path.Combine(publicDir, "hello.txt"), "hi"); + File.WriteAllText(Path.Combine(baseDir, "secret.txt"), "top secret"); + + server = new TestWebServer(); + var mapper = new LocalIOMapper(); + mapper.AddDirectoryMapping("static", publicDir); + server.AddWebService(mapper); + test = new TestTask(server) + { + CurrentStage = ServerStage.CreateDocument, + TerminationStage = ServerStage.CreateDocument, + }; + } + + [TestCleanup] + public void Cleanup() + { + foreach (var source in test.GetDataSources()) + source.Dispose(); + Directory.Delete(baseDir, true); + } + + [TestMethod] + public void TestValidDirectoryIsListed() + { + test.Request.Url = "/static/"; + var mapper = server.WebServiceGroups[ServerStage.CreateDocument] + .Get(); + Assert.IsTrue(mapper.CanWorkWith(test.Task)); + Assert.AreEqual(1, test.GetDataSources().Count); + } + + [TestMethod] + public void TestEncodedSlashTraversalIsRejected() + { + test.Request.Url = "/static/..%2f"; + var mapper = server.WebServiceGroups[ServerStage.CreateDocument] + .Get(); + Assert.IsFalse(mapper.CanWorkWith(test.Task)); + Assert.AreEqual(0, test.GetDataSources().Count); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/Sessions/TestMemorySessionService.cs b/tests/MaxLib.WebServer.Test/Sessions/TestMemorySessionService.cs new file mode 100644 index 0000000..3e0c508 --- /dev/null +++ b/tests/MaxLib.WebServer.Test/Sessions/TestMemorySessionService.cs @@ -0,0 +1,125 @@ +using System; +using System.Reflection; +using System.Threading; +using System.Threading.Tasks; +using MaxLib.WebServer.Sessions; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace MaxLib.WebServer.Test.Sessions +{ + [TestClass] + public class TestMemorySessionService + { + [TestMethod] + public async Task TestGetTreatsAnExpiredSessionAsGoneInsteadOfResurrectingIt() + { + var service = new TestableSessionService { MaxAge = TimeSpan.FromMinutes(1) }; + const string key = "expired-key"; + var stale = new Session { LastUsed = DateTime.UtcNow - TimeSpan.FromHours(1) }; + stale["marker"] = "stale-data"; + service.Sessions[key] = stale; + + var fresh = await service.ExposedGet(key).ConfigureAwait(false); + + Assert.AreNotSame(stale, fresh); + Assert.AreEqual(0, fresh.Count); + Assert.AreSame(fresh, service.Sessions[key]); + } + + [TestMethod] + public async Task TestGetKeepsAFreshSessionUntouched() + { + var service = new TestableSessionService { MaxAge = TimeSpan.FromMinutes(1) }; + const string key = "fresh-key"; + var live = new Session { LastUsed = DateTime.UtcNow }; + live["marker"] = "still-good"; + service.Sessions[key] = live; + + var result = await service.ExposedGet(key).ConfigureAwait(false); + + Assert.AreSame(live, result); + Assert.AreEqual("still-good", result["marker"]); + } + + [TestMethod] + public void TestSweepRemovesOnlyExpiredSessionsAndReportsTheOldestSurvivor() + { + var service = new MemorySessionService { MaxAge = TimeSpan.FromMinutes(10) }; + var now = DateTime.UtcNow; + service.Sessions["expired-1"] = new Session { LastUsed = now - TimeSpan.FromHours(1) }; + service.Sessions["expired-2"] = new Session { LastUsed = now - TimeSpan.FromDays(1) }; + service.Sessions["alive-older"] = new Session { LastUsed = now - TimeSpan.FromMinutes(5) }; + service.Sessions["alive-newer"] = new Session { LastUsed = now - TimeSpan.FromMinutes(1) }; + + var oldestSurviving = service.Sweep(); + + Assert.IsFalse(service.Sessions.ContainsKey("expired-1")); + Assert.IsFalse(service.Sessions.ContainsKey("expired-2")); + Assert.IsTrue(service.Sessions.ContainsKey("alive-older")); + Assert.IsTrue(service.Sessions.ContainsKey("alive-newer")); + Assert.AreEqual(service.Sessions["alive-older"].LastUsed, oldestSurviving); + } + + [TestMethod] + public void TestSweepReturnsNullWhenNoSessionSurvives() + { + var service = new MemorySessionService { MaxAge = TimeSpan.FromMinutes(1) }; + service.Sessions["expired"] = new Session { LastUsed = DateTime.UtcNow - TimeSpan.FromHours(1) }; + + var oldestSurviving = service.Sweep(); + + Assert.IsNull(oldestSurviving); + Assert.AreEqual(0, service.Sessions.Count); + } + + [TestMethod] + public async Task TestAutomaticSweepEvictsAnAlreadyExpiredSessionShortlyAfterStarting() + { + var service = new MemorySessionService + { + MaxAge = TimeSpan.FromMilliseconds(1), + AutomaticSweepMargin = TimeSpan.FromMilliseconds(1), + }; + service.Sessions["stale"] = new Session { LastUsed = DateTime.UtcNow - TimeSpan.FromDays(1) }; + try + { + service.StartAutomaticSweep(); + var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(5); + while (service.Sessions.ContainsKey("stale") && DateTime.UtcNow < deadline) + await Task.Delay(20).ConfigureAwait(false); + } + finally + { + service.Dispose(); + } + Assert.IsFalse(service.Sessions.ContainsKey("stale")); + } + + [TestMethod] + public void TestStopAutomaticSweepAndDisposeAreSafeWithoutEverStarting() + { + var service = new MemorySessionService(); + service.StopAutomaticSweep(); + service.Dispose(); + } + + [TestMethod] + public void TestRunAutomaticSweepDoesNotCrashWhenMaxAgePushesTheRescheduleDelayPastTimersCap() + { + // Timer.Change rejects due times over ~49.71 days; a long MaxAge must not push the reschedule delay past that. + // Drives RunAutomaticSweep directly via a reflected timer that never fires. + var service = new MemorySessionService { MaxAge = TimeSpan.FromDays(60) }; + service.Sessions["long-lived"] = new Session { LastUsed = DateTime.UtcNow }; + using var timer = new Timer(_ => { }, null, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan); + var sweepTimerField = typeof(MemorySessionService).GetField( + "sweepTimer", BindingFlags.NonPublic | BindingFlags.Instance); + Assert.IsNotNull(sweepTimerField, "test relies on MemorySessionService's private sweepTimer field"); + sweepTimerField!.SetValue(service, timer); + + service.RunAutomaticSweep(); + + Assert.IsTrue(service.Sessions.ContainsKey("long-lived"), + "the still-live session must survive the sweep"); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/Sessions/TestRotateSessionKeyCustomStore.cs b/tests/MaxLib.WebServer.Test/Sessions/TestRotateSessionKeyCustomStore.cs new file mode 100644 index 0000000..f82e9d6 --- /dev/null +++ b/tests/MaxLib.WebServer.Test/Sessions/TestRotateSessionKeyCustomStore.cs @@ -0,0 +1,57 @@ +using MaxLib.WebServer.Sessions; +using MaxLib.WebServer.Testing; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace MaxLib.WebServer.Test.Sessions +{ + // A session store written the way an external implementer has to write one: Session.Key + // has an internal setter, so it cannot be assigned from outside the library. + class DictionarySessionService : SessionServiceBase + { + public Dictionary Store { get; } = new(); + + protected override ValueTask Get(string key) + { + if (!Store.TryGetValue(key, out var session)) + Store[key] = session = new Session(); + return new ValueTask(session); + } + + protected override ValueTask IsKeyAvailable(string key) + => new(!Store.ContainsKey(key)); + + protected override ValueTask Remove(string key) + { + Store.Remove(key); + return default; + } + } + + [TestClass] + public class TestRotateSessionKeyCustomStore + { + [TestMethod] + public async Task TestRotateSessionKeyRetiresTheOldKeyInACustomStore() + { + var server = new TestWebServer(); + var service = new DictionarySessionService(); + server.AddWebService(service); + var test = new TestTask(server) + { + CurrentStage = ServerStage.ParseRequest, + TerminationStage = ServerStage.ParseRequest, + }; + + await service.ProgressTask(test.Task).ConfigureAwait(false); + Assert.AreEqual(1, service.Store.Count); + var oldKey = new List(service.Store.Keys)[0]; + + await service.RotateSessionKey(test.Task).ConfigureAwait(false); + + Assert.IsFalse(service.Store.ContainsKey(oldKey), + "the pre-rotation session id must no longer be stored after RotateSessionKey"); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/Sessions/TestSession.cs b/tests/MaxLib.WebServer.Test/Sessions/TestSession.cs new file mode 100644 index 0000000..28a3825 --- /dev/null +++ b/tests/MaxLib.WebServer.Test/Sessions/TestSession.cs @@ -0,0 +1,32 @@ +using MaxLib.WebServer.Sessions; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace MaxLib.WebServer.Test.Sessions +{ + [TestClass] + public class TestSession + { + [TestMethod] + public void TestModifyingDataDuringEnumerationDoesNotThrow() + { + // a plain Dictionary throws when a key is added during enumeration (as RotateSessionKey does + // with `foreach (var pair in task.Session)`); a ConcurrentDictionary tolerates it + var session = new Session + { + ["a"] = 1, + ["b"] = 2, + }; + + var seen = 0; + foreach (var pair in session) + { + session[$"added-{seen}"] = seen; + ++seen; + if (seen > 10) + break; // avoid an unbounded loop if enumeration keeps including new entries + } + + Assert.IsTrue(seen >= 2); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/Sessions/TestSessionServiceBase.cs b/tests/MaxLib.WebServer.Test/Sessions/TestSessionServiceBase.cs new file mode 100644 index 0000000..43b880d --- /dev/null +++ b/tests/MaxLib.WebServer.Test/Sessions/TestSessionServiceBase.cs @@ -0,0 +1,301 @@ +using MaxLib.WebServer.Sessions; +using MaxLib.WebServer.Testing; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.IO; +using System.Linq; +using System.Net.Security; +using System.Threading.Tasks; + +namespace MaxLib.WebServer.Test.Sessions +{ + class TestableSessionService : MemorySessionService + { + public ValueTask ExposedGenerateSessionKey() + => GenerateSessionKey(); + + public ValueTask ExposedGet(string key) + => Get(key); + } + + [TestClass] + public class TestSessionServiceBase + { + [TestMethod] + public async Task TestGenerateSessionKeyHas128BitsOfEntropy() + { + var service = new TestableSessionService(); + var key = await service.ExposedGenerateSessionKey().ConfigureAwait(false); + var bytes = Convert.FromBase64String(key); + Assert.AreEqual(16, bytes.Length); + } + + [TestMethod] + public async Task TestGenerateSessionKeyIsNotPredictableAcrossCalls() + { + var service = new TestableSessionService(); + var keys = new string[1000]; + for (var i = 0; i < keys.Length; ++i) + keys[i] = await service.ExposedGenerateSessionKey().ConfigureAwait(false); + Assert.AreEqual(keys.Length, keys.Distinct().Count()); + } + + [TestMethod] + public async Task TestGenerateSessionKeyIsThreadSafe() + { + var service = new TestableSessionService(); + var tasks = Enumerable.Range(0, 64) + .Select(_ => Task.Run(async () => await service.ExposedGenerateSessionKey().ConfigureAwait(false))) + .ToArray(); + var keys = await Task.WhenAll(tasks).ConfigureAwait(false); + Assert.AreEqual(keys.Length, keys.Distinct().Count()); + } + + [TestMethod] + public async Task TestProgressTaskIssuesASessionCookieWithA128BitKey() + { + var server = new TestWebServer(); + var service = new MemorySessionService(); + server.AddWebService(service); + var test = new TestTask(server) + { + CurrentStage = ServerStage.ParseRequest, + TerminationStage = ServerStage.ParseRequest, + }; + + await service.ProgressTask(test.Task).ConfigureAwait(false); + + var added = test.GetAddedCookies().ToArray(); + Assert.AreEqual(1, added.Length); + Assert.AreEqual("Session", added[0].Item1); + var bytes = Convert.FromBase64String(added[0].Item2.ValueString); + Assert.AreEqual(16, bytes.Length); + } + + [TestMethod] + public async Task TestProgressTaskIgnoresAnUnknownClientSuppliedSessionId() + { + var server = new TestWebServer(); + var service = new MemorySessionService(); + server.AddWebService(service); + var test = new TestTask(server) + { + CurrentStage = ServerStage.ParseRequest, + TerminationStage = ServerStage.ParseRequest, + }; + const string attackerChosenId = "FIXEDVALUE"; + test.Request.HeaderParameter.Add("Cookie", $"Session={attackerChosenId}"); + + await service.ProgressTask(test.Task).ConfigureAwait(false); + + // the attacker-chosen id must never end up in the store, or the attacker could + // fix a victim's session id in advance + Assert.IsFalse(service.Sessions.ContainsKey(attackerChosenId)); + var added = test.GetAddedCookies().Single(); + Assert.AreEqual("Session", added.Item1); + Assert.AreNotEqual(attackerChosenId, added.Item2.ValueString); + } + + [TestMethod] + public async Task TestProgressTaskRejectsAnExpiredButNotYetSweptClientSuppliedSessionId() + { + // an expired but unswept session entry must not count as "already issued" + var server = new TestWebServer(); + var service = new MemorySessionService { MaxAge = TimeSpan.FromMinutes(1) }; + server.AddWebService(service); + const string attackerChosenId = "EXPIRED-BUT-NOT-SWEPT"; + service.Sessions[attackerChosenId] = new Session + { + Key = attackerChosenId, + LastUsed = DateTime.UtcNow - TimeSpan.FromMinutes(5), + }; + var test = new TestTask(server) + { + CurrentStage = ServerStage.ParseRequest, + TerminationStage = ServerStage.ParseRequest, + }; + test.Request.HeaderParameter.Add("Cookie", $"Session={attackerChosenId}"); + + await service.ProgressTask(test.Task).ConfigureAwait(false); + + var added = test.GetAddedCookies().Single(); + Assert.AreEqual("Session", added.Item1); + Assert.AreNotEqual(attackerChosenId, added.Item2.ValueString, + "an expired-but-unswept key must be rejected the same way an unknown key is"); + Assert.AreNotEqual(attackerChosenId, test.Task.Session!.Key); + } + + [TestMethod] + public async Task TestProgressTaskReusesAnExistingSessionId() + { + var server = new TestWebServer(); + var service = new MemorySessionService(); + server.AddWebService(service); + + var first = new TestTask(server) + { + CurrentStage = ServerStage.ParseRequest, + TerminationStage = ServerStage.ParseRequest, + }; + await service.ProgressTask(first.Task).ConfigureAwait(false); + var issuedKey = first.GetAddedCookies().Single().Item2.ValueString; + first.Task.Session!["marker"] = "hello"; + + var second = new TestTask(server) + { + CurrentStage = ServerStage.ParseRequest, + TerminationStage = ServerStage.ParseRequest, + }; + second.Request.HeaderParameter.Add("Cookie", $"Session={WebServerUtils.EncodeUri(issuedKey)}"); + + await service.ProgressTask(second.Task).ConfigureAwait(false); + + Assert.AreEqual(0, second.GetAddedCookies().Count()); + Assert.AreEqual("hello", second.Task.Session!["marker"]); + } + + [TestMethod] + public async Task TestRotateSessionKeyMigratesDataAndChangesTheCookie() + { + var server = new TestWebServer(); + var service = new MemorySessionService(); + server.AddWebService(service); + var test = new TestTask(server) + { + CurrentStage = ServerStage.ParseRequest, + TerminationStage = ServerStage.ParseRequest, + }; + await service.ProgressTask(test.Task).ConfigureAwait(false); + var oldKey = test.GetAddedCookies().Single().Item2.ValueString; + test.Task.Session!["marker"] = "hello"; + + var rotated = await service.RotateSessionKey(test.Task).ConfigureAwait(false); + + var newKey = test.GetAddedCookies().Single().Item2.ValueString; + Assert.AreNotEqual(oldKey, newKey); + Assert.AreSame(rotated, test.Task.Session); + Assert.AreEqual("hello", rotated["marker"]); + Assert.IsTrue(service.Sessions.ContainsKey(newKey)); + } + + [TestMethod] + public async Task TestRotateSessionKeyRemovesTheOldSessionFromStorage() + { + // after rotation the old id must be gone, so a session id planted by an attacker stops working + var server = new TestWebServer(); + var service = new MemorySessionService(); + server.AddWebService(service); + var test = new TestTask(server) + { + CurrentStage = ServerStage.ParseRequest, + TerminationStage = ServerStage.ParseRequest, + }; + await service.ProgressTask(test.Task).ConfigureAwait(false); + var oldKey = test.GetAddedCookies().Single().Item2.ValueString; + + await service.RotateSessionKey(test.Task).ConfigureAwait(false); + + Assert.IsFalse(service.Sessions.ContainsKey(oldKey), + "the old session id must be removed once rotation completes"); + } + + [TestMethod] + public async Task TestGetAssignsTheSessionsOwnKey() + { + var service = new TestableSessionService(); + + var session = await service.ExposedGet("some-key").ConfigureAwait(false); + + Assert.AreEqual("some-key", session.Key); + } + + [TestMethod] + public async Task TestSessionCookieDefaultsToLaxRulesOverPlainConnection() + { + var server = new TestWebServer(); + var service = new MemorySessionService(); + server.AddWebService(service); + var test = new TestTask(server) + { + CurrentStage = ServerStage.ParseRequest, + TerminationStage = ServerStage.ParseRequest, + }; + // WebServerTaskCreator already sets a plain MemoryStream - not an SslStream + + await service.ProgressTask(test.Task).ConfigureAwait(false); + + var cookie = test.GetAddedCookies().Single().Item2; + Assert.IsTrue(cookie.HttpOnly); + Assert.IsFalse(cookie.Secure); + Assert.AreEqual(HttpCookie.SameSiteMode.Lax, cookie.SameSite); + } + + [TestMethod] + public async Task TestSessionCookieDefaultsToStrictRulesOverAnEncryptedConnection() + { + var server = new TestWebServer(); + var service = new MemorySessionService(); + server.AddWebService(service); + var test = new TestTask(server) + { + CurrentStage = ServerStage.ParseRequest, + TerminationStage = ServerStage.ParseRequest, + }; + test.Task.NetworkStream = new SslStream(new MemoryStream()); + + await service.ProgressTask(test.Task).ConfigureAwait(false); + + var cookie = test.GetAddedCookies().Single().Item2; + Assert.IsTrue(cookie.HttpOnly); + Assert.IsTrue(cookie.Secure); + Assert.AreEqual(HttpCookie.SameSiteMode.Strict, cookie.SameSite); + } + + [TestMethod] + public async Task TestCookieSecurityStrictAppliesEvenOverAPlainConnection() + { + // e.g. behind a reverse proxy that terminates TLS - this server only ever sees + // plain HTTP, so auto-detection alone could never produce a Secure cookie + var server = new TestWebServer(); + var service = new MemorySessionService + { + CookieSecurity = CookieSecurityMode.Strict, + }; + server.AddWebService(service); + var test = new TestTask(server) + { + CurrentStage = ServerStage.ParseRequest, + TerminationStage = ServerStage.ParseRequest, + }; + + await service.ProgressTask(test.Task).ConfigureAwait(false); + + var cookie = test.GetAddedCookies().Single().Item2; + Assert.IsTrue(cookie.Secure); + Assert.AreEqual(HttpCookie.SameSiteMode.Strict, cookie.SameSite); + } + + [TestMethod] + public async Task TestCookieSecurityLaxAppliesEvenOverAnEncryptedConnection() + { + var server = new TestWebServer(); + var service = new MemorySessionService + { + CookieSecurity = CookieSecurityMode.Lax, + }; + server.AddWebService(service); + var test = new TestTask(server) + { + CurrentStage = ServerStage.ParseRequest, + TerminationStage = ServerStage.ParseRequest, + }; + test.Task.NetworkStream = new SslStream(new MemoryStream()); + + await service.ProgressTask(test.Task).ConfigureAwait(false); + + var cookie = test.GetAddedCookies().Single().Item2; + Assert.IsFalse(cookie.Secure); + Assert.AreEqual(HttpCookie.SameSiteMode.Lax, cookie.SameSite); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/TestHttpCookie.cs b/tests/MaxLib.WebServer.Test/TestHttpCookie.cs new file mode 100644 index 0000000..1b83ea5 --- /dev/null +++ b/tests/MaxLib.WebServer.Test/TestHttpCookie.cs @@ -0,0 +1,62 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; + +#nullable enable + +namespace MaxLib.WebServer.Test +{ + [TestClass] + public class TestHttpCookie + { + [TestMethod] + public void TestToStringOmitsSecurityAttributesByDefault() + { + var cookie = new HttpCookie.Cookie("name", "value"); + Assert.AreEqual("name=value;Path=", cookie.ToString()); + } + + [TestMethod] + public void TestToStringEmitsHttpOnlySecureAndSameSiteWhenSet() + { + var cookie = new HttpCookie.Cookie( + "name", "value", new DateTime(9999, 12, 31), -1, "/", + httpOnly: true, secure: true, sameSite: HttpCookie.SameSiteMode.Strict + ); + Assert.AreEqual("name=value;Path=/;HttpOnly;Secure;SameSite=Strict", cookie.ToString()); + } + + [TestMethod] + public void TestToStringOmitsSameSiteWhenUnspecified() + { + var cookie = new HttpCookie.Cookie( + "name", "value", new DateTime(9999, 12, 31), -1, "/", + httpOnly: true, secure: false, sameSite: HttpCookie.SameSiteMode.Unspecified + ); + Assert.AreEqual("name=value;Path=/;HttpOnly", cookie.ToString()); + } + + [TestMethod] + [DataRow(HttpCookie.SameSiteMode.Lax, "Lax")] + [DataRow(HttpCookie.SameSiteMode.Strict, "Strict")] + [DataRow(HttpCookie.SameSiteMode.None, "None")] + public void TestToStringRendersEachSameSiteValue(HttpCookie.SameSiteMode mode, string expected) + { + var cookie = new HttpCookie.Cookie( + "name", "value", new DateTime(9999, 12, 31), -1, "", + httpOnly: false, secure: false, sameSite: mode + ); + StringAssert.Contains(cookie.ToString(), $";SameSite={expected}"); + } + + [TestMethod] + public void TestToStringStripsCrLfFromPathButKeepsSlashesIntact() + { + // Path is not URL-encoded like Name/Value (it legitimately contains "/"), but a raw + // CRLF must never reach the wire - see http-header-crlf-injection.md + var cookie = new HttpCookie.Cookie( + "name", "value", new DateTime(9999, 12, 31), -1, "/foo\r\nSet-Cookie: evil=1/bar" + ); + Assert.AreEqual("name=value;Path=/fooSet-Cookie: evil=1/bar", cookie.ToString()); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/TestHttpDataSource.cs b/tests/MaxLib.WebServer.Test/TestHttpDataSource.cs new file mode 100644 index 0000000..72f2277 --- /dev/null +++ b/tests/MaxLib.WebServer.Test/TestHttpDataSource.cs @@ -0,0 +1,105 @@ +using System; +using System.IO; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace MaxLib.WebServer.Test +{ + [TestClass] + public class TestHttpDataSource + { + // Signals when WriteStreamInternal runs, without touching the destination stream, to separate + // TransformToStream's worker task from BufferedSinkStream's own timing quirks. + private sealed class SignalingDataSource(ManualResetEventSlim signal) : HttpDataSource + { + public override void Dispose() => GC.SuppressFinalize(this); + public override long? Length() => null; + protected override Task WriteStreamInternal(Stream stream) + { + signal.Set(); + return Task.FromResult(0L); + } + } + + [TestMethod] + public void TestTransformToStreamActuallyRunsTheWriter() + { + // the worker task must run; otherwise this signal never fires and the wait below times out + using var signal = new ManualResetEventSlim(false); + using var source = new SignalingDataSource(signal); + using var stream = HttpDataSource.TransformToStream(source); + + Assert.IsTrue(signal.Wait(TimeSpan.FromSeconds(5)), + "TransformToStream's worker task never started running"); + } + + // Never touches the stream it's given, like a source whose underlying I/O fails before producing any bytes. + private sealed class ThrowingDataSource : HttpDataSource + { + public override void Dispose() => GC.SuppressFinalize(this); + public override long? Length() => null; + protected override Task WriteStreamInternal(Stream stream) + => throw new InvalidOperationException("boom from WriteStreamInternal"); + } + + [TestMethod] + public async Task TestTransformToStreamCompletesInsteadOfHangingWhenWriteStreamThrows() + { + // FinishWrite() must be reached even if WriteStream throws, or the reader blocks forever + using var source = new ThrowingDataSource(); + using var stream = HttpDataSource.TransformToStream(source); + + // Give the worker task time to run its try/catch/finally before reading; reading concurrently hits a + // BufferedSinkStream quirk (FinishWrite() does not wake a waiting reader), as noted on SignalingDataSource. + await Task.Delay(TimeSpan.FromMilliseconds(200)).ConfigureAwait(false); + + var buffer = new byte[16]; + var readTask = stream.ReadAsync(buffer, 0, buffer.Length); + var winner = await Task.WhenAny(readTask, Task.Delay(TimeSpan.FromSeconds(4))).ConfigureAwait(false); + + Assert.AreSame(readTask, winner, + "TransformToStream must let the reader observe completion once WriteStream throws, instead of hanging forever"); + // the read must surface the failure instead of reporting a clean EOF + var ex = await Assert.ThrowsExactlyAsync(() => readTask).ConfigureAwait(false); + Assert.IsInstanceOfType(ex.InnerException, typeof(InvalidOperationException)); + } + + // Writes some bytes before throwing, like a source whose underlying I/O fails partway through. + private sealed class PartialThenThrowDataSource : HttpDataSource + { + public override void Dispose() => GC.SuppressFinalize(this); + public override long? Length() => null; + protected override async Task WriteStreamInternal(Stream stream) + { + var data = Encoding.ASCII.GetBytes("PARTIAL-DATA-BEFORE-FAILURE"); + await stream.WriteAsync(data).ConfigureAwait(false); + await stream.FlushAsync().ConfigureAwait(false); + throw new InvalidOperationException("boom after writing partial data"); + } + } + + [TestMethod] + public async Task TestTransformToStreamSurfacesAWriteStreamFailureAfterPartialData() + { + // once partial data was written, the stream must surface the WriteStream failure after + // the data is drained instead of ending silently + using var source = new PartialThenThrowDataSource(); + using var stream = HttpDataSource.TransformToStream(source); + + // Give the worker task time to write, throw and call FinishWrite() before any read; see the note above. + await Task.Delay(TimeSpan.FromMilliseconds(200)).ConfigureAwait(false); + + var buffer = new byte[256]; + var read = await stream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false); + Assert.AreEqual("PARTIAL-DATA-BEFORE-FAILURE", Encoding.ASCII.GetString(buffer, 0, read), + "the bytes written before the failure must still be delivered"); + + var ex = await Assert.ThrowsExactlyAsync( + () => stream.ReadAsync(buffer, 0, buffer.Length)).ConfigureAwait(false); + Assert.IsInstanceOfType(ex.InnerException, typeof(InvalidOperationException)); + Assert.AreEqual("boom after writing partial data", ex.InnerException!.Message); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/TestHttpLocation.cs b/tests/MaxLib.WebServer.Test/TestHttpLocation.cs new file mode 100644 index 0000000..938e0c7 --- /dev/null +++ b/tests/MaxLib.WebServer.Test/TestHttpLocation.cs @@ -0,0 +1,70 @@ +using System; +using System.Threading.Tasks; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +#nullable enable + +namespace MaxLib.WebServer.Test +{ + [TestClass] + public class TestHttpLocation + { + [TestMethod] + public void TestSetLocationParsesAnOrdinaryPathAndQuery() + { + var location = new HttpLocation("/foo/bar?x=1"); + + Assert.AreEqual("/foo/bar", location.DocumentPath); + CollectionAssert.AreEqual(new[] { "foo", "bar" }, location.DocumentPathTiles); + Assert.AreEqual("1", location.GetParameter["x"]); + } + + [TestMethod] + public void TestSetLocationParsesMultipleQueryParameters() + { + // the query is split on '&' in code, not in the regex; every parameter must still come out in order + var location = new HttpLocation("/foo?a=1&b=2&c=3"); + + Assert.AreEqual("1", location.GetParameter["a"]); + Assert.AreEqual("2", location.GetParameter["b"]); + Assert.AreEqual("3", location.GetParameter["c"]); + } + + [TestMethod] + public void TestSetLocationFallsBackWhenQueryContainsALiteralDollarSign() + { + // a literal '$' in the query makes the regex fail, so SetLocation treats the whole raw string as the path + var location = new HttpLocation("/foo?a=1$2"); + + Assert.AreEqual("/foo?a=1$2", location.DocumentPath); + } + + [TestMethod] + public void TestSetLocationDoesNotHangOnAPathologicalQueryString() + { + // a query ending in many unmatched '$' must not cause catastrophic backtracking (ReDoS) + var url = "/?" + new string('a', 10_000) + "$"; + + var task = Task.Run(() => new HttpLocation(url)); + + Assert.IsTrue(task.Wait(TimeSpan.FromSeconds(5)), + "SetLocation took too long - looks like catastrophic backtracking regressed"); + } + + [TestMethod] + public void TestSetLocationFallsBackToTheRawUrlWhenItDoesNotMatchTheRegex() + { + // RFC 7230 §5.3.4's request-target "*" (valid for e.g. "OPTIONS *") doesn't match + // the leading-"/"-based regex at all. The fallback branch used to be immediately + // overwritten by the unconditional assignments below it, silently turning this into + // a request for "/" instead - any routing/access-control keyed on DocumentPath could + // then unexpectedly match whatever is mounted at the root. + var location = new HttpLocation("*"); + + Assert.AreEqual("*", location.DocumentPath); + CollectionAssert.AreEqual(new[] { "*" }, location.DocumentPathTiles); + Assert.AreEqual("", location.CompleteGet); + Assert.AreEqual(0, location.GetParameter.Count); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/TestHttpPartialSource.cs b/tests/MaxLib.WebServer.Test/TestHttpPartialSource.cs new file mode 100644 index 0000000..c91577f --- /dev/null +++ b/tests/MaxLib.WebServer.Test/TestHttpPartialSource.cs @@ -0,0 +1,96 @@ +using System.IO; +using System.Text; +using System.Threading.Tasks; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace MaxLib.WebServer.Test +{ + [TestClass] + public class TestHttpPartialSource + { + [TestMethod] + public async Task TestWritesRequestedRangeOnly() + { + using var source = new HttpStringDataSource("0123456789"); + using var partial = new HttpPartialSource(source, 2, 5); + + using var destination = new MemoryStream(); + await partial.WriteStream(destination).ConfigureAwait(false); + + Assert.AreEqual("23456", Encoding.UTF8.GetString(destination.ToArray())); + } + + [TestMethod] + public async Task TestDestinationStreamStaysOpenAfterWrite() + { + // WriteStreamInternal wraps the destination in a private StreamWindow that is + // disposed once writing finishes (fixes CA2000) - that must not close/dispose + // the caller-owned destination stream itself. + using var source = new HttpStringDataSource("hello world"); + using var partial = new HttpPartialSource(source, 0, null); + + using var destination = new MemoryStream(); + await partial.WriteStream(destination).ConfigureAwait(false); + + Assert.IsTrue(destination.CanWrite); + destination.WriteByte((byte)'!'); + Assert.AreEqual("hello world!", Encoding.UTF8.GetString(destination.ToArray())); + } + + [TestMethod] + public async Task TestWritesRequestedRangeOnlyWithSeekableBaseSource() + { + // BaseSource being an HttpStreamDataSource takes the other WriteStreamInternal + // branch, which wraps the destination in its own separately-fixed StreamWindow. + using var baseStream = new MemoryStream(Encoding.UTF8.GetBytes("0123456789")); + using var source = new HttpStreamDataSource(baseStream); + using var partial = new HttpPartialSource(source, 2, 5); + + using var destination = new MemoryStream(); + await partial.WriteStream(destination).ConfigureAwait(false); + + Assert.AreEqual("23456", Encoding.UTF8.GetString(destination.ToArray())); + } + + [TestMethod] + public async Task TestWritesRemainderWhenCountIsNull() + { + using var source = new HttpStringDataSource("0123456789"); + using var partial = new HttpPartialSource(source, 7, null); + + using var destination = new MemoryStream(); + await partial.WriteStream(destination).ConfigureAwait(false); + + Assert.AreEqual("789", Encoding.UTF8.GetString(destination.ToArray())); + } + + [TestMethod] + public async Task TestNestedPartialSourceWithCountUsesTheRelativeStartToComputeCount() + { + // the merged Count must be computed from the relative `start`, not the already-updated absolute Start + using var source = new HttpStringDataSource("0123456789"); + using var inner = new HttpPartialSource(source, 2, 5); // covers "23456" + using var outer = new HttpPartialSource(inner, 1, null); // relative offset 1 into inner -> "3456" + + using var destination = new MemoryStream(); + await outer.WriteStream(destination).ConfigureAwait(false); + + Assert.AreEqual("3456", Encoding.UTF8.GetString(destination.ToArray())); + } + + [TestMethod] + public async Task TestNestedPartialSourceWithBothCountsUsesTheRelativeStartToComputeCount() + { + // same as above, but for the branch where both the outer and inner Count are set + // (Math.Min(Count.Value, partial.Count.Value - start)). + using var source = new HttpStringDataSource("0123456789"); + using var inner = new HttpPartialSource(source, 2, 5); // covers "23456" + using var outer = new HttpPartialSource(inner, 1, 10); // relative offset 1 into inner, capped by inner's own remaining length + + using var destination = new MemoryStream(); + await outer.WriteStream(destination).ConfigureAwait(false); + + Assert.AreEqual("3456", Encoding.UTF8.GetString(destination.ToArray())); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/TestHttpPost.cs b/tests/MaxLib.WebServer.Test/TestHttpPost.cs new file mode 100644 index 0000000..b06148b --- /dev/null +++ b/tests/MaxLib.WebServer.Test/TestHttpPost.cs @@ -0,0 +1,63 @@ +using System; +using System.IO; +using System.Threading.Tasks; +using MaxLib.WebServer.IO; +using MaxLib.WebServer.Post; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +#nullable enable + +namespace MaxLib.WebServer.Test +{ + [TestClass] + public class TestHttpPost + { + private sealed class ThrowingPostData : IPostData + { + public bool Disposed { get; private set; } + + public string MimeType => "test/throwing"; + + public Task SetAsync(WebProgressTask task, ContentStream content, string options) + => throw new InvalidOperationException("boom"); + + public void Dispose() => Disposed = true; + } + + [TestMethod] + public async Task TestDisposesThePartiallyBuiltPostDataWhenSetAsyncThrows() + { + // SetAsync may have created temp files before failing; they must be cleaned up + // even though the IPostData is otherwise unreachable. + var postData = new ThrowingPostData(); + HttpPost.DataHandler["test/throwing"] = () => postData; + try + { + var post = new HttpPost(); + var content = new ContentStream(new NetworkReader(new MemoryStream([])), 0); + post.SetPost(new WebProgressTask(), content, "test/throwing"); + + await Assert.ThrowsExactlyAsync( + async () => await post.DataAsync!.ConfigureAwait(false)); + + Assert.IsTrue(postData.Disposed); + } + finally + { + HttpPost.DataHandler.Remove("test/throwing"); + } + } + + [TestMethod] + public void TestSetPostRecognizesAContentTypeRegardlessOfCase() + { + // a non-lowercase Content-Type must still resolve to the registered IPostData type + var post = new HttpPost(); + var content = new ContentStream(new NetworkReader(new MemoryStream([])), 0); + + post.SetPost(new WebProgressTask(), content, "Application/X-WWW-Form-Urlencoded"); + + Assert.IsInstanceOfType(post.Data); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/TestHttpRequestHeader.cs b/tests/MaxLib.WebServer.Test/TestHttpRequestHeader.cs index 6020380..431035d 100644 --- a/tests/MaxLib.WebServer.Test/TestHttpRequestHeader.cs +++ b/tests/MaxLib.WebServer.Test/TestHttpRequestHeader.cs @@ -56,6 +56,13 @@ public void TestConnectionClose() Assert.AreEqual(HttpConnectionType.Close, test.Request.FieldConnection); } + [TestMethod] + public void TestConnectionMixedCase() + { + test.Request.HeaderParameter.Add("Connection", "Keep-Alive"); + Assert.AreEqual(HttpConnectionType.KeepAlive, test.Request.FieldConnection); + } + [TestMethod] public void TestHost() { @@ -63,6 +70,26 @@ public void TestHost() Assert.AreEqual("test.domain", test.Request.Host); } + [TestMethod] + public void TestHostSetterAssignsTheValueOnAFreshRequest() + { + test.Request.Host = "set.example"; + Assert.AreEqual("set.example", test.Request.Host); + } + + [TestMethod] + public void TestHostSetterThrowsOnNull() + { + Assert.ThrowsExactly(() => test.Request.Host = null!); + } + + [TestMethod] + public void TestHeaderNameLookupIsCaseInsensitive() + { + test.Request.HeaderParameter.Add("content-type", "text/plain"); + Assert.AreEqual("text/plain", test.Request.GetHeader("Content-Type")); + } + [TestMethod] public void TestCookie() { diff --git a/tests/MaxLib.WebServer.Test/TestHttpStreamDataSource.cs b/tests/MaxLib.WebServer.Test/TestHttpStreamDataSource.cs new file mode 100644 index 0000000..d78f758 --- /dev/null +++ b/tests/MaxLib.WebServer.Test/TestHttpStreamDataSource.cs @@ -0,0 +1,47 @@ +using System.IO; +using System.Threading.Tasks; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +#nullable enable + +namespace MaxLib.WebServer.Test +{ + [TestClass] + public class TestHttpStreamDataSource + { + [TestMethod] + public async Task TestWriteStreamWithACountOnlyReadsAsMuchAsRequested() + { + // only `count` bytes may be read from the source, not everything up to its end + var source = new byte[100_000]; + for (var i = 0; i < source.Length; ++i) + source[i] = (byte)i; + using var sourceStream = new MemoryStream(source); + using var dataSource = new HttpStreamDataSource(sourceStream); + using var output = new MemoryStream(); + + var written = await dataSource.WriteStream(output, 0, 10).ConfigureAwait(false); + + Assert.AreEqual(10, written); + Assert.AreEqual(10, output.Length); + Assert.IsTrue(sourceStream.Position <= 10, + $"expected the source stream to be read no further than position 10, but it's at {sourceStream.Position}"); + } + + [TestMethod] + public async Task TestWriteStreamWithNoCountReadsTheWholeStream() + { + var source = new byte[1000]; + for (var i = 0; i < source.Length; ++i) + source[i] = (byte)i; + using var sourceStream = new MemoryStream(source); + using var dataSource = new HttpStreamDataSource(sourceStream); + using var output = new MemoryStream(); + + var written = await dataSource.WriteStream(output, 0, null).ConfigureAwait(false); + + Assert.AreEqual(1000, written); + CollectionAssert.AreEqual(source, output.ToArray()); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/TestMultipartRanges.cs b/tests/MaxLib.WebServer.Test/TestMultipartRanges.cs new file mode 100644 index 0000000..6d63702 --- /dev/null +++ b/tests/MaxLib.WebServer.Test/TestMultipartRanges.cs @@ -0,0 +1,92 @@ +using System.IO; +using System.Text; +using System.Threading.Tasks; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace MaxLib.WebServer.Test +{ + [TestClass] + public class TestMultipartRanges + { + [TestMethod] + public async Task TestSingleRangeIncludesTheFinalRequestedByte() + { + // To is inclusive: "bytes=0-4" must deliver 5 bytes, so the count is To - From + 1 + var request = new HttpRequestHeader(); + request.HeaderParameter["Range"] = "bytes=0-4"; + var response = new HttpResponseHeader(); + using var baseStream = new MemoryStream(Encoding.UTF8.GetBytes("0123456789")); + using var ranges = new MultipartRanges(baseStream, request, response, null); + + using var destination = new MemoryStream(); + await ranges.WriteStream(destination).ConfigureAwait(false); + + Assert.AreEqual(HttpStateCode.PartialContent, response.StatusCode); + Assert.AreEqual("bytes 0-4/10", response.HeaderParameter["Content-Range"]); + Assert.AreEqual("01234", Encoding.UTF8.GetString(destination.ToArray())); + } + + [TestMethod] + public async Task TestOutOfOrderRangesStillMergeWithoutDroppingBytes() + { + // FormatRanges sorts by From before merging; this dataset fails with a wrong comparator + // (List.Sort with an invalid comparator is unspecified, so smaller inputs may not catch it) + var originalJoinGap = MultipartRanges.JoinGap; + try + { + MultipartRanges.JoinGap = 0; + var request = new HttpRequestHeader(); + // ranges 90-125, 125-151, 147-192 and 173-211 all mutually overlap/touch and + // must merge into one 90-211 span regardless of the order they were requested in + request.HeaderParameter["Range"] = "bytes=44-79,90-125,147-192,125-151,173-211"; + var response = new HttpResponseHeader(); + var sourceBytes = new byte[250]; + for (var i = 0; i < sourceBytes.Length; ++i) + sourceBytes[i] = (byte)i; + using var baseStream = new MemoryStream(sourceBytes); + using var ranges = new MultipartRanges(baseStream, request, response, null); + + using var destination = new MemoryStream(); + await ranges.WriteStream(destination).ConfigureAwait(false); + + // bytes 152-172 sit inside the merged 90-211 span and must appear as one + // uninterrupted run in the output, wherever the multipart formatting places it + var expectedRun = sourceBytes[152..173]; + Assert.IsTrue(ContainsSubsequence(destination.ToArray(), expectedRun), + "bytes 152-172 are missing from the response - the out-of-order ranges failed to merge correctly"); + } + finally + { + MultipartRanges.JoinGap = originalJoinGap; + } + } + + [TestMethod] + public void TestReversedRangeIsRejectedAsNotSatisfiable() + { + // both bounds of "bytes=5-2" are in range but From > To; it must be rejected + // instead of the negative byte count throwing + var request = new HttpRequestHeader(); + request.HeaderParameter["Range"] = "bytes=5-2"; + var response = new HttpResponseHeader(); + using var baseStream = new MemoryStream(Encoding.UTF8.GetBytes("0123456789")); + + using var ranges = new MultipartRanges(baseStream, request, response, null); + + Assert.AreEqual(HttpStateCode.RequestedRangeNotSatisfiable, response.StatusCode); + } + + private static bool ContainsSubsequence(byte[] haystack, byte[] needle) + { + for (var i = 0; i <= haystack.Length - needle.Length; ++i) + { + var match = true; + for (var j = 0; j < needle.Length; ++j) + if (haystack[i + j] != needle[j]) { match = false; break; } + if (match) + return true; + } + return false; + } + } +} diff --git a/tests/MaxLib.WebServer.Test/TestSecureWebServerKeepAliveDispatch.cs b/tests/MaxLib.WebServer.Test/TestSecureWebServerKeepAliveDispatch.cs new file mode 100644 index 0000000..3b665ae --- /dev/null +++ b/tests/MaxLib.WebServer.Test/TestSecureWebServerKeepAliveDispatch.cs @@ -0,0 +1,138 @@ +using System; +using System.Net; +using System.Net.Sockets; +using System.Threading; +using System.Threading.Tasks; +using MaxLib.WebServer.SSL; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +#nullable enable + +namespace MaxLib.WebServer.Test +{ + [TestClass] + public class TestSecureWebServerKeepAliveDispatch + { + // Runs the real SecureMainTask loop of an HTTPS-only server (Server.ServerMainTask never starts) + // without accepting any connection, to check that it polls/evicts KeepAliveConnections itself. + private sealed class RecordingSecureServer : SecureWebServer + { + public bool StartListenCalled; + + public RecordingSecureServer(SecureWebServerSettings settings) : base(settings) { } + + public void SetSecureListener(TcpListener listener) => SecureListener = listener; + + protected override void SecureClientConnected(TcpClient client) { } + + protected override Task SafeClientStartListen(HttpConnection connection) + { + StartListenCalled = true; + return Task.CompletedTask; + } + + public Thread StartSecureMainTaskThread() + { + ServerExecution = true; // protected set - accessible directly from this subclass + var thread = new Thread(SecureMainTask) { IsBackground = true }; + thread.Start(); + return thread; + } + } + + [TestMethod] + public void TestSecureMainTaskEvictsAStaleKeepAliveConnectionWhenUnsafePortIsDisabled() + { + using var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + using var client = new TcpClient(); + client.Connect((IPEndPoint)listener.LocalEndpoint); + using var accepted = listener.AcceptTcpClient(); + + var settings = new SecureWebServerSettings(0, 1) // securePort, connectionTimeout=1ms + { + ConnectionDelay = TimeSpan.FromMilliseconds(1), + }; + Assert.IsFalse(settings.EnableUnsafePort, + "the two-argument constructor must select the documented HTTPS-only mode"); + + var server = new RecordingSecureServer(settings); + using var idleListener = new TcpListener(IPAddress.Loopback, 0); + idleListener.Start(); + server.SetSecureListener(idleListener); // never gets a connection - Pending() stays false + + var connection = new HttpConnection + { + NetworkClient = accepted, + LastWorkTime = Environment.TickCount - 10_000, // already far past the 1ms timeout + }; + server.KeepAliveConnections.Add(connection); + server.AllConnections.Add(connection); + + var thread = server.StartSecureMainTaskThread(); + try + { + var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(5); + while (server.KeepAliveConnections.Count > 0 && DateTime.UtcNow < deadline) + Thread.Sleep(5); + } + finally + { + server.Stop(); + thread.Join(TimeSpan.FromSeconds(2)); + } + + Assert.AreEqual(0, server.KeepAliveConnections.Count, + "SecureMainTask must evict a timed-out keep-alive connection even when EnableUnsafePort is false, or it would never be processed by anything"); + Assert.IsFalse(server.StartListenCalled, + "an already-timed-out connection must be evicted, not re-dispatched"); + } + + [TestMethod] + public void TestKeepAliveGuardTracksStartTimeDecisionNotALaterEnableUnsafePortToggle() + { + // securePort 0 lets the OS assign an unused ephemeral port + using var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + using var client = new TcpClient(); + client.Connect((IPEndPoint)listener.LocalEndpoint); + using var accepted = listener.AcceptTcpClient(); + + var settings = new SecureWebServerSettings(0, 1) // securePort, connectionTimeout=1ms + { + ConnectionDelay = TimeSpan.FromMilliseconds(1), + }; + Assert.IsFalse(settings.EnableUnsafePort, + "the two-argument constructor must select the documented HTTPS-only mode"); + + var server = new RecordingSecureServer(settings); + server.Start(); // baseLoopStarted is captured here as false - Server.ServerMainTask never starts + try + { + // toggling the setting after Start() must not change the decision of whether the base loop runs, + // or the keep-alive guard would stop servicing KeepAliveConnections + settings.EnableUnsafePort = true; + + var connection = new HttpConnection + { + NetworkClient = accepted, + LastWorkTime = Environment.TickCount - 10_000, // already far past the 1ms timeout + }; + server.KeepAliveConnections.Add(connection); + server.AllConnections.Add(connection); + + var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(5); + while (server.KeepAliveConnections.Count > 0 && DateTime.UtcNow < deadline) + Thread.Sleep(5); + + Assert.AreEqual(0, server.KeepAliveConnections.Count, + "SecureMainTask must keep evicting stale keep-alive connections after EnableUnsafePort " + + "is toggled at runtime, since Server.ServerMainTask was never actually started to pick up the slack"); + } + finally + { + server.Stop(); + } + } + } +} diff --git a/tests/MaxLib.WebServer.Test/TestServer.cs b/tests/MaxLib.WebServer.Test/TestServer.cs new file mode 100644 index 0000000..5e2c3a1 --- /dev/null +++ b/tests/MaxLib.WebServer.Test/TestServer.cs @@ -0,0 +1,118 @@ +using MaxLib.WebServer.Services; +using MaxLib.WebServer.Testing; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.IO; +using System.Net.Sockets; +using System.Threading.Tasks; + +#nullable enable + +namespace MaxLib.WebServer.Test +{ + [TestClass] + public class TestServer + { + // Throws a plain, non-HttpException exception - the kind WebServiceGroup.Execute() + // doesn't catch on its own - from whichever stage it is registered at. + private sealed class ThrowingService : WebService + { + public ThrowingService(ServerStage stage) : base(stage) { } + public override bool CanWorkWith(WebProgressTask task) => true; + public override Task ProgressTask(WebProgressTask task) + => throw new InvalidOperationException("boom"); + } + + [TestMethod] + public async Task TestUnhandledExceptionSendsFallbackResponseAndRemovesTheConnection() + { + var server = new TestWebServer(); + server.AddWebService(new ThrowingService(ServerStage.ProcessDocument)); + server.AddWebService(new HttpResponseCreator()); + server.AddWebService(new HttpSender()); + + var test = server.CreateTest(); + test.CurrentStage = ServerStage.FIRST_STAGE; + var connection = new HttpConnection(); + test.SetConnection(connection); + server.AllConnections.Add(connection); + + using var response = new MemoryStream(); + test.Task.NetworkStream = response; + + await server.RunProcessTask(test.Task, connection).ConfigureAwait(false); + + response.Position = 0; + using var r = new StreamReader(response); + var text = r.ReadToEnd(); + StringAssert.Contains(text, "500 Internal Server Error"); + + Assert.AreEqual(HttpConnectionType.Close, test.Request.FieldConnection); + Assert.IsFalse(server.AllConnections.Contains(connection), + "the connection must be removed even though the request handler threw"); + Assert.IsFalse(server.KeepAliveConnections.Contains(connection)); + } + + [TestMethod] + public async Task TestUnhandledExceptionDuringSendResponseDoesNotAttemptASecondResponse() + { + // Simulates the exception happening while the response is already being + // transmitted: bytes may already be on the wire, so no fallback response may be + // attempted - it would either corrupt what was already sent or, at best, send a + // second bogus response the client never asked for. + var server = new TestWebServer(); + server.AddWebService(new ThrowingService(ServerStage.SendResponse)); + + var test = server.CreateTest(); + test.CurrentStage = ServerStage.SendResponse; + var connection = new HttpConnection(); + test.SetConnection(connection); + server.AllConnections.Add(connection); + + using var response = new MemoryStream(); + test.Task.NetworkStream = response; + + await server.RunProcessTask(test.Task, connection).ConfigureAwait(false); + + Assert.AreEqual(0, response.Length, + "no fallback response may be written once SendResponse has already started"); + Assert.AreEqual(HttpConnectionType.Close, test.Request.FieldConnection); + Assert.IsFalse(server.AllConnections.Contains(connection)); + } + + [TestMethod] + public void TestTryAdmitConnectionAllowsConnectionsWhenNoLimitIsConfigured() + { + var server = new TestWebServer(); + using var client = new TcpClient(); + + Assert.IsTrue(server.RunTryAdmitConnection(client)); + } + + [TestMethod] + public void TestTryAdmitConnectionRejectsOnceTheConfiguredLimitIsReached() + { + var server = new TestWebServer + { + Settings = { MaxConcurrentConnections = 1 }, + }; + server.AllConnections.Add(new HttpConnection()); + using var client = new TcpClient(); + + Assert.IsFalse(server.RunTryAdmitConnection(client)); + } + + [TestMethod] + public void TestTryAdmitConnectionAllowsConnectionsBelowTheConfiguredLimit() + { + var server = new TestWebServer + { + Settings = { MaxConcurrentConnections = 2 }, + }; + server.AllConnections.Add(new HttpConnection()); + using var client = new TcpClient(); + + Assert.IsTrue(server.RunTryAdmitConnection(client)); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/TestServerAcceptLoopExceptionSafety.cs b/tests/MaxLib.WebServer.Test/TestServerAcceptLoopExceptionSafety.cs new file mode 100644 index 0000000..fea378e --- /dev/null +++ b/tests/MaxLib.WebServer.Test/TestServerAcceptLoopExceptionSafety.cs @@ -0,0 +1,113 @@ +using System; +using System.Net; +using System.Net.Sockets; +using System.Threading; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +#nullable enable + +namespace MaxLib.WebServer.Test +{ + [TestClass] + public class TestServerAcceptLoopExceptionSafety + { + // Throws on the first accepted connection, then stops the loop on the second: the loop must + // survive the exception and keep accepting. ServerMainTask() is called directly so an unhandled + // exception fails the test instead of crashing the test process. + private sealed class ThrowingAcceptServer : Server + { + public int ClientConnectedCalls; + + public ThrowingAcceptServer(WebServerSettings settings) : base(settings) { } + + public void SetListener(TcpListener listener) => Listener = listener; + + protected override void ClientConnected(TcpClient client) + { + Interlocked.Increment(ref ClientConnectedCalls); + client.Dispose(); + if (ClientConnectedCalls == 1) + throw new InvalidOperationException("simulated accept-time failure"); + ServerExecution = false; + } + + public void RunMainTaskOnceSynchronously() + { + ServerExecution = true; + ServerMainTask(); + } + } + + [TestMethod] + public void TestServerMainTaskSurvivesAnExceptionFromClientConnected() + { + using var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + using var client1 = new TcpClient(); + client1.Connect((IPEndPoint)listener.LocalEndpoint); + using var client2 = new TcpClient(); + client2.Connect((IPEndPoint)listener.LocalEndpoint); + // give the listener a moment to actually queue both pending connections + var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(5); + while (!listener.Pending() && DateTime.UtcNow < deadline) + Thread.Sleep(5); + + var settings = new WebServerSettings(1, 5000) { ConnectionDelay = TimeSpan.FromMilliseconds(1) }; + var server = new ThrowingAcceptServer(settings); + server.SetListener(listener); + + server.RunMainTaskOnceSynchronously(); + + Assert.AreEqual(2, server.ClientConnectedCalls, + "the accept loop must keep accepting further pending connections even after ClientConnected throws for an earlier one"); + } + + // Throws without ever touching (or disposing) the accepted client itself - simulating + // a failure that happens before the framework's own connection bookkeeping (e.g. + // reading RemoteEndPoint on a connection the peer already reset). + private sealed class ThrowingAfterAcceptServer : Server + { + public ThrowingAfterAcceptServer(WebServerSettings settings) : base(settings) { } + + public void SetListener(TcpListener listener) => Listener = listener; + + protected override void ClientConnected(TcpClient client) + { + ServerExecution = false; + throw new InvalidOperationException("simulated post-accept failure"); + } + + public void RunMainTaskOnceSynchronously() + { + ServerExecution = true; + ServerMainTask(); + } + } + + [TestMethod] + public void TestServerMainTaskClosesTheAcceptedClientWhenClientConnectedThrows() + { + using var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + using var client = new TcpClient(); + client.Connect((IPEndPoint)listener.LocalEndpoint); + var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(5); + while (!listener.Pending() && DateTime.UtcNow < deadline) + Thread.Sleep(5); + + var settings = new WebServerSettings(1, 5000) { ConnectionDelay = TimeSpan.FromMilliseconds(1) }; + var server = new ThrowingAfterAcceptServer(settings); + server.SetListener(listener); + + server.RunMainTaskOnceSynchronously(); + + // if the server never closes the accepted client, this blocks until the receive + // timeout instead of observing a graceful EOF (read returning 0) + client.ReceiveTimeout = 2000; + var buffer = new byte[1]; + var read = client.GetStream().Read(buffer, 0, 1); + Assert.AreEqual(0, read, + "the server must close the accepted client if ClientConnected throws, or its socket leaks forever"); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/TestServerKeepAliveDispatch.cs b/tests/MaxLib.WebServer.Test/TestServerKeepAliveDispatch.cs new file mode 100644 index 0000000..6c4849c --- /dev/null +++ b/tests/MaxLib.WebServer.Test/TestServerKeepAliveDispatch.cs @@ -0,0 +1,90 @@ +using System; +using System.Collections.Concurrent; +using System.Net; +using System.Net.Sockets; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +#nullable enable + +namespace MaxLib.WebServer.Test +{ + [TestClass] + public class TestServerKeepAliveDispatch + { + // Runs the real ServerMainTask loop without accepting or processing any connection, + // isolating the keep-alive re-dispatch decision. + private sealed class RecordingServer : Server + { + public ConcurrentBag Dispatched { get; } = new(); + + public RecordingServer(WebServerSettings settings) : base(settings) { } + + public void SetListener(TcpListener listener) => Listener = listener; + + protected override void ClientConnected(TcpClient client) { } + + protected override Task SafeClientStartListen(HttpConnection connection) + { + // deliberately never touches connection.LastWorkTime - simulates a dispatched + // task that hasn't gotten around to actually running ClientStartListen yet + Dispatched.Add(connection); + return Task.CompletedTask; + } + + public Thread StartMainTaskThread() + { + ServerExecution = true; // protected set - accessible directly from this subclass + var thread = new Thread(ServerMainTask) { IsBackground = true }; + thread.Start(); + return thread; + } + } + + [TestMethod] + public void TestAKeepAliveConnectionIsNotDispatchedTwiceBeforeItsTaskCanUpdateLastWorkTime() + { + using var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + using var client = new TcpClient(); + client.Connect((IPEndPoint)listener.LocalEndpoint); + using var accepted = listener.AcceptTcpClient(); + // give the accepted socket unread bytes, so `NetworkClient.Available > 0` holds + // for every pass of the keep-alive scan below + client.GetStream().Write(new byte[] { 1, 2, 3 }); + while (accepted.Available == 0) + Thread.Sleep(5); + + // Settings.Port is irrelevant here - Listener is replaced with idleListener below + // and Start() is never called + var settings = new WebServerSettings(1, 5000) { ConnectionDelay = TimeSpan.FromMilliseconds(1) }; + var server = new RecordingServer(settings); + using var idleListener = new TcpListener(IPAddress.Loopback, 0); + idleListener.Start(); + server.SetListener(idleListener); // never gets a connection - Pending() stays false + + var connection = new HttpConnection + { + NetworkClient = accepted, + LastWorkTime = Environment.TickCount, + }; + server.KeepAliveConnections.Add(connection); + server.AllConnections.Add(connection); + + var thread = server.StartMainTaskThread(); + try + { + Thread.Sleep(200); // several loop iterations at a 1ms delay + } + finally + { + server.Stop(); // ServerThread is null here, so this just flips ServerExecution + thread.Join(TimeSpan.FromSeconds(2)); + } + + Assert.AreEqual(1, server.Dispatched.Count, + "the same still-pending keep-alive connection must only be dispatched once"); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/TestWebServerLog.cs b/tests/MaxLib.WebServer.Test/TestWebServerLog.cs new file mode 100644 index 0000000..56e8783 --- /dev/null +++ b/tests/MaxLib.WebServer.Test/TestWebServerLog.cs @@ -0,0 +1,124 @@ +using Microsoft.Extensions.Logging; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Collections.Generic; + +#nullable enable + +namespace MaxLib.WebServer.Test +{ + // WebServerLog.SetLoggerFactory can only succeed once for the lifetime of the test + // process - a second call always throws. Tests below that need a specific factory + // bypass that guard entirely by assigning the internal WebServerLog.LoggerFactory + // property directly (visible here via [InternalsVisibleTo] on MaxLib.WebServer), and + // each such test declares its own dedicated throwaway type so its static logger + // field resolves fresh against that test's factory. No two tests ever share a type, + // so there is nothing to reset between tests, and real library types are never + // touched here since other tests in this assembly may have already initialized their + // static loggers against a different (or the default) factory. + [TestClass] + public class TestWebServerLog + { + [TestMethod] + public void ForwardsLogCallToMatchingCategoryLevelAndEventId() + { + var factory = new RecordingLoggerFactory(); + WebServerLog.LoggerFactory = factory; + + SampleTypeA.Log(); + + Assert.AreEqual(1, factory.Entries.Count); + var entry = factory.Entries[0]; + // ILoggerFactoryExtensions.CreateLogger(Type) renders nested types with '.' instead + // of the '+' that Type.FullName uses. + Assert.AreEqual(typeof(SampleTypeA).FullName!.Replace('+', '.'), entry.Category); + Assert.AreEqual(LogLevel.Error, entry.Level); + Assert.AreEqual("sample", entry.EventId.Name); + Assert.AreEqual("Something failed", entry.Message); + } + + [TestMethod] + public void PassesRealExceptionInsteadOfStringifyingIt() + { + var factory = new RecordingLoggerFactory(); + WebServerLog.LoggerFactory = factory; + + var thrown = SampleTypeB.LogWithException(); + + Assert.AreEqual(1, factory.Entries.Count); + Assert.AreSame(thrown, factory.Entries[0].Exception); + } + + [TestMethod] + public void SecondCallToSetLoggerFactoryThrows() + { + WebServerLog.SetLoggerFactory(new RecordingLoggerFactory()); + + Assert.ThrowsExactly( + () => WebServerLog.SetLoggerFactory(new RecordingLoggerFactory()) + ); + } + + static class SampleTypeA + { + static readonly ILogger logger = WebServerLog.LoggerFactory.CreateLogger(typeof(SampleTypeA)); + static readonly EventId SampleEventId = new(0, "sample"); + + public static void Log() => logger.LogError(SampleEventId, "Something failed"); + } + + static class SampleTypeB + { + static readonly ILogger logger = WebServerLog.LoggerFactory.CreateLogger(typeof(SampleTypeB)); + static readonly EventId SampleEventId = new(0, "sample"); + + public static Exception LogWithException() + { + var exception = new InvalidOperationException("boom"); + logger.LogError(SampleEventId, exception, "Something failed"); + return exception; + } + } + + sealed class RecordingLoggerFactory : ILoggerFactory + { + public List<(string Category, LogLevel Level, EventId EventId, Exception? Exception, string Message)> Entries { get; } + = new List<(string Category, LogLevel Level, EventId EventId, Exception? Exception, string Message)>(); + + public ILogger CreateLogger(string categoryName) => new RecordingLogger(categoryName, Entries); + + public void AddProvider(ILoggerProvider provider) { } + + public void Dispose() { } + } + + sealed class RecordingLogger : ILogger + { + readonly string category; + readonly List<(string Category, LogLevel Level, EventId EventId, Exception? Exception, string Message)> entries; + + public RecordingLogger(string category, + List<(string Category, LogLevel Level, EventId EventId, Exception? Exception, string Message)> entries) + { + this.category = category; + this.entries = entries; + } + + public IDisposable BeginScope(TState state) where TState : notnull => NoopDisposable.Instance; + + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) + { + entries.Add((category, logLevel, eventId, exception, formatter(state, exception))); + } + } + + sealed class NoopDisposable : IDisposable + { + public static readonly NoopDisposable Instance = new NoopDisposable(); + + public void Dispose() { } + } + } +} diff --git a/tests/MaxLib.WebServer.Test/TestWebServerUtils.cs b/tests/MaxLib.WebServer.Test/TestWebServerUtils.cs new file mode 100644 index 0000000..bafcc79 --- /dev/null +++ b/tests/MaxLib.WebServer.Test/TestWebServerUtils.cs @@ -0,0 +1,211 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; + +#nullable enable + +namespace MaxLib.WebServer.Test +{ + [TestClass] + public class TestWebServerUtils + { + [TestMethod] + public void DefaultsToIecPrefixesForShortNames() + { + Assert.AreEqual("512 B", WebServerUtils.GetVolumeString(512, true, 4)); + Assert.AreEqual("1 KiB", WebServerUtils.GetVolumeString(1024, true, 4)); + Assert.AreEqual("1 MiB", WebServerUtils.GetVolumeString(1024 * 1024, true, 4)); + Assert.AreEqual("1 GiB", WebServerUtils.GetVolumeString(1024L * 1024 * 1024, true, 4)); + } + + [TestMethod] + public void DefaultsToIecPrefixesForLongNames() + { + Assert.AreEqual("1 Kibibyte", WebServerUtils.GetVolumeString(1024, false, 4)); + Assert.AreEqual("1 Mebibyte", WebServerUtils.GetVolumeString(1024 * 1024, false, 4)); + } + + [TestMethod] + public void IecPrefixesDivideByOneThousandTwentyFourPerStep() + { + // 1536 bytes = 1.5 KiB, confirming steps use base-1024, not base-1000 + Assert.AreEqual("1.5 KiB", WebServerUtils.GetVolumeString(1536, true, 4, PrefixKind.IEC)); + } + + [TestMethod] + public void SiPrefixesUseShortNames() + { + Assert.AreEqual("512 B", WebServerUtils.GetVolumeString(512, true, 4, PrefixKind.SI)); + Assert.AreEqual("1 KB", WebServerUtils.GetVolumeString(1000, true, 4, PrefixKind.SI)); + Assert.AreEqual("1 MB", WebServerUtils.GetVolumeString(1000 * 1000, true, 4, PrefixKind.SI)); + Assert.AreEqual("1 GB", WebServerUtils.GetVolumeString(1000L * 1000 * 1000, true, 4, PrefixKind.SI)); + } + + [TestMethod] + public void SiPrefixesUseLongNames() + { + Assert.AreEqual("1 Kilobyte", WebServerUtils.GetVolumeString(1000, false, 4, PrefixKind.SI)); + Assert.AreEqual("1 Megabyte", WebServerUtils.GetVolumeString(1000 * 1000, false, 4, PrefixKind.SI)); + } + + [TestMethod] + public void SiPrefixesDivideByOneThousandPerStep() + { + // 1500 bytes = 1.5 KB, confirming steps use base-1000, not base-1024 + Assert.AreEqual("1.5 KB", WebServerUtils.GetVolumeString(1500, true, 4, PrefixKind.SI)); + } + + [TestMethod] + public void ThrowsForNegativeByteCount() + { + Assert.ThrowsExactly( + () => WebServerUtils.GetVolumeString(-1, true, 4) + ); + } + + [TestMethod] + public void ThrowsForNegativeFractionalByteCount() + { + Assert.ThrowsExactly( + () => WebServerUtils.GetVolumeString(-0.5, true, 4) + ); + } + + [TestMethod] + public void ThrowsForNaNByteCount() + { + // NaN is neither negative nor >= 0, so it slips past ThrowIfNegative and needs + // its own IsFinite check. + Assert.ThrowsExactly( + () => WebServerUtils.GetVolumeString(double.NaN, true, 4) + ); + } + + [TestMethod] + public void ThrowsForInfiniteByteCount() + { + Assert.ThrowsExactly( + () => WebServerUtils.GetVolumeString(double.PositiveInfinity, true, 4) + ); + Assert.ThrowsExactly( + () => WebServerUtils.GetVolumeString(double.NegativeInfinity, true, 4) + ); + } + + [TestMethod] + public void ZeroBytesFormatsAsZeroBytes() + { + Assert.AreEqual("0 B", WebServerUtils.GetVolumeString(0, true, 4)); + } + + [TestMethod] + public void DoesNotThrowForByteCountsBeyondLongMaxValue() + { + // long.MaxValue only reaches EiB/EB, well short of the unit table's end - this + // exercises the step-clamping guard that keeps values beyond the unit table from + // throwing. + Assert.AreEqual("8 EiB", WebServerUtils.GetVolumeString(long.MaxValue, true, 4)); + Assert.AreEqual("9.223 EB", WebServerUtils.GetVolumeString(long.MaxValue, true, 4, PrefixKind.SI)); + } + + [TestMethod] + public void ReachesTheRonnaAndQuettaPrefixesNowThatByteCountIsADouble() + { + // long.MaxValue (~9.22e18) can never reach these: 1024^9 (~1.24e27) and 1000^9 + // (~1e27) both already exceed it. Accepting a double instead of a long is what + // makes these prefixes reachable at all. + Assert.AreEqual("5 RiB", WebServerUtils.GetVolumeString(5 * Math.Pow(1024, 9), true, 4)); + Assert.AreEqual("7 QiB", WebServerUtils.GetVolumeString(7 * Math.Pow(1024, 10), true, 4)); + Assert.AreEqual("5 Robibyte", WebServerUtils.GetVolumeString(5 * Math.Pow(1024, 9), false, 4)); + Assert.AreEqual("7 Quebibyte", WebServerUtils.GetVolumeString(7 * Math.Pow(1024, 10), false, 4)); + Assert.AreEqual("5 RB", WebServerUtils.GetVolumeString(5 * Math.Pow(1000, 9), true, 4, PrefixKind.SI)); + Assert.AreEqual("7 QB", WebServerUtils.GetVolumeString(7 * Math.Pow(1000, 10), true, 4, PrefixKind.SI)); + } + + [TestMethod] + public void ClampsToQuettaForByteCountsBeyondTheUnitTable() + { + // Even double.MaxValue (~1.8e308) must not throw or index past the table - + // it clamps to the largest unit, QiB. + StringAssert.EndsWith(WebServerUtils.GetVolumeString(double.MaxValue, true, 4), " QiB"); + } + + [TestMethod] + public void FormatsByteCountsAMillionTimesLargerThanTheLargestSupportedPrefix() + { + // Once clamped at the largest step, the number itself keeps growing, so + // formatting has to keep working (grouping, digit clamping, ...) rather than + // just showing an oddly-scaled value. + // + // NOTE: this hardcodes QiB/QB (index 10, "Quebibyte"/"Quettabyte") as the + // current largest prefix. If the unit tables are extended with new prefixes, + // these expected values need to be updated to match - that is expected. + Assert.AreEqual("1,000,000 QiB", + WebServerUtils.GetVolumeString(1_000_000 * Math.Pow(1024, 10), true, 4)); + Assert.AreEqual("1,000,000 Quebibyte", + WebServerUtils.GetVolumeString(1_000_000 * Math.Pow(1024, 10), false, 4)); + Assert.AreEqual("1,000,000 QB", + WebServerUtils.GetVolumeString(1_000_000 * Math.Pow(1000, 10), true, 4, PrefixKind.SI)); + Assert.AreEqual("1,000,000 Quettabyte", + WebServerUtils.GetVolumeString(1_000_000 * Math.Pow(1000, 10), false, 4, PrefixKind.SI)); + } + + [TestMethod] + public void DigitsBelowLeadingDigitsIsClampedUpToLeadingDigits() + { + // 999 has 3 leading digits; requesting 0 digits must not truncate them away. + Assert.AreEqual("999 B", WebServerUtils.GetVolumeString(999, true, 0, PrefixKind.SI)); + } + + [TestMethod] + public void DigitsAboveTheStepUpperBoundIsClampedDown() + { + // leadingDigits(1) + 3 * step(2) = 7 significant digits is the max this step allows. + Assert.AreEqual("1.177375 MiB", WebServerUtils.GetVolumeString(1_234_567, true, 100)); + } + + [TestMethod] + public void GroupsIntegerDigitsWithThousandsSeparator() + { + // 1010 KiB stays in the KiB step (< 1024 KiB) but needs 4 leading digits, + // which must still be grouped even though the format mask is no longer + // hardcoded to the "0,000" 4-digit case. + Assert.AreEqual("1,010 KiB", WebServerUtils.GetVolumeString(1024L * 1010, true, 4)); + } + + [TestMethod] + public void RemoveCrLfLeavesOrdinaryTextUnchanged() + { + Assert.AreEqual("/some/path", WebServerUtils.RemoveCrLf("/some/path")); + } + + [TestMethod] + public void RemoveCrLfStripsEmbeddedCarriageReturnsAndLineFeeds() + { + // The classic response-splitting payload: an attacker-influenced value ending the + // current header early and injecting a whole extra header/response. + Assert.AreEqual("evilX-Injected: 1", + WebServerUtils.RemoveCrLf("evil\r\nX-Injected: 1")); + Assert.AreEqual("ab", WebServerUtils.RemoveCrLf("a\rb")); + Assert.AreEqual("ab", WebServerUtils.RemoveCrLf("a\nb")); + } + + [TestMethod] + public void BytesEqualConstantTimeReturnsTrueForEqualSequences() + { + Assert.IsTrue(WebServerUtils.BytesEqualConstantTime([1, 2, 3], [1, 2, 3])); + Assert.IsTrue(WebServerUtils.BytesEqualConstantTime([], [])); + } + + [TestMethod] + public void BytesEqualConstantTimeReturnsFalseForDifferentContent() + { + Assert.IsFalse(WebServerUtils.BytesEqualConstantTime([1, 2, 3], [1, 2, 4])); + } + + [TestMethod] + public void BytesEqualConstantTimeReturnsFalseForDifferentLength() + { + Assert.IsFalse(WebServerUtils.BytesEqualConstantTime([1, 2, 3], [1, 2, 3, 4])); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/WebSocket/EventConnectionDispatch.cs b/tests/MaxLib.WebServer.Test/WebSocket/EventConnectionDispatch.cs new file mode 100644 index 0000000..a705a80 --- /dev/null +++ b/tests/MaxLib.WebServer.Test/WebSocket/EventConnectionDispatch.cs @@ -0,0 +1,133 @@ +using MaxLib.WebServer.WebSocket; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Threading.Tasks; + +#nullable enable + +namespace MaxLib.WebServer.Test.WebSocket +{ + [TestClass] + public class EventConnectionDispatch + { + class PingEvent : EventBase + { + public int Sequence { get; set; } + } + + class RecordingConnection : EventConnection + { + public readonly List ReceivedEvents = []; + public MalformedEventJsonException? LastMalformedEvent; + public UnknownEventTypeException? LastUnknownEvent; + public InvalidEventPayloadException? LastInvalidPayload; + + public RecordingConnection(EventFactory factory) + : base(new MemoryStream(), factory) + { + } + + public Task Dispatch(Frame frame) + => ReceivedFrame(frame); + + protected override Task ReceiveClose(CloseReason? reason, string? info) + => Task.CompletedTask; + + protected override Task ReceivedFrame(EventBase @event) + { + ReceivedEvents.Add(@event); + return Task.CompletedTask; + } + + protected override Task ReceivedMalformedEvent(Frame frame, MalformedEventJsonException exception) + { + LastMalformedEvent = exception; + return Task.CompletedTask; + } + + protected override Task ReceivedUnknownEvent(Frame frame, UnknownEventTypeException exception) + { + LastUnknownEvent = exception; + return Task.CompletedTask; + } + + protected override Task ReceivedInvalidEventPayload(Frame frame, InvalidEventPayloadException exception) + { + LastInvalidPayload = exception; + return Task.CompletedTask; + } + } + + static Frame FrameFromJson(string json) + => new() + { + OpCode = OpCode.Text, + Payload = Encoding.UTF8.GetBytes(json), + FinalFrame = true, + }; + + static RecordingConnection MakeConnection() + { + var factory = new EventFactory(); + factory.Add(); + return new RecordingConnection(factory); + } + + [TestMethod] + public async Task ValidEventReachesReceivedFrame() + { + var connection = MakeConnection(); + + await connection.Dispatch(FrameFromJson("{\"$type\":\"PingEvent\",\"Sequence\":7}")); + + var received = Assert.IsInstanceOfType(Assert.ContainsSingle(connection.ReceivedEvents)); + Assert.AreEqual(7, received.Sequence); + Assert.IsNull(connection.LastMalformedEvent); + Assert.IsNull(connection.LastUnknownEvent); + Assert.IsNull(connection.LastInvalidPayload); + } + + [TestMethod] + public async Task MalformedJsonRoutesToReceivedMalformedEvent() + { + var connection = MakeConnection(); + + await connection.Dispatch(FrameFromJson("{ this is not json")); + + Assert.IsNotNull(connection.LastMalformedEvent); + Assert.IsEmpty(connection.ReceivedEvents); + Assert.IsNull(connection.LastUnknownEvent); + Assert.IsNull(connection.LastInvalidPayload); + } + + [TestMethod] + public async Task UnregisteredEventRoutesToReceivedUnknownEvent() + { + var connection = MakeConnection(); + + await connection.Dispatch(FrameFromJson("{\"$type\":\"NotRegistered\"}")); + + Assert.IsNotNull(connection.LastUnknownEvent); + Assert.AreEqual("NotRegistered", connection.LastUnknownEvent!.EventTypeName); + Assert.IsEmpty(connection.ReceivedEvents); + Assert.IsNull(connection.LastMalformedEvent); + Assert.IsNull(connection.LastInvalidPayload); + } + + [TestMethod] + public async Task BadPayloadForKnownTypeRoutesToReceivedInvalidEventPayload() + { + var connection = MakeConnection(); + + await connection.Dispatch(FrameFromJson("{\"$type\":\"PingEvent\",\"Sequence\":\"not-a-number\"}")); + + Assert.IsNotNull(connection.LastInvalidPayload); + Assert.AreEqual("PingEvent", connection.LastInvalidPayload!.EventTypeName); + Assert.IsEmpty(connection.ReceivedEvents); + Assert.IsNull(connection.LastMalformedEvent); + Assert.IsNull(connection.LastUnknownEvent); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/WebSocket/EventParseUnmappedMembers.cs b/tests/MaxLib.WebServer.Test/WebSocket/EventParseUnmappedMembers.cs new file mode 100644 index 0000000..9b81b32 --- /dev/null +++ b/tests/MaxLib.WebServer.Test/WebSocket/EventParseUnmappedMembers.cs @@ -0,0 +1,36 @@ +using MaxLib.WebServer.WebSocket; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; + +#nullable enable + +namespace MaxLib.WebServer.Test.WebSocket +{ + [TestClass] + public class EventParseUnmappedMembers + { + class PingEvent : EventBase + { + public int Sequence { get; set; } + } + + [TestMethod] + public void ParseRoundTripsWithUnmappedMemberHandlingDisallow() + { + var factory = new EventFactory(new JsonSerializerOptions + { + UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow, + }); + factory.Add(); + + var frame = factory.ToFrame(new PingEvent { Sequence = 7 }); + Assert.IsNotNull(frame); + + var parsed = factory.Parse(frame!); + var ping = Assert.IsInstanceOfType(parsed); + Assert.AreEqual(7, ping.Sequence); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/WebSocket/EventSerialization.cs b/tests/MaxLib.WebServer.Test/WebSocket/EventSerialization.cs new file mode 100644 index 0000000..b1245dd --- /dev/null +++ b/tests/MaxLib.WebServer.Test/WebSocket/EventSerialization.cs @@ -0,0 +1,270 @@ +using MaxLib.WebServer.WebSocket; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Text; +using System.Text.Json; + +#nullable enable + +namespace MaxLib.WebServer.Test.WebSocket +{ + [TestClass] + public class EventSerialization + { + class PingEvent : EventBase + { + public int Sequence { get; set; } + } + + class ChatEvent : EventBase + { + public string Message { get; set; } = ""; + } + + class NoParameterlessCtorEvent : EventBase + { + public NoParameterlessCtorEvent(int _) { } + } + + static Frame FrameFromJson(string json) + => new() + { + OpCode = OpCode.Text, + Payload = Encoding.UTF8.GetBytes(json), + FinalFrame = true, + }; + + [TestMethod] + public void RoundTripTwoRegisteredEventTypes() + { + var factory = new EventFactory(); + factory.Add(); + factory.Add(); + + var pingFrame = factory.ToFrame(new PingEvent { Sequence = 42 }); + Assert.IsNotNull(pingFrame); + var pingJson = Encoding.UTF8.GetString(pingFrame!.Payload.Span); + StringAssert.Contains(pingJson, "\"$type\":\"PingEvent\""); + + var chatFrame = factory.ToFrame(new ChatEvent { Message = "hi" }); + Assert.IsNotNull(chatFrame); + var chatJson = Encoding.UTF8.GetString(chatFrame!.Payload.Span); + StringAssert.Contains(chatJson, "\"$type\":\"ChatEvent\""); + + Assert.IsTrue(factory.TryParse(pingFrame, out var pingResult)); + var ping = Assert.IsInstanceOfType(pingResult); + Assert.AreEqual(42, ping.Sequence); + + Assert.IsTrue(factory.TryParse(chatFrame, out var chatResult)); + var chat = Assert.IsInstanceOfType(chatResult); + Assert.AreEqual("hi", chat.Message); + } + + [TestMethod] + public void AddWithExplicitKeyUsesThatKeyOnWire() + { + var factory = new EventFactory(); + factory.Add("custom.ping"); + + var frame = factory.ToFrame(new PingEvent { Sequence = 1 }); + Assert.IsNotNull(frame); + var json = Encoding.UTF8.GetString(frame!.Payload.Span); + StringAssert.Contains(json, "\"$type\":\"custom.ping\""); + + Assert.IsTrue(factory.TryParse(frame, out var result)); + Assert.IsInstanceOfType(result); + } + + [TestMethod] + public void AddViaTypeOverloadValidatesConstructor() + { + var factory = new EventFactory(); + Assert.ThrowsExactly( + () => factory.Add("x", typeof(NoParameterlessCtorEvent))); + Assert.ThrowsExactly( + () => factory.Add("y", typeof(string))); + } + + [TestMethod] + public void ParseUnregisteredTypeThrowsUnknownEventTypeException() + { + var factory = new EventFactory(); + factory.Add(); + var frame = FrameFromJson("{\"$type\":\"NotRegistered\"}"); + + var e = Assert.ThrowsExactly(() => factory.Parse(frame)); + Assert.AreEqual("NotRegistered", e.EventTypeName); + } + + [TestMethod] + public void ParseMissingTypeDiscriminatorThrowsUnknownEventTypeException() + { + var factory = new EventFactory(); + factory.Add(); + var frame = FrameFromJson("{\"sequence\":1}"); + + var e = Assert.ThrowsExactly(() => factory.Parse(frame)); + Assert.IsNull(e.EventTypeName); + } + + [TestMethod] + public void ParseMalformedJsonThrowsMalformedEventJsonException() + { + var factory = new EventFactory(); + factory.Add(); + var frame = FrameFromJson("{ this is not json"); + + Assert.ThrowsExactly(() => factory.Parse(frame)); + } + + [TestMethod] + public void ParseAcceptsAPayloadWhereTypeDiscriminatorIsNotTheFirstProperty() + { + // "$type" need not be the first property; JSON is unordered (RFC 8259) + var factory = new EventFactory(); + factory.Add(); + var frame = FrameFromJson("{\"Sequence\":5,\"$type\":\"PingEvent\"}"); + + var result = factory.Parse(frame); + + var ping = Assert.IsInstanceOfType(result); + Assert.AreEqual(5, ping.Sequence); + } + + [TestMethod] + public void ParseHonorsSeedOptionsAllowTrailingCommasOnTheTypeDiscriminatorPreScan() + { + // the "$type" pre-scan must be as lenient as the caller's seedOptions + var seed = new JsonSerializerOptions { AllowTrailingCommas = true }; + var factory = new EventFactory(seed); + factory.Add(); + var frame = FrameFromJson("{\"$type\":\"PingEvent\",\"Sequence\":5,}"); + + var result = factory.Parse(frame); + + var ping = Assert.IsInstanceOfType(result); + Assert.AreEqual(5, ping.Sequence); + } + + [TestMethod] + public void ParseHonorsSeedOptionsReadCommentHandlingOnTheTypeDiscriminatorPreScan() + { + var seed = new JsonSerializerOptions { ReadCommentHandling = JsonCommentHandling.Skip }; + var factory = new EventFactory(seed); + factory.Add(); + var frame = FrameFromJson("{\"$type\":\"PingEvent\", // comment\n\"Sequence\":5}"); + + var result = factory.Parse(frame); + + var ping = Assert.IsInstanceOfType(result); + Assert.AreEqual(5, ping.Sequence); + } + +#if NET10_0_OR_GREATER + [TestMethod] + public void ParseHonorsSeedOptionsAllowDuplicatePropertiesOnTheTypeDiscriminatorPreScan() + { + // AllowDuplicateProperties (net10.0+ only) is another leniency setting the pre-scan must honor + var seed = new JsonSerializerOptions { AllowDuplicateProperties = false }; + var factory = new EventFactory(seed); + factory.Add(); + var frame = FrameFromJson("{\"$type\":\"PingEvent\",\"$type\":\"PingEvent\",\"Sequence\":5}"); + + Assert.ThrowsExactly(() => factory.Parse(frame)); + } +#endif + + [TestMethod] + public void ParseValidTypeWithBadPayloadThrowsInvalidEventPayloadException() + { + var factory = new EventFactory(); + factory.Add(); + var frame = FrameFromJson("{\"$type\":\"PingEvent\",\"Sequence\":\"not-a-number\"}"); + + var e = Assert.ThrowsExactly(() => factory.Parse(frame)); + Assert.AreEqual("PingEvent", e.EventTypeName); + } + + [TestMethod] + public void TryParseUnregisteredTypeReturnsFalse() + { + var factory = new EventFactory(); + factory.Add(); + var frame = FrameFromJson("{\"$type\":\"NotRegistered\"}"); + + Assert.IsFalse(factory.TryParse(frame, out var @event)); + Assert.IsNull(@event); + } + + [TestMethod] + public void TryParseMalformedJsonReturnsFalse() + { + var factory = new EventFactory(); + factory.Add(); + var frame = FrameFromJson("{ this is not json"); + + Assert.IsFalse(factory.TryParse(frame, out var @event)); + Assert.IsNull(@event); + } + + [TestMethod] + public void AddAfterFirstUseThrows() + { + var factory = new EventFactory(); + factory.Add(); + factory.ToFrame(new PingEvent()); + + Assert.ThrowsExactly(() => factory.Add()); + } + + [TestMethod] + public void AddAfterAFailedParseStillThrows() + { + // the registry must be sealed even when the first use is a Parse call that throws + var factory = new EventFactory(); + factory.Add(); + var frame = FrameFromJson("{\"$type\":\"NotRegistered\"}"); + + Assert.ThrowsExactly(() => factory.Parse(frame)); + + Assert.ThrowsExactly(() => factory.Add()); + } + + [TestMethod] + public void MultipleFactoriesHaveIndependentRegistries() + { + var factoryA = new EventFactory(); + factoryA.Add("shared"); + var factoryB = new EventFactory(); + factoryB.Add("shared"); + + var frameFromA = factoryA.ToFrame(new PingEvent { Sequence = 7 }); + Assert.IsNotNull(frameFromA); + var frameFromB = factoryB.ToFrame(new ChatEvent { Message = "hey" }); + Assert.IsNotNull(frameFromB); + + Assert.IsTrue(factoryA.TryParse(frameFromA!, out var resultA)); + Assert.IsInstanceOfType(resultA); + + Assert.IsTrue(factoryB.TryParse(frameFromB!, out var resultB)); + Assert.IsInstanceOfType(resultB); + } + + [TestMethod] + public void SeedOptionsCarryForwardToWire() + { + var seed = new JsonSerializerOptions + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + }; + var factory = new EventFactory(seed); + factory.Add(); + + var frame = factory.ToFrame(new PingEvent { Sequence = 5 }); + Assert.IsNotNull(frame); + var json = Encoding.UTF8.GetString(frame!.Payload.Span); + StringAssert.Contains(json, "\"$type\":\"PingEvent\""); + StringAssert.Contains(json, "\"sequence\":5"); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/WebSocket/FrameParsing.cs b/tests/MaxLib.WebServer.Test/WebSocket/FrameParsing.cs index bc69d6f..6e3493f 100644 --- a/tests/MaxLib.WebServer.Test/WebSocket/FrameParsing.cs +++ b/tests/MaxLib.WebServer.Test/WebSocket/FrameParsing.cs @@ -4,13 +4,86 @@ using System.Collections.Generic; using System.IO; using System.Text; +using System.Threading; using System.Threading.Tasks; +#nullable enable + namespace MaxLib.WebServer.Test.WebSocket { [TestClass] public class FrameParsing { + // Stream.ReadAsync may return fewer bytes than requested; deliver one byte at a time to make sure + // Frame.TryRead doesn't mistake slow arrival for a closed connection. + private sealed class OneByteAtATimeStream(byte[] data) : MemoryStream(data) + { + public override ValueTask ReadAsync(Memory buffer, + CancellationToken cancellationToken = default) + => base.ReadAsync(buffer.Length > 1 ? buffer[..1] : buffer, cancellationToken); + } + + [TestMethod] + public async Task ReadFrameWhoseHeaderAndPayloadArriveOneByteAtATime() + { + var bytes = new byte[] { 0x82, 0x05, 1, 2, 3, 4, 5 }; + using var stream = new OneByteAtATimeStream(bytes); + + var frame = await Frame.TryRead(stream).ConfigureAwait(false); + + Assert.IsNotNull(frame); + Assert.IsTrue(frame!.FinalFrame); + Assert.AreEqual(OpCode.Binary, frame.OpCode); + Assert.IsFalse(frame.HasMaskingKey); + CollectionAssert.AreEqual(new byte[] { 1, 2, 3, 4, 5 }, frame.Payload.ToArray()); + } + + [TestMethod] + public async Task ReadLargeMaskedFrameWhoseBytesArriveOneByteAtATime() + { + // large enough for the 16-bit extended-length header field + var payload = new byte[200]; + for (var i = 0; i < payload.Length; ++i) + payload[i] = (byte)i; + var expected = (byte[])payload.Clone(); + // ApplyMask masks Frame.Payload in place, so capture the expected plaintext first + var frame = new Frame { OpCode = OpCode.Binary, Payload = payload }; + frame.ApplyMask(); + using var written = new MemoryStream(); + await frame.Write(written).ConfigureAwait(false); + + using var stream = new OneByteAtATimeStream(written.ToArray()); + var readBack = await Frame.TryRead(stream).ConfigureAwait(false); + + Assert.IsNotNull(readBack); + Assert.IsTrue(readBack!.HasMaskingKey); + readBack.UnapplyMask(); + CollectionAssert.AreEqual(expected, readBack.Payload.ToArray()); + } + + [TestMethod] + public void ApplyMaskGeneratesANonZeroMaskingKey() + { + // the masking key must not stay at its all-zero default (RFC 6455 §5.3) + var frame = new Frame { OpCode = OpCode.Text, Payload = Encoding.UTF8.GetBytes("Hello") }; + + frame.ApplyMask(); + + Assert.IsTrue(frame.HasMaskingKey); + CollectionAssert.AreNotEqual(new byte[] { 0, 0, 0, 0 }, frame.MaskingKey.ToArray()); + } + + [TestMethod] + public void ApplyMaskGeneratesADifferentKeyOnEachCall() + { + var first = new Frame { OpCode = OpCode.Text, Payload = Encoding.UTF8.GetBytes("Hello") }; + first.ApplyMask(); + var second = new Frame { OpCode = OpCode.Text, Payload = Encoding.UTF8.GetBytes("Hello") }; + second.ApplyMask(); + + CollectionAssert.AreNotEqual(first.MaskingKey.ToArray(), second.MaskingKey.ToArray()); + } + [TestMethod] public async Task ReadSingleFrameUnmaskedTextMessage() { @@ -107,5 +180,40 @@ public async Task Read64KiByteUnmaskedMessage() Assert.IsFalse(frame.HasMaskingKey); Assert.AreEqual(65536, frame.Payload.Length); } + + [TestMethod] + public async Task WriteThenReadRoundTripsAMaskedFrame() + { + // Frame.Write used to write the mask key bytes for a masked frame but never set the + // "payload is masked" bit in the length byte itself, so a frame written after + // ApplyMask() didn't actually come back as masked when read back. + var frame = new Frame { OpCode = OpCode.Text, Payload = Encoding.UTF8.GetBytes("Hello") }; + frame.ApplyMask(); + + using var stream = new MemoryStream(); + await frame.Write(stream).ConfigureAwait(false); + stream.Position = 0; + var readBack = await Frame.TryRead(stream).ConfigureAwait(false); + + Assert.IsNotNull(readBack); + Assert.IsTrue(readBack!.HasMaskingKey); + readBack.UnapplyMask(); + Assert.AreEqual("Hello", readBack.TextPayload); + } + + [TestMethod] + public async Task WriteThenReadRoundTripsAnUnmaskedFrame() + { + var frame = new Frame { OpCode = OpCode.Text, Payload = Encoding.UTF8.GetBytes("Hello") }; + + using var stream = new MemoryStream(); + await frame.Write(stream).ConfigureAwait(false); + stream.Position = 0; + var readBack = await Frame.TryRead(stream).ConfigureAwait(false); + + Assert.IsNotNull(readBack); + Assert.IsFalse(readBack!.HasMaskingKey); + Assert.AreEqual("Hello", readBack.TextPayload); + } } } diff --git a/tests/MaxLib.WebServer.Test/WebSocket/TestWebSocketConnection.cs b/tests/MaxLib.WebServer.Test/WebSocket/TestWebSocketConnection.cs new file mode 100644 index 0000000..fb96f33 --- /dev/null +++ b/tests/MaxLib.WebServer.Test/WebSocket/TestWebSocketConnection.cs @@ -0,0 +1,568 @@ +using MaxLib.WebServer.WebSocket; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +#nullable enable + +namespace MaxLib.WebServer.Test.WebSocket +{ + /// + /// A minimal concrete , for driving + /// /SendFrame directly in tests without + /// a real handshake or socket. + /// + internal sealed class TestConnection : WebSocketConnection + { + public List ReceivedFrames { get; } = new(); + public List<(CloseReason? Reason, string? Info)> ReceivedCloses { get; } = new(); + + public TestConnection(Stream stream) : base(stream) { } + + public Task Send(Frame frame) => SendFrame(frame); + + protected override Task ReceiveClose(CloseReason? reason, string? info) + { + ReceivedCloses.Add((reason, info)); + return Task.CompletedTask; + } + + protected override Task ReceivedFrame(Frame frame) + { + ReceivedFrames.Add(frame); + return Task.CompletedTask; + } + } + + [TestClass] + public class TestWebSocketConnection + { + // Encodes a single frame exactly as a real client would send it (masked by default, + // matching RFC 6455 - the server never sends masked frames itself, so only client-frame + // fixtures need this). + private static async Task EncodeFrameAsync(OpCode opCode, bool final, byte[] payload, bool masked = true) + { + using var stream = new MemoryStream(); + var frame = new Frame { OpCode = opCode, FinalFrame = final, Payload = payload }; + if (masked) + frame.ApplyMask(); + await frame.Write(stream).ConfigureAwait(false); + return stream.ToArray(); + } + + private static async Task DecodeSentCloseReasonAsync(byte[] sent) + { + using var stream = new MemoryStream(sent); + var frame = await Frame.TryRead(stream).ConfigureAwait(false); + if (frame == null || frame.OpCode != OpCode.Close || frame.Payload.Length < 2) + return null; + Frame.ToLocalByteOrder(frame.Payload.Span[0..2]); + return (CloseReason)BitConverter.ToUInt16(frame.Payload.Span[0..2]); + } + + [TestMethod] + public async Task TestReceiveLoopClosesWithProtocolErrorOnAnUnmaskedFrame() + { + // RFC 6455 §5.1: "A server MUST close the connection upon receiving a frame that + // is not masked." + var input = new MemoryStream(await EncodeFrameAsync(OpCode.Text, true, new byte[] { 1 }, masked: false) + .ConfigureAwait(false)); + var output = new MemoryStream(); + var connection = new TestConnection(new WebServerTaskCreator.BidirectionalStream(input, output)); + + await connection.ReceiveLoop().ConfigureAwait(false); + + Assert.AreEqual(0, connection.ReceivedFrames.Count, + "an unmasked frame must never reach the application"); + Assert.AreEqual(CloseReason.ProtocolError, await DecodeSentCloseReasonAsync(output.ToArray()).ConfigureAwait(false)); + } + + [TestMethod] + public async Task TestReceiveLoopRejectsAnOversizedControlFrame() + { + // RFC 6455 §5.5 caps every control frame's payload at 125 bytes. + var input = new MemoryStream(await EncodeFrameAsync(OpCode.Ping, true, new byte[126]) + .ConfigureAwait(false)); + var output = new MemoryStream(); + var connection = new TestConnection(new WebServerTaskCreator.BidirectionalStream(input, output)); + + await connection.ReceiveLoop().ConfigureAwait(false); + + Assert.AreEqual(CloseReason.ProtocolError, + await DecodeSentCloseReasonAsync(output.ToArray()).ConfigureAwait(false)); + } + + [TestMethod] + public async Task TestReceiveLoopAcceptsAControlFrameLargerThanASmallMaxMessageSize() + { + // a Ping payload between MaxMessageSize and 125 bytes is valid and must still be answered + var pingPayload = new byte[50]; + new Random(1).NextBytes(pingPayload); + // ApplyMask mutates the payload in place, so capture the expected value first + var expectedPayload = (byte[])pingPayload.Clone(); + var input = new MemoryStream(await EncodeFrameAsync(OpCode.Ping, true, pingPayload).ConfigureAwait(false)); + var output = new MemoryStream(); + var connection = new TestConnection(new WebServerTaskCreator.BidirectionalStream(input, output)) + { + MaxMessageSize = 10, + }; + + await connection.ReceiveLoop().ConfigureAwait(false); + + using var readBack = new MemoryStream(output.ToArray()); + var sentFrame = await Frame.TryRead(readBack).ConfigureAwait(false); + Assert.IsNotNull(sentFrame); + Assert.AreEqual(OpCode.Pong, sentFrame!.OpCode); + CollectionAssert.AreEqual(expectedPayload, sentFrame.Payload.ToArray()); + } + + [TestMethod] + public async Task TestReceiveLoopRejectsAFragmentedControlFrame() + { + // RFC 6455 §5.4 forbids fragmenting control frames; a fragmented one must not + // silently merge into whatever data message is being reassembled. + var input = new MemoryStream(await EncodeFrameAsync(OpCode.Ping, final: false, new byte[] { 1 }) + .ConfigureAwait(false)); + var output = new MemoryStream(); + var connection = new TestConnection(new WebServerTaskCreator.BidirectionalStream(input, output)); + + await connection.ReceiveLoop().ConfigureAwait(false); + + Assert.AreEqual(CloseReason.ProtocolError, + await DecodeSentCloseReasonAsync(output.ToArray()).ConfigureAwait(false)); + } + + [TestMethod] + public async Task TestReceiveLoopRejectsAReservedDataOpcode() + { + // RFC 6455 §5.2: opcodes other than 0x0-0x2 and 0x8-0xA are reserved and must fail the connection + var input = new MemoryStream(await EncodeFrameAsync((OpCode)0x3, true, new byte[] { 1 }) + .ConfigureAwait(false)); + var output = new MemoryStream(); + var connection = new TestConnection(new WebServerTaskCreator.BidirectionalStream(input, output)); + + await connection.ReceiveLoop().ConfigureAwait(false); + + Assert.AreEqual(0, connection.ReceivedFrames.Count); + Assert.AreEqual(CloseReason.ProtocolError, + await DecodeSentCloseReasonAsync(output.ToArray()).ConfigureAwait(false)); + } + + [TestMethod] + public async Task TestReceiveLoopRejectsAFragmentedReservedControlOpcode() + { + // 0xB is in the control range (0x8-0xF) but unassigned; it must be rejected as an unknown opcode + var input = new MemoryStream(await EncodeFrameAsync((OpCode)0xB, final: false, new byte[] { 1 }) + .ConfigureAwait(false)); + var output = new MemoryStream(); + var connection = new TestConnection(new WebServerTaskCreator.BidirectionalStream(input, output)); + + await connection.ReceiveLoop().ConfigureAwait(false); + + Assert.AreEqual(CloseReason.ProtocolError, + await DecodeSentCloseReasonAsync(output.ToArray()).ConfigureAwait(false)); + } + + [TestMethod] + public async Task TestReceiveLoopRejectsANonInitialFragmentWithTheWrongOpcode() + { + // RFC 6455 §5.4: every fragment after the first must use the Continuation opcode + using var input = new MemoryStream(); + var first = await EncodeFrameAsync(OpCode.Binary, final: false, new byte[] { 1 }).ConfigureAwait(false); + input.Write(first, 0, first.Length); + var second = await EncodeFrameAsync(OpCode.Binary, final: false, new byte[] { 2 }).ConfigureAwait(false); + input.Write(second, 0, second.Length); + input.Position = 0; + var output = new MemoryStream(); + var connection = new TestConnection(new WebServerTaskCreator.BidirectionalStream(input, output)); + + await connection.ReceiveLoop().ConfigureAwait(false); + + Assert.AreEqual(0, connection.ReceivedFrames.Count); + Assert.AreEqual(CloseReason.ProtocolError, + await DecodeSentCloseReasonAsync(output.ToArray()).ConfigureAwait(false)); + } + + [TestMethod] + public async Task TestReceiveLoopRejectsAFinalFragmentWithTheWrongOpcode() + { + using var input = new MemoryStream(); + var first = await EncodeFrameAsync(OpCode.Binary, final: false, new byte[] { 1 }).ConfigureAwait(false); + input.Write(first, 0, first.Length); + // the final fragment must also use the Continuation opcode + var last = await EncodeFrameAsync(OpCode.Binary, final: true, new byte[] { 2 }).ConfigureAwait(false); + input.Write(last, 0, last.Length); + input.Position = 0; + var output = new MemoryStream(); + var connection = new TestConnection(new WebServerTaskCreator.BidirectionalStream(input, output)); + + await connection.ReceiveLoop().ConfigureAwait(false); + + Assert.AreEqual(0, connection.ReceivedFrames.Count); + Assert.AreEqual(CloseReason.ProtocolError, + await DecodeSentCloseReasonAsync(output.ToArray()).ConfigureAwait(false)); + } + + [TestMethod] + public async Task TestCloseTruncatesAnOversizedInfoStringToTheControlFrameLimit() + { + var input = new MemoryStream(); + var output = new MemoryStream(); + var connection = new TestConnection(new WebServerTaskCreator.BidirectionalStream(input, output)); + await connection.ReceiveLoop().ConfigureAwait(false); // EOF immediately; releases the send lock + + await connection.Close(CloseReason.NormalClose, new string('a', 500)).ConfigureAwait(false); + + using var readBack = new MemoryStream(output.ToArray()); + var sentFrame = await Frame.TryRead(readBack).ConfigureAwait(false); + Assert.IsNotNull(sentFrame); + Assert.IsTrue(sentFrame!.Payload.Length <= 125, + $"a Close frame's payload must never exceed 125 bytes, was {sentFrame.Payload.Length}"); + } + + [TestMethod] + public async Task TestReceiveLoopEnforcesMaxMessageSizeDuringAccumulationNotJustAtTheEnd() + { + // Three non-final fragments of 10 bytes each add up to 30 bytes, but a final frame + // never arrives - this must be rejected mid-accumulation, not "eventually, once the + // client finishes the message" (which a client controlling this DoS never will). + using var input = new MemoryStream(); + for (var i = 0; i < 3; ++i) + { + // only the first fragment of a message carries its real opcode; every later + // fragment must be a Continuation + var opCode = i == 0 ? OpCode.Binary : OpCode.Continuation; + var chunk = await EncodeFrameAsync(opCode, false, new byte[10]).ConfigureAwait(false); + input.Write(chunk, 0, chunk.Length); + } + input.Position = 0; + var output = new MemoryStream(); + var connection = new TestConnection(new WebServerTaskCreator.BidirectionalStream(input, output)) + { + MaxMessageSize = 15, + }; + + await connection.ReceiveLoop().ConfigureAwait(false); + + Assert.AreEqual(CloseReason.TooBigMessage, + await DecodeSentCloseReasonAsync(output.ToArray()).ConfigureAwait(false)); + Assert.AreEqual(0, connection.ReceivedFrames.Count); + } + + [TestMethod] + public async Task TestReceiveLoopEnforcesMaxMessageFragmentsDuringAccumulation() + { + // Five 1-byte fragments are cheap in total bytes but each costs one queued entry - + // a size cap alone wouldn't bound this, so the fragment count is checked too. + using var input = new MemoryStream(); + for (var i = 0; i < 5; ++i) + { + // only the first fragment of a message carries its real opcode; every later + // fragment must be a Continuation + var opCode = i == 0 ? OpCode.Binary : OpCode.Continuation; + var chunk = await EncodeFrameAsync(opCode, false, new byte[] { 1 }).ConfigureAwait(false); + input.Write(chunk, 0, chunk.Length); + } + input.Position = 0; + var output = new MemoryStream(); + var connection = new TestConnection(new WebServerTaskCreator.BidirectionalStream(input, output)) + { + MaxMessageFragments = 3, + }; + + await connection.ReceiveLoop().ConfigureAwait(false); + + Assert.AreEqual(CloseReason.TooBigMessage, + await DecodeSentCloseReasonAsync(output.ToArray()).ConfigureAwait(false)); + Assert.AreEqual(0, connection.ReceivedFrames.Count); + } + + [TestMethod] + public async Task TestReceiveLoopSendsATooBigMessageCloseForAnOversizedDeclaredLength() + { + // A frame declaring a length > int.MaxValue is legal on the wire (RFC 6455's 64-bit + // extended length field allows it) but can never be represented as a Memory. + // No payload bytes are needed - Frame.TryRead(throwLargePayload: true) must reject + // this from the header alone, before ever trying to read the (nonexistent) payload. + var header = new byte[10]; + header[0] = 0x82; // FIN + Binary + header[1] = 127; // 64-bit extended length follows + var lengthBytes = new byte[8]; + Frame.ToNetworkByteOrder(BitConverter.GetBytes((ulong)int.MaxValue + 1), lengthBytes); + lengthBytes.CopyTo(header, 2); + + var input = new MemoryStream(header); + var output = new MemoryStream(); + var connection = new TestConnection(new WebServerTaskCreator.BidirectionalStream(input, output)); + + await connection.ReceiveLoop().ConfigureAwait(false); + + Assert.AreEqual(CloseReason.TooBigMessage, + await DecodeSentCloseReasonAsync(output.ToArray()).ConfigureAwait(false)); + } + + [TestMethod] + public async Task TestReceiveLoopSendsATooBigMessageCloseForASingleFrameExceedingMaxMessageSize() + { + // a single unfragmented frame declaring more than MaxMessageSize must be rejected from its header alone + var header = new byte[10]; + header[0] = 0x82; // FIN + Binary + header[1] = 127; // 64-bit extended length follows + var lengthBytes = new byte[8]; + Frame.ToNetworkByteOrder(BitConverter.GetBytes((ulong)1000), lengthBytes); + lengthBytes.CopyTo(header, 2); + + var input = new MemoryStream(header); + var output = new MemoryStream(); + var connection = new TestConnection(new WebServerTaskCreator.BidirectionalStream(input, output)) + { + MaxMessageSize = 100, + }; + + await connection.ReceiveLoop().ConfigureAwait(false); + + Assert.AreEqual(CloseReason.TooBigMessage, + await DecodeSentCloseReasonAsync(output.ToArray()).ConfigureAwait(false)); + Assert.AreEqual(0, connection.ReceivedFrames.Count); + } + + [TestMethod] + public async Task TestReceiveLoopRejectsASingleFrameUnderTheControlFrameFloorButOverMaxMessageSize() + { + // a data frame under 125 bytes but over a smaller MaxMessageSize must be rejected by ReceiveLoop itself + var input = new MemoryStream(await EncodeFrameAsync(OpCode.Binary, true, new byte[100]) + .ConfigureAwait(false)); + var output = new MemoryStream(); + var connection = new TestConnection(new WebServerTaskCreator.BidirectionalStream(input, output)) + { + MaxMessageSize = 10, + }; + + await connection.ReceiveLoop().ConfigureAwait(false); + + Assert.AreEqual(CloseReason.TooBigMessage, + await DecodeSentCloseReasonAsync(output.ToArray()).ConfigureAwait(false)); + Assert.AreEqual(0, connection.ReceivedFrames.Count); + } + + [TestMethod] + public async Task TestReceiveLoopRejectsAContinuationOpcodeAsTheFirstFrameOfAMessage() + { + // RFC 6455 §5.4: the first (or only) frame of a message must not use the Continuation opcode + var input = new MemoryStream(await EncodeFrameAsync(OpCode.Continuation, true, new byte[] { 1 }) + .ConfigureAwait(false)); + var output = new MemoryStream(); + var connection = new TestConnection(new WebServerTaskCreator.BidirectionalStream(input, output)); + + await connection.ReceiveLoop().ConfigureAwait(false); + + Assert.AreEqual(0, connection.ReceivedFrames.Count); + Assert.AreEqual(CloseReason.ProtocolError, + await DecodeSentCloseReasonAsync(output.ToArray()).ConfigureAwait(false)); + } + + [TestMethod] + public async Task TestReceiveLoopRejectsAContinuationOpcodeStartingAFragmentedMessage() + { + var input = new MemoryStream(await EncodeFrameAsync(OpCode.Continuation, false, new byte[] { 1 }) + .ConfigureAwait(false)); + var output = new MemoryStream(); + var connection = new TestConnection(new WebServerTaskCreator.BidirectionalStream(input, output)); + + await connection.ReceiveLoop().ConfigureAwait(false); + + Assert.AreEqual(0, connection.ReceivedFrames.Count); + Assert.AreEqual(CloseReason.ProtocolError, + await DecodeSentCloseReasonAsync(output.ToArray()).ConfigureAwait(false)); + } + + [TestMethod] + public async Task TestReceiveLoopReassemblesA3FragmentMessageWithTheFirstFragmentsOpcode() + { + // Per RFC 6455, only the first fragment carries the real opcode (Text/Binary); + // every later fragment - including the final one - must be Continuation. A message + // split into 3+ fragments used to have its opcode overwritten to Continuation by + // the middle fragment(s). + using var input = new MemoryStream(); + foreach (var chunk in await Task.WhenAll( + EncodeFrameAsync(OpCode.Text, false, new byte[] { 1 }), + EncodeFrameAsync(OpCode.Continuation, false, new byte[] { 2 }), + EncodeFrameAsync(OpCode.Continuation, true, new byte[] { 3 }) + ).ConfigureAwait(false)) + input.Write(chunk, 0, chunk.Length); + input.Position = 0; + var output = new MemoryStream(); + var connection = new TestConnection(new WebServerTaskCreator.BidirectionalStream(input, output)); + + await connection.ReceiveLoop().ConfigureAwait(false); + + var received = connection.ReceivedFrames.Single(); + Assert.AreEqual(OpCode.Text, received.OpCode); + CollectionAssert.AreEqual(new byte[] { 1, 2, 3 }, received.Payload.ToArray()); + } + + [TestMethod] + public async Task TestReceiveLoopAcceptsAndUnmasksAProperlyMaskedFrame() + { + var input = new MemoryStream(await EncodeFrameAsync(OpCode.Text, true, new byte[] { 1, 2, 3 }) + .ConfigureAwait(false)); + var output = new MemoryStream(); + var connection = new TestConnection(new WebServerTaskCreator.BidirectionalStream(input, output)); + + await connection.ReceiveLoop().ConfigureAwait(false); + + var received = connection.ReceivedFrames.Single(); + Assert.IsFalse(received.HasMaskingKey, "the payload must already be unmasked by the time it's delivered"); + CollectionAssert.AreEqual(new byte[] { 1, 2, 3 }, received.Payload.ToArray()); + } + + // A stream whose writes always fail, but only after signalling that the write has + // started and staying in flight for a bit - long enough for a concurrent SendFrame call + // to queue up on the connection's send lock while the first is still holding it. + private sealed class DelayedFaultyWriteStream : Stream + { + private readonly TaskCompletionSource writeStarted = + new(TaskCreationOptions.RunContinuationsAsynchronously); + public Task WriteStarted => writeStarted.Task; + + 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() { } + public override int Read(byte[] buffer, int offset, int count) => 0; + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + => Task.FromResult(0); + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) + => throw new NotSupportedException("only the async write path is exercised here"); + public override async ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) + { + writeStarted.TrySetResult(); + await Task.Delay(TimeSpan.FromMilliseconds(200), cancellationToken).ConfigureAwait(false); + throw new IOException("simulated network failure"); + } + } + + [TestMethod] + public async Task TestSendFrameReleasesItsLockEvenWhenAConcurrentWriteThrows() + { + // this is the crux of the fix: a caller already queued up on the send lock must not + // be left hanging forever just because another in-flight send happened to fail + var stream = new DelayedFaultyWriteStream(); + var connection = new TestConnection(stream); + await connection.ReceiveLoop().ConfigureAwait(false); // EOF immediately; releases the send lock once + + var first = connection.Send(new Frame { OpCode = OpCode.Binary, Payload = new byte[] { 1 } }); + await stream.WriteStarted.ConfigureAwait(false); // first now holds the lock, mid-write + + // queues up on the lock while `first` is still in flight - exactly the race that + // used to leak the lock forever + var second = connection.Send(new Frame { OpCode = OpCode.Binary, Payload = new byte[] { 2 } }); + + var both = Task.WhenAll(first, second); + var winner = await Task.WhenAny(both, Task.Delay(TimeSpan.FromSeconds(5))).ConfigureAwait(false); + Assert.AreSame(both, winner, + "SendFrame must release its lock even when a concurrent write throws"); + } + + // Records every byte written, succeeding immediately - used to inspect exactly what + // ended up on the wire. + private sealed class RecordingStream : Stream + { + public MemoryStream Written { get; } = new(); + + 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() { } + public override int Read(byte[] buffer, int offset, int count) => 0; + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + => Task.FromResult(0); + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) + { + Written.Write(buffer.Span); + return ValueTask.CompletedTask; + } + } + + [TestMethod] + public async Task TestSendFrameDoesNotSendTwoCloseFramesWhenTwoClosesRaceForTheLock() + { + // the send lock is only released by ReceiveLoop's first action, so both Send calls suspend on it; + // the call granted the lock first must set SendCloseSignal before the other passes its re-check + var stream = new RecordingStream(); + var connection = new TestConnection(stream); + var closePayload = new byte[] { 0x03, 0xE8 }; + + var first = connection.Send(new Frame { OpCode = OpCode.Close, Payload = closePayload }); + var second = connection.Send(new Frame { OpCode = OpCode.Close, Payload = closePayload }); + + await connection.ReceiveLoop().ConfigureAwait(false); // EOF immediately; releases the lock once + await Task.WhenAll(first, second).ConfigureAwait(false); + + stream.Written.Position = 0; + var frame1 = await Frame.TryRead(stream.Written).ConfigureAwait(false); + Assert.IsNotNull(frame1, "the first Close frame must still be sent"); + Assert.AreEqual(OpCode.Close, frame1!.OpCode); + var frame2 = await Frame.TryRead(stream.Written).ConfigureAwait(false); + Assert.IsNull(frame2, "a second Close frame must never be sent once the first has been"); + } + + [TestMethod] + public void TestTryReassembleFragmentedPayloadConcatenatesFragmentsInOrder() + { + var queue = new Queue>(); + queue.Enqueue(new byte[] { 1, 2, 3 }); + queue.Enqueue(new byte[] { 4, 5 }); + + var result = WebSocketConnection.TryReassembleFragmentedPayload(queue); + + Assert.IsNotNull(result); + CollectionAssert.AreEqual(new byte[] { 1, 2, 3, 4, 5 }, result!.Value.ToArray()); + Assert.AreEqual(0, queue.Count, "the queue should be fully drained on success"); + } + + [TestMethod] + public void TestTryReassembleFragmentedPayloadRejectsOversizedAccumulationInsteadOfCrashing() + { + // Two fragments individually far below any single-object allocation limit, but + // whose combined length crosses int.MaxValue - the "many small fragments" route + // described in ws-unbounded-fragment-accumulation-dos, reproduced here with just + // two frames instead of an actual multi-gigabyte transfer. Both queue entries + // share the same backing array (the rejection path never reads it, only sums + // lengths), so this only allocates it once. + var chunk = new byte[(int.MaxValue / 2) + 2]; + var queue = new Queue>(); + queue.Enqueue(chunk); + queue.Enqueue(chunk); + + // this used to throw an unhandled OverflowException from `new byte[maxSize]` + // instead of returning - see ws-fragment-reassembly-overflow-crash.md + var result = WebSocketConnection.TryReassembleFragmentedPayload(queue); + + Assert.IsNull(result); + Assert.AreEqual(2, queue.Count, + "a rejected queue is left untouched for the caller to still inspect"); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/WebSocket/TestWebSocketEndpoint.cs b/tests/MaxLib.WebServer.Test/WebSocket/TestWebSocketEndpoint.cs new file mode 100644 index 0000000..2d5470b --- /dev/null +++ b/tests/MaxLib.WebServer.Test/WebSocket/TestWebSocketEndpoint.cs @@ -0,0 +1,70 @@ +using MaxLib.WebServer.WebSocket; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.IO; +using System.Threading.Tasks; + +#nullable enable + +namespace MaxLib.WebServer.Test.WebSocket +{ + [TestClass] + public class TestWebSocketEndpoint + { + private sealed class DisposeTrackingConnection : WebSocketConnection + { + public bool Disposed { get; private set; } + + public DisposeTrackingConnection(Stream stream) : base(stream) { } + + public override async ValueTask DisposeAsync() + { + Disposed = true; + await base.DisposeAsync().ConfigureAwait(false); + } + + protected override Task ReceiveClose(CloseReason? reason, string? info) => Task.CompletedTask; + + protected override Task ReceivedFrame(Frame frame) => Task.CompletedTask; + } + + private sealed class TestEndpoint : WebSocketEndpoint + { + public override string? Protocol => null; + + public bool DisposeOnClose { get; set; } = true; + + protected override bool DisposeConnectionsOnClose => DisposeOnClose; + + protected override DisposeTrackingConnection? CreateConnection(Stream stream, HttpRequestHeader header) + => new(stream); + } + + [TestMethod] + public async Task TestConnectionClosedDisposesTheConnectionByDefault() + { + // WebProgressTask.SwitchProtocols's own doc comment used to say the caller is + // responsible for disposing a switched-protocol connection - true in general, but + // WebSocketEndpoint itself never did this either, meaning even the shipped + // WebSocket echo example (which is built on it) leaked a socket per connection. + var endpoint = new TestEndpoint(); + var connection = (DisposeTrackingConnection)(await endpoint.Create(new MemoryStream(), new HttpRequestHeader()) + .ConfigureAwait(false))!; + + await endpoint.HandleConnectionClosed(connection).ConfigureAwait(false); + + Assert.IsTrue(connection.Disposed); + } + + [TestMethod] + public async Task TestConnectionClosedLeavesTheConnectionAliveWhenOptedOut() + { + var endpoint = new TestEndpoint { DisposeOnClose = false }; + var connection = (DisposeTrackingConnection)(await endpoint.Create(new MemoryStream(), new HttpRequestHeader()) + .ConfigureAwait(false))!; + + await endpoint.HandleConnectionClosed(connection).ConfigureAwait(false); + + Assert.IsFalse(connection.Disposed); + } + } +} diff --git a/tests/MaxLib.WebServer.Test/WebSocket/TestWebSocketService.cs b/tests/MaxLib.WebServer.Test/WebSocket/TestWebSocketService.cs new file mode 100644 index 0000000..f9a5b3c --- /dev/null +++ b/tests/MaxLib.WebServer.Test/WebSocket/TestWebSocketService.cs @@ -0,0 +1,124 @@ +using MaxLib.WebServer.WebSocket; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.IO; +using System.Threading.Tasks; + +#nullable enable + +namespace MaxLib.WebServer.Test.WebSocket +{ + [TestClass] + public class TestWebSocketService + { + private sealed class MinimalConnection : WebSocketConnection + { + public MinimalConnection(Stream stream) : base(stream) { } + protected override Task ReceiveClose(CloseReason? reason, string? info) => Task.CompletedTask; + protected override Task ReceivedFrame(Frame frame) => Task.CompletedTask; + } + + private sealed class ProtocolEndpoint(string? protocol) : WebSocketEndpoint + { + public override string? Protocol => protocol; + protected override MinimalConnection? CreateConnection(Stream stream, HttpRequestHeader header) + => new(stream); + } + + private static WebProgressTask CreateUpgradeTask() + { + var task = new WebProgressTask + { + NetworkStream = new MemoryStream(), + }; + task.Request.SetHeader("Upgrade", "websocket"); + task.Request.SetHeader("Connection", "Upgrade"); + task.Request.SetHeader("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="); + task.Request.SetHeader("Sec-WebSocket-Version", "13"); + return task; + } + + [TestMethod] + public async Task TestEndpointRequiringAProtocolIsNotSelectedWhenTheClientSendsNoProtocolHeader() + { + // a non-null Protocol requires the client to ask for it; no Sec-WebSocket-Protocol header must not match + var service = new WebSocketService(); + service.Add(new ProtocolEndpoint("admin-v1")); + var task = CreateUpgradeTask(); + + await service.ProgressTask(task).ConfigureAwait(false); + + Assert.IsNull(task.SwitchProtocolHandler, + "an endpoint that requires a protocol must not be selected by a client that asked for none"); + } + + [TestMethod] + public async Task TestEndpointRequiringAProtocolIsSelectedWhenTheClientAsksForIt() + { + var service = new WebSocketService(); + service.Add(new ProtocolEndpoint("admin-v1")); + var task = CreateUpgradeTask(); + task.Request.SetHeader("Sec-WebSocket-Protocol", "admin-v1"); + + await service.ProgressTask(task).ConfigureAwait(false); + + Assert.IsNotNull(task.SwitchProtocolHandler); + } + + [TestMethod] + public async Task TestEndpointWithNoProtocolIsSelectedWhenTheClientSendsNoProtocolHeader() + { + // a null Protocol still matches a client that sends no Sec-WebSocket-Protocol header + var service = new WebSocketService(); + service.Add(new ProtocolEndpoint(null)); + var task = CreateUpgradeTask(); + + await service.ProgressTask(task).ConfigureAwait(false); + + Assert.IsNotNull(task.SwitchProtocolHandler); + } + + [TestMethod] + public async Task TestEndpointWithNoProtocolIsNotSelectedWhenTheClientAsksForAProtocol() + { + var service = new WebSocketService(); + service.Add(new ProtocolEndpoint(null)); + var task = CreateUpgradeTask(); + task.Request.SetHeader("Sec-WebSocket-Protocol", "some-protocol"); + + await service.ProgressTask(task).ConfigureAwait(false); + + Assert.IsNull(task.SwitchProtocolHandler, + "an endpoint with no protocol must not be selected by a client that asked for one"); + } + + [TestMethod] + public async Task TestEndpointWithAMixedCaseProtocolIsSelectedWhenTheClientAsksForItVerbatim() + { + // the requested protocol list is lower-cased, so a mixed-case endpoint Protocol must still match + var service = new WebSocketService(); + service.Add(new ProtocolEndpoint("Chat")); + var task = CreateUpgradeTask(); + task.Request.SetHeader("Sec-WebSocket-Protocol", "Chat"); + + await service.ProgressTask(task).ConfigureAwait(false); + + Assert.IsNotNull(task.SwitchProtocolHandler, + "an endpoint whose Protocol contains an uppercase character must still be selected"); + } + + [TestMethod] + public async Task TestResponseEchoesTheClientsOwnCasingNotTheEndpointsRegisteredCasing() + { + // the response must echo the client's offered token verbatim, not the endpoint's casing + var service = new WebSocketService(); + service.Add(new ProtocolEndpoint("chat")); + var task = CreateUpgradeTask(); + task.Request.SetHeader("Sec-WebSocket-Protocol", "Chat"); + + await service.ProgressTask(task).ConfigureAwait(false); + + Assert.AreEqual("Chat", task.Response.GetHeader("Sec-WebSocket-Protocol"), + "the response must echo the client's own casing, not the endpoint's"); + } + } +}