Adds 2 units and docs for unit 3. nfr-requirements plan

This commit is contained in:
2026-06-29 22:18:37 +02:00
parent 0e01ca1e1c
commit c156107cb1
126 changed files with 15204 additions and 80199 deletions
@@ -0,0 +1,145 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using FluentAssertions;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.IdentityModel.Tokens;
using NSubstitute;
using SlpModularCms.Core.Availability;
using SlpModularCms.Modules.Availability.Middleware;
using SlpModularCms.Modules.Availability.Services;
namespace SlpModularCms.Modules.Availability.Tests;
public class AvailabilityMiddlewareMasterGateTests
{
private readonly IAvailabilityService _localSvc;
private readonly IMasterAvailabilityService _masterSvc;
private readonly AvailabilityMiddleware _middleware;
private readonly RequestDelegate _next;
public AvailabilityMiddlewareMasterGateTests()
{
_localSvc = Substitute.For<IAvailabilityService>();
_masterSvc = Substitute.For<IMasterAvailabilityService>();
_next = Substitute.For<RequestDelegate>();
_middleware = new AvailabilityMiddleware(_next, NullLogger<AvailabilityMiddleware>.Instance);
_localSvc.IsAvailableAsync().Returns(AvailabilityStatus.Available);
_masterSvc.GetMasterStatus().Returns(new MasterGateStatus(true, null));
}
[Fact]
public async Task InvokeAsync_Passes_WhenMasterAndLocalBothAvailable()
{
var context = new DefaultHttpContext();
await _middleware.InvokeAsync(context, _localSvc, _masterSvc);
await _next.Received(1).Invoke(context);
}
[Fact]
public async Task InvokeAsync_Returns503_WhenMasterGateBlocks()
{
var context = new DefaultHttpContext();
context.Response.Body = new MemoryStream();
_masterSvc.GetMasterStatus().Returns(new MasterGateStatus(false, "Down for maintenance"));
await _middleware.InvokeAsync(context, _localSvc, _masterSvc);
await _next.DidNotReceive().Invoke(Arg.Any<HttpContext>());
context.Response.StatusCode.Should().Be(StatusCodes.Status503ServiceUnavailable);
}
[Fact]
public async Task InvokeAsync_DoesNotCheckLocalGate_WhenMasterGateBlocks()
{
var context = new DefaultHttpContext();
context.Response.Body = new MemoryStream();
_masterSvc.GetMasterStatus().Returns(new MasterGateStatus(false, null));
await _middleware.InvokeAsync(context, _localSvc, _masterSvc);
await _localSvc.DidNotReceive().IsAvailableAsync();
}
[Fact]
public async Task InvokeAsync_Returns503_WhenLocalGateBlocksAndMasterPasses()
{
var context = new DefaultHttpContext();
context.Response.Body = new MemoryStream();
_localSvc.IsAvailableAsync().Returns(AvailabilityStatus.NotAvailable);
await _middleware.InvokeAsync(context, _localSvc, _masterSvc);
await _next.DidNotReceive().Invoke(Arg.Any<HttpContext>());
context.Response.StatusCode.Should().Be(StatusCodes.Status503ServiceUnavailable);
}
[Fact]
public async Task InvokeAsync_BypassesMasterAndLocalGate_ForMasterEndpoints()
{
var context = new DefaultHttpContext();
context.Request.Path = "/api/v1/master/register";
_masterSvc.GetMasterStatus().Returns(new MasterGateStatus(false, null));
_localSvc.IsAvailableAsync().Returns(AvailabilityStatus.NotAvailable);
await _middleware.InvokeAsync(context, _localSvc, _masterSvc);
await _next.Received(1).Invoke(context);
_masterSvc.DidNotReceive().GetMasterStatus();
}
[Fact]
public async Task InvokeAsync_BypassesBothGates_ForMasterStatusEndpoint()
{
var context = new DefaultHttpContext();
context.Request.Path = "/api/v1/master/status";
_masterSvc.GetMasterStatus().Returns(new MasterGateStatus(false, null));
await _middleware.InvokeAsync(context, _localSvc, _masterSvc);
await _next.Received(1).Invoke(context);
}
[Fact]
public async Task InvokeAsync_BypassesBothGates_WhenAdminJwtPresent()
{
var context = new DefaultHttpContext();
context.Request.Headers.Authorization = $"Bearer {CreateJwtWithRole("Owner")}";
_masterSvc.GetMasterStatus().Returns(new MasterGateStatus(false, null));
_localSvc.IsAvailableAsync().Returns(AvailabilityStatus.NotAvailable);
await _middleware.InvokeAsync(context, _localSvc, _masterSvc);
await _next.Received(1).Invoke(context);
_masterSvc.DidNotReceive().GetMasterStatus();
}
[Fact]
public async Task InvokeAsync_DoesNotBypass_WhenUserRoleJwtAndMasterBlocks()
{
var context = new DefaultHttpContext();
context.Response.Body = new MemoryStream();
context.Request.Headers.Authorization = $"Bearer {CreateJwtWithRole("User")}";
_masterSvc.GetMasterStatus().Returns(new MasterGateStatus(false, null));
await _middleware.InvokeAsync(context, _localSvc, _masterSvc);
await _next.DidNotReceive().Invoke(Arg.Any<HttpContext>());
context.Response.StatusCode.Should().Be(StatusCodes.Status503ServiceUnavailable);
}
private static string CreateJwtWithRole(string role)
{
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("test-signing-key-at-least-32-chars-long!"));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
claims: [new Claim(ClaimTypes.Role, role)],
expires: DateTime.UtcNow.AddHours(1),
signingCredentials: creds);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
@@ -8,6 +8,7 @@ using Microsoft.IdentityModel.Tokens;
using NSubstitute;
using SlpModularCms.Core.Availability;
using SlpModularCms.Modules.Availability.Middleware;
using SlpModularCms.Modules.Availability.Services;
using Xunit;
namespace SlpModularCms.Modules.Availability.Tests;
@@ -15,14 +16,19 @@ namespace SlpModularCms.Modules.Availability.Tests;
public class AvailabilityMiddlewareTests
{
private readonly IAvailabilityService _service;
private readonly IMasterAvailabilityService _masterService;
private readonly AvailabilityMiddleware _middleware;
private readonly RequestDelegate _next;
public AvailabilityMiddlewareTests()
{
_service = Substitute.For<IAvailabilityService>();
_masterService = Substitute.For<IMasterAvailabilityService>();
_next = Substitute.For<RequestDelegate>();
_middleware = new AvailabilityMiddleware(_next, NullLogger<AvailabilityMiddleware>.Instance);
// Master gate passes by default in these local gate tests
_masterService.GetMasterStatus().Returns(new MasterGateStatus(true, null));
}
[Fact]
@@ -31,7 +37,7 @@ public class AvailabilityMiddlewareTests
var context = new DefaultHttpContext();
_service.IsAvailableAsync().Returns(AvailabilityStatus.Available);
await _middleware.InvokeAsync(context, _service);
await _middleware.InvokeAsync(context, _service, _masterService);
await _next.Received(1).Invoke(context);
}
@@ -43,7 +49,7 @@ public class AvailabilityMiddlewareTests
context.Response.Body = new MemoryStream();
_service.IsAvailableAsync().Returns(AvailabilityStatus.NotAvailable);
await _middleware.InvokeAsync(context, _service);
await _middleware.InvokeAsync(context, _service, _masterService);
await _next.DidNotReceive().Invoke(Arg.Any<HttpContext>());
context.Response.StatusCode.Should().Be(StatusCodes.Status503ServiceUnavailable);
@@ -56,7 +62,7 @@ public class AvailabilityMiddlewareTests
context.Request.Path = "/api/v1/Availability/status";
_service.IsAvailableAsync().Returns(AvailabilityStatus.NotAvailable);
await _middleware.InvokeAsync(context, _service);
await _middleware.InvokeAsync(context, _service, _masterService);
await _next.Received(1).Invoke(context);
}
@@ -68,7 +74,7 @@ public class AvailabilityMiddlewareTests
context.Request.Path = "/api/v1/Auth/login";
_service.IsAvailableAsync().Returns(AvailabilityStatus.NotAvailable);
await _middleware.InvokeAsync(context, _service);
await _middleware.InvokeAsync(context, _service, _masterService);
await _next.Received(1).Invoke(context);
}
@@ -80,7 +86,7 @@ public class AvailabilityMiddlewareTests
context.Request.Path = "/api/v1/Setup/status";
_service.IsAvailableAsync().Returns(AvailabilityStatus.NotAvailable);
await _middleware.InvokeAsync(context, _service);
await _middleware.InvokeAsync(context, _service, _masterService);
await _next.Received(1).Invoke(context);
}
@@ -92,7 +98,7 @@ public class AvailabilityMiddlewareTests
context.Response.Body = new MemoryStream();
_service.IsAvailableAsync().Returns(AvailabilityStatus.Maintenance);
await _middleware.InvokeAsync(context, _service);
await _middleware.InvokeAsync(context, _service, _masterService);
await _next.DidNotReceive().Invoke(Arg.Any<HttpContext>());
context.Response.StatusCode.Should().Be(StatusCodes.Status503ServiceUnavailable);
@@ -105,7 +111,7 @@ public class AvailabilityMiddlewareTests
context.Request.Headers.Authorization = $"Bearer {CreateJwtWithRole("Owner")}";
_service.IsAvailableAsync().Returns(AvailabilityStatus.Maintenance);
await _middleware.InvokeAsync(context, _service);
await _middleware.InvokeAsync(context, _service, _masterService);
await _next.Received(1).Invoke(context);
}
@@ -117,7 +123,7 @@ public class AvailabilityMiddlewareTests
context.Request.Headers.Authorization = $"Bearer {CreateJwtWithRole("Administrator")}";
_service.IsAvailableAsync().Returns(AvailabilityStatus.Maintenance);
await _middleware.InvokeAsync(context, _service);
await _middleware.InvokeAsync(context, _service, _masterService);
await _next.Received(1).Invoke(context);
}
@@ -130,7 +136,7 @@ public class AvailabilityMiddlewareTests
context.Request.Headers.Authorization = $"Bearer {CreateJwtWithRole("User")}";
_service.IsAvailableAsync().Returns(AvailabilityStatus.Maintenance);
await _middleware.InvokeAsync(context, _service);
await _middleware.InvokeAsync(context, _service, _masterService);
await _next.DidNotReceive().Invoke(Arg.Any<HttpContext>());
context.Response.StatusCode.Should().Be(StatusCodes.Status503ServiceUnavailable);
@@ -143,7 +149,7 @@ public class AvailabilityMiddlewareTests
context.Response.Body = new MemoryStream();
_service.IsAvailableAsync().Returns(AvailabilityStatus.NotAvailable);
await _middleware.InvokeAsync(context, _service);
await _middleware.InvokeAsync(context, _service, _masterService);
await _next.DidNotReceive().Invoke(Arg.Any<HttpContext>());
}
@@ -156,7 +162,7 @@ public class AvailabilityMiddlewareTests
context.Request.Headers.Authorization = "Bearer not-a-valid-jwt";
_service.IsAvailableAsync().Returns(AvailabilityStatus.NotAvailable);
await _middleware.InvokeAsync(context, _service);
await _middleware.InvokeAsync(context, _service, _masterService);
await _next.DidNotReceive().Invoke(Arg.Any<HttpContext>());
}
@@ -2,8 +2,11 @@ using System.Security.Claims;
using FluentAssertions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using NSubstitute;
using SlpModularCms.Core.Availability;
using SlpModularCms.Core.Data;
using SlpModularCms.Modules.Availability.Controllers;
using SlpModularCms.Modules.Availability.Services;
@@ -66,4 +69,29 @@ public class AvailabilityControllerTests
result.Should().BeOfType<BadRequestObjectResult>();
}
[Fact]
public async Task UpdateStatus_ReturnsOk_WhenServiceIsPersistentAvailabilityService()
{
var dbOptions = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString())
.Options;
using var context = new ApplicationDbContext(dbOptions);
var availabilityOptions = Substitute.For<IOptions<AvailabilityOptions>>();
availabilityOptions.Value.Returns(new AvailabilityOptions { CircuitBreakerSeconds = 30 });
var persistentService = new PersistentAvailabilityService(context, availabilityOptions);
var controller = new AvailabilityController(persistentService);
var httpContext = new DefaultHttpContext();
httpContext.User = new ClaimsPrincipal(
new ClaimsIdentity([new Claim(ClaimTypes.Name, "admin@test.com")], "TestAuth"));
controller.ControllerContext = new ControllerContext { HttpContext = httpContext };
var result = await controller.UpdateStatus(
new UpdateStatusRequest(AvailabilityStatus.Maintenance, "Test maintenance"));
result.Should().BeOfType<OkResult>();
}
}
@@ -0,0 +1,131 @@
using FluentAssertions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NSubstitute;
using SlpModularCms.Modules.Availability.Controllers;
using SlpModularCms.Modules.Availability.Models;
using SlpModularCms.Modules.Availability.Services;
namespace SlpModularCms.Modules.Availability.Tests.Controllers;
public class MasterControllerTests
{
private readonly IMasterAvailabilityService _svc;
private readonly MasterController _controller;
public MasterControllerTests()
{
_svc = Substitute.For<IMasterAvailabilityService>();
_controller = new MasterController(_svc);
_controller.ControllerContext = new ControllerContext
{
HttpContext = new DefaultHttpContext()
};
}
private void SetApiKeyHeader(string? value)
{
if (value != null)
_controller.HttpContext.Request.Headers["X-Master-Api-Key"] = value;
}
// --- Register ---
[Fact]
public async Task Register_Returns200_WhenSuccess()
{
SetApiKeyHeader("key123");
_svc.RegisterAsync("https://master.example.com", "key123").Returns(true);
var result = await _controller.Register(new RegisterMasterRequest("https://master.example.com"));
result.Should().BeOfType<OkResult>();
}
[Fact]
public async Task Register_Returns401_WhenKeyMismatch()
{
SetApiKeyHeader("wrong-key");
_svc.RegisterAsync(Arg.Any<string>(), "wrong-key").Returns(false);
var result = await _controller.Register(new RegisterMasterRequest("https://master.example.com"));
result.Should().BeOfType<UnauthorizedResult>();
}
[Fact]
public async Task Register_Returns401_WhenMissingHeader()
{
var result = await _controller.Register(new RegisterMasterRequest("https://master.example.com"));
result.Should().BeOfType<UnauthorizedResult>();
await _svc.DidNotReceive().RegisterAsync(Arg.Any<string>(), Arg.Any<string>());
}
// --- PushStatus ---
[Fact]
public async Task PushStatus_Returns200_WhenSuccess()
{
SetApiKeyHeader("key123");
_svc.PushStatusAsync("key123", false, "maintenance").Returns(true);
var result = await _controller.PushStatus(new PushStatusRequest(false, "maintenance"));
result.Should().BeOfType<OkResult>();
}
[Fact]
public async Task PushStatus_Returns401_WhenKeyMismatch()
{
SetApiKeyHeader("wrong");
_svc.PushStatusAsync("wrong", Arg.Any<bool>(), Arg.Any<string?>()).Returns(false);
var result = await _controller.PushStatus(new PushStatusRequest(false, null));
result.Should().BeOfType<UnauthorizedResult>();
}
[Fact]
public async Task PushStatus_Returns401_WhenMissingHeader()
{
var result = await _controller.PushStatus(new PushStatusRequest(false, null));
result.Should().BeOfType<UnauthorizedResult>();
await _svc.DidNotReceive().PushStatusAsync(Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<string?>());
}
// --- GetRegisteredUrl ---
[Fact]
public async Task GetRegisteredUrl_Returns200WithUrl_WhenSuccess()
{
SetApiKeyHeader("key123");
_svc.GetRegisteredUrlAsync("key123").Returns("https://master.example.com");
var result = await _controller.GetRegisteredUrl();
var ok = result.Should().BeOfType<OkObjectResult>().Subject;
ok.Value.Should().BeEquivalentTo(new { MasterUrl = "https://master.example.com" });
}
[Fact]
public async Task GetRegisteredUrl_Returns401_WhenKeyMismatch()
{
SetApiKeyHeader("wrong");
_svc.GetRegisteredUrlAsync("wrong").Returns((string?)null);
var result = await _controller.GetRegisteredUrl();
result.Should().BeOfType<UnauthorizedResult>();
}
[Fact]
public async Task GetRegisteredUrl_Returns401_WhenMissingHeader()
{
var result = await _controller.GetRegisteredUrl();
result.Should().BeOfType<UnauthorizedResult>();
await _svc.DidNotReceive().GetRegisteredUrlAsync(Arg.Any<string>());
}
}
@@ -98,4 +98,18 @@ public class PersistentAvailabilityServiceTests
details.Status.Should().Be(AvailabilityStatus.Available); // Fallback
}
[Fact]
public async Task UpdateStatusAsync_UpdatesExistingRecord_WhenCalledTwice()
{
await _service.UpdateStatusAsync(AvailabilityStatus.Maintenance, "First update", "Admin1");
await _service.UpdateStatusAsync(AvailabilityStatus.Available, "Reset", "Admin2");
var status = await _service.IsAvailableAsync();
status.Should().Be(AvailabilityStatus.Available);
var dbState = await _context.AvailabilityStates.SingleAsync();
dbState.Status.Should().Be(AvailabilityStatus.Available);
dbState.UpdatedBy.Should().Be("Admin2");
}
}
@@ -0,0 +1,99 @@
using FluentAssertions;
using Microsoft.EntityFrameworkCore;
using SlpModularCms.Modules.Availability.Data;
using SlpModularCms.Modules.Availability.Data.Entities;
using SlpModularCms.Modules.Availability.Repositories;
namespace SlpModularCms.Modules.Availability.Tests.Repositories;
public class MasterRegistrationRepositoryTests
{
private static AvailabilityDbContext CreateContext()
{
var options = new DbContextOptionsBuilder<AvailabilityDbContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString())
.Options;
return new AvailabilityDbContext(options);
}
[Fact]
public async Task GetAsync_ReturnsNull_WhenNoRegistrationExists()
{
await using var context = CreateContext();
var repo = new MasterRegistrationRepository(context);
var result = await repo.GetAsync();
result.Should().BeNull();
}
[Fact]
public async Task GetAsync_ReturnsRegistration_WhenExists()
{
await using var context = CreateContext();
var reg = new MasterRegistration
{
Id = MasterRegistration.SingletonId,
MasterUrl = "https://master.example.com",
ApiKey = "enc:key123",
RegisteredAt = DateTimeOffset.UtcNow
};
context.MasterRegistrations.Add(reg);
await context.SaveChangesAsync();
var repo = new MasterRegistrationRepository(context);
var result = await repo.GetAsync();
result.Should().NotBeNull();
result!.MasterUrl.Should().Be("https://master.example.com");
}
[Fact]
public async Task AddAsync_PersistsRegistration()
{
await using var context = CreateContext();
var repo = new MasterRegistrationRepository(context);
var reg = new MasterRegistration
{
Id = MasterRegistration.SingletonId,
MasterUrl = "https://master.example.com",
ApiKey = "enc:key123",
RegisteredAt = DateTimeOffset.UtcNow
};
await repo.AddAsync(reg);
await repo.SaveChangesAsync();
context.MasterRegistrations.Should().HaveCount(1);
}
[Fact]
public async Task Update_ModifiesExistingRegistration()
{
await using var context = CreateContext();
var reg = new MasterRegistration
{
Id = MasterRegistration.SingletonId,
MasterUrl = "https://old.example.com",
ApiKey = "enc:key",
RegisteredAt = DateTimeOffset.UtcNow
};
context.MasterRegistrations.Add(reg);
await context.SaveChangesAsync();
var repo = new MasterRegistrationRepository(context);
var existing = await repo.GetAsync();
existing!.MasterUrl = "https://new.example.com";
repo.Update(existing);
await repo.SaveChangesAsync();
var updated = await context.MasterRegistrations.FindAsync(MasterRegistration.SingletonId);
updated!.MasterUrl.Should().Be("https://new.example.com");
}
[Fact]
public void SingletonId_IsExpectedValue()
{
MasterRegistration.SingletonId.Should().Be(new Guid("00000000-0000-0000-0000-000000000001"));
}
}
@@ -0,0 +1,60 @@
using FluentAssertions;
using Microsoft.AspNetCore.DataProtection;
using SlpModularCms.Modules.Availability.Services;
namespace SlpModularCms.Modules.Availability.Tests.Services;
public class MasterApiKeyProtectorTests
{
private static MasterApiKeyProtector CreateProtector()
{
var provider = new EphemeralDataProtectionProvider();
return new MasterApiKeyProtector(provider);
}
[Fact]
public void Protect_Unprotect_RoundTrip_ReturnsOriginalValue()
{
var protector = CreateProtector();
var plain = "my-secret-api-key";
var encrypted = protector.Protect(plain);
var decrypted = protector.Unprotect(encrypted);
decrypted.Should().Be(plain);
}
[Fact]
public void Protect_ReturnsNonEmptyString_DifferentFromInput()
{
var protector = CreateProtector();
var plain = "my-secret-api-key";
var encrypted = protector.Protect(plain);
encrypted.Should().NotBeNullOrEmpty();
encrypted.Should().NotBe(plain);
}
[Fact]
public void Unprotect_ReturnsNull_WhenGivenInvalidCiphertext()
{
var protector = CreateProtector();
var result = protector.Unprotect("this-is-not-valid-ciphertext");
result.Should().BeNull();
}
[Fact]
public void Unprotect_ReturnsNull_WhenProtectedWithDifferentProvider()
{
var protector1 = CreateProtector();
var protector2 = CreateProtector();
var encrypted = protector1.Protect("key");
var result = protector2.Unprotect(encrypted);
result.Should().BeNull();
}
}
@@ -0,0 +1,240 @@
using FluentAssertions;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using SlpModularCms.Modules.Availability.Data.Entities;
using SlpModularCms.Modules.Availability.Repositories;
using SlpModularCms.Modules.Availability.Services;
namespace SlpModularCms.Modules.Availability.Tests.Services;
public class MasterAvailabilityServiceTests : IDisposable
{
private readonly IMasterRegistrationRepository _repo;
private readonly IMasterApiKeyProtector _protector;
private readonly MasterAvailabilityService _svc;
public MasterAvailabilityServiceTests()
{
_repo = Substitute.For<IMasterRegistrationRepository>();
_protector = Substitute.For<IMasterApiKeyProtector>();
var deps = new MasterAvailabilityServiceDependencies(
_repo,
_protector,
NullLogger<MasterAvailabilityService>.Instance);
_svc = new MasterAvailabilityService(deps);
MasterAvailabilityService.ResetStaticCacheForTest();
}
public void Dispose() => MasterAvailabilityService.ResetStaticCacheForTest();
// --- RegisterAsync ---
[Fact]
public async Task RegisterAsync_CreatesNewRegistration_WhenNoneExists()
{
_repo.GetAsync().Returns((MasterRegistration?)null);
_protector.Protect("key123").Returns("enc:key123");
var result = await _svc.RegisterAsync("https://master.example.com", "key123");
result.Should().BeTrue();
await _repo.Received(1).AddAsync(Arg.Is<MasterRegistration>(r =>
r.MasterUrl == "https://master.example.com" &&
r.ApiKey == "enc:key123" &&
r.Id == MasterRegistration.SingletonId));
await _repo.Received(1).SaveChangesAsync();
}
[Fact]
public async Task RegisterAsync_ReturnsTrue_OnReregistrationWithMatchingKey()
{
var existing = new MasterRegistration
{
Id = MasterRegistration.SingletonId,
MasterUrl = "https://old.example.com",
ApiKey = "enc:key123",
RegisteredAt = DateTimeOffset.UtcNow
};
_repo.GetAsync().Returns(existing);
_protector.Unprotect("enc:key123").Returns("key123");
var result = await _svc.RegisterAsync("https://new.example.com", "key123");
result.Should().BeTrue();
existing.MasterUrl.Should().Be("https://new.example.com");
_repo.Received(1).Update(existing);
await _repo.Received(1).SaveChangesAsync();
}
[Fact]
public async Task RegisterAsync_ReturnsFalse_WhenKeyMismatch()
{
var existing = new MasterRegistration
{
Id = MasterRegistration.SingletonId,
MasterUrl = "https://master.example.com",
ApiKey = "enc:key123",
RegisteredAt = DateTimeOffset.UtcNow
};
_repo.GetAsync().Returns(existing);
_protector.Unprotect("enc:key123").Returns("key123");
var result = await _svc.RegisterAsync("https://master.example.com", "wrong-key");
result.Should().BeFalse();
await _repo.DidNotReceive().SaveChangesAsync();
}
[Fact]
public async Task RegisterAsync_ReturnsFalse_WhenDecryptionFails()
{
var existing = new MasterRegistration
{
Id = MasterRegistration.SingletonId,
MasterUrl = "https://master.example.com",
ApiKey = "corrupt",
RegisteredAt = DateTimeOffset.UtcNow
};
_repo.GetAsync().Returns(existing);
_protector.Unprotect("corrupt").Returns((string?)null);
var result = await _svc.RegisterAsync("https://master.example.com", "key123");
result.Should().BeFalse();
}
// --- PushStatusAsync ---
[Fact]
public async Task PushStatusAsync_UpdatesStaticCache_WhenKeyValid()
{
var existing = new MasterRegistration
{
Id = MasterRegistration.SingletonId,
MasterUrl = "https://master.example.com",
ApiKey = "enc:key",
RegisteredAt = DateTimeOffset.UtcNow
};
_repo.GetAsync().Returns(existing);
_protector.Unprotect("enc:key").Returns("key");
var result = await _svc.PushStatusAsync("key", false, "Under maintenance");
result.Should().BeTrue();
var status = _svc.GetMasterStatus();
status.IsAvailable.Should().BeFalse();
status.DisableMessage.Should().Be("Under maintenance");
}
[Fact]
public async Task PushStatusAsync_ReturnsFalse_WhenNoRegistration()
{
_repo.GetAsync().Returns((MasterRegistration?)null);
var result = await _svc.PushStatusAsync("key", false, null);
result.Should().BeFalse();
await _repo.DidNotReceive().SaveChangesAsync();
}
[Fact]
public async Task PushStatusAsync_ReturnsFalse_WhenKeyMismatch()
{
var existing = new MasterRegistration
{
Id = MasterRegistration.SingletonId,
MasterUrl = "https://master.example.com",
ApiKey = "enc:key",
RegisteredAt = DateTimeOffset.UtcNow
};
_repo.GetAsync().Returns(existing);
_protector.Unprotect("enc:key").Returns("correct-key");
var result = await _svc.PushStatusAsync("wrong-key", false, null);
result.Should().BeFalse();
}
// --- GetRegisteredUrlAsync ---
[Fact]
public async Task GetRegisteredUrlAsync_ReturnsMasterUrl_WhenKeyValid()
{
var existing = new MasterRegistration
{
Id = MasterRegistration.SingletonId,
MasterUrl = "https://master.example.com",
ApiKey = "enc:key",
RegisteredAt = DateTimeOffset.UtcNow
};
_repo.GetAsync().Returns(existing);
_protector.Unprotect("enc:key").Returns("key");
var result = await _svc.GetRegisteredUrlAsync("key");
result.Should().Be("https://master.example.com");
_repo.Received(1).Update(existing);
await _repo.Received(1).SaveChangesAsync();
}
[Fact]
public async Task GetRegisteredUrlAsync_ReturnsNull_WhenNoRegistration()
{
_repo.GetAsync().Returns((MasterRegistration?)null);
var result = await _svc.GetRegisteredUrlAsync("key");
result.Should().BeNull();
}
[Fact]
public async Task GetRegisteredUrlAsync_ReturnsNull_WhenKeyMismatch()
{
var existing = new MasterRegistration
{
Id = MasterRegistration.SingletonId,
MasterUrl = "https://master.example.com",
ApiKey = "enc:key",
RegisteredAt = DateTimeOffset.UtcNow
};
_repo.GetAsync().Returns(existing);
_protector.Unprotect("enc:key").Returns("correct-key");
var result = await _svc.GetRegisteredUrlAsync("wrong-key");
result.Should().BeNull();
}
// --- GetMasterStatus ---
[Fact]
public async Task GetMasterStatus_ReflectsLastPushedStatus()
{
var existing = new MasterRegistration
{
Id = MasterRegistration.SingletonId,
MasterUrl = "https://master.example.com",
ApiKey = "enc:key",
RegisteredAt = DateTimeOffset.UtcNow
};
_repo.GetAsync().Returns(existing);
_protector.Unprotect("enc:key").Returns("key");
await _svc.PushStatusAsync("key", false, "Down for maintenance");
var status = _svc.GetMasterStatus();
status.IsAvailable.Should().BeFalse();
status.DisableMessage.Should().Be("Down for maintenance");
}
[Fact]
public void GetMasterStatus_ReturnsAvailableByDefault()
{
var status = _svc.GetMasterStatus();
status.IsAvailable.Should().BeTrue();
status.DisableMessage.Should().BeNull();
}
}
@@ -10,6 +10,7 @@
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.4" />
<PackageReference Include="FluentAssertions" Version="8.10.0" />
<PackageReference Include="Microsoft.AspNetCore.DataProtection" Version="10.0.9" />
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.3.11" />
<PackageReference Include="Microsoft.AspNetCore.TestHost" Version="10.0.9" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="10.0.9" />