| | | 1 | | namespace Elsa.Secrets.Services; |
| | | 2 | | |
| | 146 | 3 | | public class DefaultSecretManager(ISecretNameValidator nameValidator, ISecretStoreRegistry storeRegistry, ISecretTypeReg |
| | | 4 | | { |
| | | 5 | | public async Task<Secret> CreateAsync(CreateSecretRequest request, CancellationToken cancellationToken = default) |
| | | 6 | | { |
| | 48 | 7 | | ValidateName(request.Name); |
| | 44 | 8 | | var secret = await CreateSecretAsync(request, cancellationToken); |
| | 39 | 9 | | if (!await repository.TryAddOrReplaceDeletedAsync(secret, cancellationToken)) |
| | 3 | 10 | | throw new InvalidOperationException($"A secret named '{request.Name}' already exists."); |
| | | 11 | | |
| | 36 | 12 | | return secret; |
| | 36 | 13 | | } |
| | | 14 | | |
| | | 15 | | public async Task<Secret?> GetAsync(string name, CancellationToken cancellationToken = default) |
| | | 16 | | { |
| | 83 | 17 | | var secret = await repository.GetAsync(nameValidator.Normalize(name), cancellationToken); |
| | 83 | 18 | | return secret is { Status: SecretStatus.Deleted } ? null : secret; |
| | 83 | 19 | | } |
| | | 20 | | |
| | | 21 | | public async Task<IReadOnlyCollection<Secret>> ListAsync(ListSecretsRequest request, CancellationToken cancellationT |
| | | 22 | | { |
| | 9 | 23 | | return (await ListPageAsync(request, cancellationToken)).Items; |
| | 9 | 24 | | } |
| | | 25 | | |
| | | 26 | | public async Task<ListSecretsResult> ListPageAsync(ListSecretsRequest request, CancellationToken cancellationToken = |
| | | 27 | | { |
| | 16 | 28 | | var secrets = await repository.ListAsync(cancellationToken); |
| | 16 | 29 | | var query = ApplyFilters(secrets, request); |
| | 16 | 30 | | var totalCount = query.LongCount(); |
| | | 31 | | |
| | 16 | 32 | | var pageSize = request.PageSize is > 0 ? Math.Min(request.PageSize.Value, 200) : 100; |
| | 16 | 33 | | var page = request.Page is > 0 ? request.Page.Value : 0; |
| | | 34 | | |
| | 16 | 35 | | var items = query |
| | | 36 | | .OrderBy(x => x.Name) |
| | 16 | 37 | | .Skip(page * pageSize) |
| | 16 | 38 | | .Take(pageSize) |
| | 16 | 39 | | .ToList(); |
| | | 40 | | |
| | 16 | 41 | | return new ListSecretsResult { Items = items, TotalCount = totalCount }; |
| | 16 | 42 | | } |
| | | 43 | | |
| | | 44 | | public async Task<long> CountAsync(ListSecretsRequest request, CancellationToken cancellationToken = default) |
| | | 45 | | { |
| | 2 | 46 | | var secrets = await repository.ListAsync(cancellationToken); |
| | 2 | 47 | | return ApplyFilters(secrets, request).LongCount(); |
| | 2 | 48 | | } |
| | | 49 | | |
| | | 50 | | public async Task<Secret> UpdateAsync(string name, UpdateSecretRequest request, CancellationToken cancellationToken |
| | | 51 | | { |
| | 9 | 52 | | var secret = await GetExistingAsync(name, cancellationToken); |
| | 6 | 53 | | EnsureNotLifecycleManaged(secret); |
| | | 54 | | |
| | 5 | 55 | | secret.DisplayName = string.IsNullOrWhiteSpace(request.DisplayName) ? secret.Name : request.DisplayName.Trim(); |
| | 5 | 56 | | secret.Description = string.IsNullOrWhiteSpace(request.Description) ? null : request.Description.Trim(); |
| | 5 | 57 | | secret.UpdatedAt = DateTimeOffset.UtcNow; |
| | | 58 | | |
| | 5 | 59 | | await repository.SaveAsync(secret, cancellationToken); |
| | 5 | 60 | | return secret; |
| | 5 | 61 | | } |
| | | 62 | | |
| | | 63 | | public async Task<Secret> RotateAsync(string name, RotateSecretRequest request, CancellationToken cancellationToken |
| | | 64 | | { |
| | 9 | 65 | | var secret = await GetExistingAsync(name, cancellationToken); |
| | 9 | 66 | | EnsureNotLifecycleManaged(secret); |
| | 8 | 67 | | if (secret.Status == SecretStatus.Revoked) |
| | 1 | 68 | | throw new InvalidOperationException($"Secret '{secret.Name}' is revoked and cannot be rotated."); |
| | | 69 | | |
| | 7 | 70 | | var provider = typeRegistry.Get(secret.TypeName); |
| | 7 | 71 | | if (!provider.ValidateRotation(request, secret.StoreName, out var error)) |
| | 1 | 72 | | throw new InvalidOperationException(error); |
| | | 73 | | |
| | 6 | 74 | | var store = storeRegistry.Get(secret.StoreName); |
| | 6 | 75 | | EnsureCanWrite(store); |
| | | 76 | | var nextVersion = secret.Versions.Count == 0 ? 1 : secret.Versions.Max(x => x.Version) + 1; |
| | 6 | 77 | | var version = new SecretVersion { Version = nextVersion, ExpiresAt = request.ExpiresAt }; |
| | 6 | 78 | | version.Payload = await store.WriteAsync(secret, version, CreatePayload(request), cancellationToken); |
| | | 79 | | |
| | | 80 | | foreach (var activeVersion in secret.Versions.Where(x => x.Status == SecretStatus.Active)) |
| | 6 | 81 | | activeVersion.Status = SecretStatus.Retired; |
| | | 82 | | |
| | 6 | 83 | | secret.Versions.Add(version); |
| | 6 | 84 | | secret.Status = SecretStatus.Active; |
| | 6 | 85 | | secret.UpdatedAt = DateTimeOffset.UtcNow; |
| | 6 | 86 | | await repository.SaveAsync(secret, cancellationToken); |
| | | 87 | | |
| | 6 | 88 | | return secret; |
| | 6 | 89 | | } |
| | | 90 | | |
| | | 91 | | public async Task<Secret?> RevokeAsync(string name, CancellationToken cancellationToken = default) |
| | | 92 | | { |
| | 7 | 93 | | var secret = await GetAsync(name, cancellationToken); |
| | 7 | 94 | | if (secret == null) |
| | 0 | 95 | | return null; |
| | | 96 | | |
| | 7 | 97 | | EnsureNotLifecycleManaged(secret); |
| | | 98 | | |
| | 6 | 99 | | secret.Status = SecretStatus.Revoked; |
| | 6 | 100 | | secret.UpdatedAt = DateTimeOffset.UtcNow; |
| | | 101 | | foreach (var version in secret.Versions.Where(x => x.Status == SecretStatus.Active)) |
| | 6 | 102 | | version.Status = SecretStatus.Revoked; |
| | | 103 | | |
| | 6 | 104 | | await repository.SaveAsync(secret, cancellationToken); |
| | 6 | 105 | | return secret; |
| | 6 | 106 | | } |
| | | 107 | | |
| | | 108 | | public async Task<bool> DeleteAsync(string name, CancellationToken cancellationToken = default) |
| | | 109 | | { |
| | 9 | 110 | | var secret = await GetAsync(name, cancellationToken); |
| | 9 | 111 | | if (secret == null) |
| | 2 | 112 | | return false; |
| | | 113 | | |
| | 7 | 114 | | EnsureNotLifecycleManaged(secret); |
| | | 115 | | |
| | 6 | 116 | | await storeRegistry.Get(secret.StoreName).DeleteAsync(secret, cancellationToken); |
| | 6 | 117 | | secret.Status = SecretStatus.Deleted; |
| | 6 | 118 | | secret.UpdatedAt = DateTimeOffset.UtcNow; |
| | 6 | 119 | | await repository.SaveAsync(secret, cancellationToken); |
| | 6 | 120 | | return true; |
| | 8 | 121 | | } |
| | | 122 | | |
| | | 123 | | public async Task<SecretTestResponse> TestAsync(string name, CancellationToken cancellationToken = default) |
| | | 124 | | { |
| | | 125 | | try |
| | | 126 | | { |
| | 12 | 127 | | var secret = await GetExistingAsync(name, cancellationToken); |
| | 8 | 128 | | EnsureNotLifecycleManaged(secret); |
| | 7 | 129 | | var version = GetLatestActiveVersion(secret); |
| | 7 | 130 | | var succeeded = await storeRegistry.Get(secret.StoreName).TestAsync(secret, version, cancellationToken); |
| | 6 | 131 | | return new SecretTestResponse { Succeeded = succeeded, Error = succeeded ? null : "Secret value is unavailab |
| | | 132 | | } |
| | 1 | 133 | | catch (InvalidOperationException e) |
| | | 134 | | { |
| | 1 | 135 | | return new SecretTestResponse { Succeeded = false, Error = e.Message }; |
| | | 136 | | } |
| | 4 | 137 | | catch (KeyNotFoundException e) |
| | | 138 | | { |
| | 4 | 139 | | return new SecretTestResponse { Succeeded = false, Error = e.Message }; |
| | | 140 | | } |
| | 0 | 141 | | catch (ArgumentException e) |
| | | 142 | | { |
| | 0 | 143 | | return new SecretTestResponse { Succeeded = false, Error = e.Message }; |
| | | 144 | | } |
| | 0 | 145 | | catch (System.Security.Cryptography.CryptographicException e) |
| | | 146 | | { |
| | 0 | 147 | | return new SecretTestResponse { Succeeded = false, Error = e.Message }; |
| | | 148 | | } |
| | 1 | 149 | | catch (FormatException e) |
| | | 150 | | { |
| | 1 | 151 | | return new SecretTestResponse { Succeeded = false, Error = e.Message }; |
| | | 152 | | } |
| | 12 | 153 | | } |
| | | 154 | | |
| | | 155 | | public async Task<SecretPayload> ResolvePayloadAsync(string name, CancellationToken cancellationToken = default) |
| | | 156 | | { |
| | 0 | 157 | | var secret = await GetExistingAsync(name, cancellationToken); |
| | 0 | 158 | | return await ResolvePayloadAsync(secret, cancellationToken); |
| | 0 | 159 | | } |
| | | 160 | | |
| | | 161 | | public async Task<SecretPayload> ResolvePayloadAsync(Secret secret, CancellationToken cancellationToken = default) |
| | | 162 | | { |
| | 9 | 163 | | var persisted = await GetExistingAsync(secret.Name, cancellationToken); |
| | 9 | 164 | | if (!string.Equals(secret.Id, persisted.Id, StringComparison.Ordinal)) |
| | | 165 | | { |
| | 0 | 166 | | throw new InvalidOperationException($"Secret '{secret.Name}' was not found."); |
| | | 167 | | } |
| | | 168 | | |
| | 9 | 169 | | EnsureNotLifecycleManaged(persisted); |
| | 8 | 170 | | return await ReadPayloadCoreAsync(persisted, cancellationToken); |
| | 7 | 171 | | } |
| | | 172 | | |
| | | 173 | | public async Task<Secret> CreateGenerationAsync(string ownerId, string generationId, string value, CancellationToken |
| | | 174 | | { |
| | 5 | 175 | | ValidateManagedIdentity(ownerId, generationId); |
| | 5 | 176 | | var name = ManagedSecretNames.ForGeneration(ownerId, generationId); |
| | 5 | 177 | | if (await repository.GetAsync(nameValidator.Normalize(name), cancellationToken) != null) |
| | | 178 | | { |
| | 0 | 179 | | throw new InvalidOperationException($"A secret named '{name}' already exists."); |
| | | 180 | | } |
| | | 181 | | |
| | 5 | 182 | | var request = new CreateSecretRequest |
| | 5 | 183 | | { |
| | 5 | 184 | | Name = name, |
| | 5 | 185 | | TypeName = SecretTypeNames.Text, |
| | 5 | 186 | | StoreName = SecretStoreNames.Encrypted, |
| | 5 | 187 | | Value = value |
| | 5 | 188 | | }; |
| | | 189 | | |
| | 5 | 190 | | var secret = await CreateSecretAsync(request, cancellationToken); |
| | 5 | 191 | | secret.ManagedOwnerId = ownerId; |
| | 5 | 192 | | secret.ManagedGenerationId = generationId; |
| | 5 | 193 | | await repository.AddAsync(secret, cancellationToken); |
| | 5 | 194 | | return secret; |
| | 5 | 195 | | } |
| | | 196 | | |
| | | 197 | | public async Task<SecretPayload> ResolveGenerationAsync(string name, string ownerId, string generationId, Cancellati |
| | | 198 | | { |
| | 2 | 199 | | ValidateManagedIdentity(ownerId, generationId); |
| | 2 | 200 | | var secret = await GetExistingAsync(name, cancellationToken); |
| | 2 | 201 | | EnsureManagedOwner(secret, ownerId, generationId); |
| | 1 | 202 | | return await ReadPayloadCoreAsync(secret, cancellationToken); |
| | 1 | 203 | | } |
| | | 204 | | |
| | | 205 | | public async Task<bool> DeleteGenerationAsync(string name, string ownerId, string generationId, CancellationToken ca |
| | | 206 | | { |
| | 3 | 207 | | ValidateManagedIdentity(ownerId, generationId); |
| | | 208 | | // Read the repository directly so a retry after process loss can recognize its own tombstone. The |
| | | 209 | | // public GetAsync intentionally hides deleted secrets, while immutable managed-generation identities |
| | | 210 | | // must remain unavailable for recreation after cleanup. |
| | 3 | 211 | | var secret = await repository.GetAsync(nameValidator.Normalize(name), cancellationToken); |
| | 3 | 212 | | if (secret == null || !HasManagedOwner(secret, ownerId, generationId)) |
| | | 213 | | { |
| | 1 | 214 | | return false; |
| | | 215 | | } |
| | | 216 | | |
| | 2 | 217 | | if (secret.Status == SecretStatus.Deleted) |
| | | 218 | | { |
| | 0 | 219 | | return true; |
| | | 220 | | } |
| | | 221 | | |
| | 2 | 222 | | await DeleteGenerationAsync(secret, cancellationToken); |
| | 2 | 223 | | return true; |
| | 3 | 224 | | } |
| | | 225 | | |
| | | 226 | | private async Task<SecretPayload> ReadPayloadCoreAsync(Secret secret, CancellationToken cancellationToken) |
| | | 227 | | { |
| | 9 | 228 | | var version = GetLatestActiveVersion(secret); |
| | 8 | 229 | | var store = storeRegistry.Get(secret.StoreName); |
| | 8 | 230 | | var payload = await store.ReadAsync(secret, version, cancellationToken); |
| | | 231 | | |
| | 8 | 232 | | if (payload?.Value == null) |
| | 0 | 233 | | throw new InvalidOperationException($"Secret '{secret.Name}' could not be resolved."); |
| | | 234 | | |
| | 8 | 235 | | return payload; |
| | 8 | 236 | | } |
| | | 237 | | |
| | | 238 | | private async Task DeleteGenerationAsync(Secret secret, CancellationToken cancellationToken) |
| | | 239 | | { |
| | 2 | 240 | | await storeRegistry.Get(secret.StoreName).DeleteAsync(secret, cancellationToken); |
| | 2 | 241 | | secret.Status = SecretStatus.Deleted; |
| | 2 | 242 | | secret.UpdatedAt = DateTimeOffset.UtcNow; |
| | 2 | 243 | | await repository.SaveAsync(secret, cancellationToken); |
| | 2 | 244 | | } |
| | | 245 | | |
| | | 246 | | private async Task<Secret> CreateSecretAsync(CreateSecretRequest request, CancellationToken cancellationToken) |
| | | 247 | | { |
| | 49 | 248 | | var typeProvider = typeRegistry.Get(request.TypeName); |
| | 49 | 249 | | var store = storeRegistry.Get(request.StoreName); |
| | 49 | 250 | | EnsureCanWrite(store); |
| | | 251 | | |
| | 49 | 252 | | if (!typeProvider.Descriptor.SupportedStoreNames.Contains(store.Name, StringComparer.OrdinalIgnoreCase)) |
| | 0 | 253 | | throw new InvalidOperationException($"Secret type '{request.TypeName}' does not support store '{request.Stor |
| | | 254 | | |
| | 49 | 255 | | if (!typeProvider.Validate(request, out var error)) |
| | 5 | 256 | | throw new InvalidOperationException(error); |
| | | 257 | | |
| | 44 | 258 | | var secret = new Secret |
| | 44 | 259 | | { |
| | 44 | 260 | | Name = nameValidator.Normalize(request.Name), |
| | 44 | 261 | | DisplayName = string.IsNullOrWhiteSpace(request.DisplayName) ? request.Name.Trim() : request.DisplayName.Tri |
| | 44 | 262 | | Description = request.Description, |
| | 44 | 263 | | TypeName = typeProvider.Descriptor.Name, |
| | 44 | 264 | | StoreName = store.Name, |
| | 44 | 265 | | Scope = request.Scope, |
| | 44 | 266 | | Tags = request.Tags.ToHashSet(StringComparer.OrdinalIgnoreCase) |
| | 44 | 267 | | }; |
| | | 268 | | |
| | 44 | 269 | | var version = new SecretVersion { Version = 1, ExpiresAt = request.ExpiresAt }; |
| | 44 | 270 | | version.Payload = await store.WriteAsync(secret, version, CreatePayload(request), cancellationToken); |
| | 44 | 271 | | secret.Versions.Add(version); |
| | | 272 | | |
| | 44 | 273 | | return secret; |
| | 44 | 274 | | } |
| | | 275 | | |
| | | 276 | | private async Task<Secret> GetExistingAsync(string name, CancellationToken cancellationToken) |
| | | 277 | | { |
| | 41 | 278 | | var secret = await GetAsync(name, cancellationToken); |
| | 41 | 279 | | return secret == null ? throw new KeyNotFoundException($"Secret '{name}' was not found.") : secret; |
| | 34 | 280 | | } |
| | | 281 | | |
| | | 282 | | private static SecretVersion GetLatestActiveVersion(Secret secret) |
| | | 283 | | { |
| | 16 | 284 | | if (secret.Status != SecretStatus.Active) |
| | 1 | 285 | | throw new InvalidOperationException($"Secret '{secret.Name}' is not active."); |
| | | 286 | | |
| | 15 | 287 | | return secret.LatestActiveVersion ?? throw new InvalidOperationException($"Secret '{secret.Name}' has no active |
| | | 288 | | } |
| | | 289 | | |
| | | 290 | | private void ValidateName(string name) |
| | | 291 | | { |
| | 48 | 292 | | if (!nameValidator.IsValid(name, out var error)) |
| | 4 | 293 | | throw new InvalidOperationException(error); |
| | 44 | 294 | | } |
| | | 295 | | |
| | | 296 | | private static void EnsureCanWrite(ISecretStore store) |
| | | 297 | | { |
| | 55 | 298 | | if (!store.Descriptor.Capabilities.HasFlag(SecretStoreCapabilities.Write)) |
| | 0 | 299 | | throw new InvalidOperationException($"Secret store '{store.Name}' does not support writing secrets."); |
| | 55 | 300 | | } |
| | | 301 | | |
| | | 302 | | private static void EnsureNotLifecycleManaged(Secret secret) |
| | | 303 | | { |
| | 46 | 304 | | if (secret.IsLifecycleManaged) |
| | | 305 | | { |
| | 6 | 306 | | throw new InvalidOperationException("Lifecycle-managed secret generations can only be accessed through their |
| | | 307 | | } |
| | 40 | 308 | | } |
| | | 309 | | |
| | | 310 | | private static void EnsureManagedOwner(Secret secret, string ownerId, string generationId) |
| | | 311 | | { |
| | 2 | 312 | | if (!HasManagedOwner(secret, ownerId, generationId)) |
| | | 313 | | { |
| | 1 | 314 | | throw new InvalidOperationException("Managed credential generation is unavailable."); |
| | | 315 | | } |
| | 1 | 316 | | } |
| | | 317 | | |
| | | 318 | | private static bool HasManagedOwner(Secret secret, string ownerId, string generationId) |
| | | 319 | | { |
| | 5 | 320 | | return string.Equals(secret.ManagedOwnerId, ownerId, StringComparison.Ordinal) && |
| | 5 | 321 | | string.Equals(secret.ManagedGenerationId, generationId, StringComparison.Ordinal); |
| | | 322 | | } |
| | | 323 | | |
| | | 324 | | private static void ValidateManagedIdentity(string ownerId, string generationId) |
| | | 325 | | { |
| | 10 | 326 | | if (string.IsNullOrWhiteSpace(ownerId) || ownerId.Length > 200 || string.IsNullOrWhiteSpace(generationId) || gen |
| | | 327 | | { |
| | 0 | 328 | | throw new ArgumentException("A valid owner and generation identifier are required."); |
| | | 329 | | } |
| | 10 | 330 | | } |
| | | 331 | | |
| | | 332 | | private static IEnumerable<Secret> ApplyFilters(IEnumerable<Secret> secrets, ListSecretsRequest request) |
| | | 333 | | { |
| | 57 | 334 | | var query = secrets.Where(x => x.Status != SecretStatus.Deleted && !x.IsLifecycleManaged); |
| | | 335 | | |
| | 18 | 336 | | if (!string.IsNullOrWhiteSpace(request.Search)) |
| | | 337 | | { |
| | 2 | 338 | | var search = request.Search.Trim(); |
| | 2 | 339 | | query = query.Where(x => |
| | 12 | 340 | | x.Name.Contains(search, StringComparison.OrdinalIgnoreCase) || |
| | 12 | 341 | | x.DisplayName.Contains(search, StringComparison.OrdinalIgnoreCase) || |
| | 12 | 342 | | (x.Description?.Contains(search, StringComparison.OrdinalIgnoreCase) ?? false)); |
| | | 343 | | } |
| | | 344 | | |
| | 18 | 345 | | var typeNames = GetFilterValues(request.TypeName, request.TypeNames); |
| | 18 | 346 | | if (typeNames.Count > 0) |
| | 23 | 347 | | query = query.Where(x => typeNames.Contains(x.TypeName)); |
| | | 348 | | |
| | 18 | 349 | | var storeNames = GetFilterValues(request.StoreName, request.StoreNames); |
| | 18 | 350 | | if (storeNames.Count > 0) |
| | 23 | 351 | | query = query.Where(x => storeNames.Contains(x.StoreName)); |
| | | 352 | | |
| | 18 | 353 | | if (!string.IsNullOrWhiteSpace(request.Scope)) |
| | 23 | 354 | | query = query.Where(x => string.Equals(x.Scope, request.Scope, StringComparison.OrdinalIgnoreCase)); |
| | | 355 | | |
| | 18 | 356 | | if (request.Status != null) |
| | 24 | 357 | | query = query.Where(x => x.Status == request.Status); |
| | | 358 | | |
| | 18 | 359 | | return query; |
| | | 360 | | } |
| | | 361 | | |
| | | 362 | | private static HashSet<string> GetFilterValues(string? value, IEnumerable<string> values) |
| | | 363 | | { |
| | 36 | 364 | | var result = new HashSet<string>(StringComparer.OrdinalIgnoreCase); |
| | 36 | 365 | | if (!string.IsNullOrWhiteSpace(value)) |
| | 2 | 366 | | result.Add(value.Trim()); |
| | | 367 | | |
| | 108 | 368 | | foreach (var item in values.Where(x => !string.IsNullOrWhiteSpace(x))) |
| | 12 | 369 | | result.Add(item.Trim()); |
| | | 370 | | |
| | 36 | 371 | | return result; |
| | | 372 | | } |
| | | 373 | | |
| | | 374 | | private static SecretPayload CreatePayload(CreateSecretRequest request) |
| | | 375 | | { |
| | 44 | 376 | | var payload = new SecretPayload { Value = request.Value, Metadata = new Dictionary<string, string>(request.Metad |
| | 44 | 377 | | if (!string.IsNullOrWhiteSpace(request.ConfigurationKey)) |
| | 4 | 378 | | payload.Metadata["configurationKey"] = request.ConfigurationKey.Trim(); |
| | 44 | 379 | | return payload; |
| | | 380 | | } |
| | | 381 | | |
| | | 382 | | private static SecretPayload CreatePayload(RotateSecretRequest request) |
| | | 383 | | { |
| | 6 | 384 | | var payload = new SecretPayload { Value = request.Value, Metadata = new Dictionary<string, string>(request.Metad |
| | 6 | 385 | | if (!string.IsNullOrWhiteSpace(request.ConfigurationKey)) |
| | 1 | 386 | | payload.Metadata["configurationKey"] = request.ConfigurationKey.Trim(); |
| | 6 | 387 | | return payload; |
| | | 388 | | } |
| | | 389 | | } |