Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.NotificationService.Tests/OAuth2TokenServiceTests.cs
T

483 lines
21 KiB
C#

using System.Net;
using System.Text.Json;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
namespace ZB.MOM.WW.ScadaBridge.NotificationService.Tests;
/// <summary>
/// Tests for OAuth2 token flow — token acquisition, caching, and credential parsing.
/// </summary>
public class OAuth2TokenServiceTests
{
private static HttpClient CreateMockHttpClient(HttpStatusCode statusCode, string responseJson)
{
var handler = new MockHttpMessageHandler(statusCode, responseJson);
return new HttpClient(handler);
}
private static IHttpClientFactory CreateMockFactory(HttpClient client)
{
var factory = Substitute.For<IHttpClientFactory>();
factory.CreateClient(Arg.Any<string>()).Returns(client);
return factory;
}
/// <summary>Verifies that get token async returns access token from token endpoint.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task GetTokenAsync_ReturnsAccessToken_FromTokenEndpoint()
{
var tokenResponse = JsonSerializer.Serialize(new
{
access_token = "mock-access-token-12345",
expires_in = 3600,
token_type = "Bearer"
});
var client = CreateMockHttpClient(HttpStatusCode.OK, tokenResponse);
var factory = CreateMockFactory(client);
var service = new OAuth2TokenService(factory, NullLogger<OAuth2TokenService>.Instance);
var token = await service.GetTokenAsync("tenant123:client456:secret789");
Assert.Equal("mock-access-token-12345", token);
}
/// <summary>Verifies that get token async caches token on subsequent calls.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task GetTokenAsync_CachesToken_OnSubsequentCalls()
{
var tokenResponse = JsonSerializer.Serialize(new
{
access_token = "cached-token",
expires_in = 3600,
token_type = "Bearer"
});
var handler = new CountingHttpMessageHandler(HttpStatusCode.OK, tokenResponse);
var client = new HttpClient(handler);
var factory = CreateMockFactory(client);
var service = new OAuth2TokenService(factory, NullLogger<OAuth2TokenService>.Instance);
var token1 = await service.GetTokenAsync("tenant:client:secret");
var token2 = await service.GetTokenAsync("tenant:client:secret");
Assert.Equal("cached-token", token1);
Assert.Equal("cached-token", token2);
Assert.Equal(1, handler.CallCount); // Only one HTTP call should be made
}
/// <summary>Verifies that get token async invalid credential format throws invalid operation exception.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task GetTokenAsync_InvalidCredentialFormat_ThrowsInvalidOperationException()
{
var client = CreateMockHttpClient(HttpStatusCode.OK, "{}");
var factory = CreateMockFactory(client);
var service = new OAuth2TokenService(factory, NullLogger<OAuth2TokenService>.Instance);
await Assert.ThrowsAsync<InvalidOperationException>(
() => service.GetTokenAsync("invalid-no-colons"));
}
/// <summary>Verifies that get token async http failure throws http request exception.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task GetTokenAsync_HttpFailure_ThrowsHttpRequestException()
{
var client = CreateMockHttpClient(HttpStatusCode.Unauthorized, "Unauthorized");
var factory = CreateMockFactory(client);
var service = new OAuth2TokenService(factory, NullLogger<OAuth2TokenService>.Instance);
await Assert.ThrowsAsync<HttpRequestException>(
() => service.GetTokenAsync("tenant:client:secret"));
}
// ── Token cache must be keyed to credential identity ──
/// <summary>Verifies that get token async different credentials return per credential tokens.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task GetTokenAsync_DifferentCredentials_ReturnPerCredentialTokens()
{
// The singleton cached a single token ignoring the credentials
// argument, so a second SMTP config with a different tenant/client got the
// first config's token. Each distinct credential must get its own token.
var handler = new PerTenantHttpMessageHandler();
var client = new HttpClient(handler);
var factory = CreateMockFactory(client);
var service = new OAuth2TokenService(factory, NullLogger<OAuth2TokenService>.Instance);
var tokenA = await service.GetTokenAsync("tenantA:clientA:secretA");
var tokenB = await service.GetTokenAsync("tenantB:clientB:secretB");
Assert.Equal("token-for-tenantA", tokenA);
Assert.Equal("token-for-tenantB", tokenB);
}
/// <summary>Verifies that get token async same credentials cached per credential.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task GetTokenAsync_SameCredentials_CachedPerCredential()
{
// Caching still works — repeated calls with the same credential
// identity make exactly one HTTP call.
var handler = new PerTenantHttpMessageHandler();
var client = new HttpClient(handler);
var factory = CreateMockFactory(client);
var service = new OAuth2TokenService(factory, NullLogger<OAuth2TokenService>.Instance);
await service.GetTokenAsync("tenantA:clientA:secretA");
await service.GetTokenAsync("tenantA:clientA:secretA");
await service.GetTokenAsync("tenantB:clientB:secretB");
Assert.Equal(2, handler.CallCount); // one per distinct credential, not per call
}
// ── Token expiry/refresh and concurrent acquisition ──
/// <summary>Verifies that get token async expired token refreshes on next call.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task GetTokenAsync_ExpiredToken_RefreshesOnNextCall()
{
// Token expiry/refresh was untested — the cache test used a 3600s
// token so the refresh branch never ran. The service refreshes 60s before
// the stated expiry, so an expires_in of 60 makes the token immediately
// stale and the next call must fetch a fresh one.
var handler = new SequenceHttpMessageHandler(
TokenJson("first-token", expiresIn: 60),
TokenJson("second-token", expiresIn: 3600));
var client = new HttpClient(handler);
var factory = CreateMockFactory(client);
var service = new OAuth2TokenService(factory, NullLogger<OAuth2TokenService>.Instance);
var token1 = await service.GetTokenAsync("tenant:client:secret");
var token2 = await service.GetTokenAsync("tenant:client:secret");
Assert.Equal("first-token", token1);
Assert.Equal("second-token", token2); // refreshed because the first was already stale
Assert.Equal(2, handler.CallCount);
}
/// <summary>Verifies that get token async concurrent calls make exactly one http request.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task GetTokenAsync_ConcurrentCalls_MakeExactlyOneHttpRequest()
{
// The double-checked-locking path was never exercised. Many callers
// racing for the same uncached credential must collapse to a single token
// fetch, not one HTTP call per caller.
var handler = new SlowCountingHttpMessageHandler(
TokenJson("concurrent-token", expiresIn: 3600), delay: TimeSpan.FromMilliseconds(100));
var client = new HttpClient(handler);
var factory = CreateMockFactory(client);
var service = new OAuth2TokenService(factory, NullLogger<OAuth2TokenService>.Instance);
var tasks = Enumerable.Range(0, 20)
.Select(_ => service.GetTokenAsync("tenant:client:secret"))
.ToArray();
var tokens = await Task.WhenAll(tasks);
Assert.All(tokens, t => Assert.Equal("concurrent-token", t));
Assert.Equal(1, handler.CallCount);
}
// ── Configurable OAuth2 authority + scope per SMTP configuration ──
/// <summary>Verifies that get token async custom authority and scope posts to configured endpoint.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task GetTokenAsync_CustomAuthorityAndScope_PostsToConfiguredEndpoint()
{
// An IdP other than Microsoft 365: the stored authority template carries a {tenant} placeholder
// and the scope is provider-specific. Both must flow verbatim into the request.
var handler = new CapturingHttpMessageHandler(
TokenJson("custom-token", expiresIn: 3600));
var client = new HttpClient(handler);
var factory = CreateMockFactory(client);
var service = new OAuth2TokenService(factory, NullLogger<OAuth2TokenService>.Instance);
var token = await service.GetTokenAsync(
"T1:client:secret",
authority: "https://idp.example/{tenant}/token",
scope: "smtp.send");
Assert.Equal("custom-token", token);
Assert.Equal("https://idp.example/T1/token", handler.LastRequestUri!.ToString());
Assert.Equal("smtp.send", handler.LastForm!["scope"]);
}
/// <summary>Verifies that get token async preserves the Microsoft 365 defaults.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task GetTokenAsync_DefaultsPreserved_M365()
{
// No authority/scope → today's hardcoded Microsoft 365 endpoint + scope.
var handler = new CapturingHttpMessageHandler(
TokenJson("m365-token", expiresIn: 3600));
var client = new HttpClient(handler);
var factory = CreateMockFactory(client);
var service = new OAuth2TokenService(factory, NullLogger<OAuth2TokenService>.Instance);
var token = await service.GetTokenAsync("tenant:client:secret");
Assert.Equal("m365-token", token);
Assert.Equal(
"https://login.microsoftonline.com/tenant/oauth2/v2.0/token",
handler.LastRequestUri!.ToString());
Assert.Equal("https://outlook.office365.com/.default", handler.LastForm!["scope"]);
}
/// <summary>
/// Verifies that a credential rotation does not leave the old credential's cache entry
/// behind forever: once the old token has expired and the entry has been idle past the
/// stale grace, the next token request evicts it (review 2026-10-21 06/MEM-3).
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task GetTokenAsync_RotatedCredential_StaleEntryIsEvicted()
{
var handler = new CountingHttpMessageHandler(HttpStatusCode.OK, TokenJson("t", expiresIn: 3600));
var factory = CreateMockFactory(new HttpClient(handler));
var clock = new ManualTimeProvider(DateTimeOffset.Parse("2026-10-22T00:00:00Z"));
var service = new OAuth2TokenService(factory, NullLogger<OAuth2TokenService>.Instance, clock);
await service.GetTokenAsync("tenant:client:old-secret");
Assert.Equal(1, service.CachedEntryCount);
// Rotate: the old entry is still fresh, so it survives the first request with the new secret.
await service.GetTokenAsync("tenant:client:new-secret");
Assert.Equal(2, service.CachedEntryCount);
// Well past the old token's expiry plus the stale grace — the next request sweeps it.
clock.Advance(TimeSpan.FromHours(3));
await service.GetTokenAsync("tenant:client:new-secret");
Assert.Equal(1, service.CachedEntryCount);
}
/// <summary>
/// Verifies that an entry whose token was never acquired (bad credentials) is also evicted
/// once idle past the stale grace, rather than lingering with a null token forever.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task GetTokenAsync_FailedCredential_IdleEntryIsEvicted()
{
var handler = new CountingHttpMessageHandler(HttpStatusCode.OK, TokenJson("t", expiresIn: 3600));
var factory = CreateMockFactory(new HttpClient(handler));
var clock = new ManualTimeProvider(DateTimeOffset.Parse("2026-10-22T00:00:00Z"));
var service = new OAuth2TokenService(factory, NullLogger<OAuth2TokenService>.Instance, clock);
await Assert.ThrowsAsync<InvalidOperationException>(() => service.GetTokenAsync("not-a-triple"));
Assert.Equal(1, service.CachedEntryCount);
clock.Advance(TimeSpan.FromHours(2));
await service.GetTokenAsync("tenant:client:secret");
Assert.Equal(1, service.CachedEntryCount);
}
/// <summary>A hand-advanced clock for the cache-eviction tests.</summary>
private sealed class ManualTimeProvider(DateTimeOffset start) : TimeProvider
{
private DateTimeOffset _now = start;
/// <summary>Moves the clock forward.</summary>
/// <param name="by">The amount to advance.</param>
public void Advance(TimeSpan by) => _now += by;
/// <inheritdoc />
public override DateTimeOffset GetUtcNow() => _now;
}
private static string TokenJson(string accessToken, int expiresIn) =>
JsonSerializer.Serialize(new
{
access_token = accessToken,
expires_in = expiresIn,
token_type = "Bearer"
});
/// <summary>HTTP handler returning a different response per invocation, in order.</summary>
private class SequenceHttpMessageHandler : HttpMessageHandler
{
private readonly string[] _responses;
/// <summary>The number of HTTP requests the handler has served.</summary>
public int CallCount { get; private set; }
/// <summary>Initializes a new instance of <c>SequenceHttpMessageHandler</c>.</summary>
/// <param name="responses">The responses.</param>
public SequenceHttpMessageHandler(params string[] responses) => _responses = responses;
/// <inheritdoc />
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
var body = _responses[Math.Min(CallCount, _responses.Length - 1)];
CallCount++;
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(body)
});
}
}
/// <summary>HTTP handler that delays and counts invocations (thread-safe count).</summary>
private class SlowCountingHttpMessageHandler : HttpMessageHandler
{
private readonly string _response;
private readonly TimeSpan _delay;
private int _callCount;
/// <summary>The number of HTTP requests the handler has served.</summary>
public int CallCount => _callCount;
/// <summary>Initializes a new instance of <c>SlowCountingHttpMessageHandler</c>.</summary>
/// <param name="response">The response.</param>
/// <param name="delay">The delay.</param>
public SlowCountingHttpMessageHandler(string response, TimeSpan delay)
{
_response = response;
_delay = delay;
}
/// <inheritdoc />
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
Interlocked.Increment(ref _callCount);
await Task.Delay(_delay, cancellationToken);
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(_response)
};
}
}
/// <summary>
/// HTTP handler that returns a distinct access token per tenant id, parsed from
/// the request URL (<c>https://login.microsoftonline.com/{tenantId}/...</c>).
/// </summary>
private class PerTenantHttpMessageHandler : HttpMessageHandler
{
/// <summary>The number of HTTP requests the handler has served.</summary>
public int CallCount { get; private set; }
/// <inheritdoc />
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
CallCount++;
var segments = request.RequestUri!.AbsolutePath.Trim('/').Split('/');
var tenantId = segments[0];
var json = JsonSerializer.Serialize(new
{
access_token = $"token-for-{tenantId}",
expires_in = 3600,
token_type = "Bearer"
});
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(json)
});
}
}
/// <summary>
/// HTTP handler that captures the request URI and the posted form fields so a
/// test can assert the token endpoint and scope actually sent.
/// </summary>
private class CapturingHttpMessageHandler : HttpMessageHandler
{
private readonly string _response;
/// <summary>The URI of the most recent request, if any.</summary>
public Uri? LastRequestUri { get; private set; }
/// <summary>The form fields posted in the most recent request, if any.</summary>
public IReadOnlyDictionary<string, string>? LastForm { get; private set; }
/// <summary>Initializes a new instance of <c>CapturingHttpMessageHandler</c>.</summary>
/// <param name="response">The response.</param>
public CapturingHttpMessageHandler(string response) => _response = response;
/// <inheritdoc />
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
LastRequestUri = request.RequestUri;
var body = request.Content == null
? string.Empty
: await request.Content.ReadAsStringAsync(cancellationToken);
LastForm = body
.Split('&', StringSplitOptions.RemoveEmptyEntries)
.Select(pair => pair.Split('=', 2))
.ToDictionary(
p => Uri.UnescapeDataString(p[0]),
p => p.Length > 1 ? Uri.UnescapeDataString(p[1]) : string.Empty);
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(_response)
};
}
}
/// <summary>
/// Simple mock HTTP handler that returns a fixed response.
/// </summary>
private class MockHttpMessageHandler : HttpMessageHandler
{
private readonly HttpStatusCode _statusCode;
private readonly string _responseContent;
/// <summary>Initializes a new instance of <c>MockHttpMessageHandler</c>.</summary>
/// <param name="statusCode">The status code.</param>
/// <param name="responseContent">The response content.</param>
public MockHttpMessageHandler(HttpStatusCode statusCode, string responseContent)
{
_statusCode = statusCode;
_responseContent = responseContent;
}
/// <inheritdoc />
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
return Task.FromResult(new HttpResponseMessage(_statusCode)
{
Content = new StringContent(_responseContent)
});
}
}
/// <summary>
/// Mock HTTP handler that counts invocations.
/// </summary>
private class CountingHttpMessageHandler : HttpMessageHandler
{
private readonly HttpStatusCode _statusCode;
private readonly string _responseContent;
/// <summary>The number of HTTP requests the handler has served.</summary>
public int CallCount { get; private set; }
/// <summary>Initializes a new instance of <c>CountingHttpMessageHandler</c>.</summary>
/// <param name="statusCode">The status code.</param>
/// <param name="responseContent">The response content.</param>
public CountingHttpMessageHandler(HttpStatusCode statusCode, string responseContent)
{
_statusCode = statusCode;
_responseContent = responseContent;
}
/// <inheritdoc />
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
CallCount++;
return Task.FromResult(new HttpResponseMessage(_statusCode)
{
Content = new StringContent(_responseContent)
});
}
}
}