-
Notifications
You must be signed in to change notification settings - Fork 349
Expand file tree
/
Copy pathDeserializationVariableReplacementSettings.cs
More file actions
296 lines (260 loc) · 13.3 KB
/
Copy pathDeserializationVariableReplacementSettings.cs
File metadata and controls
296 lines (260 loc) · 13.3 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Text.RegularExpressions;
using Azure.Core;
using Azure.DataApiBuilder.Config.Converters;
using Azure.DataApiBuilder.Config.ObjectModel;
using Azure.DataApiBuilder.Service.Exceptions;
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
using Microsoft.Extensions.Logging;
namespace Azure.DataApiBuilder.Config
{
public class DeserializationVariableReplacementSettings
{
public bool DoReplaceEnvVar { get; set; }
public bool DoReplaceAkvVar { get; set; }
public EnvironmentVariableReplacementFailureMode EnvFailureMode { get; set; } = EnvironmentVariableReplacementFailureMode.Throw;
/// <summary>
/// When true, connection-string Application Name (telemetry) injection is skipped during this
/// parse. This is set for nested child config loads in a multi-database setup: a child config
/// lacks the global runtime section and knows only its own entities, so the top-level load
/// performs the injection once over the fully-merged config for every data source.
/// </summary>
public bool SkipApplicationNameInjection { get; set; }
// @env\(' : match @env('
// @akv\(' : match @akv('
// .*? : lazy match any character except newline 0 or more times
// (?='\)) : look ahead for ')' which will combine with our lazy match
// ie: in @env('hello')goodbye') we match @env('hello')
// '\) : consume the ') into the match (look ahead doesn't capture)
// This pattern lazy matches any string that starts with @env(' and ends with ') OR @akv(' and ends with ')
// Example: fooBAR@env('hello-world')bash)FOO') match: @env('hello-world')
// Example: fooBAR@akv('secret-name')bash)FOO') match: @akv('secret-name')
// This matching pattern allows for the @env('<match>') / @akv('<match>') to be safely nested
// within strings that contain ')' after our match.
// Note that there is no escape character currently for ')' to exist within the name of the variable.
public const string OUTER_ENV_PATTERN = @"@env\('.*?(?='\))'\)";
public const string OUTER_AKV_PATTERN = @"@akv\('.*?(?='\))'\)";
// [^@env\(] : any substring that is not @env(
// [^@akv\(] : any substring that is not @akv(
// .* : any char except newline any number of times
// (?=\)) : look ahead for end char of )
// This pattern greedy matches all characters that are not a part of @env() / @akv()
// ie: @env('hello@env('goodbye')world') match: 'hello@env('goodbye')world'
public const string INNER_ENV_PATTERN = @"[^@env\(].*(?=\))";
public const string INNER_AKV_PATTERN = @"[^@akv\(].*(?=\))";
private readonly AzureKeyVaultOptions? _azureKeyVaultOptions;
private readonly SecretClient? _akvClient;
private readonly Dictionary<string, string>? _akvFileSecrets;
private readonly ILogger? _logger;
public Dictionary<Regex, Func<Match, string>> ReplacementStrategies { get; private set; } = new();
public DeserializationVariableReplacementSettings(
AzureKeyVaultOptions? azureKeyVaultOptions = null,
bool doReplaceEnvVar = false,
bool doReplaceAkvVar = false,
EnvironmentVariableReplacementFailureMode envFailureMode = EnvironmentVariableReplacementFailureMode.Throw,
ILogger? logger = null)
{
_azureKeyVaultOptions = azureKeyVaultOptions;
DoReplaceEnvVar = doReplaceEnvVar;
DoReplaceAkvVar = doReplaceAkvVar;
EnvFailureMode = envFailureMode;
_logger = logger;
if (DoReplaceEnvVar)
{
ReplacementStrategies.Add(
new Regex(OUTER_ENV_PATTERN, RegexOptions.Compiled),
ReplaceEnvVariable);
}
if (DoReplaceAkvVar && _azureKeyVaultOptions is not null)
{
// Determine if endpoint points to a local .akv file. If so, load secrets from file; otherwise, use remote AKV.
if (IsLocalAkvFileEndpoint(_azureKeyVaultOptions.Endpoint))
{
_akvFileSecrets = LoadAkvFileSecrets(_azureKeyVaultOptions.Endpoint!, _logger);
}
else
{
_akvClient = CreateSecretClient(_azureKeyVaultOptions);
}
ReplacementStrategies.Add(
new Regex(OUTER_AKV_PATTERN, RegexOptions.Compiled),
ReplaceAkvVariable);
}
}
// Checks if the endpoint is a path to a local .akv file.
private static bool IsLocalAkvFileEndpoint(string? endpoint)
=> !string.IsNullOrWhiteSpace(endpoint)
&& endpoint.EndsWith(".akv", StringComparison.OrdinalIgnoreCase)
&& File.Exists(endpoint);
// Loads key=value pairs from a .akv file, similar to .env style. Lines starting with '#' are comments.
private static Dictionary<string, string> LoadAkvFileSecrets(string filePath, ILogger? logger = null)
{
Dictionary<string, string> secrets = new(StringComparer.OrdinalIgnoreCase);
foreach (string rawLine in File.ReadAllLines(filePath))
{
string line = rawLine.Trim();
if (string.IsNullOrEmpty(line) || line.StartsWith('#'))
{
continue;
}
int eqIndex = line.IndexOf('=');
if (eqIndex <= 0)
{
logger?.LogDebug("Ignoring malformed line in AKV secrets file {FilePath}: {Line}", filePath, rawLine);
continue;
}
string key = line.Substring(0, eqIndex).Trim();
string value = line[(eqIndex + 1)..].Trim();
// Remove optional surrounding quotes
if (value.Length >= 2 && ((value.StartsWith('"') && value.EndsWith('"')) || (value.StartsWith('\'') && value.EndsWith('\''))))
{
value = value[1..^1];
}
if (!string.IsNullOrEmpty(key))
{
if (!secrets.TryAdd(key, value))
{
logger?.LogDebug("Duplicate key '{Key}' encountered in AKV secrets file {FilePath}. Skipping later value.", key, filePath);
}
}
}
return secrets;
}
private string ReplaceEnvVariable(Match match)
{
// strips first and last characters, ie: '''hello'' --> ''hello'
string name = Regex.Match(match.Value, INNER_ENV_PATTERN).Value[1..^1];
string? value = Environment.GetEnvironmentVariable(name);
if (EnvFailureMode is EnvironmentVariableReplacementFailureMode.Throw)
{
return value is not null ? value :
throw new DataApiBuilderException(
message: $"Environmental Variable, {name}, not found.",
statusCode: System.Net.HttpStatusCode.ServiceUnavailable,
subStatusCode: DataApiBuilderException.SubStatusCodes.ErrorInInitialization);
}
else
{
return value ?? match.Value;
}
}
private string ReplaceAkvVariable(Match match)
{
// strips first and last characters, ie: '''hello'' --> ''hello'
string name = Regex.Match(match.Value, INNER_AKV_PATTERN).Value[1..^1];
// Validate AKV secret name per rules:
// Allowed: alphanumeric and hyphen (-)
// Disallowed: spaces or any other symbols
// Must start and end with alphanumeric
// Length: 1 to 127 chars
if (!IsValidAkvSecretName(name, out string validationError))
{
throw new DataApiBuilderException(
message: $"Azure Key Vault secret name '{name}' is invalid. {validationError} Requirements: allowed characters are alphanumeric and hyphen (-); must start and end with an alphanumeric character; length 1-127 characters; case-insensitive.",
statusCode: System.Net.HttpStatusCode.ServiceUnavailable,
subStatusCode: DataApiBuilderException.SubStatusCodes.ErrorInInitialization);
}
string? value = GetAkvVariable(name);
if (EnvFailureMode == EnvironmentVariableReplacementFailureMode.Throw)
{
return value is not null ? value :
throw new DataApiBuilderException(message: $"Azure Key Vault Variable, '{name}', not found.",
statusCode: System.Net.HttpStatusCode.ServiceUnavailable,
subStatusCode: DataApiBuilderException.SubStatusCodes.ErrorInInitialization);
}
else
{
return value ?? match.Value;
}
}
private static bool IsValidAkvSecretName(string name, out string error)
{
error = string.Empty;
if (string.IsNullOrEmpty(name))
{
error = "Name cannot be null or empty.";
return false;
}
if (name.Length < 1 || name.Length > 127)
{
error = $"Length {name.Length} is outside allowed range (1-127).";
return false;
}
// Must start and end with alphanumeric
if (!char.IsLetterOrDigit(name[0]) || !char.IsLetterOrDigit(name[^1]))
{
error = "Must start and end with an alphanumeric character.";
return false;
}
// Allowed characters: letters, digits, hyphen.
for (int i = 0; i < name.Length; i++)
{
char c = name[i];
if (!(char.IsLetterOrDigit(c) || c == '-'))
{
error = $"Invalid character '{c}' at position {i}.";
return false;
}
}
return true;
}
private static SecretClient CreateSecretClient(AzureKeyVaultOptions options)
{
if (string.IsNullOrWhiteSpace(options.Endpoint))
{
throw new DataApiBuilderException(
"Missing 'endpoint' property is required to connect to Azure Key Vault.",
System.Net.HttpStatusCode.InternalServerError,
DataApiBuilderException.SubStatusCodes.ErrorInInitialization);
}
// If endpoint is a local .akv file, we should not create a SecretClient.
if (IsLocalAkvFileEndpoint(options.Endpoint))
{
throw new DataApiBuilderException(
"Attempted to create Azure Key Vault client for local .akv file endpoint.",
System.Net.HttpStatusCode.InternalServerError,
DataApiBuilderException.SubStatusCodes.ErrorInInitialization);
}
SecretClientOptions clientOptions = new();
if (options.RetryPolicy is not null)
{
// Convert AKVRetryPolicyMode to RetryMode
RetryMode retryMode = options.RetryPolicy.Mode switch
{
AKVRetryPolicyMode.Fixed => RetryMode.Fixed,
AKVRetryPolicyMode.Exponential => RetryMode.Exponential,
null => RetryMode.Exponential,
_ => RetryMode.Exponential
};
clientOptions.Retry.Mode = retryMode;
clientOptions.Retry.MaxRetries = options.RetryPolicy.MaxCount ?? AKVRetryPolicyOptions.DEFAULT_MAX_COUNT;
clientOptions.Retry.Delay = TimeSpan.FromSeconds(options.RetryPolicy.DelaySeconds ?? AKVRetryPolicyOptions.DEFAULT_DELAY_SECONDS);
clientOptions.Retry.MaxDelay = TimeSpan.FromSeconds(options.RetryPolicy.MaxDelaySeconds ?? AKVRetryPolicyOptions.DEFAULT_MAX_DELAY_SECONDS);
clientOptions.Retry.NetworkTimeout = TimeSpan.FromSeconds(options.RetryPolicy.NetworkTimeoutSeconds ?? AKVRetryPolicyOptions.DEFAULT_NETWORK_TIMEOUT_SECONDS);
}
return new SecretClient(new Uri(options.Endpoint), new DefaultAzureCredential(), clientOptions); // CodeQL [SM05137] DefaultAzureCredential will use Managed Identity if available or fallback to default.
}
private string? GetAkvVariable(string name)
{
// If using local .akv file secrets, return from dictionary.
if (_akvFileSecrets is not null)
{
return _akvFileSecrets.TryGetValue(name, out string? value) ? value : null;
}
if (_akvClient is null)
{
throw new InvalidOperationException("Azure Key Vault client is not initialized.");
}
try
{
return _akvClient.GetSecret(name).Value.Value;
}
catch (Azure.RequestFailedException ex) when (ex.Status == 404)
{
return null;
}
}
}
}