< Summary - Envilder Node.js SDK

Information
Class: src/sdks/nodejs/src/application/map-file-validator.ts
Assembly: Default
File(s): src/sdks/nodejs/src/application/map-file-validator.ts
Tag: 605_44106794472
Line coverage
95%
Covered lines: 80
Uncovered lines: 4
Coverable lines: 84
Total lines: 271
Line coverage: 95.2%
Branch coverage
89%
Covered branches: 51
Total branches: 57
Branch coverage: 89.4%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

File(s)

src/sdks/nodejs/src/application/map-file-validator.ts

#LineLine coverage
 1import type { MapFileError } from '../domain/contract-validation-result.js';
 2import type { EnvilderOptions } from '../domain/envilder-options.js';
 3import {
 4  invalidEnvironmentVariableNameMessage,
 5  isValidEnvironmentVariableName,
 6  quoteName,
 7} from '../domain/environment-variable-name.js';
 8
 9/**
 10 * Checks a map file against `spec/map-file.v1.json` and the provider
 11 * configuration it resolves to, with the same rules and wording as
 12 * `envilder validate --offline`. The SDK supports fewer providers than the
 13 * schema declares, so `gcp`, `hashicorp` and `file` are reported as
 14 * unsupported. Builder overrides take precedence over `$config`, as they do
 15 * on a load. No mapped value ever reaches an error.
 16 */
 17
 218const SUPPORTED_PROVIDERS: readonly string[] = ['aws', 'azure'];
 19
 220const DEFAULT_PROVIDER = 'aws';
 21
 222const CONFIG_FIELDS = [
 23  'provider',
 24  'profile',
 25  'vaultUrl',
 26  'projectId',
 27  'namespace',
 28  'path',
 29  'name',
 30  'description',
 31  'owner',
 32  'environment',
 33];
 34
 235const URI_FIELDS = new Set(['vaultUrl']);
 36
 37/** Provider-specific `$config` fields and the providers that accept each. */
 238const PROVIDER_SPECIFIC_FIELDS: Readonly<Record<string, readonly string[]>> = {
 39  profile: ['aws'],
 40  vaultUrl: ['azure', 'hashicorp'],
 41  projectId: ['gcp'],
 42  namespace: ['hashicorp'],
 43  path: ['file'],
 44};
 45
 46/** The `$config` field each supported provider cannot work without. */
 247const REQUIRED_PROVIDER_FIELDS: Readonly<Record<string, string>> = {
 48  azure: 'vaultUrl',
 49};
 50
 251const PROVIDER_LABELS: Readonly<Record<string, string>> = {
 52  aws: 'AWS',
 53  azure: 'Azure',
 54};
 55
 56/** The builder method that overrides each field, named in errors. */
 257const OVERRIDE_METHODS: Readonly<Record<string, string>> = {
 58  provider: 'withProvider()',
 59  profile: 'withProfile()',
 60  vaultUrl: 'withVaultUrl()',
 61};
 62
 63/** Parses and validates the raw content of a map file. */
 64export function validateMapFileContent(
 65  json: string,
 66  overrides: EnvilderOptions,
 67): MapFileError[] {
 68  let document: unknown;
 1569  try {
 1570    document = JSON.parse(json);
 71  } catch {
 72    // The parser's message quotes the surrounding text, which can be a
 73    // secret pasted into the file, so it is not repeated.
 174    return [{ key: '(root)', message: 'The map file is not valid JSON.' }];
 75  }
 1476  return validateMapFile(document, overrides);
 77}
 78
 79/** Validates a parsed map file and returns every error found. */
 80export function validateMapFile(
 81  document: unknown,
 82  overrides: EnvilderOptions,
 83): MapFileError[] {
 2984  if (!isJsonObject(document)) {
 185    return [{ key: '(root)', message: 'The map file must be a JSON object.' }];
 86  }
 87
 2888  const errors: MapFileError[] = [];
 2889  let fileConfig: Record<string, unknown> = {};
 2890  for (const [key, value] of Object.entries(document)) {
 4591    if (key === '$schema') {
 192      errors.push(...validateUri('$schema', value));
 4493    } else if (key === '$config') {
 1294      if (isJsonObject(value)) {
 1295        fileConfig = value;
 1296        errors.push(...validateConfigFields(value));
 97      } else {
 098        errors.push({ key: '$config', message: '$config must be an object.' });
 99      }
 32100    } else if (key.startsWith('$')) {
 2101      errors.push({
 102        key,
 103        message: `${formatKey(key)} is reserved: only $schema and $config may start with "$".`,
 104      });
 105    } else {
 30106      errors.push(...validateMapping(key, value));
 107    }
 108  }
 109
 28110  errors.push(...validateProviderConfiguration(fileConfig, overrides));
 28111  return errors;
 112}
 113
 114function validateMapping(key: string, value: unknown): MapFileError[] {
 30115  const errors: MapFileError[] = [];
 30116  if (!isValidEnvironmentVariableName(key)) {
 1117    errors.push({
 118      key,
 119      message: `${invalidEnvironmentVariableNameMessage(key)}.`,
 120    });
 121  }
 30122  if (typeof value !== 'string') {
 123    // The type only: the value itself may be a secret pasted by mistake.
 3124    errors.push({
 125      key,
 126      message: `${formatKey(key)} must map to a string secret path, not ${describeType(value)}.`,
 127    });
 128  }
 30129  return errors;
 130}
 131
 132function validateConfigFields(config: Record<string, unknown>): MapFileError[] {
 12133  const errors: MapFileError[] = [];
 12134  for (const [field, value] of Object.entries(config)) {
 21135    const key = `$config.${field}`;
 21136    if (!CONFIG_FIELDS.includes(field)) {
 1137      errors.push({
 138        key,
 139        message: `${formatKey(key)} is not a known field. Allowed fields: ${CONFIG_FIELDS.join(', ')}.`,
 140      });
 20141    } else if (typeof value !== 'string') {
 1142      errors.push({
 143        key,
 144        message: `${key} must be a string, not ${describeType(value)}.`,
 145      });
 19146    } else if (URI_FIELDS.has(field)) {
 5147      errors.push(...validateUri(key, value));
 148    }
 149  }
 12150  return errors;
 151}
 152
 153function validateUri(key: string, value: unknown): MapFileError[] {
 6154  if (typeof value !== 'string') {
 0155    return [
 156      { key, message: `${key} must be a string, not ${describeType(value)}.` },
 157    ];
 158  }
 6159  if (!isUri(value)) {
 1160    return [{ key, message: `${key} must be an absolute URI.` }];
 161  }
 5162  return [];
 163}
 164
 165/** A configuration field with the key that named it, for the report. */
 166type SourcedValue = { readonly value: string; readonly source: string };
 167
 168function validateProviderConfiguration(
 169  fileConfig: Record<string, unknown>,
 170  overrides: EnvilderOptions,
 171): MapFileError[] {
 28172  const effective = resolveEffectiveConfig(fileConfig, overrides);
 28173  const provider = effective.provider ?? {
 174    value: DEFAULT_PROVIDER,
 175    source: '$config.provider',
 176  };
 177
 28178  if (!SUPPORTED_PROVIDERS.includes(provider.value)) {
 1179    return [
 180      {
 181        key: provider.source,
 182        message:
 183          `Unsupported provider: ${formatKey(provider.value)}.` +
 184          ` Supported providers: ${SUPPORTED_PROVIDERS.join(', ')}.`,
 185      },
 186    ];
 187  }
 188
 27189  const errors: MapFileError[] = [];
 27190  for (const [field, validProviders] of Object.entries(
 191    PROVIDER_SPECIFIC_FIELDS,
 192  )) {
 135193    const setting = effective[field];
 135194    if (setting === undefined || validProviders.includes(provider.value)) {
 132195      continue;
 196    }
 3197    const usable = validProviders.filter((name) =>
 4198      SUPPORTED_PROVIDERS.includes(name),
 199    );
 3200    errors.push({
 201      key: setting.source,
 202      message:
 203        `${setting.source} is only supported with the` +
 204        ` ${(usable.length > 0 ? usable : validProviders).join(' or ')} provider` +
 205        ` (current provider: ${provider.value}).`,
 206    });
 207  }
 208
 27209  const required = REQUIRED_PROVIDER_FIELDS[provider.value];
 27210  if (required !== undefined && effective[required] === undefined) {
 3211    errors.push({
 212      key: `$config.${required}`,
 213      message:
 214        `${required} is required when using` +
 215        ` ${PROVIDER_LABELS[provider.value]} provider.` +
 216        ` Set it in $config.${required} in your map file` +
 217        ` or via ${OVERRIDE_METHODS[required]}.`,
 218    });
 219  }
 27220  return errors;
 221}
 222
 223function resolveEffectiveConfig(
 224  fileConfig: Record<string, unknown>,
 225  overrides: EnvilderOptions,
 226): Record<string, SourcedValue | undefined> {
 28227  const effective: Record<string, SourcedValue | undefined> = {};
 28228  for (const field of CONFIG_FIELDS) {
 280229    const value = fileConfig[field];
 280230    if (typeof value === 'string') {
 19231      effective[field] = { value, source: `$config.${field}` };
 232    }
 233  }
 234  // Blank overrides are ignored, as they are on a load.
 28235  for (const [field, method] of Object.entries(OVERRIDE_METHODS)) {
 84236    const value = overrides[field as keyof EnvilderOptions]?.trim();
 84237    if (value) {
 5238      effective[field] = {
 239        value: field === 'provider' ? value.toLowerCase() : value,
 240        source: method,
 241      };
 242    }
 243  }
 28244  return effective;
 245}
 246
 247function isJsonObject(value: unknown): value is Record<string, unknown> {
 41248  return typeof value === 'object' && value !== null && !Array.isArray(value);
 249}
 250
 251function isUri(value: string): boolean {
 6252  return /^[A-Za-z][A-Za-z0-9+.-]*:\S*$/.test(value) && URL.canParse(value);
 253}
 254
 255function describeType(value: unknown): string {
 4256  if (value === null) {
 0257    return 'null';
 258  }
 4259  if (Array.isArray(value)) {
 0260    return 'an array';
 261  }
 4262  return typeof value === 'object' ? 'an object' : `a ${typeof value}`;
 263}
 264
 265/**
 266 * Keys are untrusted input: anything outside a plain identifier is quoted, so
 267 * a key carrying a line break cannot split a message.
 268 */
 269function formatKey(key: string): string {
 7270  return /^[A-Za-z0-9_$./-]+$/.test(key) ? key : quoteName(key);
 271}