elsa-core/test/unit/Elsa.ExternalAuthentication.UnitTests/Permissions/PermissionGrantPipelineTests.cs
Sipke Schoorstra f969cd61e8
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 06:04:32 +02:00

331 lines
20 KiB
C#

using Elsa.Permissions;
using System.Security.Claims;
using System.Text.Json;
using Elsa.Authorization;
using Elsa.ExternalAuthentication.Contracts;
using Elsa.ExternalAuthentication.Models;
using Elsa.ExternalAuthentication.Options;
using Elsa.ExternalAuthentication.Permissions;
using Elsa.ExternalAuthentication.Services;
using Elsa.Identity.Contracts;
using Elsa.Identity.Entities;
using Elsa.Identity.Models;
using Microsoft.Extensions.Options;
namespace Elsa.ExternalAuthentication.UnitTests.Permissions;
public class PermissionGrantPipelineTests
{
[Fact]
public async Task ComposesRoleAndMappedClaimGrantsInOrderWithDeterministicDeduplication()
{
var userProvider = new StaticUserProvider(new User { Id = "user-a", TenantId = "tenant-a", Roles = ["role-a"] });
var roleProvider = new StaticRoleProvider(new Role { Id = "role-a", Name = "Operators", TenantId = "tenant-a", Permissions = ["workflows:read", "workflows:manage"] });
var resolver = CreateResolver(userProvider, roleProvider, new ExternalAuthenticationOptions());
var context = CreateContext(
[
new GrantSourceSelection("elsa-roles", 1, JsonSerializer.SerializeToElement(new { }), 0),
new GrantSourceSelection("claim-mapping", 1, JsonSerializer.SerializeToElement(new { claimType = "department", mappings = new[] { new { value = "engineering", permissions = new[] { "workflows:read", "reports:view" } } } }), 1)
],
new Dictionary<string, IReadOnlyCollection<string>> { ["department"] = ["engineering"] });
var result = await resolver.ResolveAsync(context);
Assert.Equal(["workflows:manage", "workflows:read", "reports:view"], result.Grants.Select(x => x.Permission));
Assert.Equal("elsa-roles", result.Grants.First(x => x.Permission == "workflows:read").SourceType);
Assert.Equal("role-a", result.Grants.First(x => x.Permission == "workflows:manage").SourceReference);
Assert.Equal("department:engineering", result.Grants.Last().SourceReference);
}
[Fact]
public async Task LeavesUnmappedClaimsUnauthorizedAndWarnsForUnknownDescriptorsWithoutRejectingThem()
{
var options = new ExternalAuthenticationOptions();
options.PermissionGrants.AllowedPermissions = ["reports:view", "reports:blocked"];
options.PermissionGrants.DeniedPermissions = ["reports:blocked"];
var resolver = CreateResolver(new StaticUserProvider(null), new StaticRoleProvider(), options);
var context = CreateContext(
[new GrantSourceSelection("claim-mapping", 1, JsonSerializer.SerializeToElement(new { claimType = "department", mappings = new[] { new { value = "engineering", permissions = new[] { "reports:view", "reports:blocked" } } } }), 0)],
new Dictionary<string, IReadOnlyCollection<string>> { ["department"] = ["sales"] });
var unmapped = await resolver.ResolveAsync(context);
Assert.Empty(unmapped.Grants);
var mappedContext = context with { ProjectedClaims = new Dictionary<string, IReadOnlyCollection<string>> { ["department"] = ["engineering"] } };
var mapped = await resolver.ResolveAsync(mappedContext);
Assert.Equal(["reports:view"], mapped.Grants.Select(x => x.Permission));
Assert.Contains(mapped.Warnings, warning => warning.Code == "permission_denied_by_deployment");
Assert.Contains(mapped.Warnings, warning => warning.Code == "unknown_permission_descriptor" && warning.Message.Contains("reports:view", StringComparison.Ordinal));
}
[Fact]
public async Task SupportsTheQuickstartMappingObjectShapeAndEmitsEachWarningOnce()
{
var resolver = CreateResolver(new StaticUserProvider(null), new StaticRoleProvider(), new ExternalAuthenticationOptions());
var settings = JsonSerializer.SerializeToElement(new { claimType = "groups", mappings = new Dictionary<string, string[]> { ["elsa-workflow-admins"] = ["workflows:read", "reports:view"] } });
var context = CreateContext(
[
new GrantSourceSelection("group-mapping", 1, settings, 0),
new GrantSourceSelection("group-mapping", 1, settings, 1)
],
new Dictionary<string, IReadOnlyCollection<string>> { ["groups"] = ["elsa-workflow-admins"] });
var result = await resolver.ResolveAsync(context);
Assert.Equal(["reports:view", "workflows:read"], result.Grants.Select(x => x.Permission));
Assert.Single(result.Warnings, warning => warning.Code == "unknown_permission_descriptor" && warning.Message.Contains("reports:view", StringComparison.Ordinal));
}
[Fact]
public async Task RepeatedDeniedGrantsEmitOneDeploymentBoundaryWarning()
{
var options = new ExternalAuthenticationOptions();
options.PermissionGrants.DeniedPermissions = ["reports:view"];
var resolver = CreateResolver(new StaticUserProvider(null), new StaticRoleProvider(), options);
var settings = JsonSerializer.SerializeToElement(new { claimType = "department", mappings = new Dictionary<string, string[]> { ["engineering"] = ["reports:view"] } });
var context = CreateContext(
[
new GrantSourceSelection("claim-mapping", 1, settings, 0),
new GrantSourceSelection("claim-mapping", 1, settings, 1)
],
new Dictionary<string, IReadOnlyCollection<string>> { ["department"] = ["engineering"] });
var result = await resolver.ResolveAsync(context);
Assert.Empty(result.Grants);
Assert.Single(result.Warnings, warning => warning.Code == "permission_denied_by_deployment");
}
[Fact]
public async Task PassThroughClaimsGrantNothingWithoutAnExplicitNonEmptyBoundary()
{
var resolver = CreateResolver(new StaticUserProvider(null), new StaticRoleProvider(), new ExternalAuthenticationOptions());
var empty = CreateContext(
[new GrantSourceSelection("claim-pass-through", 1, JsonSerializer.SerializeToElement(new { claimType = "permissions", allowedPermissions = Array.Empty<string>() }), 0)],
new Dictionary<string, IReadOnlyCollection<string>> { ["permissions"] = ["reports:view", "workflows:manage"] });
var emptyResult = await resolver.ResolveAsync(empty);
Assert.Empty(emptyResult.Grants);
var bounded = empty with
{
Connection = new EffectiveIdentityProviderConnection(new IdentityProviderConnection
{
Id = "connection-a", TenantId = "tenant-a", Key = "contoso", AdapterType = "oidc", AdapterSettingsVersion = 1, DisplayName = "Contoso",
PermissionGrantSources = [new GrantSourceSelection("claim-pass-through", 1, JsonSerializer.SerializeToElement(new { claimType = "permissions", allowedPermissions = new[] { "reports:view" } }), 0)]
}, ConnectionSourceOwnership.Configuration, new ConnectionScope(ConnectionScopeKind.Tenant, "tenant-a"), ConnectionValidity.Valid, false, "test")
};
var boundedResult = await resolver.ResolveAsync(bounded);
Assert.Equal(["reports:view"], boundedResult.Grants.Select(x => x.Permission));
}
[Fact]
public async Task DelegationRequiresTheActorToPossessMappedPermissionsUnlessUnrestrictedAndStillHonorsDeploymentDeny()
{
var selection = new GrantSourceSelection("group-mapping", 1, JsonSerializer.SerializeToElement(new { claimType = "groups", mappings = new Dictionary<string, string[]> { ["operators"] = ["workflows:manage"] } }), 0);
var options = new ExternalAuthenticationOptions();
var authorizer = new DefaultPermissionDelegationAuthorizer(Microsoft.Extensions.Options.Options.Create(options), PermissionEvaluator.Shared);
var ordinaryActor = CreateActor(DelegatePermission, "workflows:read");
var ordinary = await authorizer.AuthorizeAsync(ordinaryActor, [selection]);
Assert.False(ordinary.IsAuthorized);
Assert.Equal(["workflows:manage"], ordinary.UnauthorizedPermissions);
options.PermissionGrants.DeniedPermissions = ["workflows:manage"];
var unrestricted = await authorizer.AuthorizeAsync(CreateActor(DelegateUnrestrictedPermission), [selection]);
Assert.False(unrestricted.IsAuthorized);
Assert.Equal(["workflows:manage"], unrestricted.UnauthorizedPermissions);
}
[Fact]
public async Task DelegationRequiresTheActorToPossessEachExplicitPassThroughPermission()
{
var selection = new GrantSourceSelection("claim-pass-through", 1, JsonSerializer.SerializeToElement(new { claimType = "permissions", allowedPermissions = new[] { "reports:view" } }), 0);
var authorizer = new DefaultPermissionDelegationAuthorizer(Microsoft.Extensions.Options.Options.Create(new ExternalAuthenticationOptions()), PermissionEvaluator.Shared);
var denied = await authorizer.AuthorizeAsync(CreateActor(DelegatePermission), [selection]);
var allowed = await authorizer.AuthorizeAsync(CreateActor(DelegatePermission, "reports:view"), [selection]);
Assert.False(denied.IsAuthorized);
Assert.Equal(["reports:view"], denied.UnauthorizedPermissions);
Assert.True(allowed.IsAuthorized);
}
[Theory]
// A deny of a subtree reaches every permission beneath it, the case the ordinal boundary missed.
[InlineData("workflows/*:delete", "workflows/definitions:delete")]
// And a wildcard grant cannot outflank a deny spelled out by name.
[InlineData("workflows/definitions:delete", "workflows/*:delete")]
// A verb wildcard reaches in both directions too.
[InlineData("workflows/definitions:*", "workflows/definitions:delete")]
[InlineData("workflows/definitions:delete", "workflows/definitions:*")]
public async Task DeploymentDenyAndGrantAreMatchedAsPatternsInBothDirections(string denied, string granted)
{
var options = new ExternalAuthenticationOptions();
options.PermissionGrants.DeniedPermissions = [denied];
var resolver = CreateResolver(new StaticUserProvider(null), new StaticRoleProvider(), options);
var result = await resolver.ResolveAsync(MappedContext(granted));
Assert.Empty(result.Grants);
Assert.Contains(result.Warnings, warning => warning.Code == "permission_denied_by_deployment");
}
[Theory]
// An allow entry must cover the whole grant, so a subtree admits the permissions beneath it...
[InlineData("workflows/*:delete", "workflows/definitions:delete", true)]
[InlineData("workflows/definitions:*", "workflows/definitions:delete", true)]
// ...but a grant broader than anything allowed is refused rather than admitted for the overlap.
[InlineData("workflows/definitions:delete", "workflows/*:delete", false)]
[InlineData("workflows/definitions:delete", "workflows/definitions:*", false)]
public async Task DeploymentAllowListCoversGrantsBeneathItButNotGrantsBeyondIt(string allowed, string granted, bool isAdmitted)
{
var options = new ExternalAuthenticationOptions();
options.PermissionGrants.AllowedPermissions = [allowed];
var resolver = CreateResolver(new StaticUserProvider(null), new StaticRoleProvider(), options);
var result = await resolver.ResolveAsync(MappedContext(granted));
Assert.Equal(isAdmitted ? [granted] : Array.Empty<string>(), result.Grants.Select(x => x.Permission));
}
[Theory]
// An allow list that parses to nothing must not read as "no allow list", which means unrestricted.
[InlineData(new[] { "not a permission" }, new string[0])]
// One bad entry among good ones is still a boundary the deployment cannot have meant.
[InlineData(new[] { "workflows/*:delete", "external-authentication:connections:read" }, new string[0])]
// A deny entry that does not parse would otherwise stop denying what it names, silently.
[InlineData(new string[0], new[] { "external-authentication:connections:read" })]
public async Task AGrantBoundaryThatDoesNotParseAdmitsNothing(string[] allowed, string[] denied)
{
var options = new ExternalAuthenticationOptions();
options.PermissionGrants.AllowedPermissions = allowed;
options.PermissionGrants.DeniedPermissions = denied;
var resolver = CreateResolver(new StaticUserProvider(null), new StaticRoleProvider(), options);
var result = await resolver.ResolveAsync(MappedContext("workflows/definitions:delete"));
Assert.Empty(result.Grants);
Assert.Contains(result.Warnings, warning => warning.Code == "permission_denied_by_deployment");
}
[Fact]
public async Task RolePermissionsAreMatchedAgainstTheDenyBoundaryAsPatterns()
{
var options = new ExternalAuthenticationOptions();
options.PermissionGrants.DeniedPermissions = ["workflows/*:delete"];
var userProvider = new StaticUserProvider(new User { Id = "user-a", TenantId = "tenant-a", Roles = ["role-a"] });
var roleProvider = new StaticRoleProvider(new Role { Id = "role-a", Name = "Operators", TenantId = "tenant-a", Permissions = ["workflows/definitions:delete", "workflows/definitions:view"] });
var resolver = CreateResolver(userProvider, roleProvider, options);
var context = CreateContext(
[new GrantSourceSelection("elsa-roles", 1, JsonSerializer.SerializeToElement(new { }), 0)],
new Dictionary<string, IReadOnlyCollection<string>>());
var result = await resolver.ResolveAsync(context);
Assert.Equal(["workflows/definitions:view"], result.Grants.Select(x => x.Permission));
Assert.Contains(result.Warnings, warning => warning.Code == "permission_denied_by_deployment");
}
[Fact]
public async Task GrantsThatAreNotWellFormedPermissionsAreDroppedRatherThanCarriedIntoAToken()
{
var resolver = CreateResolver(new StaticUserProvider(null), new StaticRoleProvider(), new ExternalAuthenticationOptions());
var result = await resolver.ResolveAsync(MappedContext("external-authentication:connections:read"));
Assert.Empty(result.Grants);
Assert.Contains(result.Warnings, warning => warning.Code == "malformed_permission");
}
[Theory]
// The actor must cover what they delegate, so a subtree grant delegates the permissions beneath it...
[InlineData("workflows/*:delete", "workflows/definitions:delete", true)]
// ...and holding one leaf does not let an actor delegate the whole subtree.
[InlineData("workflows/definitions:delete", "workflows/*:delete", false)]
[InlineData(PermissionNames.All, "workflows/*:delete", true)]
public async Task DelegationMatchesTheActorsOwnGrantsAsPatterns(string held, string delegated, bool isAuthorized)
{
var authorizer = new DefaultPermissionDelegationAuthorizer(Microsoft.Extensions.Options.Options.Create(new ExternalAuthenticationOptions()), PermissionEvaluator.Shared);
var selection = new GrantSourceSelection("group-mapping", 1, JsonSerializer.SerializeToElement(new { claimType = "groups", mappings = new Dictionary<string, string[]> { ["operators"] = [delegated] } }), 0);
var result = await authorizer.AuthorizeAsync(CreateActor(DelegatePermission, held), [selection]);
Assert.Equal(isAuthorized, result.IsAuthorized);
}
[Fact]
public async Task DelegationPermissionItselfIsHonouredThroughAWildcardGrant()
{
var authorizer = new DefaultPermissionDelegationAuthorizer(Microsoft.Extensions.Options.Options.Create(new ExternalAuthenticationOptions()), PermissionEvaluator.Shared);
var selection = new GrantSourceSelection("group-mapping", 1, JsonSerializer.SerializeToElement(new { claimType = "groups", mappings = new Dictionary<string, string[]> { ["operators"] = ["reports:view"] } }), 0);
var subtree = await authorizer.AuthorizeAsync(CreateActor($"{ExternalAuthenticationResourcePermissions.PermissionGrants}:*", "reports:view"), [selection]);
var without = await authorizer.AuthorizeAsync(CreateActor("reports:view"), [selection]);
Assert.True(subtree.IsAuthorized);
Assert.False(without.IsAuthorized);
}
private const string DelegatePermission = $"{ExternalAuthenticationResourcePermissions.PermissionGrants}:{ExternalAuthenticationVerbs.Delegate}";
private const string DelegateUnrestrictedPermission = $"{ExternalAuthenticationResourcePermissions.PermissionGrants}:{ExternalAuthenticationVerbs.DelegateUnrestricted}";
private static PermissionGrantResolutionContext MappedContext(string permission) => CreateContext(
[new GrantSourceSelection("claim-mapping", 1, JsonSerializer.SerializeToElement(new { claimType = "department", mappings = new Dictionary<string, string[]> { ["engineering"] = [permission] } }), 0)],
new Dictionary<string, IReadOnlyCollection<string>> { ["department"] = ["engineering"] });
[Theory]
// A grant the catalog advertises, resource and verb both matching, is not warned about.
[InlineData("reports:view", false)]
// A verb the resource does not declare is a gap worth surfacing.
[InlineData("reports:delete", true)]
// So is a resource nothing advertises.
[InlineData("nothing/here:view", true)]
// A wildcard names a pattern rather than one resource, so there is no descriptor to look it up in.
[InlineData("reports:*", false)]
[InlineData("*", false)]
public async Task UnknownDescriptorWarningTracksTheCoreCatalog(string permission, bool expectsWarning)
{
var resolver = new DefaultPermissionGrantResolver(
[new ClaimMappingPermissionGrantSource()],
new DefaultPermissionDescriptorRegistry([new StaticDescriptorProvider(new PermissionDescriptor("reports", [CoreVerbs.View], "Reports", "", "Reports"))]),
Microsoft.Extensions.Options.Options.Create(new ExternalAuthenticationOptions()));
var result = await resolver.ResolveAsync(MappedContext(permission));
Assert.Equal(expectsWarning, result.Warnings.Any(x => x.Code == "unknown_permission_descriptor"));
}
private static DefaultPermissionGrantResolver CreateResolver(IUserProvider userProvider, IRoleProvider roleProvider, ExternalAuthenticationOptions options) => new(
[new ElsaRolePermissionGrantSource(userProvider, roleProvider), new ClaimMappingPermissionGrantSource(), new GroupMappingPermissionGrantSource(), new ClaimPassThroughPermissionGrantSource()],
new DefaultPermissionDescriptorRegistry([]),
Microsoft.Extensions.Options.Options.Create(options));
private static PermissionGrantResolutionContext CreateContext(IReadOnlyCollection<GrantSourceSelection> selections, IReadOnlyDictionary<string, IReadOnlyCollection<string>> claims)
{
var connection = new IdentityProviderConnection { Id = "connection-a", TenantId = "tenant-a", Key = "contoso", AdapterType = "oidc", AdapterSettingsVersion = 1, DisplayName = "Contoso", PermissionGrantSources = selections.ToArray() };
return new PermissionGrantResolutionContext("tenant-a", "user-a", new EffectiveIdentityProviderConnection(connection, ConnectionSourceOwnership.Configuration, new ConnectionScope(ConnectionScopeKind.Tenant, "tenant-a"), ConnectionValidity.Valid, false, "test"), null, claims);
}
private static ClaimsPrincipal CreateActor(params string[] permissions) => new(new ClaimsIdentity(permissions.Select(x => new Claim(PermissionNames.ClaimType, x)), "test"));
private sealed class StaticUserProvider(User? user) : IUserProvider
{
public Task<User?> FindAsync(UserFilter filter, CancellationToken cancellationToken = default) => Task.FromResult(user?.Id == filter.Id ? user : null);
}
private sealed class StaticRoleProvider(params Role[] roles) : IRoleProvider
{
public ValueTask<IEnumerable<Role>> FindManyAsync(RoleFilter filter, CancellationToken cancellationToken = default) => ValueTask.FromResult<IEnumerable<Role>>(roles.Where(x => filter.Ids?.Contains(x.Id) ?? true));
}
private sealed class StaticDescriptorProvider(params PermissionDescriptor[] descriptors) : IPermissionDescriptorProvider
{
public IEnumerable<PermissionDescriptor> GetDescriptors() => descriptors;
}
}