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 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 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