|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Text.RegularExpressions; |
| 4 | +using BlazorWebFormsComponents; |
| 5 | +using Bunit; |
| 6 | +using Microsoft.AspNetCore.Components.Rendering; |
| 7 | +using Microsoft.AspNetCore.DataProtection; |
| 8 | +using Microsoft.AspNetCore.Http; |
| 9 | +using Microsoft.AspNetCore.Routing; |
| 10 | +using Microsoft.Extensions.DependencyInjection; |
| 11 | +using Microsoft.Extensions.Logging; |
| 12 | +using Microsoft.Extensions.Primitives; |
| 13 | +using Moq; |
| 14 | +using Shouldly; |
| 15 | +using Xunit; |
| 16 | + |
| 17 | +using BWFCBase = BlazorWebFormsComponents.BaseWebFormsComponent; |
| 18 | + |
| 19 | +namespace BlazorWebFormsComponents.Test; |
| 20 | + |
| 21 | +/// <summary> |
| 22 | +/// Integration tests for ViewState round-trip: hidden field rendering, POST deserialization, |
| 23 | +/// tampered payload handling, null-ID guard, and size warning logging. |
| 24 | +/// </summary> |
| 25 | +public class ViewStateRoundTripTests : IDisposable |
| 26 | +{ |
| 27 | + private BunitContext _ctx; |
| 28 | + |
| 29 | + public ViewStateRoundTripTests() |
| 30 | + { |
| 31 | + InitContext(); |
| 32 | + } |
| 33 | + |
| 34 | + public void Dispose() => _ctx?.Dispose(); |
| 35 | + |
| 36 | + private void InitContext() |
| 37 | + { |
| 38 | + _ctx = new BunitContext(); |
| 39 | + _ctx.JSInterop.SetupVoid("bwfc.Page.OnAfterRender"); |
| 40 | + _ctx.Services.AddSingleton<LinkGenerator>(new Mock<LinkGenerator>().Object); |
| 41 | + _ctx.Services.AddSingleton<IDataProtectionProvider>(new EphemeralDataProtectionProvider()); |
| 42 | + _ctx.Services.AddLogging(); |
| 43 | + } |
| 44 | + |
| 45 | + #region Test Components |
| 46 | + |
| 47 | + private class ViewStateTestComponent : BWFCBase |
| 48 | + { |
| 49 | + public void SetViewState(string key, object value) => ViewState[key] = value; |
| 50 | + public object? GetViewState(string key) => ViewState[key]; |
| 51 | + |
| 52 | + protected override void BuildRenderTree(RenderTreeBuilder builder) |
| 53 | + { |
| 54 | + builder.OpenElement(0, "form"); |
| 55 | + builder.AddAttribute(1, "method", "post"); |
| 56 | + RenderViewStateField(builder); |
| 57 | + builder.OpenElement(2, "span"); |
| 58 | + builder.AddContent(3, ViewState["greeting"]?.ToString() ?? "none"); |
| 59 | + builder.CloseElement(); |
| 60 | + builder.CloseElement(); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + private class ViewStateNoIdComponent : BWFCBase |
| 65 | + { |
| 66 | + protected override void BuildRenderTree(RenderTreeBuilder builder) |
| 67 | + { |
| 68 | + builder.OpenElement(0, "form"); |
| 69 | + RenderViewStateField(builder); |
| 70 | + builder.OpenElement(1, "span"); |
| 71 | + builder.AddContent(2, "no-id"); |
| 72 | + builder.CloseElement(); |
| 73 | + builder.CloseElement(); |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + #endregion |
| 78 | + |
| 79 | + #region Helpers |
| 80 | + |
| 81 | + private void RegisterHttpContextWithMethod(string method) |
| 82 | + { |
| 83 | + var httpContext = new DefaultHttpContext(); |
| 84 | + httpContext.Request.Method = method; |
| 85 | + var mock = new Mock<IHttpContextAccessor>(); |
| 86 | + mock.Setup(x => x.HttpContext).Returns(httpContext); |
| 87 | + _ctx.Services.AddSingleton<IHttpContextAccessor>(mock.Object); |
| 88 | + } |
| 89 | + |
| 90 | + private void RegisterPostContextWithForm(Dictionary<string, StringValues> formFields) |
| 91 | + { |
| 92 | + var httpContext = new DefaultHttpContext(); |
| 93 | + httpContext.Request.Method = "POST"; |
| 94 | + httpContext.Request.ContentType = "application/x-www-form-urlencoded"; |
| 95 | + httpContext.Request.Form = new FormCollection(formFields); |
| 96 | + var mock = new Mock<IHttpContextAccessor>(); |
| 97 | + mock.Setup(x => x.HttpContext).Returns(httpContext); |
| 98 | + _ctx.Services.AddSingleton<IHttpContextAccessor>(mock.Object); |
| 99 | + } |
| 100 | + |
| 101 | + private void RegisterNoDataProtection() |
| 102 | + { |
| 103 | + // Replace the default registration with nothing — re-init context without DataProtection |
| 104 | + _ctx?.Dispose(); |
| 105 | + _ctx = new BunitContext(); |
| 106 | + _ctx.JSInterop.SetupVoid("bwfc.Page.OnAfterRender"); |
| 107 | + _ctx.Services.AddSingleton<LinkGenerator>(new Mock<LinkGenerator>().Object); |
| 108 | + _ctx.Services.AddLogging(); |
| 109 | + // Deliberately NOT registering IDataProtectionProvider |
| 110 | + } |
| 111 | + |
| 112 | + private static string? ExtractHiddenFieldValue(string markup, string fieldName) |
| 113 | + { |
| 114 | + var pattern = $@"<input[^>]*name=""{Regex.Escape(fieldName)}""[^>]*value=""([^""]*)""[^>]*/?\s*>"; |
| 115 | + var match = Regex.Match(markup, pattern); |
| 116 | + return match.Success ? match.Groups[1].Value : null; |
| 117 | + } |
| 118 | + |
| 119 | + #endregion |
| 120 | + |
| 121 | + #region Tests |
| 122 | + |
| 123 | + [Fact] |
| 124 | + public void Render_WithDirtyViewState_EmitsHiddenField() |
| 125 | + { |
| 126 | + RegisterHttpContextWithMethod("GET"); |
| 127 | + |
| 128 | + var cut = _ctx.Render<ViewStateTestComponent>(p => p |
| 129 | + .Add(c => c.ID, "myComp")); |
| 130 | + |
| 131 | + cut.Instance.SetViewState("greeting", "Hello"); |
| 132 | + cut.Render(); |
| 133 | + |
| 134 | + var markup = cut.Markup; |
| 135 | + markup.ShouldContain("__bwfc_viewstate_myComp"); |
| 136 | + markup.ShouldContain("type=\"hidden\""); |
| 137 | + } |
| 138 | + |
| 139 | + [Fact] |
| 140 | + public void Render_WithCleanViewState_NoHiddenField() |
| 141 | + { |
| 142 | + RegisterHttpContextWithMethod("GET"); |
| 143 | + |
| 144 | + var cut = _ctx.Render<ViewStateTestComponent>(p => p |
| 145 | + .Add(c => c.ID, "myComp")); |
| 146 | + |
| 147 | + var markup = cut.Markup; |
| 148 | + markup.ShouldNotContain("__bwfc_viewstate_"); |
| 149 | + } |
| 150 | + |
| 151 | + [Fact] |
| 152 | + public void Render_WithoutDataProtection_NoHiddenField() |
| 153 | + { |
| 154 | + RegisterNoDataProtection(); |
| 155 | + RegisterHttpContextWithMethod("GET"); |
| 156 | + |
| 157 | + var cut = _ctx.Render<ViewStateTestComponent>(p => p |
| 158 | + .Add(c => c.ID, "myComp")); |
| 159 | + |
| 160 | + cut.Instance.SetViewState("greeting", "Hello"); |
| 161 | + cut.Render(); |
| 162 | + |
| 163 | + var markup = cut.Markup; |
| 164 | + markup.ShouldNotContain("__bwfc_viewstate_"); |
| 165 | + } |
| 166 | + |
| 167 | + [Fact] |
| 168 | + public void RoundTrip_SetValue_PostBack_ReadsCorrectValue() |
| 169 | + { |
| 170 | + // Share a single DataProtectionProvider across both render phases |
| 171 | + var sharedDpp = new EphemeralDataProtectionProvider(); |
| 172 | + |
| 173 | + // Phase 1: GET render — fresh context with shared DPP |
| 174 | + _ctx.Dispose(); |
| 175 | + _ctx = new BunitContext(); |
| 176 | + _ctx.JSInterop.SetupVoid("bwfc.Page.OnAfterRender"); |
| 177 | + _ctx.Services.AddSingleton<LinkGenerator>(new Mock<LinkGenerator>().Object); |
| 178 | + _ctx.Services.AddSingleton<IDataProtectionProvider>(sharedDpp); |
| 179 | + _ctx.Services.AddLogging(); |
| 180 | + RegisterHttpContextWithMethod("GET"); |
| 181 | + |
| 182 | + var cut = _ctx.Render<ViewStateTestComponent>(p => p |
| 183 | + .Add(c => c.ID, "rt1")); |
| 184 | + |
| 185 | + cut.Instance.SetViewState("greeting", "Hello"); |
| 186 | + cut.Render(); |
| 187 | + |
| 188 | + var payload = ExtractHiddenFieldValue(cut.Markup, "__bwfc_viewstate_rt1"); |
| 189 | + payload.ShouldNotBeNullOrEmpty("Hidden field payload should be emitted"); |
| 190 | + |
| 191 | + // Phase 2: POST render — new context with same shared DPP |
| 192 | + _ctx.Dispose(); |
| 193 | + _ctx = new BunitContext(); |
| 194 | + _ctx.JSInterop.SetupVoid("bwfc.Page.OnAfterRender"); |
| 195 | + _ctx.Services.AddSingleton<LinkGenerator>(new Mock<LinkGenerator>().Object); |
| 196 | + _ctx.Services.AddSingleton<IDataProtectionProvider>(sharedDpp); |
| 197 | + _ctx.Services.AddLogging(); |
| 198 | + |
| 199 | + RegisterPostContextWithForm(new Dictionary<string, StringValues> |
| 200 | + { |
| 201 | + ["__bwfc_viewstate_rt1"] = new StringValues(payload) |
| 202 | + }); |
| 203 | + |
| 204 | + var cut2 = _ctx.Render<ViewStateTestComponent>(p => p |
| 205 | + .Add(c => c.ID, "rt1")); |
| 206 | + |
| 207 | + // ViewState should have been deserialized from the form data |
| 208 | + cut2.Markup.ShouldContain("Hello"); |
| 209 | + } |
| 210 | + |
| 211 | + [Fact] |
| 212 | + public void RoundTrip_TamperedPayload_SilentlyIgnored() |
| 213 | + { |
| 214 | + RegisterPostContextWithForm(new Dictionary<string, StringValues> |
| 215 | + { |
| 216 | + ["__bwfc_viewstate_tampered1"] = new StringValues("TAMPERED_INVALID_DATA!!!") |
| 217 | + }); |
| 218 | + |
| 219 | + // Should not throw — tampered payload is silently ignored |
| 220 | + var cut = _ctx.Render<ViewStateTestComponent>(p => p |
| 221 | + .Add(c => c.ID, "tampered1")); |
| 222 | + |
| 223 | + cut.Instance.GetViewState("greeting").ShouldBeNull(); |
| 224 | + cut.Markup.ShouldContain("none"); |
| 225 | + } |
| 226 | + |
| 227 | + [Fact] |
| 228 | + public void Render_WithNullID_SkipsViewStateField() |
| 229 | + { |
| 230 | + RegisterHttpContextWithMethod("GET"); |
| 231 | + |
| 232 | + // No ID set on the component |
| 233 | + var cut = _ctx.Render<ViewStateNoIdComponent>(); |
| 234 | + |
| 235 | + // Force dirty ViewState via the internal dictionary |
| 236 | + // The component doesn't expose SetViewState, but we can check the guard behavior |
| 237 | + // by verifying no hidden field is emitted even though BuildRenderTree calls RenderViewStateField |
| 238 | + var markup = cut.Markup; |
| 239 | + markup.ShouldNotContain("__bwfc_viewstate_"); |
| 240 | + } |
| 241 | + |
| 242 | + [Fact] |
| 243 | + public void SizeWarning_LargePayload_LogsWarning() |
| 244 | + { |
| 245 | + var mockLogger = new Mock<ILogger>(); |
| 246 | + mockLogger.Setup(l => l.IsEnabled(It.IsAny<LogLevel>())).Returns(true); |
| 247 | + |
| 248 | + var protector = new EphemeralDataProtectionProvider().CreateProtector("BWFC.ViewState"); |
| 249 | + var viewState = new ViewStateDictionary(); |
| 250 | + |
| 251 | + // Stuff enough data to exceed the 4096 byte threshold |
| 252 | + for (var i = 0; i < 100; i++) |
| 253 | + { |
| 254 | + viewState[$"key_{i}"] = new string('x', 100); |
| 255 | + } |
| 256 | + |
| 257 | + viewState.Serialize(protector, mockLogger.Object, warningThresholdBytes: 512); |
| 258 | + |
| 259 | + mockLogger.Verify( |
| 260 | + l => l.Log( |
| 261 | + LogLevel.Warning, |
| 262 | + It.IsAny<EventId>(), |
| 263 | + It.Is<It.IsAnyType>((v, t) => v.ToString()!.Contains("ViewState payload is")), |
| 264 | + It.IsAny<Exception>(), |
| 265 | + It.IsAny<Func<It.IsAnyType, Exception?, string>>()), |
| 266 | + Times.Once); |
| 267 | + } |
| 268 | + |
| 269 | + #endregion |
| 270 | +} |
0 commit comments