mirror of
https://github.com/azaion/satellite-provider.git
synced 2026-06-21 21:31:14 +00:00
c396740644
AZ-491 (3 SP): eliminate the cycle-2 duplicate of JWT-minting logic that existed in both SatelliteProvider.Tests/TestUtilities/ JwtTokenFactory.cs (unit-side) and SatelliteProvider.IntegrationTests/ JwtTestHelpers.cs (integration-side), where the same Expires < NotBefore bug needed parallel fixes in commitsf64d0d7+11b7074. Option A chosen: new SatelliteProvider.TestSupport class library (no test framework) holds the canonical JwtTokenFactory.Create / CreateExpired / TamperSignature. Both Tests and IntegrationTests consume it via ProjectReference; production projects (Api, Common, DataAccess, Services.*) cannot depend on it. The notBefore-shift workaround is preserved with an inline regression-prevention comment back-referencing the cycle-2 fix commits. SatelliteProvider.IntegrationTests/JwtTestHelpers.cs is stripped to runner-only concerns: ResolveSecretOrThrow, AttachDefaultAuthorization, and the DefaultSubject = "integration-tests" constant. Call sites in Program.cs, JwtIntegrationTests.cs, and UavUploadTests.cs (10 sites) switched to JwtTokenFactory.* with JwtTestHelpers.DefaultSubject explicitly passed for the runner subject - behavior parity preserved. Dockerfile for IntegrationTests gets the new TestSupport csproj in its pre-restore COPY layer. Api Dockerfile unchanged (TestSupport is NOT a production dependency). A new code-review SKILL.md Phase 6 checklist row flags near-identical helper logic across test projects as a Medium / Maintainability finding with explicit cycle-2 retro back-reference, so this whole pattern stops at one occurrence. module-layout.md adds a TestSupport Shared/Cross-Cutting entry documenting the production-isolation invariant. tests_unit.md + tests_integration.md updated to describe the consolidated layout. sln updated. Test-suite gate (AC-2 + AC-3) deferred to Step 16 Final Test Run per implement-skill convention. Per-batch review verdict: PASS_WITH_WARNINGS with 1 Low (pre-existing 7.0.3 version pin preserved verbatim from cycle-2 IntegrationTests csproj for parity; not blocking; deferred bump). Co-authored-by: Cursor <cursoragent@cursor.com>
153 lines
5.5 KiB
C#
153 lines
5.5 KiB
C#
using System.IdentityModel.Tokens.Jwt;
|
|
using FluentAssertions;
|
|
using Microsoft.AspNetCore.Authentication;
|
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Options;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
using SatelliteProvider.Api.Authentication;
|
|
using SatelliteProvider.TestSupport;
|
|
using AuthExtensions = SatelliteProvider.Api.Authentication.AuthenticationServiceCollectionExtensions;
|
|
|
|
namespace SatelliteProvider.Tests.Authentication;
|
|
|
|
public class AuthenticationServiceCollectionExtensionsTests : IDisposable
|
|
{
|
|
private const string ValidSecret = "test-secret-that-is-definitely-longer-than-32-bytes";
|
|
private readonly string? _originalEnv;
|
|
|
|
public AuthenticationServiceCollectionExtensionsTests()
|
|
{
|
|
_originalEnv = Environment.GetEnvironmentVariable(AuthExtensions.JwtSecretEnvVar);
|
|
Environment.SetEnvironmentVariable(AuthExtensions.JwtSecretEnvVar, null);
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
Environment.SetEnvironmentVariable(AuthExtensions.JwtSecretEnvVar, _originalEnv);
|
|
GC.SuppressFinalize(this);
|
|
}
|
|
|
|
[Fact]
|
|
public void AddSatelliteJwt_RegistersJwtBearerScheme()
|
|
{
|
|
// Arrange
|
|
var services = new ServiceCollection();
|
|
services.AddLogging();
|
|
var configuration = BuildConfiguration(("Jwt:Secret", ValidSecret));
|
|
|
|
// Act
|
|
services.AddSatelliteJwt(configuration);
|
|
var provider = services.BuildServiceProvider();
|
|
var schemeProvider = provider.GetRequiredService<IAuthenticationSchemeProvider>();
|
|
var scheme = schemeProvider.GetSchemeAsync(JwtBearerDefaults.AuthenticationScheme).GetAwaiter().GetResult();
|
|
|
|
// Assert
|
|
scheme.Should().NotBeNull("JwtBearer scheme should be registered");
|
|
scheme!.HandlerType.Should().Be(typeof(JwtBearerHandler));
|
|
}
|
|
|
|
[Fact]
|
|
public void AddSatelliteJwt_ConfiguresTokenValidationParameters_AsPerContract()
|
|
{
|
|
// Arrange
|
|
var services = new ServiceCollection();
|
|
services.AddLogging();
|
|
var configuration = BuildConfiguration(("Jwt:Secret", ValidSecret));
|
|
|
|
// Act
|
|
services.AddSatelliteJwt(configuration);
|
|
var provider = services.BuildServiceProvider();
|
|
var options = provider.GetRequiredService<IOptionsMonitor<JwtBearerOptions>>().Get(JwtBearerDefaults.AuthenticationScheme);
|
|
|
|
// Assert
|
|
var p = options.TokenValidationParameters;
|
|
p.ValidateIssuerSigningKey.Should().BeTrue();
|
|
p.ValidateLifetime.Should().BeTrue();
|
|
p.ValidateIssuer.Should().BeFalse();
|
|
p.ValidateAudience.Should().BeFalse();
|
|
p.RequireSignedTokens.Should().BeTrue();
|
|
p.RequireExpirationTime.Should().BeTrue();
|
|
p.ClockSkew.Should().Be(TimeSpan.FromSeconds(30));
|
|
p.IssuerSigningKey.Should().BeOfType<SymmetricSecurityKey>();
|
|
}
|
|
|
|
[Fact]
|
|
public void AddSatelliteJwt_ThrowsOnMissingSecret()
|
|
{
|
|
// Arrange
|
|
var services = new ServiceCollection();
|
|
var configuration = BuildConfiguration();
|
|
|
|
// Act
|
|
var act = () => services.AddSatelliteJwt(configuration);
|
|
|
|
// Assert
|
|
act.Should().Throw<InvalidOperationException>()
|
|
.WithMessage("*JWT secret is not configured*");
|
|
}
|
|
|
|
[Fact]
|
|
public void AddSatelliteJwt_ThrowsOnEmptySecret()
|
|
{
|
|
// Arrange
|
|
var services = new ServiceCollection();
|
|
var configuration = BuildConfiguration(("Jwt:Secret", ""));
|
|
|
|
// Act
|
|
var act = () => services.AddSatelliteJwt(configuration);
|
|
|
|
// Assert
|
|
act.Should().Throw<InvalidOperationException>()
|
|
.WithMessage("*JWT secret is not configured*");
|
|
}
|
|
|
|
[Fact]
|
|
public void AddSatelliteJwt_ThrowsOnShortSecret()
|
|
{
|
|
// Arrange
|
|
var services = new ServiceCollection();
|
|
var configuration = BuildConfiguration(("Jwt:Secret", "too-short-secret"));
|
|
|
|
// Act
|
|
var act = () => services.AddSatelliteJwt(configuration);
|
|
|
|
// Assert
|
|
act.Should().Throw<InvalidOperationException>()
|
|
.WithMessage("*at least 32 bytes*");
|
|
}
|
|
|
|
[Fact]
|
|
public void AddSatelliteJwt_PrefersEnvironmentVariableOverConfiguration()
|
|
{
|
|
// Arrange
|
|
const string envSecret = "env-secret-also-longer-than-thirty-two-bytes-for-hmac";
|
|
Environment.SetEnvironmentVariable(AuthExtensions.JwtSecretEnvVar, envSecret);
|
|
var services = new ServiceCollection();
|
|
services.AddLogging();
|
|
var configuration = BuildConfiguration(("Jwt:Secret", "config-secret-also-32-bytes-long-aaaaaaaaaa"));
|
|
|
|
// Act
|
|
services.AddSatelliteJwt(configuration);
|
|
var provider = services.BuildServiceProvider();
|
|
var options = provider.GetRequiredService<IOptionsMonitor<JwtBearerOptions>>().Get(JwtBearerDefaults.AuthenticationScheme);
|
|
var token = JwtTokenFactory.Create(envSecret);
|
|
var handler = new JwtSecurityTokenHandler();
|
|
var act = () => handler.ValidateToken(token, options.TokenValidationParameters, out _);
|
|
|
|
// Assert
|
|
act.Should().NotThrow("token signed with env secret must validate when env secret takes precedence");
|
|
}
|
|
|
|
private static IConfiguration BuildConfiguration(params (string Key, string Value)[] pairs)
|
|
{
|
|
var builder = new ConfigurationBuilder();
|
|
if (pairs.Length > 0)
|
|
{
|
|
builder.AddInMemoryCollection(pairs.Select(p => new KeyValuePair<string, string?>(p.Key, p.Value)));
|
|
}
|
|
return builder.Build();
|
|
}
|
|
}
|