From fdf5770edf98b07f9f0e46fef44f07f14a4a407a Mon Sep 17 00:00:00 2001 From: Blank Date: Mon, 23 Nov 2026 23:14:15 +0800 Subject: [PATCH 1/3] =?UTF-8?q?feat(http):=20HttpActionContext=20=E9=80=8F?= =?UTF-8?q?=E4=BC=A0=E8=AF=B7=E6=B1=82=E5=8E=9F=E6=A0=B7=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 业务处理器此前只能拿到 IP/URL/参数字典,请求头、HTTP 方法、 Content-Type 等在处理器内不可达,派生项目只能把会话令牌降级 为查询参数鉴权。新增 init-only 快照属性:Headers(键不区分 大小写、同名多值逗号合并)、Method、ContentType、 TraceIdentifier、QueryString、Cookies、Scheme、IsLocal、 RequestAborted,并在 HttpHandler 两处构造点(普通 JSON / 强类型 Request)统一填充;补两条管线回归测试覆盖两条路径 的快照正确性与大小写不敏感读取。 Closes #997 --- GameFrameX.Network.HTTP/HttpActionContext.cs | 87 ++++++++++++++- GameFrameX.Network.HTTP/HttpHandler.cs | 24 +++- .../HttpHandlerPipelineConsistencyTests.cs | 103 ++++++++++++++++++ 3 files changed, 210 insertions(+), 4 deletions(-) diff --git a/GameFrameX.Network.HTTP/HttpActionContext.cs b/GameFrameX.Network.HTTP/HttpActionContext.cs index 4e620e78c..6dbdc954b 100644 --- a/GameFrameX.Network.HTTP/HttpActionContext.cs +++ b/GameFrameX.Network.HTTP/HttpActionContext.cs @@ -32,10 +32,12 @@ namespace GameFrameX.Network.HTTP; /// -/// HTTP 处理管线统一请求上下文,承载客户端 IP、请求 URL、参数字典、消息对象与请求消息对象。 +/// HTTP 处理管线统一请求上下文,承载客户端 IP、请求 URL、参数字典、消息对象与请求消息对象, +/// 以及请求头快照、HTTP 方法、Content-Type、追踪标识、原始查询串、Cookie、Scheme、本机判定与请求中断令牌。 /// /// -/// Unified request context for the HTTP handling pipeline, carrying the client IP, request URL, parameter dictionary, message object, and request message object. +/// Unified request context for the HTTP handling pipeline, carrying the client IP, request URL, parameter dictionary, message object, and request message object, +/// plus the request header snapshot, HTTP method, Content-Type, trace identifier, raw query string, cookies, scheme, loopback flag, and request-abort token. /// public sealed class HttpActionContext { @@ -66,6 +68,87 @@ public sealed class HttpActionContext /// 请求参数字典 / Request parameter dictionary public Dictionary Parameters { get; init; } + /// + /// 获取请求头快照(键不区分大小写;同名多值以逗号合并),供业务处理器读取鉴权头、User-Agent 等原样信息。 + /// + /// + /// Gets the request header snapshot (case-insensitive keys; multiple values of the same name joined by comma), allowing business handlers to read authorization headers, User-Agent, etc. verbatim. + /// + /// 请求头快照 / Request header snapshot + public Dictionary Headers { get; init; } + + /// + /// 获取 HTTP 请求方法(GET/POST 等)。 + /// + /// + /// Gets the HTTP request method (GET/POST, etc.). + /// + /// HTTP 请求方法 / HTTP request method + public string Method { get; init; } + + /// + /// 获取请求体的 Content-Type;无请求体时为 null。 + /// + /// + /// Gets the Content-Type of the request body; null when the request has no body. + /// + /// 请求体 Content-Type / Request body Content-Type + public string ContentType { get; init; } + + /// + /// 获取请求的追踪标识(关联标识),用于日志与链路追踪对齐。 + /// + /// + /// Gets the trace identifier (correlation identifier) of the request, used for log and tracing alignment. + /// + /// 追踪标识 / Trace identifier + public string TraceIdentifier { get; init; } + + /// + /// 获取原始查询串(含前导 '?';无查询参数时为空串),供签名校验与原样日志使用。 + /// + /// + /// Gets the raw query string (with leading '?'; empty when absent), for signature validation and verbatim logging. + /// + /// 原始查询串 / Raw query string + public string QueryString { get; init; } + + /// + /// 获取解析后的请求 Cookie(键不区分大小写)。 + /// + /// + /// Gets the parsed request cookies (case-insensitive keys). + /// + /// 请求 Cookie 字典 / Request cookie dictionary + public IReadOnlyDictionary Cookies { get; init; } + + /// + /// 获取请求协议方案(http/https),供构造回调绝对地址。 + /// + /// + /// Gets the request scheme (http/https), for building absolute callback URLs. + /// + /// 请求方案 / Request scheme + public string Scheme { get; init; } + + /// + /// 获取请求是否来自本机回环地址(GM / 运维端点信任本机的判定依据)。 + /// + /// + /// Gets whether the request originates from a loopback address (basis for trusting local GM / operation endpoints). + /// + /// 是否本机请求 / Whether the request is local + public bool IsLocal { get; init; } + + /// + /// 获取请求中断令牌:客户端断开连接时触发,长轮询 / 慢处理器应观测该令牌提前释放资源。 + /// + /// + /// Gets the request-abort token: fired when client disconnects; long-poll or slow handlers should observe it to release early. + /// + /// 请求中断令牌 / Request abort token + public CancellationToken RequestAborted { get; init; } + /// /// 获取 ProtoBuf 形态的消息对象。 /// diff --git a/GameFrameX.Network.HTTP/HttpHandler.cs b/GameFrameX.Network.HTTP/HttpHandler.cs index 35b9bd060..f0c89deac 100644 --- a/GameFrameX.Network.HTTP/HttpHandler.cs +++ b/GameFrameX.Network.HTTP/HttpHandler.cs @@ -123,7 +123,27 @@ public static async Task HandleRequestAsync(HttpContext context, Func(context.Request.Headers.Count, StringComparer.OrdinalIgnoreCase); + foreach (var header in context.Request.Headers) + { + requestHeaders[header.Key] = string.Join(", ", header.Value); + } + + var requestCookies = new Dictionary(context.Request.Cookies.Count, StringComparer.OrdinalIgnoreCase); + foreach (var cookie in context.Request.Cookies) + { + requestCookies[cookie.Key] = cookie.Value; + } + + var requestMethod = context.Request.Method; + var requestContentType = context.Request.ContentType; + var traceIdentifier = context.TraceIdentifier; + var requestQueryString = context.Request.QueryString.Value ?? string.Empty; + var requestScheme = context.Request.Scheme; + var isLocalRequest = context.Connection.RemoteIpAddress is not null && System.Net.IPAddress.IsLoopback(context.Connection.RemoteIpAddress); + var requestAborted = context.RequestAborted; + var actionContext = new HttpActionContext { Ip = ip, Url = url, Parameters = paramMap, Headers = requestHeaders, Method = requestMethod, ContentType = requestContentType, TraceIdentifier = traceIdentifier, QueryString = requestQueryString, Cookies = requestCookies, Scheme = requestScheme, IsLocal = isLocalRequest, RequestAborted = requestAborted, MessageObject = message }; var validation = await TryValidateAndResolveHandlerAsync(context, baseHandler, command, actionContext, aopHandlerTypes); if (!validation.IsValid) { @@ -147,7 +167,7 @@ public static async Task HandleRequestAsync(HttpContext context, Func new SnapshotCaptureHttpHandler(c => captured = c)); + + AssertSnapshot(captured, context); + Assert.Null(captured.Request); + } + + [Fact] + public async Task HandleRequest_ShouldExposeRequestSnapshot_ForTypedRequestHandler() + { + EnsureSettings(); + HttpActionContext captured = null; + var context = CreateContext("application/json", new MemoryStream(Encoding.UTF8.GetBytes("{\"userId\":2}"))); + PrepareSnapshotRequest(context); + + await HttpHandler.HandleRequestAsync(context, _ => new TypedSnapshotCaptureHttpHandler(c => captured = c)); + + AssertSnapshot(captured, context); + Assert.IsType(captured.Request); + } + [Fact] public void CheckSign_ShouldReturnLocalizedMessage_WhenSignParametersMissing() { @@ -258,6 +288,35 @@ private static DefaultHttpContext CreateContext(string contentType, Stream body) return context; } + // 构造携带自定义鉴权头、多值头、Cookie、查询串与回环地址的请求,用于断言 HttpActionContext 的原样信息快照 + // Build a request with custom auth header, multi-value header, cookies, query string and loopback address to assert the verbatim snapshot on HttpActionContext + private static void PrepareSnapshotRequest(DefaultHttpContext context) + { + context.Request.Scheme = "http"; + context.Request.QueryString = new QueryString("?trace=abc"); + context.Request.Headers["X-HandshakeAuthorization"] = "session-token"; + context.Request.Headers["Accept-Language"] = new StringValues(new[] { "zh-CN", "en-US", }); + context.Request.Headers["Cookie"] = "session=cookie-value"; + context.Connection.RemoteIpAddress = IPAddress.Loopback; + } + + private static void AssertSnapshot(HttpActionContext captured, DefaultHttpContext context) + { + Assert.NotNull(captured); + Assert.Equal("POST", captured.Method); + Assert.Equal("application/json", captured.ContentType); + Assert.Equal("?trace=abc", captured.QueryString); + Assert.Equal("http", captured.Scheme); + Assert.True(captured.IsLocal); + Assert.Equal(context.TraceIdentifier, captured.TraceIdentifier); + Assert.False(string.IsNullOrEmpty(captured.TraceIdentifier)); + Assert.Equal(context.RequestAborted, captured.RequestAborted); + // 键大小写不敏感:以与原头不同的大小写读取 + Assert.Equal("session-token", captured.Headers["X-HANDSHAKEAUTHORIZATION"]); + Assert.Equal("zh-CN, en-US", captured.Headers["Accept-Language"]); + Assert.Equal("cookie-value", captured.Cookies["SESSION"]); + } + private static async Task ReadEnvelopeAsync(DefaultHttpContext context) { context.Response.Body.Seek(0, SeekOrigin.Begin); @@ -373,6 +432,50 @@ private sealed class ValidationProbeRequest : IHttpMessageRequest public string OptionalName { get; set; } } + /// + /// 快照捕获处理器(普通 JSON 路径):捕获 以断言请求原样信息快照。 + /// + private sealed class SnapshotCaptureHttpHandler : BaseHttpHandler + { + private readonly Action _capture; + + public SnapshotCaptureHttpHandler(Action capture) + { + _capture = capture; + } + + public override Task ActionAsync(HttpActionContext context) + { + _capture(context); + return Task.FromResult(HttpJsonResultData.SuccessString()); + } + } + + /// + /// 快照捕获处理器(强类型 Request 路径):验证第二个 HttpActionContext 构造点同样填充快照。 + /// + [HttpMessageMapping(typeof(SnapshotProbeRequest))] + private sealed class TypedSnapshotCaptureHttpHandler : BaseHttpHandler + { + private readonly Action _capture; + + public TypedSnapshotCaptureHttpHandler(Action capture) + { + _capture = capture; + } + + public override Task ActionAsync(HttpActionContext context) + { + _capture(context); + return Task.FromResult(HttpJsonResultData.SuccessString()); + } + } + + private sealed class SnapshotProbeRequest : IHttpMessageRequest + { + public string Token { get; set; } + } + private sealed class RejectingAopHandler : IHttpAopHandler { public int Priority From f2f4c902e8abd08b5da95947e22274a0f20d651f Mon Sep 17 00:00:00 2001 From: Blank Date: Mon, 23 Nov 2026 23:28:26 +0800 Subject: [PATCH 2/3] =?UTF-8?q?fix(test):=20=E6=94=B6=E5=8F=A3=E6=95=8F?= =?UTF-8?q?=E6=84=9F=E8=AF=8D=E5=90=8E=E5=8F=B0=E5=88=9D=E5=A7=8B=E5=8C=96?= =?UTF-8?q?=E7=94=A8=E4=BE=8B=E7=9A=84=E9=9D=99=E6=80=81=E8=AF=8D=E5=BA=93?= =?UTF-8?q?=E7=AB=9E=E6=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Init_WithBackgroundThread_ShouldNotBlock 以 Task.Run 后台注册词表 后即返回,慢机上该任务可能延迟到同序列后续用例执行期间才运行, ResetRegistrationState 会清空静态词库并冲掉先同步注册好的词表, 造成后续 HasBlockWords 假失败(CI database-contracts 门禁偶发红, 本地快机被 100ms Sleep 掩盖)。计时断言后轮询可检出探针词,等待 后台注册真正完成再收尾;探针词改为不超过 10 字符的 bgword1/2, 原 background1/2 长度 11 超出算法 8 位截断上限,本身不可检出。 --- .../Utility/IllegalWordDetectionTests.cs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/Tests/GameFrameX.Tests/Utility/IllegalWordDetectionTests.cs b/Tests/GameFrameX.Tests/Utility/IllegalWordDetectionTests.cs index fd51a7b59..f3d234f6c 100644 --- a/Tests/GameFrameX.Tests/Utility/IllegalWordDetectionTests.cs +++ b/Tests/GameFrameX.Tests/Utility/IllegalWordDetectionTests.cs @@ -110,8 +110,9 @@ public void Init_WithNullArray_ShouldNotThrow() [Fact] public void Init_WithBackgroundThread_ShouldNotBlock() { - // Arrange - var badWords = new[] { "background1", "background2" }; + // Arrange:探测词须不超过 10 字符——算法 FastLength/StartCache 按 8 位截断, + // 更长的词扫描会在到达末字符前被 StartCache 上限截断而不可检出,无法充当完成探针 + var badWords = new[] { "bgword1", "bgword2" }; var startTime = DateTime.Now; // Act @@ -121,6 +122,16 @@ public void Init_WithBackgroundThread_ShouldNotBlock() // Assert // 后台初始化应该很快返回 Assert.True((endTime - startTime).TotalMilliseconds < 100); + + // 等待后台注册真正完成再收尾:慢机上 Task.Run 可能延迟到同序列后续用例执行期间才重置静态词库, + // 会把先同步注册好的词表冲掉造成 HasBlockWords 假失败(CI database-contracts 门禁偶发红) + var deadline = DateTime.UtcNow.AddSeconds(10); + while (!IllegalWordDetection.HasBlockWords("bgword1") && DateTime.UtcNow < deadline) + { + System.Threading.Thread.Sleep(10); + } + + Assert.True(IllegalWordDetection.HasBlockWords("bgword1")); } #endregion From 77855ece0d3b6b931b9e0d921c6150726478c92d Mon Sep 17 00:00:00 2001 From: Blank Date: Mon, 23 Nov 2026 23:33:25 +0800 Subject: [PATCH 3/3] =?UTF-8?q?build(ci):=20=E4=BF=AE=E5=A4=8D=20database-?= =?UTF-8?q?contracts=20=E6=8A=98=E5=8F=A0=E6=A0=87=E9=87=8F=E7=A9=BA?= =?UTF-8?q?=E8=A1=8C=E6=8B=86=E6=96=AD=E5=91=BD=E4=BB=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Run Database Contract Suite 的 run: > 折叠块中夹了一个空行,YAML 折叠标量里空行会还原为真实换行,脚本被拆成两行:dotnet test 全量 通过后,--logger GitHubActions 被当作独立命令执行(command not found,exit 127),门禁必然红。此前该 bug 一直被更早的测试失败 (bash -e 提前中止)掩盖。移除空行恢复单命令折叠。 --- .github/workflows/database-contracts.yml | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/.github/workflows/database-contracts.yml b/.github/workflows/database-contracts.yml index 8fdbf9e20..e176a689b 100644 --- a/.github/workflows/database-contracts.yml +++ b/.github/workflows/database-contracts.yml @@ -55,9 +55,7 @@ jobs: - name: Run Database Contract Suite run: > - dotnet test Tests/GameFrameX.Tests/GameFrameX.Tests.csproj --no-build - - --logger GitHubActions + dotnet test Tests/GameFrameX.Tests/GameFrameX.Tests.csproj --no-build --logger GitHubActions - name: Run Hotfix and Wrapper Assembly Tests run: dotnet test Tests/GameFrameX.Hotfix.Tests/GameFrameX.Hotfix.Tests.csproj --no-build --logger GitHubActions