| | | 1 | | using System.Security.Claims; |
| | | 2 | | using System.Security.Cryptography; |
| | | 3 | | using System.Text; |
| | | 4 | | using Elsa.Identity.Contracts; |
| | | 5 | | using Elsa.Identity.Models; |
| | | 6 | | |
| | | 7 | | namespace Elsa.Identity.Services; |
| | | 8 | | |
| | | 9 | | /// <inheritdoc /> |
| | 8 | 10 | | public sealed class RoleDeletionCoordinator( |
| | 8 | 11 | | IRoleStore roleStore, |
| | 8 | 12 | | IRoleAuthorizationService roleAuthorizationService, |
| | 8 | 13 | | IEnumerable<IRoleDeletionDependencyContributor> contributors) : IRoleDeletionCoordinator |
| | | 14 | | { |
| | 13 | 15 | | private readonly IReadOnlyDictionary<string, IRoleDeletionDependencyContributor> _contributors = contributors.ToDict |
| | | 16 | | |
| | | 17 | | /// <inheritdoc /> |
| | | 18 | | public async ValueTask<RoleDeletionInspectionResult> InspectAsync(string roleId, ClaimsPrincipal actor, Cancellation |
| | | 19 | | { |
| | 9 | 20 | | var role = await roleStore.FindAsync(new() { Id = roleId }, cancellationToken); |
| | 9 | 21 | | if (role is null) |
| | 0 | 22 | | return new RoleDeletionInspectionResult.NotFound(); |
| | 9 | 23 | | if (!HasPermission(actor, "delete:role") || !roleAuthorizationService.CanMutateRole(actor, role)) |
| | 1 | 24 | | return new RoleDeletionInspectionResult.Forbidden(); |
| | | 25 | | |
| | 8 | 26 | | var snapshots = await InspectContributorsAsync(roleId, cancellationToken); |
| | 8 | 27 | | return new RoleDeletionInspectionResult.Success(CreateImpact(roleId, snapshots)); |
| | 9 | 28 | | } |
| | | 29 | | |
| | | 30 | | /// <inheritdoc /> |
| | | 31 | | public async ValueTask<RoleDeletionOperationResult> DeleteAsync(string roleId, ClaimsPrincipal actor, CancellationTo |
| | | 32 | | { |
| | 1 | 33 | | var inspection = await InspectAsync(roleId, actor, cancellationToken); |
| | 1 | 34 | | if (inspection is RoleDeletionInspectionResult.NotFound) |
| | 0 | 35 | | return new RoleDeletionOperationResult.NotFound(); |
| | 1 | 36 | | if (inspection is RoleDeletionInspectionResult.Forbidden) |
| | 0 | 37 | | return new RoleDeletionOperationResult.Forbidden(); |
| | | 38 | | |
| | 1 | 39 | | var impact = ((RoleDeletionInspectionResult.Success)inspection).Impact; |
| | 1 | 40 | | if (!impact.CanDelete) |
| | 1 | 41 | | return new RoleDeletionOperationResult.Blocked(impact); |
| | | 42 | | |
| | 0 | 43 | | await roleStore.DeleteAsync(new() { Id = roleId }, cancellationToken); |
| | 0 | 44 | | return new RoleDeletionOperationResult.Deleted([]); |
| | 1 | 45 | | } |
| | | 46 | | |
| | | 47 | | /// <inheritdoc /> |
| | | 48 | | public async ValueTask<RoleDeletionOperationResult> RemediateAndDeleteAsync(RoleDeletionRemediationCommand command, |
| | | 49 | | { |
| | 3 | 50 | | var inspection = await InspectAsync(command.RoleId, command.Actor, cancellationToken); |
| | 3 | 51 | | if (inspection is RoleDeletionInspectionResult.NotFound) |
| | 0 | 52 | | return new RoleDeletionOperationResult.NotFound(); |
| | 3 | 53 | | if (inspection is RoleDeletionInspectionResult.Forbidden) |
| | 0 | 54 | | return new RoleDeletionOperationResult.Forbidden(); |
| | | 55 | | |
| | 3 | 56 | | var impact = ((RoleDeletionInspectionResult.Success)inspection).Impact; |
| | 3 | 57 | | if (!string.Equals(impact.DependencyVersion, command.ExpectedDependencyVersion, StringComparison.Ordinal)) |
| | 0 | 58 | | return new RoleDeletionOperationResult.PreconditionFailed(impact); |
| | 7 | 59 | | if (impact.Dependencies.Any(x => x.Ownership == RoleDeletionDependencyOwnership.Configuration)) |
| | 0 | 60 | | return new RoleDeletionOperationResult.Blocked(impact); |
| | 3 | 61 | | if (impact.CanDelete) |
| | | 62 | | { |
| | 0 | 63 | | await roleStore.DeleteAsync(new() { Id = command.RoleId }, cancellationToken); |
| | 0 | 64 | | return new RoleDeletionOperationResult.Deleted([]); |
| | | 65 | | } |
| | | 66 | | |
| | 3 | 67 | | var warnings = GetRequiredConfirmations(impact, command); |
| | 3 | 68 | | if (warnings.Count != 0) |
| | 1 | 69 | | return new RoleDeletionOperationResult.ConfirmationRequired(impact, warnings); |
| | | 70 | | |
| | 2 | 71 | | var snapshots = await InspectContributorsAsync(command.RoleId, cancellationToken); |
| | 2 | 72 | | var currentImpact = CreateImpact(command.RoleId, snapshots); |
| | 2 | 73 | | if (!string.Equals(currentImpact.DependencyVersion, command.ExpectedDependencyVersion, StringComparison.Ordinal) |
| | 0 | 74 | | return new RoleDeletionOperationResult.PreconditionFailed(currentImpact); |
| | | 75 | | |
| | 2 | 76 | | var requests = snapshots |
| | 4 | 77 | | .Where(x => x.Dependencies.Any(dependency => dependency.Ownership == RoleDeletionDependencyOwnership.Databas |
| | 2 | 78 | | .Select(snapshot => new RoleReferenceRemovalRequest( |
| | 2 | 79 | | command.RoleId, |
| | 2 | 80 | | command.Actor, |
| | 2 | 81 | | snapshot.Version, |
| | 5 | 82 | | snapshot.Dependencies.Where(x => x.Ownership == RoleDeletionDependencyOwnership.Database).ToArray())) |
| | 2 | 83 | | .ToArray(); |
| | | 84 | | |
| | 8 | 85 | | foreach (var request in requests) |
| | | 86 | | { |
| | 2 | 87 | | var validation = await _contributors[request.Dependencies.First().Source].ValidateRemovalAsync(request, canc |
| | 2 | 88 | | if (validation is RoleReferenceRemovalValidationResult.Forbidden) |
| | 0 | 89 | | return new RoleDeletionOperationResult.Forbidden(); |
| | 2 | 90 | | if (validation is RoleReferenceRemovalValidationResult.Conflict) |
| | 0 | 91 | | return new RoleDeletionOperationResult.PreconditionFailed(await GetCurrentImpactAsync(command.RoleId, ca |
| | | 92 | | } |
| | | 93 | | |
| | 2 | 94 | | var changedOwnerIds = new List<string>(); |
| | 7 | 95 | | foreach (var request in requests) |
| | | 96 | | { |
| | 2 | 97 | | var removal = await _contributors[request.Dependencies.First().Source].RemoveEditableReferencesAsync(request |
| | | 98 | | switch (removal) |
| | | 99 | | { |
| | | 100 | | case RoleReferenceRemovalResult.Success success: |
| | 1 | 101 | | changedOwnerIds.AddRange(success.ChangedOwnerIds); |
| | 1 | 102 | | break; |
| | | 103 | | case RoleReferenceRemovalResult.Conflict conflict: |
| | 0 | 104 | | changedOwnerIds.AddRange(conflict.ChangedOwnerIds); |
| | 0 | 105 | | return new RoleDeletionOperationResult.Incomplete(await GetCurrentImpactAsync(command.RoleId, cancel |
| | | 106 | | case RoleReferenceRemovalResult.Failed failed: |
| | 1 | 107 | | changedOwnerIds.AddRange(failed.ChangedOwnerIds); |
| | 1 | 108 | | return new RoleDeletionOperationResult.Incomplete(await GetCurrentImpactAsync(command.RoleId, cancel |
| | | 109 | | } |
| | | 110 | | } |
| | | 111 | | |
| | 1 | 112 | | var finalInspection = await InspectAsync(command.RoleId, command.Actor, cancellationToken); |
| | 1 | 113 | | if (finalInspection is RoleDeletionInspectionResult.NotFound) |
| | 0 | 114 | | return new RoleDeletionOperationResult.NotFound(); |
| | 1 | 115 | | if (finalInspection is RoleDeletionInspectionResult.Forbidden) |
| | 0 | 116 | | return new RoleDeletionOperationResult.Forbidden(); |
| | | 117 | | |
| | 1 | 118 | | var finalImpact = ((RoleDeletionInspectionResult.Success)finalInspection).Impact; |
| | 1 | 119 | | if (!finalImpact.CanDelete) |
| | 0 | 120 | | return new RoleDeletionOperationResult.Incomplete(finalImpact, changedOwnerIds.Distinct(StringComparer.Ordin |
| | | 121 | | |
| | 1 | 122 | | await roleStore.DeleteAsync(new() { Id = command.RoleId }, cancellationToken); |
| | 1 | 123 | | return new RoleDeletionOperationResult.Deleted(changedOwnerIds.Distinct(StringComparer.Ordinal).ToArray()); |
| | 3 | 124 | | } |
| | | 125 | | |
| | | 126 | | private async ValueTask<IReadOnlyCollection<RoleDeletionDependencySnapshot>> InspectContributorsAsync(string roleId, |
| | | 127 | | { |
| | 11 | 128 | | var snapshots = new List<RoleDeletionDependencySnapshot>(_contributors.Count); |
| | 66 | 129 | | foreach (var contributor in _contributors.OrderBy(x => x.Key, StringComparer.Ordinal).Select(x => x.Value)) |
| | | 130 | | { |
| | 11 | 131 | | var snapshot = await contributor.InspectAsync(roleId, cancellationToken); |
| | 11 | 132 | | if (!string.Equals(snapshot.Source, contributor.Source, StringComparison.Ordinal) || |
| | 24 | 133 | | snapshot.Dependencies.Any(x => !string.Equals(x.Source, contributor.Source, StringComparison.Ordinal))) |
| | 0 | 134 | | throw new InvalidOperationException($"Role-deletion contributor '{contributor.Source}' returned a mismat |
| | 11 | 135 | | snapshots.Add(snapshot); |
| | 11 | 136 | | } |
| | | 137 | | |
| | 11 | 138 | | return snapshots; |
| | 11 | 139 | | } |
| | | 140 | | |
| | | 141 | | private static RoleDeletionImpact CreateImpact(string roleId, IReadOnlyCollection<RoleDeletionDependencySnapshot> sn |
| | | 142 | | { |
| | 11 | 143 | | var dependencies = snapshots |
| | 11 | 144 | | .SelectMany(x => x.Dependencies) |
| | 6 | 145 | | .OrderBy(x => x.Source, StringComparer.Ordinal) |
| | 6 | 146 | | .ThenBy(x => x.Ownership) |
| | 6 | 147 | | .ThenBy(x => x.OwnerId, StringComparer.Ordinal) |
| | 6 | 148 | | .ThenBy(x => x.PolicyBranch, StringComparer.Ordinal) |
| | 11 | 149 | | .ToArray(); |
| | | 150 | | // The current coordinator has no unit of work spanning contributor stores and IRoleStore. |
| | | 151 | | // Contributor-local atomicity alone cannot make the complete remove-then-delete command atomic. |
| | 32 | 152 | | var hasEditableDependencies = snapshots.Any(x => x.Dependencies.Any(dependency => dependency.Ownership == RoleDe |
| | 11 | 153 | | var executionMode = hasEditableDependencies ? RoleDeletionExecutionMode.BestEffort : RoleDeletionExecutionMode.A |
| | 11 | 154 | | return new RoleDeletionImpact( |
| | 11 | 155 | | roleId, |
| | 11 | 156 | | CalculateDependencyVersion(snapshots), |
| | 11 | 157 | | executionMode, |
| | 11 | 158 | | dependencies.Length == 0, |
| | 13 | 159 | | dependencies.Length != 0 && dependencies.All(x => x.Ownership == RoleDeletionDependencyOwnership.Database), |
| | 11 | 160 | | dependencies); |
| | | 161 | | } |
| | | 162 | | |
| | | 163 | | private static string CalculateDependencyVersion(IEnumerable<RoleDeletionDependencySnapshot> snapshots) |
| | | 164 | | { |
| | 11 | 165 | | var payload = string.Join( |
| | 11 | 166 | | "\n", |
| | 11 | 167 | | snapshots |
| | 11 | 168 | | .OrderBy(x => x.Source, StringComparer.Ordinal) |
| | 22 | 169 | | .SelectMany(snapshot => new[] { $"{snapshot.Source}|{snapshot.Version}|{snapshot.SupportsAtomicRemoval}" |
| | 22 | 170 | | .Concat(snapshot.Dependencies |
| | 13 | 171 | | .OrderBy(x => x.Ownership) |
| | 13 | 172 | | .ThenBy(x => x.OwnerId, StringComparer.Ordinal) |
| | 13 | 173 | | .ThenBy(x => x.PolicyBranch, StringComparer.Ordinal) |
| | 35 | 174 | | .Select(x => $"{x.Source}|{x.OwnerId}|{x.OwnerKey}|{x.PolicyBranch}|{x.Ownership}|{x.Configurati |
| | 11 | 175 | | return $"role-dependencies-{Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(payload))).ToLowerInvaria |
| | | 176 | | } |
| | | 177 | | |
| | | 178 | | private static IReadOnlyCollection<string> GetRequiredConfirmations(RoleDeletionImpact impact, RoleDeletionRemediati |
| | | 179 | | { |
| | 3 | 180 | | var warnings = new List<string>(); |
| | 3 | 181 | | if (!command.ConfirmRemoveFromEditablePolicies) |
| | 1 | 182 | | warnings.Add("confirm_remove_from_editable_jit_policies"); |
| | 7 | 183 | | if (impact.Dependencies.Any(x => x.RemovesLastDefaultRole) && !command.ConfirmEmptyDefaultRoles) |
| | 1 | 184 | | warnings.Add("removes_last_default_role"); |
| | 3 | 185 | | if (impact.ExecutionMode == RoleDeletionExecutionMode.BestEffort && !command.ConfirmBestEffort) |
| | 1 | 186 | | warnings.Add("confirm_best_effort"); |
| | 3 | 187 | | return warnings; |
| | | 188 | | } |
| | | 189 | | |
| | | 190 | | private async ValueTask<RoleDeletionImpact> GetCurrentImpactAsync(string roleId, CancellationToken cancellationToken |
| | 1 | 191 | | CreateImpact(roleId, await InspectContributorsAsync(roleId, cancellationToken)); |
| | | 192 | | |
| | | 193 | | private static bool HasPermission(ClaimsPrincipal actor, string permission) => |
| | 17 | 194 | | actor.FindAll(PermissionNames.ClaimType).Any(x => x.Value == PermissionNames.All || string.Equals(x.Value, permi |
| | | 195 | | } |