elsa-core/test/integration/Elsa.ExternalAuthentication.IntegrationTests/Links/IdentityLinkAuthorizationTests.cs

106 lines
5.1 KiB
C#
Raw Normal View History

refactor(auth)!: retire the legacy permission constants and duplicate descriptor types (#7987) * refactor(auth)!: retire the legacy permission constants and duplicate descriptors Completes the cutover started in #7980. Seven `<Module>Permissions` classes holding `verb:resource` strings are removed: AIPermissions, ConsoleLogs, Dashboard, ExternalAuthentication, OpenTelemetry, Secrets and StructuredLogs. AIPermissions was not in #7982's list, which was written before the cutover finished; it is dead by the same measure as the rest. Removed rather than marked obsolete, which #7982 asked to be an explicit decision. Every string these classes held carries two colons, so it does not parse under the new grammar and authorizes nothing. Keeping them obsolete would leave code that compiles, still reads as a permission check, and silently grants no access -- a warning that is easy to suppress in front of a runtime failure that is invisible. A compile error names the call site and can be fixed against the migration guide's mapping table. Classes their own modules still reference, WorkflowPermissions and IdentityPermissions among them, are untouched. External Authentication's parallel descriptor system is collapsed onto the core types: its own PermissionDescriptor record, its IPermissionDescriptorProvider and IPermissionDescriptorRegistry, and DefaultPermissionDescriptorRegistry. That was not only tidiness. The module's registry was fed exclusively by its legacy names, so after the cutover every well-formed grant failed the `unknown_permission_descriptor` check and the warning fired constantly for correct configuration. The resolver now consults the core catalog, which is keyed by resource and lists the verbs each accepts, and a wildcard is treated as advertised because it names a pattern rather than a resource to look up. The descriptor endpoint serves the core catalog too: choosing what an external mapping may confer means choosing from everything Elsa declares. The module contributes its resource descriptors explicitly rather than relying on the host's assembly scan, for the same reason it registers AddElsaAuthorization itself. The two naming tests now pin the new resource name instead of the legacy string. The convention worth holding was always that the module is called 'diagnostics/console-logs', not that a retired constant kept its old value. Refs #7982 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(client): match the permission descriptor client model to the catalog Moving the descriptor endpoint onto the core catalog changed its shape from a single permission string to a resource plus the verbs that resource accepts, and the Refit client model kept the old one. It still deserialized and still compiled, handing callers a blank Name and no way to reach the verbs -- the data went missing without anything failing. The client model now mirrors the served descriptor, and a contract test compares the two property sets so the next divergence is a test failure rather than an empty field. NonCoreVerbs is excluded: the server derives it from SupportedVerbs, so a client holding the verbs can compute it. Found by review, not by the suites: nothing here throws. Refs #7982 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-25 04:04:32 +00:00
using Elsa.Authorization;
2026-07-24 16:59:17 +00:00
using System.Net;
using System.Security.Claims;
using System.Text.Encodings.Web;
using Elsa.ExternalAuthentication.Features;
using Elsa.ExternalAuthentication.Contracts;
using Elsa.ExternalAuthentication.Permissions;
using Elsa.ExternalAuthentication.Services;
using Elsa.Common;
using Elsa.Common.Multitenancy;
using Elsa.Common.Services;
using Elsa.Identity.Contracts;
using Elsa.Identity.Entities;
using Elsa.Identity.Providers;
using Elsa.Identity.Services;
using Elsa.Workflows;
using FastEndpoints;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using NSubstitute;
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-20 22:36:11 +00:00
using Elsa.ExternalAuthentication.IntegrationTests.Fixtures;
2026-07-24 16:59:17 +00:00
namespace Elsa.ExternalAuthentication.IntegrationTests.Links;
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-20 22:36:11 +00:00
[Collection(nameof(EndpointSecurityCollection))]
2026-07-24 16:59:17 +00:00
public class IdentityLinkAuthorizationTests : IAsyncLifetime
{
private WebApplication? _app;
private HttpClient? _client;
private bool _wasSecurityEnabled;
public async Task InitializeAsync()
{
_wasSecurityEnabled = EndpointSecurityOptions.SecurityIsEnabled;
EndpointSecurityOptions.SecurityIsEnabled = true;
var builder = WebApplication.CreateSlimBuilder();
builder.WebHost.UseTestServer();
builder.Services.AddAuthentication(TestAuthenticationHandler.AuthenticationScheme).AddScheme<AuthenticationSchemeOptions, TestAuthenticationHandler>(TestAuthenticationHandler.AuthenticationScheme, _ => { });
builder.Services.AddAuthorization();
builder.Services.AddSingleton<MemoryStore<User>>();
builder.Services.AddSingleton<IIdentityGenerator, GuidIdentityGenerator>();
builder.Services.AddSingleton<Elsa.Common.ISystemClock, Elsa.Common.Services.SystemClock>();
builder.Services.AddSingleton<IExternalAuthenticationHandleHasher, HmacExternalAuthenticationHandleHasher>();
builder.Services.AddSingleton<InMemoryExternalIdentityProvisionerState>();
builder.Services.AddSingleton<IIdentityProviderConnectionRegistry>(Substitute.For<IIdentityProviderConnectionRegistry>());
var tenant = Substitute.For<ITenantAccessor>();
tenant.TenantId.Returns("tenant-a");
builder.Services.AddSingleton(tenant);
builder.Services.AddScoped<IUserStore, MemoryUserStore>();
builder.Services.AddScoped<IUserProvider, StoreBasedUserProvider>();
builder.Services.AddSingleton<IRoleProvider>(Substitute.For<IRoleProvider>());
2026-07-24 16:59:17 +00:00
builder.Services.AddScoped<InMemoryExternalIdentityProvisioner>();
builder.Services.AddScoped<IExternalIdentityProvisioner>(services => services.GetRequiredService<InMemoryExternalIdentityProvisioner>());
builder.Services.AddScoped<IExternalIdentityLinkManagementStore>(services => services.GetRequiredService<InMemoryExternalIdentityProvisioner>());
builder.Services.AddScoped<ExternalIdentityLinkManagementService>();
builder.Services.AddFastEndpoints(options =>
{
options.Assemblies = [typeof(ExternalAuthenticationFeature).Assembly];
options.Filter = endpoint => endpoint.Namespace == "Elsa.ExternalAuthentication.Endpoints.IdentityLinks";
});
_app = builder.Build();
_app.UseAuthentication();
_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 UserOptionsRequiresTheLinkManagementPermissionRatherThanAnUnrelatedPermission()
{
using var request = new HttpRequestMessage(HttpMethod.Get, "/external-authentication/user-options");
refactor(auth)!: retire the legacy permission constants and duplicate descriptor types (#7987) * refactor(auth)!: retire the legacy permission constants and duplicate descriptors Completes the cutover started in #7980. Seven `<Module>Permissions` classes holding `verb:resource` strings are removed: AIPermissions, ConsoleLogs, Dashboard, ExternalAuthentication, OpenTelemetry, Secrets and StructuredLogs. AIPermissions was not in #7982's list, which was written before the cutover finished; it is dead by the same measure as the rest. Removed rather than marked obsolete, which #7982 asked to be an explicit decision. Every string these classes held carries two colons, so it does not parse under the new grammar and authorizes nothing. Keeping them obsolete would leave code that compiles, still reads as a permission check, and silently grants no access -- a warning that is easy to suppress in front of a runtime failure that is invisible. A compile error names the call site and can be fixed against the migration guide's mapping table. Classes their own modules still reference, WorkflowPermissions and IdentityPermissions among them, are untouched. External Authentication's parallel descriptor system is collapsed onto the core types: its own PermissionDescriptor record, its IPermissionDescriptorProvider and IPermissionDescriptorRegistry, and DefaultPermissionDescriptorRegistry. That was not only tidiness. The module's registry was fed exclusively by its legacy names, so after the cutover every well-formed grant failed the `unknown_permission_descriptor` check and the warning fired constantly for correct configuration. The resolver now consults the core catalog, which is keyed by resource and lists the verbs each accepts, and a wildcard is treated as advertised because it names a pattern rather than a resource to look up. The descriptor endpoint serves the core catalog too: choosing what an external mapping may confer means choosing from everything Elsa declares. The module contributes its resource descriptors explicitly rather than relying on the host's assembly scan, for the same reason it registers AddElsaAuthorization itself. The two naming tests now pin the new resource name instead of the legacy string. The convention worth holding was always that the module is called 'diagnostics/console-logs', not that a retired constant kept its old value. Refs #7982 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(client): match the permission descriptor client model to the catalog Moving the descriptor endpoint onto the core catalog changed its shape from a single permission string to a resource plus the verbs that resource accepts, and the Refit client model kept the old one. It still deserialized and still compiled, handing callers a blank Name and no way to reach the verbs -- the data went missing without anything failing. The client model now mirrors the served descriptor, and a contract test compares the two property sets so the next divergence is a test failure rather than an empty field. NonCoreVerbs is excluded: the server derives it from SupportedVerbs, so a client holding the verbs can compute it. Found by review, not by the suites: nothing here throws. Refs #7982 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-25 04:04:32 +00:00
request.Headers.Add(TestAuthenticationHandler.PermissionHeader, $"{ExternalAuthenticationResourcePermissions.Connections}:{CoreVerbs.View}");
2026-07-24 16:59:17 +00:00
Assert.Equal(HttpStatusCode.Forbidden, (await _client!.SendAsync(request)).StatusCode);
}
private sealed class TestAuthenticationHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder)
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
public const string AuthenticationScheme = "test";
public const string PermissionHeader = "X-Test-Permissions";
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
var permissions = Request.Headers[PermissionHeader].SelectMany(x => x?.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) ?? []);
var identity = new ClaimsIdentity(permissions.Select(x => new Claim(PermissionNames.ClaimType, x)), AuthenticationScheme);
return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), AuthenticationScheme)));
}
}
}