-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSecretProcessor.cs
68 lines (59 loc) · 2.34 KB
/
SecretProcessor.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using System.Runtime.InteropServices;
using System.Text.Json;
using W4k.Extensions.Configuration.Aws.SecretsManager.Json;
namespace W4k.Extensions.Configuration.Aws.SecretsManager;
/// <summary>
/// Default secrets processor reference container.
/// </summary>
public static class SecretsProcessor
{
/// <summary>
/// Processor of JSON secrets.
/// </summary>
public static readonly ISecretProcessor Json =
new SecretProcessor<JsonElement>(
new JsonElementParser(),
new JsonElementTokenizer());
}
/// <inheritdoc/>
/// <remarks>
/// Helper class to simplify creation of custom secrets' processor.
/// </remarks>
public class SecretProcessor<T> : ISecretProcessor
{
private readonly ISecretStringParser<T> _parser;
private readonly IConfigurationTokenizer<T> _tokenizer;
/// <summary>
/// Initializes new instance of <see cref="SecretProcessor{T}"/>.
/// </summary>
/// <param name="parser">Secret string parser.</param>
/// <param name="tokenizer">Configuration tokenizer.</param>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="parser"/> or <paramref name="tokenizer"/> is <see langword="null"/>.</exception>
public SecretProcessor(ISecretStringParser<T> parser, IConfigurationTokenizer<T> tokenizer)
{
ArgumentNullException.ThrowIfNull(parser);
ArgumentNullException.ThrowIfNull(tokenizer);
_parser = parser;
_tokenizer = tokenizer;
}
/// <inheritdoc/>
public Dictionary<string, string?> GetConfigurationData(SecretsManagerConfigurationSource source, string secretString)
{
if (!_parser.TryParse(secretString, out var secretValue))
{
throw new FormatException($"Secret '{source.SecretName}' cannot be parsed, have you used appropriate secrets processor?");
}
var transformers = CollectionsMarshal.AsSpan(source.KeyTransformers);
var data = new Dictionary<string, string?>(StringComparer.OrdinalIgnoreCase);
foreach (var (key, value) in _tokenizer.Tokenize(secretValue, source.ConfigurationKeyPrefix))
{
var transformedKey = key;
foreach (var t in transformers)
{
transformedKey = t.Transform(transformedKey);
}
data[transformedKey] = value;
}
return data;
}
}