elsa-core/test/integration/Elsa.ExternalAuthentication.IntegrationTests/Compatibility/LegacyIdentityEndpointTests.cs
Sipke Schoorstra 1b38c3511d
fix: stop two silent serialization and test-isolation traps (#7969)
* fix: stop two silent serialization and test-isolation traps

Two follow-ups from #7957.

ExternalAuthentication tests: the same process-global
EndpointSecurityOptions.SecurityIsEnabled race the shells API tests had,
across the six classes in that assembly that build an endpoint host —
five setting it to false and IdentityLinkAuthorizationTests to true.
Unlike the shells case these all call UseAuthorization(), so it does not
surface as a missing-middleware error: anonymous endpoints answer
401/403, and the authorization test's endpoints come back AllowAnonymous
and stop enforcing what it asserts. A module initializer cannot fix it
since the assembly genuinely needs both values, so the six now share one
collection with DisableParallelization. They are also the only six that
build a host, so nothing else can observe a leaked value.

Unaliased payloads: a payload whose type has no registered serialization
alias is written without a _type discriminator and read back as an
ExpandoObject whose keys carry the state serializer's camel-case naming
policy, so a consumer that published Status finds status. The
degradation is deliberate — the alias registry is an allow-list that
keeps arbitrary CLR type names out of deserialization — but it was
silent. It is now reported once per type, naming the type and both
lossless alternatives, and PublishEvent.Payload documents them. Measured
across the integration suite, only genuine user payload types reach this
path, so the warning does not fire for Elsa's own types.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix: check the log level before claiming the once-per-type warning slot

WarnAboutUnaliasedType claimed a type's single report via TryAdd before
LogWarning applied its level filter, so a type first serialized while
Warning was disabled spent its slot on a call that logged nothing and
then stayed silent forever, including after the level was raised at
runtime. Check IsEnabled first, so the slot is only consumed by a report
that is actually emitted.

The regression test needs the capture to be the only logging provider:
IsEnabled on the composite logger is an OR across providers, so the test
builder's own xunit provider would otherwise keep Warning enabled
regardless of what the test asked for.

Reported by Greptile on #7969.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-21 00:36:11 +02:00

138 lines
6.3 KiB
C#

using System.Net;
using System.Net.Http.Json;
using System.Security.Claims;
using System.Text.Encodings.Web;
using System.Text.Json;
using Elsa.Identity.Contracts;
using Elsa.Identity.Constants;
using Elsa.Identity.Entities;
using Elsa.Identity.Models;
using FastEndpoints;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NSubstitute;
using Elsa.ExternalAuthentication.IntegrationTests.Fixtures;
namespace Elsa.ExternalAuthentication.IntegrationTests.Compatibility;
/// <summary>
/// Protects the existing direct local-credential contracts while the broker-local flow remains additive.
/// </summary>
[Collection(nameof(EndpointSecurityCollection))]
public sealed class LegacyIdentityEndpointTests : IAsyncLifetime
{
private readonly IUserCredentialsValidator _credentialsValidator = Substitute.For<IUserCredentialsValidator>();
private readonly IUserProvider _userProvider = Substitute.For<IUserProvider>();
private readonly IAccessTokenIssuer _tokenIssuer = Substitute.For<IAccessTokenIssuer>();
private WebApplication? _app;
private HttpClient? _client;
private bool _wasSecurityEnabled;
public async Task InitializeAsync()
{
_wasSecurityEnabled = EndpointSecurityOptions.SecurityIsEnabled;
EndpointSecurityOptions.SecurityIsEnabled = false;
var builder = WebApplication.CreateSlimBuilder();
builder.WebHost.UseTestServer();
builder.Services.AddFastEndpoints(options =>
{
options.Assemblies = [typeof(Elsa.Identity.Features.IdentityFeature).Assembly];
options.Filter = endpoint => endpoint.Namespace is "Elsa.Identity.Endpoints.Login" or "Elsa.Identity.Endpoints.RefreshToken";
});
builder.Services.AddSingleton(_credentialsValidator);
builder.Services.AddSingleton(_userProvider);
builder.Services.AddSingleton(_tokenIssuer);
builder.Services
.AddAuthentication()
.AddScheme<AuthenticationSchemeOptions, RefreshTokenAuthenticationHandler>(IdentityAuthenticationSchemes.RefreshToken, _ => { });
builder.Services.AddAuthorization();
_app = builder.Build();
_app.Use(async (context, next) =>
{
context.User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.Name, "admin")], "legacy-refresh"));
await next(context);
});
_app.UseAuthorization();
_app.UseFastEndpoints();
await _app.StartAsync();
_client = _app.GetTestClient();
}
public async Task DisposeAsync()
{
EndpointSecurityOptions.SecurityIsEnabled = _wasSecurityEnabled;
_client?.Dispose();
if (_app is not null)
{
await _app.StopAsync();
await _app.DisposeAsync();
}
}
[Fact]
public async Task IdentityLoginRetainsItsRouteCredentialValidationAndResponseShape()
{
var user = new User { Id = "user-a", Name = "admin" };
_credentialsValidator.ValidateAsync("admin", "password", Arg.Any<CancellationToken>()).Returns(user);
_tokenIssuer.IssueTokensAsync(user, Arg.Any<CancellationToken>()).Returns(new IssuedTokens("access-a", "refresh-a"));
var response = await _client!.PostAsJsonAsync("/identity/login", new { username = " admin ", password = " password " });
var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.True(document.RootElement.GetProperty("isAuthenticated").GetBoolean());
Assert.Equal("access-a", document.RootElement.GetProperty("accessToken").GetString());
Assert.Equal("refresh-a", document.RootElement.GetProperty("refreshToken").GetString());
await _credentialsValidator.Received(1).ValidateAsync("admin", "password", Arg.Any<CancellationToken>());
}
[Fact]
public async Task IdentityLoginRetainsItsGenericUnauthenticatedResponse()
{
_credentialsValidator.ValidateAsync("unknown", "wrong", Arg.Any<CancellationToken>()).Returns((User?)null);
var response = await _client!.PostAsJsonAsync("/identity/login", new { username = "unknown", password = "wrong" });
var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.False(document.RootElement.GetProperty("isAuthenticated").GetBoolean());
Assert.Equal(JsonValueKind.Null, document.RootElement.GetProperty("accessToken").ValueKind);
Assert.Equal(JsonValueKind.Null, document.RootElement.GetProperty("refreshToken").ValueKind);
}
[Fact]
public async Task IdentityRefreshTokenRetainsItsRouteAndLocalTokenContract()
{
var user = new User { Id = "user-a", Name = "admin" };
_userProvider.FindAsync(Arg.Is<UserFilter>(filter => filter.Name == "admin"), Arg.Any<CancellationToken>()).Returns(user);
_tokenIssuer.IssueTokensAsync(user, Arg.Any<CancellationToken>()).Returns(new IssuedTokens("access-b", "refresh-b"));
var response = await _client!.PostAsync("/identity/refresh-token", null);
var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.True(document.RootElement.GetProperty("isAuthenticated").GetBoolean());
Assert.Equal("access-b", document.RootElement.GetProperty("accessToken").GetString());
Assert.Equal("refresh-b", document.RootElement.GetProperty("refreshToken").GetString());
}
private sealed class RefreshTokenAuthenticationHandler(
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder) : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
var identity = new ClaimsIdentity([new Claim(ClaimTypes.Name, "admin")], Scheme.Name);
var ticket = new AuthenticationTicket(new ClaimsPrincipal(identity), Scheme.Name);
return Task.FromResult(AuthenticateResult.Success(ticket));
}
}
}