< Summary - Envilder .NET SDK

Information
Class: Envilder.MapFileValidator
Assembly: Envilder
File(s): /home/runner/work/envilder/envilder/src/sdks/dotnet/Application/MapFileValidator.cs
Tag: 605_44106794472
Line coverage
98%
Covered lines: 160
Uncovered lines: 2
Coverable lines: 162
Total lines: 326
Line coverage: 98.7%
Branch coverage
86%
Covered branches: 109
Total branches: 126
Branch coverage: 86.5%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%11100%
ValidateContent(...)100%11100%
Validate(...)100%1818100%
ValidateMapping(...)100%44100%
ValidateConfigFields(...)100%88100%
ValidateUri(...)75%4480%
ValidateProviderConfiguration(...)94.44%1818100%
ResolveEffectiveConfig(...)100%1616100%
IsUri(...)100%88100%
IsScheme(...)75%44100%
IsAsciiLetter(...)87.5%88100%
DescribeType(...)75%8888.89%
FormatKey(...)83.33%66100%
.ctor(...)100%11100%

File(s)

/home/runner/work/envilder/envilder/src/sdks/dotnet/Application/MapFileValidator.cs

#LineLine coverage
 1namespace Envilder;
 2
 3using Envilder.Domain;
 4using System;
 5using System.Collections.Generic;
 6using System.Linq;
 7using System.Text.Json;
 8
 9/// <summary>
 10/// Checks a map file against <c>spec/map-file.v1.json</c> and the provider
 11/// configuration it resolves to, with the same rules and wording as
 12/// <c>envilder validate --offline</c>. The SDK supports fewer providers than
 13/// the schema declares, so <c>gcp</c>, <c>hashicorp</c> and <c>file</c> are
 14/// reported as unsupported. Builder overrides take precedence over
 15/// <c>$config</c>, as they do on a load. No mapped value ever reaches an error.
 16/// </summary>
 17internal static class MapFileValidator
 18{
 19  private const string DefaultProvider = "aws";
 20
 121  private static readonly string[] SupportedProviders = ["aws", "azure"];
 22
 123  private static readonly string[] ConfigFields =
 124  [
 125    "provider",
 126    "profile",
 127    "vaultUrl",
 128    "projectId",
 129    "namespace",
 130    "path",
 131    "name",
 132    "description",
 133    "owner",
 134    "environment",
 135  ];
 36
 137  private static readonly string[] UriFields = ["vaultUrl"];
 38
 139  private static readonly (string Field, string[] Providers)[] ProviderSpecificFields =
 140  [
 141    ("profile", ["aws"]),
 142    ("vaultUrl", ["azure", "hashicorp"]),
 143    ("projectId", ["gcp"]),
 144    ("namespace", ["hashicorp"]),
 145    ("path", ["file"]),
 146  ];
 47
 148  private static readonly Dictionary<string, string> RequiredProviderFields = new()
 149  {
 150    ["azure"] = "vaultUrl",
 151  };
 52
 153  private static readonly Dictionary<string, string> ProviderLabels = new()
 154  {
 155    ["aws"] = "AWS",
 156    ["azure"] = "Azure",
 157  };
 58
 159  private static readonly Dictionary<string, string> OverrideMethods = new()
 160  {
 161    ["provider"] = "WithProvider()",
 162    ["profile"] = "WithProfile()",
 163    ["vaultUrl"] = "WithVaultUrl()",
 164  };
 65
 66  /// <summary>Parses and validates the raw content of a map file.</summary>
 67  public static IReadOnlyList<MapFileError> ValidateContent(string json, EnvilderOptions overrides)
 68  {
 69    try
 70    {
 171      using var document = JsonDocument.Parse(json);
 172      return Validate(document.RootElement, overrides);
 73    }
 174    catch (JsonException)
 75    {
 76      // The parser's message quotes the surrounding text, which can be a
 77      // secret pasted into the file, so it is not repeated.
 178      return [new("(root)", "The map file is not valid JSON.")];
 79    }
 180  }
 81
 82  private static List<MapFileError> Validate(JsonElement root, EnvilderOptions overrides)
 83  {
 184    if (root.ValueKind != JsonValueKind.Object)
 85    {
 186      return [new("(root)", "The map file must be a JSON object.")];
 87    }
 88
 189    var errors = new List<MapFileError>();
 190    var fileConfig = new Dictionary<string, JsonElement>();
 191    foreach (var property in root.EnumerateObject())
 92    {
 193      var key = property.Name;
 194      if (key == "$schema")
 95      {
 196        errors.AddRange(ValidateUri("$schema", property.Value));
 97      }
 198      else if (key == "$config")
 99      {
 1100        if (property.Value.ValueKind == JsonValueKind.Object)
 101        {
 1102          fileConfig = property.Value.EnumerateObject()
 1103            .GroupBy(field => field.Name)
 1104            .ToDictionary(group => group.Key, group => group.Last().Value);
 1105          errors.AddRange(ValidateConfigFields(property.Value));
 106        }
 107        else
 108        {
 1109          errors.Add(new("$config", "$config must be an object."));
 110        }
 111      }
 1112      else if (key.StartsWith("$", StringComparison.Ordinal))
 113      {
 1114        errors.Add(new(
 1115          key,
 1116          $"{FormatKey(key)} is reserved: only $schema and $config may start with \"$\"."));
 117      }
 118      else
 119      {
 1120        errors.AddRange(ValidateMapping(key, property.Value));
 121      }
 122    }
 123
 1124    errors.AddRange(ValidateProviderConfiguration(fileConfig, overrides));
 1125    return errors;
 126  }
 127
 128  private static List<MapFileError> ValidateMapping(string key, JsonElement value)
 129  {
 1130    var errors = new List<MapFileError>();
 1131    if (!EnvironmentVariableName.IsValid(key))
 132    {
 1133      errors.Add(new(key, $"{EnvironmentVariableName.InvalidMessage(key)}."));
 134    }
 135
 1136    if (value.ValueKind != JsonValueKind.String)
 137    {
 138      // The type only: the value itself may be a secret pasted by mistake.
 1139      errors.Add(new(
 1140        key,
 1141        $"{FormatKey(key)} must map to a string secret path, not {DescribeType(value)}."));
 142    }
 143
 1144    return errors;
 145  }
 146
 147  private static List<MapFileError> ValidateConfigFields(JsonElement config)
 148  {
 1149    var errors = new List<MapFileError>();
 1150    foreach (var property in config.EnumerateObject())
 151    {
 1152      var field = property.Name;
 1153      var key = $"$config.{field}";
 1154      if (!ConfigFields.Contains(field))
 155      {
 1156        errors.Add(new(
 1157          key,
 1158          $"{FormatKey(key)} is not a known field. Allowed fields: {string.Join(", ", ConfigFields)}."));
 159      }
 1160      else if (property.Value.ValueKind != JsonValueKind.String)
 161      {
 1162        errors.Add(new(key, $"{key} must be a string, not {DescribeType(property.Value)}."));
 163      }
 1164      else if (UriFields.Contains(field))
 165      {
 1166        errors.AddRange(ValidateUri(key, property.Value));
 167      }
 168    }
 169
 1170    return errors;
 171  }
 172
 173  private static List<MapFileError> ValidateUri(string key, JsonElement value)
 174  {
 1175    if (value.ValueKind != JsonValueKind.String)
 176    {
 0177      return [new(key, $"{key} must be a string, not {DescribeType(value)}.")];
 178    }
 179
 1180    return IsUri(value.GetString()!)
 1181      ? []
 1182      : [new(key, $"{key} must be an absolute URI.")];
 183  }
 184
 185  private static List<MapFileError> ValidateProviderConfiguration(
 186    Dictionary<string, JsonElement> fileConfig,
 187    EnvilderOptions overrides)
 188  {
 1189    var effective = ResolveEffectiveConfig(fileConfig, overrides);
 1190    var provider = effective.TryGetValue("provider", out var configured)
 1191      ? configured
 1192      : new(DefaultProvider, "$config.provider");
 193
 1194    if (!SupportedProviders.Contains(provider.Value))
 195    {
 1196      return
 1197      [
 1198        new(
 1199          provider.Source,
 1200          $"Unsupported provider: {FormatKey(provider.Value)}."
 1201          + $" Supported providers: {string.Join(", ", SupportedProviders)}."),
 1202      ];
 203    }
 204
 1205    var errors = new List<MapFileError>();
 1206    foreach (var (field, validProviders) in ProviderSpecificFields)
 207    {
 1208      if (!effective.TryGetValue(field, out var setting) || validProviders.Contains(provider.Value))
 209      {
 210        continue;
 211      }
 212
 1213      var usable = validProviders.Where(name => SupportedProviders.Contains(name)).ToList();
 1214      var names = string.Join(" or ", usable.Count > 0 ? usable : validProviders.ToList());
 1215      errors.Add(new(
 1216        setting.Source,
 1217        $"{setting.Source} is only supported with the {names} provider"
 1218        + $" (current provider: {provider.Value})."));
 219    }
 220
 1221    if (RequiredProviderFields.TryGetValue(provider.Value, out var required)
 1222      && !effective.ContainsKey(required))
 223    {
 1224      errors.Add(new(
 1225        $"$config.{required}",
 1226        $"{required} is required when using {ProviderLabels[provider.Value]} provider."
 1227        + $" Set it in $config.{required} in your map file"
 1228        + $" or via {OverrideMethods[required]}."));
 229    }
 230
 1231    return errors;
 232  }
 233
 234  private static Dictionary<string, SourcedValue> ResolveEffectiveConfig(
 235    Dictionary<string, JsonElement> fileConfig,
 236    EnvilderOptions overrides)
 237  {
 1238    var effective = new Dictionary<string, SourcedValue>();
 1239    foreach (var field in ConfigFields)
 240    {
 1241      if (fileConfig.TryGetValue(field, out var value) && value.ValueKind == JsonValueKind.String)
 242      {
 1243        effective[field] = new(value.GetString()!, $"$config.{field}");
 244      }
 245    }
 246
 247    // Blank overrides are ignored, as they are on a load.
 1248    var overridden = new Dictionary<string, string?>
 1249    {
 1250      ["provider"] = overrides.Provider?.ToString(),
 1251      ["profile"] = overrides.Profile,
 1252      ["vaultUrl"] = overrides.VaultUrl,
 1253    };
 1254    foreach (var entry in OverrideMethods)
 255    {
 1256      var field = entry.Key;
 1257      var value = overridden[field]?.Trim();
 1258      if (!string.IsNullOrEmpty(value))
 259      {
 1260        effective[field] = new(
 1261          field == "provider" ? value!.ToLowerInvariant() : value!,
 1262          entry.Value);
 263      }
 264    }
 265
 1266    return effective;
 267  }
 268
 269  private static bool IsUri(string value)
 270  {
 1271    var colon = value.IndexOf(':');
 1272    return colon > 0
 1273      && IsScheme(value.Substring(0, colon))
 1274      && !value.Any(char.IsWhiteSpace)
 1275      && Uri.TryCreate(value, UriKind.Absolute, out _);
 276  }
 277
 278  private static bool IsScheme(string scheme)
 279  {
 1280    return IsAsciiLetter(scheme[0])
 1281      && scheme.All(c => IsAsciiLetter(c) || (c is >= '0' and <= '9') || c is '+' or '.' or '-');
 282  }
 283
 284  private static bool IsAsciiLetter(char c)
 285  {
 1286    return c is (>= 'A' and <= 'Z') or (>= 'a' and <= 'z');
 287  }
 288
 289  private static string DescribeType(JsonElement value)
 290  {
 1291    return value.ValueKind switch
 1292    {
 1293      JsonValueKind.Null => "null",
 1294      JsonValueKind.Array => "an array",
 1295      JsonValueKind.Object => "an object",
 0296      JsonValueKind.String => "a string",
 1297      JsonValueKind.Number => "a number",
 1298      _ => "a boolean",
 1299    };
 300  }
 301
 302  /// <summary>
 303  /// Keys are untrusted input: anything outside a plain identifier is quoted,
 304  /// so a key carrying a line break cannot split a message.
 305  /// </summary>
 306  private static string FormatKey(string key)
 307  {
 1308    var plain = key.Length > 0 && key.All(c =>
 1309      IsAsciiLetter(c) || (c is >= '0' and <= '9') || c is '_' or '$' or '.' or '/' or '-');
 1310    return plain ? key : EnvironmentVariableName.Quote(key);
 311  }
 312
 313  /// <summary>A configuration field with the key that named it, for the report.</summary>
 314  private sealed class SourcedValue
 315  {
 1316    public SourcedValue(string value, string source)
 317    {
 1318      Value = value;
 1319      Source = source;
 1320    }
 321
 322    public string Value { get; }
 323
 324    public string Source { get; }
 325  }
 326}