Files
Heimdall/tests/Heimdall.Web.Tests/Services/HeimdallAuthStateProviderTests.cs
T

169 lines
7.4 KiB
C#
Raw Normal View History

using System.Security.Claims;
using Heimdall.Web.Services;
using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
using Microsoft.AspNetCore.Http;
using Microsoft.JSInterop;
using NSubstitute;
using Shouldly;
namespace Heimdall.Web.Tests.Services;
/// <summary>
/// Tests for HeimdallAuthStateProvider — focused on the cookie (SSR) and
/// anonymous paths. The ProtectedSessionStorage path requires a live Blazor
/// circuit (server-side Data Protection + JS interop) and is covered by the
/// E2E Playwright suite instead.
/// </summary>
public class HeimdallAuthStateProviderTests
{
private static HeimdallAuthStateProvider CreateProvider(
IHttpContextAccessor httpContextAccessor,
AuthState? authState = null)
{
// ProtectedSessionStorage is sealed and cannot be substituted; a real
// instance with a mocked IJSRuntime works fine because the storage
// path throws outside a live circuit and is caught by the provider.
var jsRuntime = Substitute.For<IJSRuntime>();
var storage = new ProtectedSessionStorage(jsRuntime, new FakeDataProtectionProvider());
return new HeimdallAuthStateProvider(
storage,
authState ?? new AuthState(),
httpContextAccessor);
}
private static IHttpContextAccessor CreateContextAccessor(ClaimsPrincipal? user = null)
{
var context = new DefaultHttpContext();
context.User = user ?? new ClaimsPrincipal(new ClaimsIdentity());
var accessor = Substitute.For<IHttpContextAccessor>();
accessor.HttpContext.Returns(context);
return accessor;
}
[Fact]
public async Task GetAuthenticationStateAsync_WithAuthenticatedCookie_ReturnsUserState()
{
var userId = Guid.NewGuid();
var principal = new ClaimsPrincipal(new ClaimsIdentity(
[
new Claim(ClaimTypes.NameIdentifier, userId.ToString()),
new Claim(ClaimTypes.Name, "Admin User"),
new Claim(ClaimTypes.Email, "admin@heimdall.test"),
new Claim(ClaimTypes.Role, "Admin")
], "Cookies"));
var authState = new AuthState();
var provider = CreateProvider(CreateContextAccessor(principal), authState);
var result = await provider.GetAuthenticationStateAsync();
result.User.Identity!.IsAuthenticated.ShouldBeTrue();
result.User.Identity!.AuthenticationType.ShouldBe("Cookies");
// The cookie principal is returned as-is
result.User.FindFirst(ClaimTypes.NameIdentifier)!.Value.ShouldBe(userId.ToString());
// AuthState is populated for downstream consumers
authState.IsLoggedIn.ShouldBeTrue();
authState.User!.Email.ShouldBe("admin@heimdall.test");
}
[Fact]
public async Task GetAuthenticationStateAsync_WithAnonymousUser_ReturnsAnonymous()
{
var provider = CreateProvider(CreateContextAccessor());
var result = await provider.GetAuthenticationStateAsync();
result.User.Identity!.IsAuthenticated.ShouldBeFalse();
}
[Fact]
public async Task GetAuthenticationStateAsync_WithoutHttpContext_ReturnsAnonymous()
{
var accessor = Substitute.For<IHttpContextAccessor>();
accessor.HttpContext.Returns((HttpContext?)null);
var provider = CreateProvider(accessor);
var result = await provider.GetAuthenticationStateAsync();
result.User.Identity!.IsAuthenticated.ShouldBeFalse();
}
[Fact]
public async Task GetAuthenticationStateAsync_StaticRender_WithStorageThatThrows_FallsBackToCookieWithoutJsInterop()
{
// Simulates the SSR/static-render phase: HttpContext is present (no
// active Blazor circuit), so the provider must NOT touch
// ProtectedSessionStorage (JS interop) — it would throw
// "JavaScript interop calls cannot be issued at this time".
// Regression test for the F5/reload error on authenticated pages.
var principal = new ClaimsPrincipal(new ClaimsIdentity(
[
new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()),
new Claim(ClaimTypes.Name, "Admin User"),
new Claim(ClaimTypes.Email, "admin@heimdall.test"),
new Claim(ClaimTypes.Role, "Admin")
], "Cookies"));
// An IJSRuntime that throws on any invocation: if the provider called
// storage during static render, this test would fail with the real
// error instead of falling back to the cookie.
var storage = new ProtectedSessionStorage(new ThrowingJSRuntime(), new FakeDataProtectionProvider());
var authState = new AuthState();
var provider = new HeimdallAuthStateProvider(storage, authState, CreateContextAccessor(principal));
var result = await provider.GetAuthenticationStateAsync();
result.User.Identity!.IsAuthenticated.ShouldBeTrue();
result.User.Identity!.AuthenticationType.ShouldBe("Cookies");
authState.IsLoggedIn.ShouldBeTrue();
}
[Fact]
public async Task NotifyLoginAsync_StaticRender_DoesNotCallStorageButUpdatesState()
{
// Regression: during static render (HttpContext present), NotifyLogin
// must not invoke JS interop storage — state is updated in-memory and
// the cookie is handled separately by AuthHelper.
var accessor = Substitute.For<IHttpContextAccessor>();
accessor.HttpContext.Returns(new DefaultHttpContext());
var storage = new ProtectedSessionStorage(new ThrowingJSRuntime(), new FakeDataProtectionProvider());
var authState = new AuthState();
var provider = new HeimdallAuthStateProvider(storage, authState, accessor);
await provider.NotifyLoginAsync(new AuthResponse(
"access-token", "refresh-token", DateTime.UtcNow.AddHours(1), false,
new UserInfo(Guid.NewGuid(), "admin@heimdall.test", "Admin User", ["Admin"])));
authState.IsLoggedIn.ShouldBeTrue();
}
}
/// <summary>Minimal IDataProtectionProvider for ProtectedBrowserStorage.</summary>
internal sealed class FakeDataProtectionProvider : Microsoft.AspNetCore.DataProtection.IDataProtectionProvider
{
public Microsoft.AspNetCore.DataProtection.IDataProtector CreateProtector(string purpose)
=> new FakeDataProtector();
}
internal sealed class FakeDataProtector : Microsoft.AspNetCore.DataProtection.IDataProtector
{
public byte[] Protect(byte[] plaintext) => plaintext;
public byte[] Unprotect(byte[] protectedData) => protectedData;
public Microsoft.AspNetCore.DataProtection.IDataProtector CreateProtector(string purpose) => this;
}
/// <summary>
/// IJSRuntime that always throws the classic static-render error — used to
/// prove the auth provider never touches JS interop outside an active circuit.
/// </summary>
internal sealed class ThrowingJSRuntime : IJSRuntime
{
public ValueTask<TValue> InvokeAsync<TValue>(string identifier, object?[]? args)
=> throw new InvalidOperationException(
"JavaScript interop calls cannot be issued at this time. " +
"This is because the component is being statically rendered.");
public ValueTask<TValue> InvokeAsync<TValue>(string identifier, CancellationToken cancellationToken, object?[]? args)
=> throw new InvalidOperationException(
"JavaScript interop calls cannot be issued at this time. " +
"This is because the component is being statically rendered.");
}