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

145 lines
5.6 KiB
C#

using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using Heimdall.Web.Services;
using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.JSInterop;
using NSubstitute;
namespace Heimdall.Web.Tests.Services;
public sealed class TokenRefreshHandlerTests : IDisposable
{
private readonly MockInnerHandler _innerHandler;
private readonly HttpClient _httpClient;
private readonly AuthState _authState;
private readonly TokenRefreshHandler _handler;
public TokenRefreshHandlerTests()
{
_innerHandler = new MockInnerHandler();
_authState = new AuthState();
var authStateProvider = Substitute.For<HeimdallAuthStateProvider>(
new ProtectedSessionStorage(Substitute.For<IJSRuntime>(), Substitute.For<IDataProtectionProvider>()),
_authState,
Substitute.For<IHttpContextAccessor>());
var config = Substitute.For<IConfiguration>();
config.GetValue<string>("ApiBaseUrl").Returns("http://localhost:8080");
_handler = new TokenRefreshHandler(_authState, authStateProvider, Substitute.For<IHttpContextAccessor>(), config);
var pipeline = _innerHandler.CreatePipeline(_handler);
_httpClient = new HttpClient(pipeline) { BaseAddress = new Uri("http://localhost:8080/") };
}
public void Dispose() => _httpClient.Dispose();
[Fact]
public async Task SendAsync_Non401Response_PassesThrough()
{
_innerHandler.QueueResponse(HttpStatusCode.OK);
var response = await _httpClient.GetAsync("api/sites");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[Fact]
public async Task SendAsync_401WithoutRefreshToken_DoesNotRetry()
{
_innerHandler.QueueResponse(HttpStatusCode.Unauthorized);
var response = await _httpClient.GetAsync("api/sites");
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Equal(1, _innerHandler.CallCount);
}
[Fact]
public async Task SendAsync_AuthEndpoint_DoesNotIntercept()
{
_innerHandler.QueueResponse(HttpStatusCode.Unauthorized);
var response = await _httpClient.PostAsync("api/auth/login", null);
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Equal(1, _innerHandler.CallCount);
}
}
public class MockInnerHandler : HttpMessageHandler
{
private readonly Queue<HttpResponseMessage> _responses = new();
public int CallCount { get; private set; }
public List<HttpRequestMessage> Requests { get; } = [];
public void QueueResponse(HttpStatusCode status, object? body = null)
{
var response = new HttpResponseMessage(status);
if (body is not null)
response.Content = JsonContent.Create(body, options: new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});
_responses.Enqueue(response);
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
{
CallCount++;
Requests.Add(request);
var response = _responses.Count > 0 ? _responses.Dequeue() : new HttpResponseMessage(HttpStatusCode.OK);
return Task.FromResult(response);
}
public HttpMessageHandler CreatePipeline(DelegatingHandler handler)
{
handler.InnerHandler = this;
return handler;
}
}
public class SessionRefreshRegressionTests
{
[Fact]
public async Task Expired_nonempty_token_refreshes_against_actual_api_origin_without_http_context()
{
var auth = new AuthState { AccessToken = "expired", RefreshToken = "refresh" };
var provider = Substitute.For<HeimdallAuthStateProvider>(
new ProtectedSessionStorage(Substitute.For<IJSRuntime>(), Substitute.For<IDataProtectionProvider>()),
auth, Substitute.For<IHttpContextAccessor>());
provider.When(x => x.NotifyLoginAsync(Arg.Any<AuthResponse>())).Do(x => auth.Login(x.Arg<AuthResponse>()!));
var raw = new MockInnerHandler();
raw.QueueResponse(HttpStatusCode.OK, new AuthResponse("fresh", "rotated", DateTime.UtcNow.AddMinutes(15), false,
new UserInfo(Guid.NewGuid(), "test@example.test", "Test", [])));
var factory = Substitute.For<IHttpClientFactory>();
factory.CreateClient("HeimdallRefresh").Returns(_ => new HttpClient(raw, false));
var api = new MockInnerHandler();
api.QueueResponse(HttpStatusCode.Unauthorized);
api.QueueResponse(HttpStatusCode.OK);
using var handler = new TokenRefreshHandler(auth, provider, new HttpContextAccessor(), new ConfigurationBuilder().Build(), factory)
{ InnerHandler = api };
using var client = new HttpClient(handler) { BaseAddress = new Uri("http://127.0.0.1:5287/") };
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "expired");
var response = await client.GetAsync("api/sites");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(1, raw.CallCount);
Assert.Equal("http://127.0.0.1:5287/api/auth/refresh", raw.Requests[0].RequestUri!.AbsoluteUri);
Assert.Equal("fresh", api.Requests[1].Headers.Authorization!.Parameter);
}
[Fact]
public void Refresh_locks_are_owned_by_each_session()
{
var a = new AuthState();
var b = new AuthState();
Assert.NotSame(a.RefreshLock, b.RefreshLock);
}
}