-
Notifications
You must be signed in to change notification settings - Fork 244
Expand file tree
/
Copy pathConfigurationValidator.cs
More file actions
217 lines (189 loc) · 8.29 KB
/
ConfigurationValidator.cs
File metadata and controls
217 lines (189 loc) · 8.29 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
using LanguageExt;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Nodes;
using YamlDotNet.Core;
namespace common;
public record ConfigurationValidationError(string PropertyPath, string Message)
{
public override string ToString() => $"{PropertyPath}: {Message}";
}
public static class ConfigurationValidator
{
private static readonly ImmutableHashSet<string> ValidExtractorSections = ImmutableHashSet.Create(
StringComparer.OrdinalIgnoreCase,
"apiNames",
"backendNames",
"diagnosticNames",
"gatewayNames",
"groupNames",
"loggerNames",
"namedValueNames",
"policyFragmentNames",
"productNames",
"subscriptionNames",
"tagNames",
"versionSetNames",
"workspaceNames"
);
public static Either<ImmutableList<ConfigurationValidationError>, ConfigurationJson> ValidateExtractorConfiguration(
ConfigurationJson configurationJson,
ILogger? logger = null)
{
var errors = new List<ConfigurationValidationError>();
// Validate root structure
ValidateRootStructure(configurationJson.Value, errors);
// Validate each known section
ValidateKnownSections(configurationJson.Value, errors, logger);
// Check for unknown sections
ValidateUnknownSections(configurationJson.Value, errors, logger);
return errors.Count == 0
? Either<ImmutableList<ConfigurationValidationError>, ConfigurationJson>.Right(configurationJson)
: Either<ImmutableList<ConfigurationValidationError>, ConfigurationJson>.Left(errors.ToImmutableList());
}
public static Either<ImmutableList<ConfigurationValidationError>, ConfigurationJson> ValidateExtractorConfigurationFromFile(
FileInfo configurationFile,
ILogger? logger = null)
{
try
{
if (!configurationFile.Exists)
{
return Either<ImmutableList<ConfigurationValidationError>, ConfigurationJson>.Left(
ImmutableList.Create(new ConfigurationValidationError("file", $"Configuration file '{configurationFile.FullName}' does not exist.")));
}
using var reader = File.OpenText(configurationFile.FullName);
var configurationJson = ConfigurationJson.FromYaml(reader);
return ValidateExtractorConfiguration(configurationJson, logger);
}
catch (YamlException yamlEx)
{
return Either<ImmutableList<ConfigurationValidationError>, ConfigurationJson>.Left(
ImmutableList.Create(new ConfigurationValidationError("yaml", $"YAML parsing error: {yamlEx.Message}")));
}
catch (JsonException jsonEx)
{
return Either<ImmutableList<ConfigurationValidationError>, ConfigurationJson>.Left(
ImmutableList.Create(new ConfigurationValidationError("json", $"JSON conversion error: {jsonEx.Message}")));
}
catch (IOException ioEx)
{
return Either<ImmutableList<ConfigurationValidationError>, ConfigurationJson>.Left(
ImmutableList.Create(new ConfigurationValidationError("file", $"File I/O error: {ioEx.Message}")));
}
catch (UnauthorizedAccessException authEx)
{
return Either<ImmutableList<ConfigurationValidationError>, ConfigurationJson>.Left(
ImmutableList.Create(new ConfigurationValidationError("access", $"Access denied: {authEx.Message}")));
}
}
private static void ValidateRootStructure(JsonObject rootObject, List<ConfigurationValidationError> errors)
{
if (rootObject.Count == 0)
{
errors.Add(new ConfigurationValidationError("root", "Configuration file is empty or contains no valid sections."));
return;
}
// Check if all properties are arrays (as expected for extractor config)
foreach (var property in rootObject)
{
if (property.Value is not JsonArray)
{
errors.Add(new ConfigurationValidationError(
property.Key,
$"Property '{property.Key}' must be an array of strings."));
}
}
}
private static void ValidateKnownSections(JsonObject rootObject, List<ConfigurationValidationError> errors, ILogger? logger)
{
foreach (var sectionName in ValidExtractorSections)
{
if (rootObject.TryGetPropertyValue(sectionName, out var sectionNode) && sectionNode is JsonArray sectionArray)
{
ValidateStringArray(sectionName, sectionArray, errors);
}
}
}
private static void ValidateStringArray(string sectionName, JsonArray array, List<ConfigurationValidationError> errors)
{
if (array.Count == 0)
{
errors.Add(new ConfigurationValidationError(sectionName, $"Section '{sectionName}' is empty. Consider removing it if no items need to be extracted."));
return;
}
var duplicates = new System.Collections.Generic.HashSet<string>();
var seen = new System.Collections.Generic.HashSet<string>(StringComparer.OrdinalIgnoreCase);
for (int i = 0; i < array.Count; i++)
{
var item = array[i];
// Check if item is a string
if (item is not JsonValue jsonValue || jsonValue.TryGetValue<string>(out var stringValue) == false)
{
errors.Add(new ConfigurationValidationError(
$"{sectionName}[{i}]",
"All items in the array must be strings."));
continue;
}
// Check for empty or whitespace strings
if (string.IsNullOrWhiteSpace(stringValue))
{
errors.Add(new ConfigurationValidationError(
$"{sectionName}[{i}]",
"Items cannot be empty or contain only whitespace."));
continue;
}
// Check for duplicates
if (!seen.Add(stringValue))
{
duplicates.Add(stringValue);
}
// Validate naming conventions
ValidateNamingConvention(sectionName, i, stringValue, errors);
}
// Report duplicates
foreach (var duplicate in duplicates)
{
errors.Add(new ConfigurationValidationError(
sectionName,
$"Duplicate item found: '{duplicate}'. Each item should be unique."));
}
}
private static void ValidateNamingConvention(string sectionName, int index, string name, List<ConfigurationValidationError> errors)
{
// Basic naming convention validation
if (name.Length > 256)
{
errors.Add(new ConfigurationValidationError(
$"{sectionName}[{index}]",
$"Name '{name}' is too long. Maximum length is 256 characters."));
}
// Check for invalid characters (basic validation)
if (name.Contains("//", StringComparison.Ordinal) || name.Contains("\\\\", StringComparison.Ordinal))
{
errors.Add(new ConfigurationValidationError(
$"{sectionName}[{index}]",
$"Name '{name}' contains invalid character sequences."));
}
}
private static void ValidateUnknownSections(JsonObject rootObject, List<ConfigurationValidationError> errors, ILogger? logger)
{
var unknownSections = rootObject
.Where(kvp => !ValidExtractorSections.Contains(kvp.Key))
.Select(kvp => kvp.Key)
.ToList();
foreach (var unknownSection in unknownSections)
{
var message = $"Unknown configuration section: '{unknownSection}'. Valid sections are: {string.Join(", ", ValidExtractorSections.OrderBy(s => s))}";
logger?.LogWarning("Configuration validation warning: {Message}", message);
// For now, treat unknown sections as warnings, not errors
// Uncomment the next line if you want to treat them as errors
// errors.Add(new ConfigurationValidationError(unknownSection, message));
}
}
}