< Summary - Envilder .NET SDK

Information
Class: Envilder.MapFileValidator.SourcedValue
Assembly: Envilder
File(s): /home/runner/work/envilder/envilder/src/sdks/dotnet/Application/MapFileValidator.cs
Tag: 605_44106794472
Line coverage
100%
Covered lines: 4
Uncovered lines: 0
Coverable lines: 4
Total lines: 326
Line coverage: 100%
Branch coverage
N/A
Covered branches: 0
Total branches: 0
Branch coverage: N/A
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.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
 21  private static readonly string[] SupportedProviders = ["aws", "azure"];
 22
 23  private static readonly string[] ConfigFields =
 24  [
 25    "provider",
 26    "profile",
 27    "vaultUrl",
 28    "projectId",
 29    "namespace",
 30    "path",
 31    "name",
 32    "description",
 33    "owner",
 34    "environment",
 35  ];
 36
 37  private static readonly string[] UriFields = ["vaultUrl"];
 38
 39  private static readonly (string Field, string[] Providers)[] ProviderSpecificFields =
 40  [
 41    ("profile", ["aws"]),
 42    ("vaultUrl", ["azure", "hashicorp"]),
 43    ("projectId", ["gcp"]),
 44    ("namespace", ["hashicorp"]),
 45    ("path", ["file"]),
 46  ];
 47
 48  private static readonly Dictionary<string, string> RequiredProviderFields = new()
 49  {
 50    ["azure"] = "vaultUrl",
 51  };
 52
 53  private static readonly Dictionary<string, string> ProviderLabels = new()
 54  {
 55    ["aws"] = "AWS",
 56    ["azure"] = "Azure",
 57  };
 58
 59  private static readonly Dictionary<string, string> OverrideMethods = new()
 60  {
 61    ["provider"] = "WithProvider()",
 62    ["profile"] = "WithProfile()",
 63    ["vaultUrl"] = "WithVaultUrl()",
 64  };
 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    {
 71      using var document = JsonDocument.Parse(json);
 72      return Validate(document.RootElement, overrides);
 73    }
 74    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.
 78      return [new("(root)", "The map file is not valid JSON.")];
 79    }
 80  }
 81
 82  private static List<MapFileError> Validate(JsonElement root, EnvilderOptions overrides)
 83  {
 84    if (root.ValueKind != JsonValueKind.Object)
 85    {
 86      return [new("(root)", "The map file must be a JSON object.")];
 87    }
 88
 89    var errors = new List<MapFileError>();
 90    var fileConfig = new Dictionary<string, JsonElement>();
 91    foreach (var property in root.EnumerateObject())
 92    {
 93      var key = property.Name;
 94      if (key == "$schema")
 95      {
 96        errors.AddRange(ValidateUri("$schema", property.Value));
 97      }
 98      else if (key == "$config")
 99      {
 100        if (property.Value.ValueKind == JsonValueKind.Object)
 101        {
 102          fileConfig = property.Value.EnumerateObject()
 103            .GroupBy(field => field.Name)
 104            .ToDictionary(group => group.Key, group => group.Last().Value);
 105          errors.AddRange(ValidateConfigFields(property.Value));
 106        }
 107        else
 108        {
 109          errors.Add(new("$config", "$config must be an object."));
 110        }
 111      }
 112      else if (key.StartsWith("$", StringComparison.Ordinal))
 113      {
 114        errors.Add(new(
 115          key,
 116          $"{FormatKey(key)} is reserved: only $schema and $config may start with \"$\"."));
 117      }
 118      else
 119      {
 120        errors.AddRange(ValidateMapping(key, property.Value));
 121      }
 122    }
 123
 124    errors.AddRange(ValidateProviderConfiguration(fileConfig, overrides));
 125    return errors;
 126  }
 127
 128  private static List<MapFileError> ValidateMapping(string key, JsonElement value)
 129  {
 130    var errors = new List<MapFileError>();
 131    if (!EnvironmentVariableName.IsValid(key))
 132    {
 133      errors.Add(new(key, $"{EnvironmentVariableName.InvalidMessage(key)}."));
 134    }
 135
 136    if (value.ValueKind != JsonValueKind.String)
 137    {
 138      // The type only: the value itself may be a secret pasted by mistake.
 139      errors.Add(new(
 140        key,
 141        $"{FormatKey(key)} must map to a string secret path, not {DescribeType(value)}."));
 142    }
 143
 144    return errors;
 145  }
 146
 147  private static List<MapFileError> ValidateConfigFields(JsonElement config)
 148  {
 149    var errors = new List<MapFileError>();
 150    foreach (var property in config.EnumerateObject())
 151    {
 152      var field = property.Name;
 153      var key = $"$config.{field}";
 154      if (!ConfigFields.Contains(field))
 155      {
 156        errors.Add(new(
 157          key,
 158          $"{FormatKey(key)} is not a known field. Allowed fields: {string.Join(", ", ConfigFields)}."));
 159      }
 160      else if (property.Value.ValueKind != JsonValueKind.String)
 161      {
 162        errors.Add(new(key, $"{key} must be a string, not {DescribeType(property.Value)}."));
 163      }
 164      else if (UriFields.Contains(field))
 165      {
 166        errors.AddRange(ValidateUri(key, property.Value));
 167      }
 168    }
 169
 170    return errors;
 171  }
 172
 173  private static List<MapFileError> ValidateUri(string key, JsonElement value)
 174  {
 175    if (value.ValueKind != JsonValueKind.String)
 176    {
 177      return [new(key, $"{key} must be a string, not {DescribeType(value)}.")];
 178    }
 179
 180    return IsUri(value.GetString()!)
 181      ? []
 182      : [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  {
 189    var effective = ResolveEffectiveConfig(fileConfig, overrides);
 190    var provider = effective.TryGetValue("provider", out var configured)
 191      ? configured
 192      : new(DefaultProvider, "$config.provider");
 193
 194    if (!SupportedProviders.Contains(provider.Value))
 195    {
 196      return
 197      [
 198        new(
 199          provider.Source,
 200          $"Unsupported provider: {FormatKey(provider.Value)}."
 201          + $" Supported providers: {string.Join(", ", SupportedProviders)}."),
 202      ];
 203    }
 204
 205    var errors = new List<MapFileError>();
 206    foreach (var (field, validProviders) in ProviderSpecificFields)
 207    {
 208      if (!effective.TryGetValue(field, out var setting) || validProviders.Contains(provider.Value))
 209      {
 210        continue;
 211      }
 212
 213      var usable = validProviders.Where(name => SupportedProviders.Contains(name)).ToList();
 214      var names = string.Join(" or ", usable.Count > 0 ? usable : validProviders.ToList());
 215      errors.Add(new(
 216        setting.Source,
 217        $"{setting.Source} is only supported with the {names} provider"
 218        + $" (current provider: {provider.Value})."));
 219    }
 220
 221    if (RequiredProviderFields.TryGetValue(provider.Value, out var required)
 222      && !effective.ContainsKey(required))
 223    {
 224      errors.Add(new(
 225        $"$config.{required}",
 226        $"{required} is required when using {ProviderLabels[provider.Value]} provider."
 227        + $" Set it in $config.{required} in your map file"
 228        + $" or via {OverrideMethods[required]}."));
 229    }
 230
 231    return errors;
 232  }
 233
 234  private static Dictionary<string, SourcedValue> ResolveEffectiveConfig(
 235    Dictionary<string, JsonElement> fileConfig,
 236    EnvilderOptions overrides)
 237  {
 238    var effective = new Dictionary<string, SourcedValue>();
 239    foreach (var field in ConfigFields)
 240    {
 241      if (fileConfig.TryGetValue(field, out var value) && value.ValueKind == JsonValueKind.String)
 242      {
 243        effective[field] = new(value.GetString()!, $"$config.{field}");
 244      }
 245    }
 246
 247    // Blank overrides are ignored, as they are on a load.
 248    var overridden = new Dictionary<string, string?>
 249    {
 250      ["provider"] = overrides.Provider?.ToString(),
 251      ["profile"] = overrides.Profile,
 252      ["vaultUrl"] = overrides.VaultUrl,
 253    };
 254    foreach (var entry in OverrideMethods)
 255    {
 256      var field = entry.Key;
 257      var value = overridden[field]?.Trim();
 258      if (!string.IsNullOrEmpty(value))
 259      {
 260        effective[field] = new(
 261          field == "provider" ? value!.ToLowerInvariant() : value!,
 262          entry.Value);
 263      }
 264    }
 265
 266    return effective;
 267  }
 268
 269  private static bool IsUri(string value)
 270  {
 271    var colon = value.IndexOf(':');
 272    return colon > 0
 273      && IsScheme(value.Substring(0, colon))
 274      && !value.Any(char.IsWhiteSpace)
 275      && Uri.TryCreate(value, UriKind.Absolute, out _);
 276  }
 277
 278  private static bool IsScheme(string scheme)
 279  {
 280    return IsAsciiLetter(scheme[0])
 281      && scheme.All(c => IsAsciiLetter(c) || (c is >= '0' and <= '9') || c is '+' or '.' or '-');
 282  }
 283
 284  private static bool IsAsciiLetter(char c)
 285  {
 286    return c is (>= 'A' and <= 'Z') or (>= 'a' and <= 'z');
 287  }
 288
 289  private static string DescribeType(JsonElement value)
 290  {
 291    return value.ValueKind switch
 292    {
 293      JsonValueKind.Null => "null",
 294      JsonValueKind.Array => "an array",
 295      JsonValueKind.Object => "an object",
 296      JsonValueKind.String => "a string",
 297      JsonValueKind.Number => "a number",
 298      _ => "a boolean",
 299    };
 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  {
 308    var plain = key.Length > 0 && key.All(c =>
 309      IsAsciiLetter(c) || (c is >= '0' and <= '9') || c is '_' or '$' or '.' or '/' or '-');
 310    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}

Methods/Properties

.ctor(string, string)