| | | 1 | | using System.Security.Claims; |
| | | 2 | | using Elsa.Common; |
| | | 3 | | using Elsa.Common.Models; |
| | | 4 | | using Elsa.ExternalAuthentication.Contracts; |
| | | 5 | | using Elsa.ExternalAuthentication.Models; |
| | | 6 | | using Elsa.ExternalAuthentication.Notifications; |
| | | 7 | | using Elsa.Identity.Contracts; |
| | | 8 | | using Elsa.Identity.Models; |
| | | 9 | | using Elsa.Mediator.Contracts; |
| | | 10 | | using Microsoft.Extensions.DependencyInjection; |
| | | 11 | | |
| | | 12 | | namespace Elsa.ExternalAuthentication.Services; |
| | | 13 | | |
| | | 14 | | /// <summary> |
| | | 15 | | /// Coordinates tenant-safe administrator operations over external identity links. |
| | | 16 | | /// </summary> |
| | 72 | 17 | | public sealed class ExternalIdentityLinkManagementService( |
| | 72 | 18 | | IExternalIdentityProvisioner provisioner, |
| | 72 | 19 | | IExternalIdentityLinkManagementStore links, |
| | 72 | 20 | | IIdentityProviderConnectionRegistry connections, |
| | 72 | 21 | | IUserStore users, |
| | 72 | 22 | | ISystemClock clock, |
| | 72 | 23 | | IServiceProvider services) |
| | | 24 | | { |
| | | 25 | | public async ValueTask<Page<ExternalIdentityLink>> ListAsync(string tenantId, ExternalIdentityLinkFilter filter, Can |
| | | 26 | | { |
| | 11 | 27 | | ValidateTargetTenant(tenantId); |
| | 11 | 28 | | ArgumentNullException.ThrowIfNull(filter); |
| | 11 | 29 | | filter.TenantId = tenantId; |
| | 11 | 30 | | return await links.FindAsync(filter, cancellationToken); |
| | 11 | 31 | | } |
| | | 32 | | |
| | | 33 | | public async ValueTask<Page<ExternalIdentityLinkUser>> FindUsersAsync(string tenantId, string? search, CancellationT |
| | | 34 | | { |
| | 2 | 35 | | ValidateTargetTenant(tenantId); |
| | 2 | 36 | | var normalizedSearch = search?.Trim(); |
| | 2 | 37 | | var usersInTenant = (await users.FindManyAsync(new UserFilter { TenantId = tenantId }, cancellationToken)) |
| | 4 | 38 | | .Where(x => string.IsNullOrEmpty(normalizedSearch) || x.Name.Contains(normalizedSearch, StringComparison.Ord |
| | 4 | 39 | | .OrderBy(x => x.Name, StringComparer.Ordinal) |
| | 4 | 40 | | .ThenBy(x => x.Id, StringComparer.Ordinal) |
| | 4 | 41 | | .Select(x => new ExternalIdentityLinkUser(x.Id, x.Name)) |
| | 2 | 42 | | .ToArray(); |
| | 2 | 43 | | return Page.Of<ExternalIdentityLinkUser>(usersInTenant, usersInTenant.Length); |
| | 2 | 44 | | } |
| | | 45 | | |
| | | 46 | | public async ValueTask<ExternalIdentityLinkPrelinkResult> PrelinkAsync(string tenantId, string userId, string connec |
| | | 47 | | { |
| | 33 | 48 | | ValidateTargetTenant(tenantId); |
| | 33 | 49 | | ArgumentException.ThrowIfNullOrWhiteSpace(userId); |
| | 33 | 50 | | ArgumentException.ThrowIfNullOrWhiteSpace(connectionKey); |
| | 33 | 51 | | var normalizedIssuer = NormalizeIssuer(issuer); |
| | 33 | 52 | | var normalizedSubject = NormalizeSubject(subject); |
| | | 53 | | |
| | 33 | 54 | | var user = await users.FindAsync(new UserFilter { Id = userId }, cancellationToken); |
| | 33 | 55 | | if (user is null || !string.Equals(user.TenantId, tenantId, StringComparison.Ordinal)) |
| | 1 | 56 | | return new ExternalIdentityLinkPrelinkResult.UserNotFound(); |
| | | 57 | | |
| | | 58 | | // Manual administration may target disabled or invalid connections, but never archived, shadowed, or cross-tena |
| | 32 | 59 | | var connection = await FindManageableConnectionAsync(tenantId, connectionKey, cancellationToken); |
| | 32 | 60 | | if (connection is null) |
| | 2 | 61 | | return new ExternalIdentityLinkPrelinkResult.ConnectionNotFound(); |
| | | 62 | | |
| | | 63 | | try |
| | | 64 | | { |
| | 30 | 65 | | var result = await provisioner.CreateLinkOrGetExistingAsync(new ProvisioningRequest( |
| | 30 | 66 | | tenantId, |
| | 30 | 67 | | ConnectionRevisionCalculator.NormalizeKey(connection.Connection.Key), |
| | 30 | 68 | | new ExternalIdentity(normalizedIssuer, normalizedSubject, new Dictionary<string, IReadOnlyCollection<str |
| | 30 | 69 | | null, |
| | 30 | 70 | | user.Id), cancellationToken); |
| | | 71 | | |
| | 30 | 72 | | if (!string.Equals(result.UserId, user.Id, StringComparison.Ordinal)) |
| | 1 | 73 | | return new ExternalIdentityLinkPrelinkResult.Conflict(result.Link); |
| | | 74 | | |
| | 29 | 75 | | if (result.WasLinkCreated) |
| | 14 | 76 | | await PublishAsync(actor, result.Link, "prelinked", cancellationToken); |
| | 29 | 77 | | return new ExternalIdentityLinkPrelinkResult.Success(result.Link, result.WasLinkCreated); |
| | | 78 | | } |
| | 0 | 79 | | catch (InvalidOperationException) |
| | | 80 | | { |
| | | 81 | | // The provisioner protects its own user/tenant invariant. Do not turn a malformed or cross-tenant target in |
| | 0 | 82 | | return new ExternalIdentityLinkPrelinkResult.UserNotFound(); |
| | | 83 | | } |
| | 33 | 84 | | } |
| | | 85 | | |
| | | 86 | | public async ValueTask<bool> UnlinkAsync(string tenantId, string linkId, ClaimsPrincipal actor, CancellationToken ca |
| | | 87 | | { |
| | 1 | 88 | | ValidateTargetTenant(tenantId); |
| | 1 | 89 | | ArgumentException.ThrowIfNullOrWhiteSpace(linkId); |
| | 1 | 90 | | var existing = await links.FindAsync(new ExternalIdentityLinkFilter { TenantId = tenantId }, cancellationToken); |
| | 2 | 91 | | var link = existing.Items.FirstOrDefault(x => string.Equals(x.Id, linkId, StringComparison.Ordinal)); |
| | 1 | 92 | | if (link is null || !await links.DeleteAsync(tenantId, linkId, cancellationToken)) |
| | 0 | 93 | | return false; |
| | | 94 | | |
| | 1 | 95 | | await PublishAsync(actor, link, "unlinked", cancellationToken); |
| | 1 | 96 | | return true; |
| | 1 | 97 | | } |
| | | 98 | | |
| | | 99 | | public async ValueTask<ExternalIdentityLinkReplaceResult> ReplaceAsync( |
| | | 100 | | string tenantId, |
| | | 101 | | string linkId, |
| | | 102 | | string userId, |
| | | 103 | | string connectionKey, |
| | | 104 | | string issuer, |
| | | 105 | | string subject, |
| | | 106 | | ClaimsPrincipal actor, |
| | | 107 | | CancellationToken cancellationToken = default) |
| | | 108 | | { |
| | 9 | 109 | | ValidateTargetTenant(tenantId); |
| | 9 | 110 | | ArgumentException.ThrowIfNullOrWhiteSpace(linkId); |
| | 9 | 111 | | ArgumentException.ThrowIfNullOrWhiteSpace(userId); |
| | 9 | 112 | | ArgumentException.ThrowIfNullOrWhiteSpace(connectionKey); |
| | 9 | 113 | | var normalizedIssuer = NormalizeIssuer(issuer); |
| | 8 | 114 | | var normalizedSubject = NormalizeSubject(subject); |
| | | 115 | | |
| | 8 | 116 | | var user = await users.FindAsync(new UserFilter { Id = userId }, cancellationToken); |
| | 8 | 117 | | if (user is null || !string.Equals(user.TenantId, tenantId, StringComparison.Ordinal)) |
| | 0 | 118 | | return new ExternalIdentityLinkReplaceResult.NotFound(); |
| | | 119 | | |
| | 8 | 120 | | var connection = await FindManageableConnectionAsync(tenantId, connectionKey, cancellationToken); |
| | 8 | 121 | | if (connection is null) |
| | 1 | 122 | | return new ExternalIdentityLinkReplaceResult.NotFound(); |
| | | 123 | | |
| | | 124 | | ExternalIdentityLinkReplaceResult result; |
| | | 125 | | try |
| | | 126 | | { |
| | 7 | 127 | | result = await provisioner.ReplaceAsync( |
| | 7 | 128 | | new ExternalIdentityLinkReplaceRequest( |
| | 7 | 129 | | tenantId, |
| | 7 | 130 | | linkId, |
| | 7 | 131 | | user.Id, |
| | 7 | 132 | | ConnectionRevisionCalculator.NormalizeKey(connection.Connection.Key), |
| | 7 | 133 | | new ExternalIdentity(normalizedIssuer, normalizedSubject, new Dictionary<string, IReadOnlyCollection |
| | 7 | 134 | | cancellationToken); |
| | 7 | 135 | | } |
| | 0 | 136 | | catch (InvalidOperationException) |
| | | 137 | | { |
| | 0 | 138 | | return new ExternalIdentityLinkReplaceResult.NotFound(); |
| | | 139 | | } |
| | | 140 | | |
| | | 141 | | switch (result) |
| | | 142 | | { |
| | | 143 | | case ExternalIdentityLinkReplaceResult.Success success: |
| | 4 | 144 | | await PublishReplacementAsync(actor, success.OldLink, success.NewLink, null, user.Id, success.NewLink.Co |
| | 4 | 145 | | break; |
| | | 146 | | case ExternalIdentityLinkReplaceResult.Conflict conflict: |
| | 2 | 147 | | await PublishReplacementAsync( |
| | 2 | 148 | | actor, |
| | 2 | 149 | | conflict.OldLink, |
| | 2 | 150 | | null, |
| | 2 | 151 | | conflict.ConflictingLink, |
| | 2 | 152 | | user.Id, |
| | 2 | 153 | | ConnectionRevisionCalculator.NormalizeKey(connection.Connection.Key), |
| | 2 | 154 | | SecurityEventOutcome.Failed, |
| | 2 | 155 | | cancellationToken); |
| | | 156 | | break; |
| | | 157 | | } |
| | | 158 | | |
| | 7 | 159 | | return result; |
| | 8 | 160 | | } |
| | | 161 | | |
| | | 162 | | private async ValueTask<EffectiveIdentityProviderConnection?> FindManageableConnectionAsync(string tenantId, string |
| | | 163 | | { |
| | 40 | 164 | | var normalizedKey = ConnectionRevisionCalculator.NormalizeKey(connectionKey); |
| | 40 | 165 | | var registry = await connections.GetAsync(tenantId, cancellationToken); |
| | 40 | 166 | | return registry.Connections.FirstOrDefault(x => |
| | 81 | 167 | | !x.IsShadowed && |
| | 81 | 168 | | !x.Connection.ArchivedAt.HasValue && |
| | 81 | 169 | | string.Equals(ConnectionRevisionCalculator.NormalizeKey(x.Connection.Key), normalizedKey, StringComparison.O |
| | 40 | 170 | | } |
| | | 171 | | |
| | | 172 | | private async ValueTask PublishAsync(ClaimsPrincipal actor, ExternalIdentityLink link, string operation, Cancellatio |
| | | 173 | | { |
| | 15 | 174 | | var sender = services.GetService<INotificationSender>(); |
| | 15 | 175 | | if (sender is null) |
| | 0 | 176 | | return; |
| | | 177 | | |
| | 15 | 178 | | var context = new SecurityEventContext( |
| | 15 | 179 | | actor.FindFirstValue(ClaimTypes.NameIdentifier) ?? actor.FindFirstValue("sub"), |
| | 15 | 180 | | link.TenantId, |
| | 15 | 181 | | link.ConnectionKey, |
| | 15 | 182 | | link.UserId, |
| | 15 | 183 | | clock.UtcNow, |
| | 15 | 184 | | SecurityEventOutcome.Succeeded, |
| | 15 | 185 | | Guid.NewGuid().ToString("N"), |
| | 15 | 186 | | "External identity link management operation completed."); |
| | 15 | 187 | | await sender.SendAsync(new ExternalIdentityLinkChanged(context, operation, link.Id), cancellationToken); |
| | 15 | 188 | | } |
| | | 189 | | |
| | | 190 | | private async ValueTask PublishReplacementAsync( |
| | | 191 | | ClaimsPrincipal actor, |
| | | 192 | | ExternalIdentityLink oldLink, |
| | | 193 | | ExternalIdentityLink? newLink, |
| | | 194 | | ExternalIdentityLink? conflictingLink, |
| | | 195 | | string targetUserId, |
| | | 196 | | string targetConnectionKey, |
| | | 197 | | SecurityEventOutcome outcome, |
| | | 198 | | CancellationToken cancellationToken) |
| | | 199 | | { |
| | 6 | 200 | | var sender = services.GetService<INotificationSender>(); |
| | 6 | 201 | | if (sender is null) |
| | 0 | 202 | | return; |
| | | 203 | | |
| | 6 | 204 | | var context = new SecurityEventContext( |
| | 6 | 205 | | actor.FindFirstValue(ClaimTypes.NameIdentifier) ?? actor.FindFirstValue("sub"), |
| | 6 | 206 | | oldLink.TenantId, |
| | 6 | 207 | | targetConnectionKey, |
| | 6 | 208 | | targetUserId, |
| | 6 | 209 | | clock.UtcNow, |
| | 6 | 210 | | outcome, |
| | 6 | 211 | | Guid.NewGuid().ToString("N"), |
| | 6 | 212 | | outcome == SecurityEventOutcome.Succeeded |
| | 6 | 213 | | ? "External identity link replacement completed." |
| | 6 | 214 | | : "External identity link replacement was rejected because the identity is already linked."); |
| | 6 | 215 | | await sender.SendAsync( |
| | 6 | 216 | | new ExternalIdentityLinkReplaced( |
| | 6 | 217 | | context, |
| | 6 | 218 | | oldLink.Id, |
| | 6 | 219 | | newLink?.Id, |
| | 6 | 220 | | oldLink.UserId, |
| | 6 | 221 | | targetUserId, |
| | 6 | 222 | | oldLink.ConnectionKey, |
| | 6 | 223 | | targetConnectionKey, |
| | 6 | 224 | | conflictingLink?.Id, |
| | 6 | 225 | | conflictingLink?.UserId, |
| | 6 | 226 | | conflictingLink?.ConnectionKey), |
| | 6 | 227 | | cancellationToken); |
| | 6 | 228 | | } |
| | | 229 | | |
| | | 230 | | private static string NormalizeIssuer(string issuer) |
| | | 231 | | { |
| | 42 | 232 | | if (!Uri.TryCreate(issuer?.Trim(), UriKind.Absolute, out var uri) || !string.Equals(uri.Scheme, Uri.UriSchemeHtt |
| | 1 | 233 | | throw new ArgumentException("The issuer must be an absolute HTTPS URI without a query or fragment.", nameof( |
| | 41 | 234 | | return uri.GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped).TrimEnd('/'); |
| | | 235 | | } |
| | | 236 | | |
| | | 237 | | private static string NormalizeSubject(string subject) |
| | | 238 | | { |
| | 41 | 239 | | var normalized = subject?.Trim(); |
| | 41 | 240 | | if (string.IsNullOrEmpty(normalized) || normalized.Length > 4096) |
| | 0 | 241 | | throw new ArgumentException("The subject is required and must not exceed 4096 characters.", nameof(subject)) |
| | 41 | 242 | | return normalized; |
| | | 243 | | } |
| | | 244 | | |
| | | 245 | | private static void ValidateTargetTenant(string tenantId) |
| | | 246 | | { |
| | 56 | 247 | | ArgumentNullException.ThrowIfNull(tenantId); |
| | 56 | 248 | | if (string.Equals(tenantId, ConnectionScope.HostTenantId, StringComparison.Ordinal)) |
| | 0 | 249 | | throw new ArgumentException("External identity links require a resolved tenant.", nameof(tenantId)); |
| | 56 | 250 | | } |
| | | 251 | | } |
| | | 252 | | |
| | | 253 | | public sealed record ExternalIdentityLinkUser(string Id, string DisplayName); |
| | | 254 | | |
| | | 255 | | public abstract record ExternalIdentityLinkPrelinkResult |
| | | 256 | | { |
| | | 257 | | private ExternalIdentityLinkPrelinkResult() { } |
| | | 258 | | public sealed record Success(ExternalIdentityLink Link, bool WasCreated) : ExternalIdentityLinkPrelinkResult; |
| | | 259 | | public sealed record Conflict(ExternalIdentityLink Link) : ExternalIdentityLinkPrelinkResult; |
| | | 260 | | public sealed record UserNotFound : ExternalIdentityLinkPrelinkResult; |
| | | 261 | | public sealed record ConnectionNotFound : ExternalIdentityLinkPrelinkResult; |
| | | 262 | | } |