| | | 1 | | using System.Text.Json; |
| | | 2 | | using Elsa.ExternalAuthentication.Models; |
| | | 3 | | |
| | | 4 | | namespace Elsa.ExternalAuthentication.Services; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// Prevents adapter setting fields that are declared as secret bindings from being persisted or returned as ordinary se |
| | | 8 | | /// </summary> |
| | | 9 | | public static class AdapterSettingsSecretFieldGuard |
| | | 10 | | { |
| | | 11 | | /// <summary>Throws when a descriptor-declared secret is supplied through an adapter settings document.</summary> |
| | | 12 | | public static void ThrowIfContainsDeclaredSecret(JsonElement settings, ExternalAuthenticationAdapterDescriptor descr |
| | | 13 | | { |
| | 1 | 14 | | if (settings.ValueKind != JsonValueKind.Object) |
| | 0 | 15 | | return; |
| | | 16 | | |
| | 1 | 17 | | var names = GetSecretFieldNames(descriptor); |
| | 2 | 18 | | var name = names.FirstOrDefault(name => settings.TryGetProperty(name, out _)); |
| | 1 | 19 | | if (name is not null) |
| | 1 | 20 | | throw new InvalidOperationException($"Configuration connection '{connectionKey}' supplies secret field '{nam |
| | 0 | 21 | | } |
| | | 22 | | |
| | | 23 | | /// <summary>Returns a settings document with descriptor-declared secret fields redacted.</summary> |
| | | 24 | | public static JsonElement RedactDeclaredSecrets(JsonElement settings, ExternalAuthenticationAdapterDescriptor descri |
| | | 25 | | { |
| | 32 | 26 | | if (settings.ValueKind != JsonValueKind.Object) |
| | 0 | 27 | | return settings.ValueKind == JsonValueKind.Undefined ? default : settings.Clone(); |
| | | 28 | | |
| | 32 | 29 | | var names = GetSecretFieldNames(descriptor); |
| | 64 | 30 | | if (names.Count == 0 || !names.Any(name => settings.TryGetProperty(name, out _))) |
| | 31 | 31 | | return settings.Clone(); |
| | | 32 | | |
| | 1 | 33 | | using var stream = new MemoryStream(); |
| | 1 | 34 | | using (var writer = new Utf8JsonWriter(stream)) |
| | | 35 | | { |
| | 1 | 36 | | writer.WriteStartObject(); |
| | 6 | 37 | | foreach (var property in settings.EnumerateObject()) |
| | | 38 | | { |
| | 2 | 39 | | writer.WritePropertyName(property.Name); |
| | 2 | 40 | | if (names.Contains(property.Name)) |
| | 1 | 41 | | writer.WriteStringValue(ExternalAuthenticationRedactor.RedactedValue); |
| | | 42 | | else |
| | 1 | 43 | | property.Value.WriteTo(writer); |
| | | 44 | | } |
| | | 45 | | |
| | 1 | 46 | | writer.WriteEndObject(); |
| | 1 | 47 | | } |
| | | 48 | | |
| | 1 | 49 | | using var document = JsonDocument.Parse(stream.ToArray()); |
| | 1 | 50 | | return document.RootElement.Clone(); |
| | 1 | 51 | | } |
| | | 52 | | |
| | | 53 | | private static HashSet<string> GetSecretFieldNames(ExternalAuthenticationAdapterDescriptor descriptor) => |
| | 33 | 54 | | descriptor.Fields |
| | 65 | 55 | | .Where(x => x.IsSecretBinding) |
| | 33 | 56 | | .Select(x => x.Name) |
| | 33 | 57 | | .ToHashSet(StringComparer.Ordinal); |
| | | 58 | | } |