| | | 1 | | using System.Security.Claims; |
| | | 2 | | using System.Security.Cryptography; |
| | | 3 | | using System.Text; |
| | | 4 | | using System.Text.Json; |
| | | 5 | | using Elsa.Common.Multitenancy; |
| | | 6 | | using Elsa.Connections.Contracts; |
| | | 7 | | using Elsa.Connections.Models; |
| | | 8 | | using Elsa.Secrets.Contracts; |
| | | 9 | | using Elsa.Secrets.Models; |
| | | 10 | | |
| | | 11 | | namespace Elsa.Connections.Services; |
| | | 12 | | |
| | | 13 | | /// <summary>Coordinates one-time provider refreshes through durable intent, provider-call, stage, and publish states.</ |
| | 149 | 14 | | public sealed class DefaultConnectionLifecycleService( |
| | 149 | 15 | | IConnectionLifecycleStore store, |
| | 149 | 16 | | IConnectionUseAuthorizer authorizer, |
| | 149 | 17 | | IManagedSecretManager secrets, |
| | 149 | 18 | | TimeProvider timeProvider, |
| | 149 | 19 | | ITenantAccessor tenantAccessor, |
| | 149 | 20 | | IConnectionCredentialProvider? provider = null, |
| | 149 | 21 | | IConnectionOffboardingProvider? offboardingProvider = null) : IConnectionLifecycleService, IStaticApiKeyLifecycleSer |
| | | 22 | | { |
| | 51 | 23 | | private static readonly TimeSpan OperationLeaseDuration = TimeSpan.FromMinutes(2); |
| | 51 | 24 | | private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web); |
| | 51 | 25 | | private static readonly ClaimsPrincipal SystemPrincipal = new(new ClaimsIdentity( |
| | 51 | 26 | | [new Claim(ClaimTypes.NameIdentifier, "elsa-connections-lifecycle"), new Claim("elsa:identity-kind", "system")], |
| | 51 | 27 | | "Elsa.Connections.Server")); |
| | | 28 | | |
| | | 29 | | public async Task<ConnectionLifecycleResult> ConnectAsync(ClaimsPrincipal principal, ConnectConnectionRequest reques |
| | | 30 | | { |
| | 37 | 31 | | if (string.IsNullOrWhiteSpace(request.TenantId) || string.IsNullOrWhiteSpace(request.EnvironmentId) || |
| | 37 | 32 | | string.IsNullOrWhiteSpace(request.ProviderId) || string.IsNullOrWhiteSpace(request.ProviderAccountId) || |
| | 37 | 33 | | string.IsNullOrWhiteSpace(request.InitialCredentials.AccessToken) || string.IsNullOrWhiteSpace(request.Initi |
| | 37 | 34 | | request.InitialCredentials.AccessTokenExpiresAt <= timeProvider.GetUtcNow()) |
| | | 35 | | { |
| | 0 | 36 | | return new ConnectionLifecycleResult(false, "connection_input_invalid", null); |
| | | 37 | | } |
| | | 38 | | |
| | 37 | 39 | | return await ConnectCoreAsync(principal, request.TenantId, request.EnvironmentId, request.ProviderId, |
| | 37 | 40 | | request.ProviderAccountId, Serialize(request.InitialCredentials), ConnectionCredentialKind.OAuth, |
| | 37 | 41 | | request.InitialCredentials.AccessTokenExpiresAt, cancellationToken); |
| | 37 | 42 | | } |
| | | 43 | | |
| | | 44 | | public async Task<ConnectionLifecycleResult> ConnectApiKeyAsync(ClaimsPrincipal principal, ConnectApiKeyConnectionRe |
| | | 45 | | { |
| | 13 | 46 | | if (string.IsNullOrWhiteSpace(request.TenantId) || string.IsNullOrWhiteSpace(request.EnvironmentId) || |
| | 13 | 47 | | string.IsNullOrWhiteSpace(request.ProviderId) || string.IsNullOrWhiteSpace(request.ProviderAccountId) || |
| | 13 | 48 | | string.IsNullOrWhiteSpace(request.ApiKey)) |
| | | 49 | | { |
| | 0 | 50 | | return new ConnectionLifecycleResult(false, "connection_input_invalid", null); |
| | | 51 | | } |
| | | 52 | | |
| | 13 | 53 | | return await ConnectCoreAsync(principal, request.TenantId, request.EnvironmentId, request.ProviderId, |
| | 13 | 54 | | request.ProviderAccountId, SerializeApiKey(request.ApiKey), ConnectionCredentialKind.ApiKey, null, cancellat |
| | 13 | 55 | | } |
| | | 56 | | |
| | | 57 | | private async Task<ConnectionLifecycleResult> ConnectCoreAsync( |
| | | 58 | | ClaimsPrincipal principal, |
| | | 59 | | string tenantId, |
| | | 60 | | string environmentId, |
| | | 61 | | string providerId, |
| | | 62 | | string providerAccountId, |
| | | 63 | | string encryptedEnvelope, |
| | | 64 | | ConnectionCredentialKind credentialKind, |
| | | 65 | | DateTimeOffset? credentialExpiresAt, |
| | | 66 | | CancellationToken cancellationToken) |
| | | 67 | | { |
| | 50 | 68 | | if (!await AuthorizeAsync(principal, ConnectionUseKind.Human, tenantId, environmentId, "", "manage:connect", can |
| | | 69 | | { |
| | 0 | 70 | | return new ConnectionLifecycleResult(false, "connection_unavailable", null); |
| | | 71 | | } |
| | | 72 | | |
| | 50 | 73 | | using var tenantContext = PushTenant(tenantId); |
| | 50 | 74 | | var connectionId = Guid.NewGuid().ToString("N"); |
| | 50 | 75 | | var operationId = Guid.NewGuid().ToString("N"); |
| | 50 | 76 | | var secretName = ManagedSecretNames.ForGeneration(connectionId, operationId); |
| | 50 | 77 | | var connection = new IntegrationConnection |
| | 50 | 78 | | { |
| | 50 | 79 | | Id = connectionId, |
| | 50 | 80 | | TenantId = tenantId, |
| | 50 | 81 | | EnvironmentId = environmentId, |
| | 50 | 82 | | ProviderId = providerId, |
| | 50 | 83 | | ProviderAccountId = providerAccountId, |
| | 50 | 84 | | Status = ConnectionStatus.Active, |
| | 50 | 85 | | Revision = 1, |
| | 50 | 86 | | OperationId = operationId, |
| | 50 | 87 | | OperationExpectedRevision = 1, |
| | 50 | 88 | | OperationFence = 1, |
| | 50 | 89 | | OperationLeaseExpiresAt = timeProvider.GetUtcNow() + OperationLeaseDuration, |
| | 50 | 90 | | OperationStatus = CredentialOperationStatus.CredentialReceived, |
| | 50 | 91 | | PlannedSecretName = secretName, |
| | 50 | 92 | | PlannedGenerationId = operationId |
| | 50 | 93 | | }; |
| | | 94 | | |
| | | 95 | | // Persist owner metadata and planned generation before encrypted material so a process crash is recoverable. |
| | | 96 | | try |
| | | 97 | | { |
| | 50 | 98 | | await store.CreateAsync(connection, cancellationToken); |
| | 50 | 99 | | } |
| | 0 | 100 | | catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) |
| | | 101 | | { |
| | 0 | 102 | | throw; |
| | | 103 | | } |
| | 0 | 104 | | catch (Exception) |
| | | 105 | | { |
| | 0 | 106 | | return new ConnectionLifecycleResult(false, "connection_create_unknown", null, connectionId); |
| | | 107 | | } |
| | | 108 | | try |
| | | 109 | | { |
| | 50 | 110 | | await secrets.CreateGenerationAsync(connectionId, operationId, encryptedEnvelope, cancellationToken); |
| | 50 | 111 | | if (!await store.TryRecordStagedGenerationAsync(connectionId, tenantId, environmentId, 1, operationId, 1, se |
| | 50 | 112 | | credentialKind, credentialExpiresAt, cancellationToken) || |
| | 50 | 113 | | !await store.TryPublishGenerationAsync(connectionId, tenantId, environmentId, 1, operationId, 1, cancell |
| | | 114 | | { |
| | 1 | 115 | | await TryMarkRecoveryRequiredAsync(connection, tenantId, environmentId, "connection_publish_conflict"); |
| | 1 | 116 | | return new ConnectionLifecycleResult(false, "connection_publish_conflict", 1, connectionId); |
| | | 117 | | } |
| | 48 | 118 | | } |
| | 0 | 119 | | catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) |
| | | 120 | | { |
| | 0 | 121 | | await TryMarkRecoveryRequiredAsync(connection, tenantId, environmentId, "connection_outcome_unknown"); |
| | 0 | 122 | | throw new OperationCanceledException("Connection setup was cancelled; creation outcome is unknown.", cancell |
| | | 123 | | } |
| | | 124 | | catch (Exception) |
| | | 125 | | { |
| | 1 | 126 | | await TryMarkRecoveryRequiredAsync(connection, tenantId, environmentId, "connection_outcome_unknown"); |
| | 1 | 127 | | return new ConnectionLifecycleResult(false, "connection_outcome_unknown", 1, connectionId); |
| | | 128 | | } |
| | | 129 | | |
| | 48 | 130 | | connection.CurrentSecretName = secretName; |
| | 48 | 131 | | connection.CurrentGenerationId = operationId; |
| | 48 | 132 | | connection.OperationStatus = CredentialOperationStatus.Completed; |
| | 48 | 133 | | connection.Revision = 2; |
| | 48 | 134 | | return new ConnectionLifecycleResult(true, null, connection.Revision, connectionId, ToMetadata(connection)); |
| | 50 | 135 | | } |
| | | 136 | | |
| | | 137 | | public async Task<ConnectionLifecycleResult> ReplaceApiKeyAsync( |
| | | 138 | | ClaimsPrincipal principal, |
| | | 139 | | string tenantId, |
| | | 140 | | string environmentId, |
| | | 141 | | string connectionId, |
| | | 142 | | long expectedRevision, |
| | | 143 | | string apiKey, |
| | | 144 | | CancellationToken cancellationToken = default) |
| | | 145 | | { |
| | 12 | 146 | | if (string.IsNullOrWhiteSpace(apiKey) || expectedRevision <= 0 || |
| | 12 | 147 | | !await AuthorizeAsync(principal, ConnectionUseKind.Human, tenantId, environmentId, connectionId, "manage:rot |
| | | 148 | | { |
| | 0 | 149 | | return new ConnectionLifecycleResult(false, "connection_unavailable", null); |
| | | 150 | | } |
| | | 151 | | |
| | 12 | 152 | | using var tenantContext = PushTenant(tenantId); |
| | 12 | 153 | | var current = await store.FindAsync(connectionId, tenantId, environmentId, cancellationToken); |
| | 12 | 154 | | if (current is not { Status: ConnectionStatus.Active } || current.Revision != expectedRevision || |
| | 12 | 155 | | !await IsApiKeyGenerationAsync(current, cancellationToken)) |
| | | 156 | | { |
| | 6 | 157 | | return new ConnectionLifecycleResult(false, "connection_unavailable", current?.Revision, connectionId, |
| | 6 | 158 | | current == null ? null : ToMetadata(current)); |
| | | 159 | | } |
| | | 160 | | |
| | 6 | 161 | | var operationId = Guid.NewGuid().ToString("N"); |
| | 6 | 162 | | var claimed = await store.TryClaimCredentialUpdateAsync(connectionId, tenantId, environmentId, |
| | 6 | 163 | | expectedRevision, operationId, timeProvider.GetUtcNow() + OperationLeaseDuration, cancellationToken); |
| | 6 | 164 | | if (claimed == null) |
| | | 165 | | { |
| | 0 | 166 | | var latest = await store.FindAsync(connectionId, tenantId, environmentId, cancellationToken); |
| | 0 | 167 | | return new ConnectionLifecycleResult(false, "connection_conflict", latest?.Revision, connectionId, |
| | 0 | 168 | | latest == null ? null : ToMetadata(latest)); |
| | | 169 | | } |
| | | 170 | | |
| | 6 | 171 | | var expectedOperationRevision = claimed.OperationExpectedRevision; |
| | 6 | 172 | | var fence = claimed.OperationFence; |
| | 6 | 173 | | var secretName = ManagedSecretNames.ForGeneration(connectionId, operationId); |
| | | 174 | | try |
| | | 175 | | { |
| | 6 | 176 | | if (!await store.TryAcceptCredentialUpdateAsync(connectionId, tenantId, environmentId, |
| | 6 | 177 | | expectedOperationRevision, operationId, fence, timeProvider.GetUtcNow(), cancellationToken)) |
| | | 178 | | { |
| | 0 | 179 | | await TryReleaseUnstartedRefreshAsync(claimed, tenantId, environmentId, "rotation_conflict"); |
| | 0 | 180 | | return new ConnectionLifecycleResult(false, "rotation_conflict", expectedOperationRevision, connectionId |
| | | 181 | | } |
| | | 182 | | |
| | 6 | 183 | | await secrets.CreateGenerationAsync(connectionId, operationId, SerializeApiKey(apiKey), cancellationToken); |
| | 6 | 184 | | if (!await store.TryRecordStagedGenerationAsync(connectionId, tenantId, environmentId, expectedOperationRevi |
| | 6 | 185 | | operationId, fence, secretName, operationId, ConnectionCredentialKind.ApiKey, null, cancellationToke |
| | | 186 | | { |
| | 1 | 187 | | await CleanupUnreferencedOrphanGenerationAsync(connectionId, tenantId, environmentId, operationId, cance |
| | 1 | 188 | | await TryMarkRecoveryRequiredAsync(claimed, tenantId, environmentId, "rotation_publish_conflict"); |
| | 1 | 189 | | return new ConnectionLifecycleResult(false, "rotation_publish_conflict", expectedOperationRevision, conn |
| | | 190 | | } |
| | | 191 | | |
| | 4 | 192 | | if (!await store.TryPublishGenerationAsync(connectionId, tenantId, environmentId, expectedOperationRevision, |
| | 4 | 193 | | operationId, fence, cancellationToken)) |
| | | 194 | | { |
| | 0 | 195 | | await TryMarkRecoveryRequiredAsync(claimed, tenantId, environmentId, "rotation_publish_conflict"); |
| | 0 | 196 | | return new ConnectionLifecycleResult(false, "rotation_publish_conflict", expectedOperationRevision, conn |
| | | 197 | | } |
| | | 198 | | |
| | 4 | 199 | | var published = await store.FindAsync(connectionId, tenantId, environmentId, cancellationToken); |
| | 4 | 200 | | return published == null |
| | 4 | 201 | | ? new ConnectionLifecycleResult(false, "connection_unavailable", null) |
| | 4 | 202 | | : new ConnectionLifecycleResult(true, null, published.Revision, connectionId, ToMetadata(published)); |
| | | 203 | | } |
| | 0 | 204 | | catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) |
| | | 205 | | { |
| | 0 | 206 | | await TryMarkRecoveryRequiredAsync(claimed, tenantId, environmentId, "rotation_outcome_unknown"); |
| | 0 | 207 | | throw new OperationCanceledException("API-key replacement outcome is unknown.", cancellationToken); |
| | | 208 | | } |
| | | 209 | | catch (Exception) |
| | | 210 | | { |
| | 1 | 211 | | await TryMarkRecoveryRequiredAsync(claimed, tenantId, environmentId, "rotation_outcome_unknown"); |
| | 1 | 212 | | return new ConnectionLifecycleResult(false, "rotation_outcome_unknown", expectedOperationRevision, connectio |
| | | 213 | | } |
| | 12 | 214 | | } |
| | | 215 | | |
| | | 216 | | public async Task<ConnectionAccessCredential> ResolveForUseAsync(ClaimsPrincipal principal, string tenantId, string |
| | | 217 | | { |
| | 29 | 218 | | if (!await AuthorizeAsync(principal, ConnectionUseKind.Human, tenantId, environmentId, connectionId, "use", canc |
| | | 219 | | { |
| | 0 | 220 | | throw new ConnectionUnavailableException(); |
| | | 221 | | } |
| | | 222 | | |
| | 29 | 223 | | return await ResolveAuthorizedCredentialAsync(tenantId, environmentId, connectionId, cancellationToken); |
| | 15 | 224 | | } |
| | | 225 | | |
| | | 226 | | public async Task<ConnectionAccessCredential> ResolveForUseAsync(string tenantId, string environmentId, string conne |
| | | 227 | | { |
| | 7 | 228 | | if (!await AuthorizeAsync(SystemPrincipal, ConnectionUseKind.BackgroundSystem, tenantId, environmentId, connecti |
| | | 229 | | { |
| | 1 | 230 | | throw new ConnectionUnavailableException(); |
| | | 231 | | } |
| | | 232 | | |
| | 6 | 233 | | return await ResolveAuthorizedCredentialAsync(tenantId, environmentId, connectionId, cancellationToken); |
| | 6 | 234 | | } |
| | | 235 | | |
| | | 236 | | private async Task<ConnectionAccessCredential> ResolveAuthorizedCredentialAsync(string tenantId, string environmentI |
| | | 237 | | { |
| | 35 | 238 | | using var tenantContext = PushTenant(tenantId); |
| | 35 | 239 | | var connection = await store.FindAsync(connectionId, tenantId, environmentId, cancellationToken); |
| | 35 | 240 | | if (!CanUseCurrentGeneration(connection)) |
| | | 241 | | { |
| | 3 | 242 | | throw new ConnectionUnavailableException(); |
| | | 243 | | } |
| | | 244 | | |
| | | 245 | | CredentialEnvelope? material; |
| | | 246 | | try |
| | | 247 | | { |
| | 32 | 248 | | var payload = await secrets.ResolveGenerationAsync(connection!.CurrentSecretName!, connection.Id, connection |
| | 26 | 249 | | material = Deserialize(payload.Value); |
| | 26 | 250 | | } |
| | 0 | 251 | | catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) |
| | | 252 | | { |
| | 0 | 253 | | throw new OperationCanceledException("Connection access was cancelled.", cancellationToken); |
| | | 254 | | } |
| | 6 | 255 | | catch (Exception) |
| | | 256 | | { |
| | 6 | 257 | | throw new ConnectionUnavailableException(); |
| | | 258 | | } |
| | | 259 | | |
| | 26 | 260 | | if (!IsValidEnvelope(material) || |
| | 26 | 261 | | (material!.Kind ?? ConnectionCredentialKind.OAuth) == ConnectionCredentialKind.OAuth && |
| | 26 | 262 | | material.AccessTokenExpiresAt <= timeProvider.GetUtcNow()) |
| | | 263 | | { |
| | 4 | 264 | | throw new ConnectionUnavailableException(); |
| | | 265 | | } |
| | | 266 | | |
| | 22 | 267 | | var validMaterial = material!; |
| | | 268 | | |
| | 22 | 269 | | var latest = await store.FindAsync(connectionId, tenantId, environmentId, cancellationToken); |
| | 22 | 270 | | if (latest == null || latest.Status != ConnectionStatus.Active || |
| | 22 | 271 | | latest.Revision != connection.Revision || latest.CurrentGenerationId != connection.CurrentGenerationId || |
| | 22 | 272 | | latest.CurrentSecretName != connection.CurrentSecretName || |
| | 22 | 273 | | latest.OperationStatus is not (CredentialOperationStatus.None or CredentialOperationStatus.Completed)) |
| | | 274 | | { |
| | 1 | 275 | | throw new ConnectionUnavailableException(); |
| | | 276 | | } |
| | | 277 | | |
| | 21 | 278 | | return validMaterial.Kind == ConnectionCredentialKind.ApiKey |
| | 21 | 279 | | ? new ConnectionAccessCredential(ConnectionCredentialKind.ApiKey, validMaterial.AccessToken!, null) |
| | 21 | 280 | | : new ConnectionAccessCredential(ConnectionCredentialKind.OAuth, validMaterial.AccessToken!, validMaterial.A |
| | 21 | 281 | | } |
| | | 282 | | |
| | | 283 | | public async Task<ConnectionOffboardingOperationResult> DisconnectAsync( |
| | | 284 | | ClaimsPrincipal principal, |
| | | 285 | | string tenantId, |
| | | 286 | | string environmentId, |
| | | 287 | | string connectionId, |
| | | 288 | | CancellationToken cancellationToken = default) |
| | | 289 | | { |
| | 17 | 290 | | if (!await AuthorizeAsync(principal, ConnectionUseKind.Human, tenantId, environmentId, connectionId, "manage:dis |
| | | 291 | | { |
| | 0 | 292 | | return new ConnectionOffboardingOperationResult(false, "connection_unavailable", null, null, null); |
| | | 293 | | } |
| | | 294 | | |
| | 17 | 295 | | using var tenantContext = PushTenant(tenantId); |
| | 17 | 296 | | var connection = await store.FindAsync(connectionId, tenantId, environmentId, cancellationToken); |
| | 17 | 297 | | if (connection == null) |
| | | 298 | | { |
| | 0 | 299 | | return new ConnectionOffboardingOperationResult(false, "connection_unavailable", null, null, null); |
| | | 300 | | } |
| | | 301 | | |
| | 17 | 302 | | var operationId = GetOffboardingOperationId(tenantId, environmentId, connectionId, ConnectionOffboardingOperatio |
| | 17 | 303 | | var existing = await store.FindOffboardingOperationAsync(operationId, tenantId, environmentId, connectionId, can |
| | 17 | 304 | | if (existing != null) |
| | | 305 | | { |
| | 2 | 306 | | return new ConnectionOffboardingOperationResult(true, null, operationId, existing.Status, connection.Revisio |
| | | 307 | | } |
| | | 308 | | |
| | 15 | 309 | | var now = timeProvider.GetUtcNow(); |
| | 15 | 310 | | var operation = new ConnectionOffboardingOperation |
| | 15 | 311 | | { |
| | 15 | 312 | | Id = operationId, |
| | 15 | 313 | | TenantId = tenantId, |
| | 15 | 314 | | EnvironmentId = environmentId, |
| | 15 | 315 | | ConnectionId = connectionId, |
| | 15 | 316 | | ProviderId = connection.ProviderId, |
| | 15 | 317 | | ProviderAccountId = connection.ProviderAccountId, |
| | 15 | 318 | | Kind = ConnectionOffboardingOperationKind.LocalDisconnect, |
| | 15 | 319 | | Status = ConnectionOffboardingOperationStatus.Completed, |
| | 15 | 320 | | Fence = 1, |
| | 15 | 321 | | CreatedAt = now, |
| | 15 | 322 | | UpdatedAt = now |
| | 15 | 323 | | }; |
| | 15 | 324 | | var disconnected = await store.TryDisconnectAndRecordAsync(connectionId, tenantId, environmentId, connection.Rev |
| | 15 | 325 | | if (disconnected != null) |
| | | 326 | | { |
| | 15 | 327 | | return new ConnectionOffboardingOperationResult(true, null, operationId, operation.Status, disconnected.Revi |
| | | 328 | | } |
| | | 329 | | |
| | 0 | 330 | | var latestOperation = await store.FindOffboardingOperationAsync(operationId, tenantId, environmentId, connection |
| | 0 | 331 | | var latestConnection = await store.FindAsync(connectionId, tenantId, environmentId, cancellationToken); |
| | 0 | 332 | | return latestOperation != null && latestConnection != null |
| | 0 | 333 | | ? new ConnectionOffboardingOperationResult(true, null, operationId, latestOperation.Status, latestConnection |
| | 0 | 334 | | : new ConnectionOffboardingOperationResult(false, "connection_conflict", operationId, null, latestConnection |
| | 17 | 335 | | } |
| | | 336 | | |
| | | 337 | | public async Task<ConnectionOffboardingOperationResult> RequestTokenRevocationAsync( |
| | | 338 | | ClaimsPrincipal principal, |
| | | 339 | | string tenantId, |
| | | 340 | | string environmentId, |
| | | 341 | | string connectionId, |
| | | 342 | | string generationId, |
| | | 343 | | CancellationToken cancellationToken = default) |
| | | 344 | | { |
| | 10 | 345 | | if (!await AuthorizeAsync(principal, ConnectionUseKind.Human, tenantId, environmentId, connectionId, "manage:rev |
| | | 346 | | { |
| | 0 | 347 | | return new ConnectionOffboardingOperationResult(false, "connection_unavailable", null, null, null); |
| | | 348 | | } |
| | | 349 | | |
| | 10 | 350 | | return await QueueOffboardingOperationAsync(tenantId, environmentId, connectionId, |
| | 10 | 351 | | ConnectionOffboardingOperationKind.TokenPairRevocation, generationId, cancellationToken); |
| | 10 | 352 | | } |
| | | 353 | | |
| | | 354 | | public async Task<ConnectionOffboardingOperationResult> RequestInstallationUninstallAsync( |
| | | 355 | | ClaimsPrincipal principal, |
| | | 356 | | string tenantId, |
| | | 357 | | string environmentId, |
| | | 358 | | string connectionId, |
| | | 359 | | CancellationToken cancellationToken = default) |
| | | 360 | | { |
| | 6 | 361 | | if (!await AuthorizeAsync(principal, ConnectionUseKind.Human, tenantId, environmentId, connectionId, "manage:uni |
| | | 362 | | { |
| | 0 | 363 | | return new ConnectionOffboardingOperationResult(false, "connection_unavailable", null, null, null); |
| | | 364 | | } |
| | | 365 | | |
| | 6 | 366 | | return await QueueOffboardingOperationAsync(tenantId, environmentId, connectionId, |
| | 6 | 367 | | ConnectionOffboardingOperationKind.InstallationUninstall, null, cancellationToken); |
| | 6 | 368 | | } |
| | | 369 | | |
| | | 370 | | public async Task<ConnectionOffboardingOperationResult> ReconcileOffboardingAsync( |
| | | 371 | | string tenantId, |
| | | 372 | | string environmentId, |
| | | 373 | | string connectionId, |
| | | 374 | | CancellationToken cancellationToken = default) |
| | | 375 | | { |
| | 16 | 376 | | if (!await AuthorizeAsync(SystemPrincipal, ConnectionUseKind.BackgroundSystem, tenantId, environmentId, connecti |
| | | 377 | | { |
| | 0 | 378 | | return new ConnectionOffboardingOperationResult(false, "connection_unavailable", null, null, null); |
| | | 379 | | } |
| | | 380 | | |
| | 16 | 381 | | using var tenantContext = PushTenant(tenantId); |
| | 16 | 382 | | var now = timeProvider.GetUtcNow(); |
| | 16 | 383 | | var stableRevocationIdempotency = offboardingProvider?.SupportsStableOperationIdIdempotency(ConnectionOffboardin |
| | 16 | 384 | | var stableUninstallIdempotency = offboardingProvider?.SupportsStableOperationIdIdempotency(ConnectionOffboarding |
| | 16 | 385 | | var pending = await store.FindNextOffboardingOperationAsync( |
| | 16 | 386 | | tenantId, environmentId, connectionId, now, stableRevocationIdempotency, stableUninstallIdempotency, cancell |
| | 16 | 387 | | if (pending == null) |
| | | 388 | | { |
| | 4 | 389 | | var current = await store.FindAsync(connectionId, tenantId, environmentId, cancellationToken); |
| | 4 | 390 | | return new ConnectionOffboardingOperationResult(true, null, null, null, current?.Revision); |
| | | 391 | | } |
| | | 392 | | |
| | 12 | 393 | | var supportsStableIdempotency = offboardingProvider?.SupportsStableOperationIdIdempotency(pending.Kind) == true; |
| | | 394 | | |
| | 12 | 395 | | if (!supportsStableIdempotency && pending.Status == ConnectionOffboardingOperationStatus.UnknownOutcome) |
| | | 396 | | { |
| | 1 | 397 | | return await GetOffboardingResultAsync(pending.Id, tenantId, environmentId, connectionId, false, |
| | 1 | 398 | | "offboarding_outcome_unknown", cancellationToken); |
| | | 399 | | } |
| | | 400 | | |
| | 11 | 401 | | if (!supportsStableIdempotency && pending.Status == ConnectionOffboardingOperationStatus.ProviderCallStarted && |
| | 11 | 402 | | pending.LeaseExpiresAt <= now) |
| | | 403 | | { |
| | 2 | 404 | | await store.TryMarkOffboardingOutcomeUnknownIfLeaseExpiredAsync(pending.Id, tenantId, environmentId, connect |
| | 2 | 405 | | pending.Fence, now, "provider_outcome_unknown", CancellationToken.None); |
| | 2 | 406 | | return await GetOffboardingResultAsync(pending.Id, tenantId, environmentId, connectionId, false, |
| | 2 | 407 | | "offboarding_outcome_unknown", cancellationToken); |
| | | 408 | | } |
| | | 409 | | |
| | 9 | 410 | | var claimed = await store.TryClaimOffboardingOperationAsync( |
| | 9 | 411 | | pending.Id, tenantId, environmentId, connectionId, pending.Fence, now, now + OperationLeaseDuration, cancell |
| | 9 | 412 | | if (claimed == null) |
| | | 413 | | { |
| | 0 | 414 | | return await GetOffboardingResultAsync(pending.Id, tenantId, environmentId, connectionId, false, "offboardin |
| | | 415 | | } |
| | | 416 | | |
| | 9 | 417 | | if (offboardingProvider == null) |
| | | 418 | | { |
| | 0 | 419 | | await ReleaseOffboardingClaimAsync(claimed, tenantId, environmentId, connectionId, "offboarding_provider_una |
| | 0 | 420 | | return await GetOffboardingResultAsync(claimed.Id, tenantId, environmentId, connectionId, false, "offboardin |
| | | 421 | | } |
| | | 422 | | |
| | 9 | 423 | | CredentialMaterial? credentials = null; |
| | 9 | 424 | | if (claimed.Kind == ConnectionOffboardingOperationKind.TokenPairRevocation) |
| | | 425 | | { |
| | | 426 | | try |
| | | 427 | | { |
| | 7 | 428 | | if (string.IsNullOrWhiteSpace(claimed.GenerationId)) |
| | | 429 | | { |
| | 0 | 430 | | throw new ConnectionUnavailableException(); |
| | | 431 | | } |
| | | 432 | | |
| | 7 | 433 | | var secretName = ManagedSecretNames.ForGeneration(connectionId, claimed.GenerationId); |
| | 7 | 434 | | var payload = await secrets.ResolveGenerationAsync(secretName, connectionId, claimed.GenerationId, cance |
| | 7 | 435 | | var envelope = Deserialize(payload.Value); |
| | 7 | 436 | | var accessTokenExpiresAt = envelope?.AccessTokenExpiresAt; |
| | 7 | 437 | | if (envelope is not { Kind: null or ConnectionCredentialKind.OAuth, AccessToken: not null, RefreshToken: |
| | 7 | 438 | | !accessTokenExpiresAt.HasValue) |
| | | 439 | | { |
| | 0 | 440 | | throw new ConnectionUnavailableException(); |
| | | 441 | | } |
| | | 442 | | |
| | 7 | 443 | | credentials = new CredentialMaterial(envelope.AccessToken, envelope.RefreshToken, accessTokenExpiresAt.V |
| | 7 | 444 | | } |
| | 0 | 445 | | catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) |
| | | 446 | | { |
| | 0 | 447 | | await ReleaseOffboardingClaimAsync(claimed, tenantId, environmentId, connectionId, "offboarding_cancelle |
| | 0 | 448 | | throw new OperationCanceledException("Credential offboarding was cancelled before the provider call.", c |
| | | 449 | | } |
| | | 450 | | catch (Exception) |
| | | 451 | | { |
| | 0 | 452 | | await ReleaseOffboardingClaimAsync(claimed, tenantId, environmentId, connectionId, "credential_unavailab |
| | 0 | 453 | | return await GetOffboardingResultAsync(claimed.Id, tenantId, environmentId, connectionId, false, "creden |
| | | 454 | | } |
| | | 455 | | } |
| | | 456 | | |
| | 9 | 457 | | now = timeProvider.GetUtcNow(); |
| | 9 | 458 | | if (!await store.TryStartOffboardingProviderCallAsync(claimed.Id, tenantId, environmentId, connectionId, claimed |
| | | 459 | | { |
| | 0 | 460 | | await ReleaseOffboardingClaimAsync(claimed, tenantId, environmentId, connectionId, "offboarding_conflict"); |
| | 0 | 461 | | return await GetOffboardingResultAsync(claimed.Id, tenantId, environmentId, connectionId, false, "offboardin |
| | | 462 | | } |
| | | 463 | | |
| | | 464 | | try |
| | | 465 | | { |
| | 9 | 466 | | var providerResult = claimed.Kind switch |
| | 9 | 467 | | { |
| | 7 | 468 | | ConnectionOffboardingOperationKind.TokenPairRevocation when credentials != null => |
| | 7 | 469 | | await offboardingProvider.RevokeTokenPairAsync(claimed.ProviderId, claimed.ProviderAccountId, claime |
| | 9 | 470 | | ConnectionOffboardingOperationKind.InstallationUninstall => |
| | 2 | 471 | | await offboardingProvider.UninstallInstallationAsync(claimed.ProviderId, claimed.ProviderAccountId, |
| | 0 | 472 | | _ => ConnectionOffboardingProviderResult.TerminalFailure |
| | 9 | 473 | | }; |
| | | 474 | | |
| | 9 | 475 | | now = timeProvider.GetUtcNow(); |
| | | 476 | | switch (providerResult) |
| | | 477 | | { |
| | | 478 | | case ConnectionOffboardingProviderResult.Succeeded: |
| | | 479 | | // Once the provider has confirmed success, caller cancellation must not turn that known |
| | | 480 | | // result into an unknown operation. Persist the semantic outcome independently. |
| | 7 | 481 | | await store.TryCompleteOffboardingOperationAsync(claimed.Id, tenantId, environmentId, connectionId, |
| | 7 | 482 | | break; |
| | | 483 | | case ConnectionOffboardingProviderResult.RetryableFailure: |
| | 0 | 484 | | await RecordOffboardingFailureAsync(claimed, tenantId, environmentId, connectionId, |
| | 0 | 485 | | ConnectionOffboardingOperationStatus.RetryScheduled, "provider_retryable_failure"); |
| | 0 | 486 | | break; |
| | | 487 | | case ConnectionOffboardingProviderResult.TerminalFailure: |
| | 0 | 488 | | await RecordOffboardingFailureAsync(claimed, tenantId, environmentId, connectionId, |
| | 0 | 489 | | ConnectionOffboardingOperationStatus.TerminalFailure, "provider_terminal_failure"); |
| | 0 | 490 | | break; |
| | | 491 | | case ConnectionOffboardingProviderResult.UnknownOutcome: |
| | 2 | 492 | | await RecordOffboardingFailureAsync(claimed, tenantId, environmentId, connectionId, |
| | 2 | 493 | | ConnectionOffboardingOperationStatus.UnknownOutcome, "provider_outcome_unknown", supportsStableI |
| | | 494 | | break; |
| | | 495 | | } |
| | 9 | 496 | | } |
| | 0 | 497 | | catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) |
| | | 498 | | { |
| | 0 | 499 | | await RecordOffboardingFailureAsync(claimed, tenantId, environmentId, connectionId, |
| | 0 | 500 | | ConnectionOffboardingOperationStatus.UnknownOutcome, "provider_outcome_unknown", supportsStableIdempoten |
| | 0 | 501 | | throw new OperationCanceledException("Credential offboarding was cancelled; provider outcome is unknown.", c |
| | | 502 | | } |
| | | 503 | | catch (Exception) |
| | | 504 | | { |
| | 0 | 505 | | await RecordOffboardingFailureAsync(claimed, tenantId, environmentId, connectionId, |
| | 0 | 506 | | ConnectionOffboardingOperationStatus.UnknownOutcome, "provider_outcome_unknown", supportsStableIdempoten |
| | | 507 | | } |
| | | 508 | | |
| | 9 | 509 | | return await GetOffboardingResultAsync(claimed.Id, tenantId, environmentId, connectionId, true, null, cancellati |
| | 15 | 510 | | } |
| | | 511 | | |
| | | 512 | | public Task<ConnectionLifecycleResult> RefreshAsync(ClaimsPrincipal principal, string tenantId, string environmentId |
| | 26 | 513 | | RefreshCoreAsync(principal, ConnectionUseKind.Human, tenantId, environmentId, connectionId, cancellationToken); |
| | | 514 | | |
| | | 515 | | public Task<ConnectionLifecycleResult> RefreshAsync(string tenantId, string environmentId, string connectionId, Canc |
| | 1 | 516 | | RefreshCoreAsync(SystemPrincipal, ConnectionUseKind.BackgroundSystem, tenantId, environmentId, connectionId, can |
| | | 517 | | |
| | | 518 | | private async Task<ConnectionLifecycleResult> RefreshCoreAsync(ClaimsPrincipal principal, ConnectionUseKind useKind, |
| | | 519 | | { |
| | 27 | 520 | | if (!await AuthorizeAsync(principal, useKind, tenantId, environmentId, connectionId, "manage:refresh", cancellat |
| | | 521 | | { |
| | 4 | 522 | | return new ConnectionLifecycleResult(false, "connection_unavailable", null); |
| | | 523 | | } |
| | | 524 | | |
| | 23 | 525 | | using var tenantContext = PushTenant(tenantId); |
| | 23 | 526 | | var current = await store.FindAsync(connectionId, tenantId, environmentId, cancellationToken); |
| | 23 | 527 | | if (current == null) |
| | | 528 | | { |
| | 0 | 529 | | return new ConnectionLifecycleResult(false, "connection_unavailable", null); |
| | | 530 | | } |
| | 23 | 531 | | if (!CanUseCurrentGeneration(current)) |
| | | 532 | | { |
| | 4 | 533 | | var code = current.Status == ConnectionStatus.Active ? "refresh_conflict" : "connection_unavailable"; |
| | 4 | 534 | | return new ConnectionLifecycleResult(false, code, current.Revision, connectionId, ToMetadata(current)); |
| | | 535 | | } |
| | | 536 | | |
| | | 537 | | // Read before claiming so a static key never advances the revision through an unsupported |
| | | 538 | | // refresh. A failed read is still a safe, pre-provider failure and leaves the connection usable. |
| | | 539 | | CredentialEnvelope? currentMaterial; |
| | 19 | 540 | | var preflightReadFailed = false; |
| | | 541 | | try |
| | | 542 | | { |
| | 19 | 543 | | var payload = await secrets.ResolveGenerationAsync(current.CurrentSecretName!, current.Id, current.CurrentGe |
| | 18 | 544 | | currentMaterial = Deserialize(payload.Value); |
| | 18 | 545 | | } |
| | 0 | 546 | | catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) |
| | | 547 | | { |
| | 0 | 548 | | throw; |
| | | 549 | | } |
| | 1 | 550 | | catch (Exception) |
| | | 551 | | { |
| | 1 | 552 | | currentMaterial = null; |
| | 1 | 553 | | preflightReadFailed = true; |
| | 1 | 554 | | } |
| | | 555 | | |
| | 19 | 556 | | if (currentMaterial?.Kind == ConnectionCredentialKind.ApiKey && IsValidEnvelope(currentMaterial)) |
| | | 557 | | { |
| | 2 | 558 | | return new ConnectionLifecycleResult(false, "credential_refresh_unsupported", current.Revision, connectionId |
| | | 559 | | } |
| | | 560 | | |
| | 17 | 561 | | if (provider == null) |
| | | 562 | | { |
| | 0 | 563 | | var code = IsValidEnvelope(currentMaterial) ? "credential_provider_unavailable" : "credential_unavailable"; |
| | 0 | 564 | | return new ConnectionLifecycleResult(false, code, current.Revision, connectionId, ToMetadata(current)); |
| | | 565 | | } |
| | | 566 | | |
| | 17 | 567 | | var operationId = Guid.NewGuid().ToString("N"); |
| | 17 | 568 | | var claimed = await store.TryClaimRefreshAsync(connectionId, tenantId, environmentId, current!.Revision, operati |
| | 17 | 569 | | if (claimed == null) |
| | | 570 | | { |
| | | 571 | | // Another worker may already have claimed or completed the refresh. Return state reloaded after the |
| | | 572 | | // lost CAS instead of reporting the revision from this worker's stale pre-claim snapshot. |
| | 0 | 573 | | var latest = await store.FindAsync(connectionId, tenantId, environmentId, cancellationToken); |
| | 0 | 574 | | return latest == null |
| | 0 | 575 | | ? new ConnectionLifecycleResult(false, "connection_unavailable", null) |
| | 0 | 576 | | : new ConnectionLifecycleResult(false, "refresh_conflict", latest.Revision, connectionId, ToMetadata(lat |
| | | 577 | | } |
| | | 578 | | |
| | 17 | 579 | | var expectedRevision = claimed.OperationExpectedRevision; |
| | 17 | 580 | | var fence = claimed.OperationFence; |
| | 17 | 581 | | var providerCallStarted = false; |
| | | 582 | | try |
| | | 583 | | { |
| | 17 | 584 | | if (preflightReadFailed) |
| | | 585 | | { |
| | 1 | 586 | | return await ReleaseUnstartedRefreshAsync(claimed, tenantId, environmentId, "refresh_not_started"); |
| | | 587 | | } |
| | | 588 | | |
| | 16 | 589 | | var oldPayload = await secrets.ResolveGenerationAsync(claimed.CurrentSecretName!, claimed.Id, claimed.Curren |
| | 16 | 590 | | var oldMaterial = Deserialize(oldPayload.Value); |
| | 16 | 591 | | if (oldMaterial?.Kind == ConnectionCredentialKind.ApiKey) |
| | | 592 | | { |
| | 0 | 593 | | return await ReleaseUnstartedRefreshAsync(claimed, tenantId, environmentId, "credential_refresh_unsuppor |
| | | 594 | | } |
| | | 595 | | |
| | 16 | 596 | | if (oldMaterial == null || oldMaterial.Kind is not null and not ConnectionCredentialKind.OAuth || |
| | 16 | 597 | | string.IsNullOrWhiteSpace(oldMaterial.AccessToken) || string.IsNullOrWhiteSpace(oldMaterial.RefreshToken |
| | | 598 | | { |
| | 0 | 599 | | return await ReleaseUnstartedRefreshAsync(claimed, tenantId, environmentId, "credential_unavailable"); |
| | | 600 | | } |
| | | 601 | | |
| | | 602 | | // Persist this edge before crossing the provider boundary. After it, no worker may replay the token. |
| | 16 | 603 | | if (!await store.TryStartProviderCallAsync(connectionId, tenantId, environmentId, expectedRevision, operatio |
| | | 604 | | { |
| | 0 | 605 | | return await ReleaseUnstartedRefreshAsync(claimed, tenantId, environmentId, "refresh_conflict"); |
| | | 606 | | } |
| | 16 | 607 | | providerCallStarted = true; |
| | | 608 | | |
| | 16 | 609 | | var refreshed = await provider.RefreshAsync(claimed.ProviderId, claimed.ProviderAccountId, oldMaterial.Refre |
| | 15 | 610 | | if (refreshed == null || string.IsNullOrWhiteSpace(refreshed.RefreshToken) || string.IsNullOrWhiteSpace(refr |
| | | 611 | | { |
| | 0 | 612 | | return await RequireRecoveryAsync(claimed, tenantId, environmentId, "provider_refresh_unknown"); |
| | | 613 | | } |
| | | 614 | | |
| | 15 | 615 | | var nextName = ManagedSecretNames.ForGeneration(connectionId, operationId); |
| | 15 | 616 | | var encryptedEnvelope = Serialize(refreshed); |
| | 15 | 617 | | await secrets.CreateGenerationAsync(connectionId, operationId, encryptedEnvelope, cancellationToken); |
| | | 618 | | |
| | 15 | 619 | | if (!await store.TryRecordStagedGenerationAsync(connectionId, tenantId, environmentId, expectedRevision, ope |
| | 15 | 620 | | nextName, operationId, ConnectionCredentialKind.OAuth, refreshed.AccessTokenExpiresAt, cancellationT |
| | | 621 | | { |
| | 1 | 622 | | return await RequireRecoveryAsync(claimed, tenantId, environmentId, "credential_stage_unknown"); |
| | | 623 | | } |
| | | 624 | | |
| | 13 | 625 | | if (!await store.TryPublishGenerationAsync(connectionId, tenantId, environmentId, expectedRevision, operatio |
| | | 626 | | { |
| | 2 | 627 | | return await RequireRecoveryAsync(claimed, tenantId, environmentId, "generation_publish_conflict"); |
| | | 628 | | } |
| | | 629 | | |
| | 11 | 630 | | var published = await store.FindAsync(connectionId, tenantId, environmentId, cancellationToken); |
| | 11 | 631 | | return published == null |
| | 11 | 632 | | ? new ConnectionLifecycleResult(false, "connection_unavailable", null) |
| | 11 | 633 | | : new ConnectionLifecycleResult(true, null, published.Revision, connectionId, ToMetadata(published)); |
| | | 634 | | } |
| | 1 | 635 | | catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) |
| | | 636 | | { |
| | 1 | 637 | | if (providerCallStarted) |
| | | 638 | | { |
| | 1 | 639 | | await TryMarkRecoveryRequiredAsync(claimed, tenantId, environmentId, "refresh_outcome_unknown"); |
| | 1 | 640 | | throw new OperationCanceledException("Credential refresh was cancelled; provider outcome is unknown.", c |
| | | 641 | | } |
| | | 642 | | |
| | 0 | 643 | | await TryReleaseUnstartedRefreshAsync(claimed, tenantId, environmentId, "refresh_not_started"); |
| | 0 | 644 | | throw new OperationCanceledException("Credential refresh was cancelled before the provider call.", cancellat |
| | | 645 | | } |
| | | 646 | | catch (Exception) |
| | | 647 | | { |
| | 1 | 648 | | if (!providerCallStarted) |
| | | 649 | | { |
| | 0 | 650 | | return await ReleaseUnstartedRefreshAsync(claimed, tenantId, environmentId, "refresh_not_started"); |
| | | 651 | | } |
| | | 652 | | |
| | | 653 | | // Provider/network/persistence errors after the durable call-start edge can hide a one-time refresh-token r |
| | 1 | 654 | | await TryMarkRecoveryRequiredAsync(claimed, tenantId, environmentId, "refresh_outcome_unknown"); |
| | 1 | 655 | | return new ConnectionLifecycleResult(false, "refresh_outcome_unknown", expectedRevision); |
| | | 656 | | } |
| | 26 | 657 | | } |
| | | 658 | | |
| | | 659 | | public Task<ConnectionLifecycleResult> CleanupGenerationAsync( |
| | | 660 | | ClaimsPrincipal principal, |
| | | 661 | | string tenantId, |
| | | 662 | | string environmentId, |
| | | 663 | | string connectionId, |
| | | 664 | | string generationId, |
| | | 665 | | CancellationToken cancellationToken = default) => |
| | 19 | 666 | | CleanupGenerationCoreAsync(principal, ConnectionUseKind.Human, tenantId, environmentId, connectionId, generation |
| | | 667 | | |
| | | 668 | | public Task<ConnectionLifecycleResult> CleanupGenerationAsync( |
| | | 669 | | string tenantId, |
| | | 670 | | string environmentId, |
| | | 671 | | string connectionId, |
| | | 672 | | string generationId, |
| | | 673 | | CancellationToken cancellationToken = default) => |
| | 0 | 674 | | CleanupGenerationCoreAsync(SystemPrincipal, ConnectionUseKind.BackgroundSystem, tenantId, environmentId, connect |
| | | 675 | | |
| | | 676 | | private async Task<ConnectionLifecycleResult> CleanupGenerationCoreAsync( |
| | | 677 | | ClaimsPrincipal principal, |
| | | 678 | | ConnectionUseKind useKind, |
| | | 679 | | string tenantId, |
| | | 680 | | string environmentId, |
| | | 681 | | string connectionId, |
| | | 682 | | string generationId, |
| | | 683 | | CancellationToken cancellationToken) |
| | | 684 | | { |
| | 19 | 685 | | if (!await AuthorizeAsync(principal, useKind, tenantId, environmentId, connectionId, "manage:cleanup", cancellat |
| | | 686 | | { |
| | 0 | 687 | | return new ConnectionLifecycleResult(false, "connection_unavailable", null); |
| | | 688 | | } |
| | | 689 | | |
| | 19 | 690 | | if (string.IsNullOrWhiteSpace(generationId)) |
| | | 691 | | { |
| | 0 | 692 | | return new ConnectionLifecycleResult(false, "generation_unavailable", null); |
| | | 693 | | } |
| | | 694 | | |
| | 19 | 695 | | using var tenantContext = PushTenant(tenantId); |
| | 19 | 696 | | var connection = await store.FindAsync(connectionId, tenantId, environmentId, cancellationToken); |
| | 19 | 697 | | if (connection == null) |
| | | 698 | | { |
| | 0 | 699 | | return new ConnectionLifecycleResult(false, "connection_unavailable", null); |
| | | 700 | | } |
| | | 701 | | |
| | 19 | 702 | | var cleanup = await store.FindGenerationCleanupAsync(connectionId, tenantId, environmentId, generationId, cancel |
| | 19 | 703 | | if (cleanup?.Status == ConnectionGenerationCleanupStatus.Deleted) |
| | | 704 | | { |
| | 1 | 705 | | return new ConnectionLifecycleResult(true, null, connection.Revision, connectionId, ToMetadata(connection)); |
| | | 706 | | } |
| | | 707 | | |
| | 18 | 708 | | var now = timeProvider.GetUtcNow(); |
| | 18 | 709 | | var cleanupClaim = await store.TryClaimGenerationCleanupAsync( |
| | 18 | 710 | | connectionId, tenantId, environmentId, connection.Revision, generationId, now, now + OperationLeaseDuration, |
| | 18 | 711 | | if (cleanupClaim == null) |
| | | 712 | | { |
| | 9 | 713 | | cleanup = await store.FindGenerationCleanupAsync(connectionId, tenantId, environmentId, generationId, cancel |
| | 9 | 714 | | connection = await store.FindAsync(connectionId, tenantId, environmentId, cancellationToken); |
| | 9 | 715 | | if (cleanup?.Status == ConnectionGenerationCleanupStatus.Deleted && connection != null) |
| | | 716 | | { |
| | 0 | 717 | | return new ConnectionLifecycleResult(true, null, connection.Revision, connectionId, ToMetadata(connectio |
| | | 718 | | } |
| | | 719 | | |
| | 9 | 720 | | var errorCode = cleanup != null && cleanup.Status == ConnectionGenerationCleanupStatus.Deleting && cleanup.L |
| | 9 | 721 | | ? "generation_cleanup_in_progress" |
| | 9 | 722 | | : "generation_in_use"; |
| | 9 | 723 | | return new ConnectionLifecycleResult(false, errorCode, connection?.Revision, connectionId, connection is nul |
| | | 724 | | } |
| | | 725 | | |
| | 9 | 726 | | var name = ManagedSecretNames.ForGeneration(connectionId, generationId); |
| | | 727 | | try |
| | | 728 | | { |
| | | 729 | | // This host-only Secrets primitive validates the immutable owner/generation marker. The lifecycle |
| | | 730 | | // store claim above is the authorization and no-reference proof; raw host callers must not bypass it. |
| | 9 | 731 | | if (!await secrets.DeleteGenerationAsync(name, connectionId, generationId, cancellationToken)) |
| | | 732 | | { |
| | 1 | 733 | | await store.CancelGenerationCleanupAsync(connectionId, tenantId, environmentId, generationId, cleanupCla |
| | 1 | 734 | | return new ConnectionLifecycleResult(false, "generation_unavailable", connection.Revision, connectionId, |
| | | 735 | | } |
| | | 736 | | |
| | 8 | 737 | | if (!await store.CompleteGenerationCleanupAsync(connectionId, tenantId, environmentId, generationId, cleanup |
| | | 738 | | { |
| | 0 | 739 | | return new ConnectionLifecycleResult(false, "generation_cleanup_unknown", connection.Revision, connectio |
| | | 740 | | } |
| | 8 | 741 | | } |
| | 0 | 742 | | catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) |
| | | 743 | | { |
| | | 744 | | // Keep the durable Deleting tombstone. A retry repeats only the idempotent owner-checked deletion. |
| | 0 | 745 | | throw new OperationCanceledException("Credential generation cleanup was cancelled; cleanup outcome is unknow |
| | | 746 | | } |
| | 0 | 747 | | catch (Exception) |
| | | 748 | | { |
| | | 749 | | // Keep the durable Deleting tombstone if the external Secrets write may have completed. |
| | 0 | 750 | | return new ConnectionLifecycleResult(false, "generation_cleanup_unknown", connection.Revision, connectionId, |
| | | 751 | | } |
| | | 752 | | |
| | 8 | 753 | | var updated = await store.FindAsync(connectionId, tenantId, environmentId, cancellationToken); |
| | 8 | 754 | | return updated == null |
| | 8 | 755 | | ? new ConnectionLifecycleResult(false, "connection_unavailable", null) |
| | 8 | 756 | | : new ConnectionLifecycleResult(true, null, updated.Revision, connectionId, ToMetadata(updated)); |
| | 19 | 757 | | } |
| | | 758 | | |
| | | 759 | | public async Task<ConnectionLifecycleResult> ReconcileAsync(string tenantId, string environmentId, string connection |
| | | 760 | | { |
| | 24 | 761 | | if (!await AuthorizeAsync(SystemPrincipal, ConnectionUseKind.BackgroundSystem, tenantId, environmentId, connecti |
| | | 762 | | { |
| | 0 | 763 | | return new ConnectionLifecycleResult(false, "connection_unavailable", null); |
| | | 764 | | } |
| | | 765 | | |
| | 24 | 766 | | using var tenantContext = PushTenant(tenantId); |
| | 24 | 767 | | var connection = await store.FindAsync(connectionId, tenantId, environmentId, cancellationToken); |
| | 24 | 768 | | if (connection == null) |
| | | 769 | | { |
| | 0 | 770 | | return new ConnectionLifecycleResult(false, "connection_unavailable", null); |
| | | 771 | | } |
| | | 772 | | |
| | 24 | 773 | | if (connection.OperationStatus is CredentialOperationStatus.None or CredentialOperationStatus.Completed) |
| | | 774 | | { |
| | 1 | 775 | | return new ConnectionLifecycleResult(true, null, connection.Revision); |
| | | 776 | | } |
| | | 777 | | |
| | 23 | 778 | | if (connection.OperationStatus == CredentialOperationStatus.Claimed) |
| | | 779 | | { |
| | 5 | 780 | | var expiredClaim = await store.TryReleaseExpiredRefreshClaimAsync( |
| | 5 | 781 | | connection.Id, tenantId, environmentId, connection.OperationId!, connection.OperationFence, |
| | 5 | 782 | | timeProvider.GetUtcNow(), "refresh_not_started", cancellationToken); |
| | 5 | 783 | | if (expiredClaim) |
| | | 784 | | { |
| | 3 | 785 | | var released = await store.FindAsync(connectionId, tenantId, environmentId, cancellationToken); |
| | 3 | 786 | | return new ConnectionLifecycleResult(false, |
| | 3 | 787 | | released?.Status == ConnectionStatus.Active ? "refresh_not_started" : "connection_unavailable", |
| | 3 | 788 | | released?.Revision, connectionId); |
| | | 789 | | } |
| | | 790 | | |
| | 2 | 791 | | var latest = await store.FindAsync(connectionId, tenantId, environmentId, cancellationToken); |
| | 2 | 792 | | return new ConnectionLifecycleResult(false, |
| | 2 | 793 | | latest is { Status: ConnectionStatus.Active, OperationStatus: CredentialOperationStatus.Claimed or Crede |
| | 2 | 794 | | ? "operation_in_progress" |
| | 2 | 795 | | : "connection_unavailable", |
| | 2 | 796 | | latest?.Revision ?? connection.Revision, connectionId); |
| | | 797 | | } |
| | | 798 | | |
| | 18 | 799 | | if (connection.OperationStatus is CredentialOperationStatus.ProviderCallStarted or CredentialOperationStatus.Cre |
| | | 800 | | { |
| | 9 | 801 | | var expired = await store.TryMarkRecoveryRequiredIfLeaseExpiredAsync(connection.Id, tenantId, environmentId, |
| | 9 | 802 | | if (expired) |
| | | 803 | | { |
| | 5 | 804 | | if (connection.OperationStatus == CredentialOperationStatus.CredentialReceived && |
| | 5 | 805 | | await IsApiKeySourceGenerationAsync(connection, cancellationToken)) |
| | | 806 | | { |
| | 1 | 807 | | var recovery = await store.FindAsync(connectionId, tenantId, environmentId, cancellationToken); |
| | 1 | 808 | | if (recovery != null) |
| | | 809 | | { |
| | 1 | 810 | | var restored = await RestoreApiKeySourceIfPlanMissingAsync(recovery, tenantId, environmentId, ca |
| | 1 | 811 | | if (restored != null) |
| | | 812 | | { |
| | 1 | 813 | | return restored; |
| | | 814 | | } |
| | | 815 | | } |
| | | 816 | | } |
| | | 817 | | |
| | 4 | 818 | | return new ConnectionLifecycleResult(false, "refresh_outcome_unknown", connection.Revision + (connection |
| | | 819 | | } |
| | | 820 | | |
| | 4 | 821 | | return new ConnectionLifecycleResult(false, "operation_in_progress", connection.Revision); |
| | | 822 | | } |
| | | 823 | | |
| | 9 | 824 | | if (connection.OperationStatus == CredentialOperationStatus.Staged) |
| | | 825 | | { |
| | 2 | 826 | | if (connection.OperationLeaseExpiresAt > timeProvider.GetUtcNow()) |
| | | 827 | | { |
| | 1 | 828 | | return new ConnectionLifecycleResult(false, "operation_in_progress", connection.Revision); |
| | | 829 | | } |
| | | 830 | | |
| | 1 | 831 | | if (await store.TryPublishGenerationAsync(connectionId, tenantId, environmentId, connection.OperationExpecte |
| | | 832 | | { |
| | 1 | 833 | | return new ConnectionLifecycleResult(true, null, connection.OperationExpectedRevision + 1); |
| | | 834 | | } |
| | | 835 | | |
| | 0 | 836 | | await TryMarkRecoveryRequiredAsync(connection, tenantId, environmentId, "generation_publish_conflict"); |
| | 0 | 837 | | return new ConnectionLifecycleResult(false, "generation_publish_conflict", connection.Revision + (connection |
| | | 838 | | } |
| | | 839 | | |
| | 7 | 840 | | if (connection.OperationStatus == CredentialOperationStatus.RecoveryRequired && connection.Status == ConnectionS |
| | 7 | 841 | | !string.IsNullOrWhiteSpace(connection.PlannedSecretName) && !string.IsNullOrWhiteSpace(connection.PlannedGen |
| | | 842 | | { |
| | | 843 | | try |
| | | 844 | | { |
| | 5 | 845 | | var payload = await secrets.ResolveGenerationAsync(connection.PlannedSecretName, connection.Id, connecti |
| | 5 | 846 | | if (Deserialize(payload.Value) is { } envelope && IsValidEnvelope(envelope) && |
| | 5 | 847 | | (envelope.Kind == ConnectionCredentialKind.ApiKey |
| | 5 | 848 | | ? await CanPromoteApiKeyRecoveryAsync(connection, cancellationToken) |
| | 5 | 849 | | : envelope.Kind is null or ConnectionCredentialKind.OAuth) && |
| | 5 | 850 | | await store.TryPromoteRecoveryGenerationAsync(connectionId, tenantId, environmentId, connection.Revi |
| | 5 | 851 | | connection.OperationId!, connection.OperationFence, envelope.Kind ?? ConnectionCredentialKind.OA |
| | 5 | 852 | | envelope.AccessTokenExpiresAt, cancellationToken)) |
| | | 853 | | { |
| | 5 | 854 | | return new ConnectionLifecycleResult(true, null, connection.Revision + 1); |
| | | 855 | | } |
| | 0 | 856 | | } |
| | | 857 | | catch (KeyNotFoundException) |
| | | 858 | | { |
| | 0 | 859 | | var restored = await RestoreApiKeySourceIfPlanMissingAsync(connection, tenantId, environmentId, cancella |
| | 0 | 860 | | if (restored != null) |
| | | 861 | | { |
| | 0 | 862 | | return restored; |
| | | 863 | | } |
| | | 864 | | } |
| | 0 | 865 | | catch (Exception) |
| | | 866 | | { |
| | | 867 | | // Missing or invalid planned material is not safe to publish; retain RecoveryRequired. |
| | 0 | 868 | | } |
| | | 869 | | } |
| | | 870 | | |
| | 2 | 871 | | return new ConnectionLifecycleResult(false, "recovery_required", connection.Revision); |
| | 24 | 872 | | } |
| | | 873 | | |
| | | 874 | | private async Task<bool> AuthorizeAsync(ClaimsPrincipal principal, ConnectionUseKind kind, string tenantId, string e |
| | 217 | 875 | | await authorizer.AuthorizeAsync(new ConnectionUseRequest(principal, kind, tenantId, environmentId, connectionId, |
| | | 876 | | |
| | | 877 | | private async Task<ConnectionOffboardingOperationResult> QueueOffboardingOperationAsync( |
| | | 878 | | string tenantId, |
| | | 879 | | string environmentId, |
| | | 880 | | string connectionId, |
| | | 881 | | ConnectionOffboardingOperationKind kind, |
| | | 882 | | string? generationId, |
| | | 883 | | CancellationToken cancellationToken) |
| | | 884 | | { |
| | 16 | 885 | | if (kind == ConnectionOffboardingOperationKind.TokenPairRevocation && string.IsNullOrWhiteSpace(generationId) || |
| | 16 | 886 | | kind == ConnectionOffboardingOperationKind.InstallationUninstall && generationId != null) |
| | | 887 | | { |
| | 0 | 888 | | return new ConnectionOffboardingOperationResult(false, "connection_unavailable", null, null, null); |
| | | 889 | | } |
| | | 890 | | |
| | 16 | 891 | | using var tenantContext = PushTenant(tenantId); |
| | 16 | 892 | | var connection = await store.FindAsync(connectionId, tenantId, environmentId, cancellationToken); |
| | 16 | 893 | | if (connection is not { Status: ConnectionStatus.Disconnected } || |
| | 16 | 894 | | connection.OperationStatus is not (CredentialOperationStatus.None or CredentialOperationStatus.Completed)) |
| | | 895 | | { |
| | 3 | 896 | | return new ConnectionOffboardingOperationResult(false, "connection_unavailable", null, null, connection?.Rev |
| | | 897 | | } |
| | | 898 | | |
| | 13 | 899 | | var operationId = GetOffboardingOperationId(tenantId, environmentId, connectionId, kind, generationId); |
| | 13 | 900 | | var existing = await store.FindOffboardingOperationAsync(operationId, tenantId, environmentId, connectionId, can |
| | 13 | 901 | | if (existing != null) |
| | | 902 | | { |
| | 1 | 903 | | return new ConnectionOffboardingOperationResult(true, null, operationId, existing.Status, connection.Revisio |
| | | 904 | | } |
| | | 905 | | |
| | 12 | 906 | | if (kind == ConnectionOffboardingOperationKind.TokenPairRevocation) |
| | | 907 | | { |
| | | 908 | | try |
| | | 909 | | { |
| | 8 | 910 | | var payload = await secrets.ResolveGenerationAsync(ManagedSecretNames.ForGeneration(connectionId, genera |
| | 8 | 911 | | if (Deserialize(payload.Value) is not { Kind: null or ConnectionCredentialKind.OAuth }) |
| | | 912 | | { |
| | 0 | 913 | | throw new ConnectionUnavailableException(); |
| | | 914 | | } |
| | 8 | 915 | | } |
| | 0 | 916 | | catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) |
| | | 917 | | { |
| | 0 | 918 | | throw; |
| | | 919 | | } |
| | 0 | 920 | | catch (Exception) |
| | | 921 | | { |
| | 0 | 922 | | return new ConnectionOffboardingOperationResult(false, "connection_unavailable", null, null, connection. |
| | | 923 | | } |
| | | 924 | | } |
| | | 925 | | |
| | 12 | 926 | | var now = timeProvider.GetUtcNow(); |
| | 12 | 927 | | var operation = new ConnectionOffboardingOperation |
| | 12 | 928 | | { |
| | 12 | 929 | | Id = operationId, |
| | 12 | 930 | | TenantId = tenantId, |
| | 12 | 931 | | EnvironmentId = environmentId, |
| | 12 | 932 | | ConnectionId = connectionId, |
| | 12 | 933 | | ProviderId = connection.ProviderId, |
| | 12 | 934 | | ProviderAccountId = connection.ProviderAccountId, |
| | 12 | 935 | | Kind = kind, |
| | 12 | 936 | | GenerationId = generationId, |
| | 12 | 937 | | Status = ConnectionOffboardingOperationStatus.Pending, |
| | 12 | 938 | | Fence = 1, |
| | 12 | 939 | | CreatedAt = now, |
| | 12 | 940 | | UpdatedAt = now |
| | 12 | 941 | | }; |
| | | 942 | | |
| | 12 | 943 | | var queued = await store.TryQueueOffboardingOperationAsync(connection.Revision, operation, cancellationToken); |
| | 12 | 944 | | if (queued != null) |
| | | 945 | | { |
| | 12 | 946 | | return new ConnectionOffboardingOperationResult(true, null, operationId, queued.Status, connection.Revision |
| | | 947 | | } |
| | | 948 | | |
| | 0 | 949 | | var latestOperation = await store.FindOffboardingOperationAsync(operationId, tenantId, environmentId, connection |
| | 0 | 950 | | var latestConnection = await store.FindAsync(connectionId, tenantId, environmentId, cancellationToken); |
| | 0 | 951 | | return latestOperation != null && latestConnection != null |
| | 0 | 952 | | ? new ConnectionOffboardingOperationResult(true, null, operationId, latestOperation.Status, latestConnection |
| | 0 | 953 | | : new ConnectionOffboardingOperationResult(false, "connection_conflict", operationId, null, latestConnection |
| | 16 | 954 | | } |
| | | 955 | | |
| | | 956 | | private async Task<ConnectionOffboardingOperationResult> GetOffboardingResultAsync( |
| | | 957 | | string operationId, |
| | | 958 | | string tenantId, |
| | | 959 | | string environmentId, |
| | | 960 | | string connectionId, |
| | | 961 | | bool accepted, |
| | | 962 | | string? safeErrorCode, |
| | | 963 | | CancellationToken cancellationToken) |
| | | 964 | | { |
| | 12 | 965 | | var operation = await store.FindOffboardingOperationAsync(operationId, tenantId, environmentId, connectionId, ca |
| | 11 | 966 | | var connection = await store.FindAsync(connectionId, tenantId, environmentId, cancellationToken); |
| | 11 | 967 | | return new ConnectionOffboardingOperationResult(accepted, safeErrorCode, operation?.Id, operation?.Status, conne |
| | 11 | 968 | | } |
| | | 969 | | |
| | | 970 | | private async Task ReleaseOffboardingClaimAsync( |
| | | 971 | | ConnectionOffboardingOperation operation, |
| | | 972 | | string tenantId, |
| | | 973 | | string environmentId, |
| | | 974 | | string connectionId, |
| | | 975 | | string safeErrorCode) |
| | | 976 | | { |
| | 0 | 977 | | var now = timeProvider.GetUtcNow(); |
| | | 978 | | try |
| | | 979 | | { |
| | 0 | 980 | | await store.TryReleaseOffboardingClaimAsync(operation.Id, tenantId, environmentId, connectionId, operation.F |
| | 0 | 981 | | now, now + TimeSpan.FromSeconds(30), safeErrorCode, CancellationToken.None); |
| | 0 | 982 | | } |
| | 0 | 983 | | catch (Exception) |
| | | 984 | | { |
| | | 985 | | // An expired claim is safe to retry; the provider-call state is never advanced here. |
| | 0 | 986 | | } |
| | 0 | 987 | | } |
| | | 988 | | |
| | | 989 | | private async Task RecordOffboardingFailureAsync( |
| | | 990 | | ConnectionOffboardingOperation operation, |
| | | 991 | | string tenantId, |
| | | 992 | | string environmentId, |
| | | 993 | | string connectionId, |
| | | 994 | | ConnectionOffboardingOperationStatus status, |
| | | 995 | | string safeErrorCode, |
| | | 996 | | bool supportsStableIdempotency = true) |
| | | 997 | | { |
| | 2 | 998 | | var now = timeProvider.GetUtcNow(); |
| | 2 | 999 | | DateTimeOffset? nextAttemptAt = status == ConnectionOffboardingOperationStatus.RetryScheduled || |
| | 2 | 1000 | | status == ConnectionOffboardingOperationStatus.UnknownOutcome && supportsStableIdempotency |
| | 2 | 1001 | | ? now + TimeSpan.FromSeconds(30) |
| | 2 | 1002 | | : null; |
| | | 1003 | | try |
| | | 1004 | | { |
| | 2 | 1005 | | await store.TryRecordOffboardingFailureAsync(operation.Id, tenantId, environmentId, connectionId, operation. |
| | 2 | 1006 | | status, now, nextAttemptAt, safeErrorCode, CancellationToken.None); |
| | 2 | 1007 | | } |
| | 0 | 1008 | | catch (Exception) |
| | | 1009 | | { |
| | | 1010 | | // The durable provider-call lease expires and reconciliation retries with the same idempotency key. |
| | 0 | 1011 | | } |
| | 2 | 1012 | | } |
| | | 1013 | | |
| | | 1014 | | private static string GetOffboardingOperationId( |
| | | 1015 | | string tenantId, |
| | | 1016 | | string environmentId, |
| | | 1017 | | string connectionId, |
| | | 1018 | | ConnectionOffboardingOperationKind kind, |
| | | 1019 | | string? generationId) |
| | | 1020 | | { |
| | 30 | 1021 | | var canonicalIdentity = JsonSerializer.SerializeToUtf8Bytes(new string?[] |
| | 30 | 1022 | | { |
| | 30 | 1023 | | tenantId, |
| | 30 | 1024 | | environmentId, |
| | 30 | 1025 | | connectionId, |
| | 30 | 1026 | | kind.ToString(), |
| | 30 | 1027 | | generationId |
| | 30 | 1028 | | }, JsonOptions); |
| | 30 | 1029 | | return Convert.ToHexString(SHA256.HashData(canonicalIdentity)).ToLowerInvariant(); |
| | | 1030 | | } |
| | | 1031 | | |
| | | 1032 | | private static bool CanUseCurrentGeneration(IntegrationConnection? connection) => |
| | 58 | 1033 | | connection is { Status: ConnectionStatus.Active, OperationStatus: CredentialOperationStatus.None or CredentialOp |
| | 58 | 1034 | | !string.IsNullOrWhiteSpace(connection.CurrentSecretName) && !string.IsNullOrWhiteSpace(connection.CurrentGenerat |
| | | 1035 | | |
| | 96 | 1036 | | private static ConnectionLifecycleMetadata ToMetadata(IntegrationConnection connection) => new( |
| | 96 | 1037 | | connection.Id, |
| | 96 | 1038 | | connection.ProviderId, |
| | 96 | 1039 | | connection.ProviderAccountId, |
| | 96 | 1040 | | connection.Status, |
| | 96 | 1041 | | connection.Revision, |
| | 96 | 1042 | | connection.CurrentGenerationId); |
| | | 1043 | | |
| | 212 | 1044 | | private IDisposable PushTenant(string tenantId) => tenantAccessor.PushContext(new Tenant { Id = tenantId, Name = ten |
| | | 1045 | | |
| | | 1046 | | private async Task<ConnectionLifecycleResult> ReleaseUnstartedRefreshAsync(IntegrationConnection connection, string |
| | | 1047 | | { |
| | 1 | 1048 | | await TryReleaseUnstartedRefreshAsync(connection, tenantId, environmentId, safeErrorCode); |
| | 1 | 1049 | | var latest = await store.FindAsync(connection.Id, tenantId, environmentId, CancellationToken.None); |
| | 1 | 1050 | | return latest == null |
| | 1 | 1051 | | ? new ConnectionLifecycleResult(false, "connection_unavailable", null) |
| | 1 | 1052 | | : new ConnectionLifecycleResult(false, latest.Status == ConnectionStatus.Active ? safeErrorCode : "connectio |
| | 1 | 1053 | | } |
| | | 1054 | | |
| | | 1055 | | private async Task TryReleaseUnstartedRefreshAsync(IntegrationConnection connection, string tenantId, string environ |
| | | 1056 | | { |
| | | 1057 | | try |
| | | 1058 | | { |
| | 1 | 1059 | | await store.TryReleaseUnstartedRefreshAsync(connection.Id, tenantId, environmentId, |
| | 1 | 1060 | | connection.OperationId!, connection.OperationFence, safeErrorCode, CancellationToken.None); |
| | 1 | 1061 | | } |
| | 0 | 1062 | | catch (Exception) |
| | | 1063 | | { |
| | | 1064 | | // The active credential remains the only published generation; reconciliation can release this claim after |
| | 0 | 1065 | | } |
| | 1 | 1066 | | } |
| | | 1067 | | |
| | 52 | 1068 | | private static string Serialize(CredentialMaterial material) => JsonSerializer.Serialize( |
| | 52 | 1069 | | new CredentialEnvelope(ConnectionCredentialKind.OAuth, material.AccessToken, material.RefreshToken, material.Acc |
| | | 1070 | | |
| | 19 | 1071 | | private static string SerializeApiKey(string apiKey) => JsonSerializer.Serialize( |
| | 19 | 1072 | | new CredentialEnvelope(ConnectionCredentialKind.ApiKey, apiKey, null, null), JsonOptions); |
| | | 1073 | | |
| | | 1074 | | private static CredentialEnvelope? Deserialize(string? json) |
| | | 1075 | | { |
| | 93 | 1076 | | if (string.IsNullOrWhiteSpace(json)) |
| | | 1077 | | { |
| | 0 | 1078 | | return null; |
| | | 1079 | | } |
| | | 1080 | | |
| | | 1081 | | try |
| | | 1082 | | { |
| | 93 | 1083 | | return JsonSerializer.Deserialize<CredentialEnvelope>(json, JsonOptions); |
| | | 1084 | | } |
| | 0 | 1085 | | catch (JsonException) |
| | | 1086 | | { |
| | 0 | 1087 | | return null; |
| | | 1088 | | } |
| | 93 | 1089 | | } |
| | | 1090 | | |
| | | 1091 | | private async Task<bool> IsApiKeyGenerationAsync(IntegrationConnection connection, CancellationToken cancellationTok |
| | | 1092 | | { |
| | 10 | 1093 | | if (string.IsNullOrWhiteSpace(connection.CurrentSecretName) || string.IsNullOrWhiteSpace(connection.CurrentGener |
| | | 1094 | | { |
| | 0 | 1095 | | return false; |
| | | 1096 | | } |
| | | 1097 | | |
| | | 1098 | | try |
| | | 1099 | | { |
| | 10 | 1100 | | var payload = await secrets.ResolveGenerationAsync(connection.CurrentSecretName, connection.Id, connection.C |
| | 10 | 1101 | | var envelope = Deserialize(payload.Value); |
| | 10 | 1102 | | return envelope?.Kind == ConnectionCredentialKind.ApiKey && IsValidEnvelope(envelope); |
| | | 1103 | | } |
| | 0 | 1104 | | catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) |
| | | 1105 | | { |
| | 0 | 1106 | | throw; |
| | | 1107 | | } |
| | 0 | 1108 | | catch (Exception) |
| | | 1109 | | { |
| | 0 | 1110 | | return false; |
| | | 1111 | | } |
| | 10 | 1112 | | } |
| | | 1113 | | |
| | | 1114 | | private async Task<bool> IsApiKeySourceGenerationAsync(IntegrationConnection connection, CancellationToken cancellat |
| | | 1115 | | { |
| | 5 | 1116 | | var generationId = connection.OperationSourceGenerationId; |
| | 5 | 1117 | | if (string.IsNullOrWhiteSpace(generationId) || connection.CurrentGenerationId != generationId) |
| | | 1118 | | { |
| | 2 | 1119 | | return false; |
| | | 1120 | | } |
| | | 1121 | | |
| | | 1122 | | try |
| | | 1123 | | { |
| | 3 | 1124 | | var name = ManagedSecretNames.ForGeneration(connection.Id, generationId); |
| | 3 | 1125 | | var payload = await secrets.ResolveGenerationAsync(name, connection.Id, generationId, cancellationToken); |
| | 3 | 1126 | | var envelope = Deserialize(payload.Value); |
| | 3 | 1127 | | return envelope?.Kind == ConnectionCredentialKind.ApiKey && IsValidEnvelope(envelope); |
| | | 1128 | | } |
| | 0 | 1129 | | catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) |
| | | 1130 | | { |
| | 0 | 1131 | | throw; |
| | | 1132 | | } |
| | 0 | 1133 | | catch (Exception) |
| | | 1134 | | { |
| | 0 | 1135 | | return false; |
| | | 1136 | | } |
| | 5 | 1137 | | } |
| | | 1138 | | |
| | | 1139 | | private async Task<bool> CanPromoteApiKeyRecoveryAsync(IntegrationConnection connection, CancellationToken cancellat |
| | 2 | 1140 | | await IsApiKeySourceGenerationAsync(connection, cancellationToken) || |
| | 2 | 1141 | | string.IsNullOrWhiteSpace(connection.CurrentGenerationId) && string.IsNullOrWhiteSpace(connection.OperationSourc |
| | | 1142 | | |
| | | 1143 | | private static bool IsValidEnvelope(CredentialEnvelope? envelope) |
| | | 1144 | | { |
| | 45 | 1145 | | if (envelope == null || string.IsNullOrWhiteSpace(envelope.AccessToken)) |
| | | 1146 | | { |
| | 0 | 1147 | | return false; |
| | | 1148 | | } |
| | | 1149 | | |
| | 45 | 1150 | | return envelope.Kind switch |
| | 45 | 1151 | | { |
| | 14 | 1152 | | null or ConnectionCredentialKind.OAuth => !string.IsNullOrWhiteSpace(envelope.RefreshToken) && envelope.Acce |
| | 30 | 1153 | | ConnectionCredentialKind.ApiKey => envelope.RefreshToken is null && !envelope.AccessTokenExpiresAt.HasValue, |
| | 1 | 1154 | | _ => false |
| | 45 | 1155 | | }; |
| | | 1156 | | } |
| | | 1157 | | |
| | | 1158 | | private async Task<ConnectionLifecycleResult?> RestoreApiKeySourceIfPlanMissingAsync( |
| | | 1159 | | IntegrationConnection connection, |
| | | 1160 | | string tenantId, |
| | | 1161 | | string environmentId, |
| | | 1162 | | CancellationToken cancellationToken) |
| | | 1163 | | { |
| | 1 | 1164 | | if (connection.Status != ConnectionStatus.RecoveryRequired || |
| | 1 | 1165 | | connection.OperationStatus != CredentialOperationStatus.RecoveryRequired || |
| | 1 | 1166 | | string.IsNullOrWhiteSpace(connection.OperationId) || |
| | 1 | 1167 | | string.IsNullOrWhiteSpace(connection.PlannedSecretName) || |
| | 1 | 1168 | | string.IsNullOrWhiteSpace(connection.PlannedGenerationId) || |
| | 1 | 1169 | | !await IsApiKeySourceGenerationAsync(connection, cancellationToken)) |
| | | 1170 | | { |
| | 0 | 1171 | | return null; |
| | | 1172 | | } |
| | | 1173 | | |
| | | 1174 | | try |
| | | 1175 | | { |
| | 1 | 1176 | | await secrets.ResolveGenerationAsync(connection.PlannedSecretName, connection.Id, connection.PlannedGenerati |
| | 0 | 1177 | | return null; |
| | | 1178 | | } |
| | | 1179 | | catch (KeyNotFoundException) |
| | | 1180 | | { |
| | 1 | 1181 | | var restored = await store.TryRestoreSourceGenerationAfterMissingPlanAsync( |
| | 1 | 1182 | | connection.Id, tenantId, environmentId, connection.Revision, connection.OperationId, |
| | 1 | 1183 | | connection.OperationFence, connection.OperationSourceGenerationId!, "api_key_replacement_not_staged", ca |
| | 1 | 1184 | | if (!restored) |
| | | 1185 | | { |
| | 0 | 1186 | | return null; |
| | | 1187 | | } |
| | | 1188 | | |
| | 1 | 1189 | | var latest = await store.FindAsync(connection.Id, tenantId, environmentId, cancellationToken); |
| | 1 | 1190 | | return latest == null |
| | 1 | 1191 | | ? new ConnectionLifecycleResult(false, "connection_unavailable", null) |
| | 1 | 1192 | | : new ConnectionLifecycleResult(true, null, latest.Revision, connection.Id, ToMetadata(latest)); |
| | | 1193 | | } |
| | 1 | 1194 | | } |
| | | 1195 | | |
| | | 1196 | | private async Task CleanupUnreferencedOrphanGenerationAsync( |
| | | 1197 | | string connectionId, |
| | | 1198 | | string tenantId, |
| | | 1199 | | string environmentId, |
| | | 1200 | | string generationId, |
| | | 1201 | | CancellationToken cancellationToken) |
| | | 1202 | | { |
| | 1 | 1203 | | var connection = await store.FindAsync(connectionId, tenantId, environmentId, cancellationToken); |
| | 1 | 1204 | | if (connection == null) |
| | | 1205 | | { |
| | 0 | 1206 | | return; |
| | | 1207 | | } |
| | | 1208 | | |
| | 1 | 1209 | | var now = timeProvider.GetUtcNow(); |
| | 1 | 1210 | | var claim = await store.TryClaimGenerationCleanupAsync(connectionId, tenantId, environmentId, |
| | 1 | 1211 | | connection.Revision, generationId, now, now + OperationLeaseDuration, cancellationToken); |
| | 1 | 1212 | | if (claim == null) |
| | | 1213 | | { |
| | 0 | 1214 | | return; |
| | | 1215 | | } |
| | | 1216 | | |
| | | 1217 | | try |
| | | 1218 | | { |
| | 1 | 1219 | | if (await secrets.DeleteGenerationAsync(ManagedSecretNames.ForGeneration(connectionId, generationId), connec |
| | | 1220 | | { |
| | 1 | 1221 | | await store.CompleteGenerationCleanupAsync(connectionId, tenantId, environmentId, generationId, claim.Fe |
| | | 1222 | | } |
| | | 1223 | | else |
| | | 1224 | | { |
| | 0 | 1225 | | await store.CancelGenerationCleanupAsync(connectionId, tenantId, environmentId, generationId, claim.Fenc |
| | | 1226 | | } |
| | 1 | 1227 | | } |
| | 0 | 1228 | | catch (Exception) |
| | | 1229 | | { |
| | | 1230 | | // Keep the durable cleanup claim for idempotent retry; do not affect the restored current generation. |
| | 0 | 1231 | | } |
| | 1 | 1232 | | } |
| | | 1233 | | |
| | | 1234 | | private async Task<ConnectionLifecycleResult> RequireRecoveryAsync(IntegrationConnection connection, string tenantId |
| | | 1235 | | { |
| | 3 | 1236 | | await TryMarkRecoveryRequiredAsync(connection, tenantId, environmentId, code); |
| | 3 | 1237 | | return new ConnectionLifecycleResult(false, code, connection.OperationExpectedRevision); |
| | 3 | 1238 | | } |
| | | 1239 | | |
| | | 1240 | | private async Task TryMarkRecoveryRequiredAsync(IntegrationConnection connection, string tenantId, string environmen |
| | | 1241 | | { |
| | | 1242 | | try |
| | | 1243 | | { |
| | 9 | 1244 | | await store.MarkRecoveryRequiredAsync(connection.Id, tenantId, environmentId, connection.OperationId!, conne |
| | 9 | 1245 | | } |
| | 0 | 1246 | | catch |
| | | 1247 | | { |
| | | 1248 | | // Durable provider-call intent remains for startup reconciliation; never replay automatically. |
| | 0 | 1249 | | } |
| | 9 | 1250 | | } |
| | | 1251 | | |
| | 902 | 1252 | | private sealed record CredentialEnvelope(ConnectionCredentialKind? Kind, string? AccessToken, string? RefreshToken, |
| | | 1253 | | } |