All files / build-tools validate-cfn.ts

72.41% Statements 84/116
68.57% Branches 24/35
75.75% Functions 25/33
71.81% Lines 79/110

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337                                                                                          1x                         1x   7x 7x 7x     7x       7x       7x 7x     7x 7x                                             7x       7x 7x 7x 7x               7x 7x     7x               14x 14x   14x                                 14x 14x   14x 2x           14x   14x 14x 14x   14x 4x 4x 2x 2x           2x 2x 1x     2x       14x 12x 2x       14x 14x           3x       3x 3x   3x 3x 1x         44x       39x 39x 39x 28x   39x               28x 28x         7x         28x         1x 1x     11x   11x                               7x     114x 114x 114x   114x       153x     153x 153x 74x   79x         74x 74x   74x                       1x                                                     1x            
/* eslint-disable no-console */
/**
 * CloudFormation spec validator
 *
 * "Why not JSON Schema?", you might ask, and it's a fair question. The answer is:
 * because the error reporting from JSON schema is pretty bad, and I want the validation
 * errors reported from this check to be blindingly obvious, as non-spec-experts
 * are going to have to consume and understand them.
 *
 * I tried JSON Schema validation and its errors look like:
 *
 * ```
 * - instance.PropertyTypes["..."].Properties.Xyz does not match allOf schema <#/definitions/Typed> with 7 error[s]:
 * - instance.PropertyTypes["..."].Properties.Xyz requires property "PrimitiveType"
 * - instance.PropertyTypes["..."].Properties.Xyz requires property "Type"
 * - instance.PropertyTypes["..."].Properties.Xyz requires property "Type"
 * - instance.PropertyTypes["..."].Properties.Xyz requires property "ItemType"
 * - instance.PropertyTypes["..."].Properties.Xyz requires property "Type"
 * - instance.PropertyTypes["..."].Properties.Xyz requires property "PrimitiveItemType"
 * - instance.PropertyTypes["..."].Properties.Xyz is not exactly one from "Primitive","Complex Type","Collection of Primitives","Collection of Complex Types"
 * ```
 *
 * No bueno. In contrast, this script prints:
 *
 * ```
 * {
 *   "ResourceTypes": {
 *     "AWS::SageMaker::Device": {
 *       "Properties": {
 *         "Device": {
 *
 * !!!       must have exactly one of 'Type', 'PrimitiveType', found: {"Type":"Device","PrimitiveType":"Json"} !!!
 *
 *           "Documentation": "http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-sagemaker-device.html#cfn-sagemaker-device-device",
 *           "UpdateType": "Mutable",
 *           "Required": false,
 *           "PrimitiveType": "Json",
 *           "Type": "Device"
 *         }
 *       }
 *     }
 *   }
 * }
 * ```
 */
import * as fs from 'fs-extra';
 
export interface CfnSpec {
  PropertyTypes: Record<string, any>;
  ResourceTypes: Record<string, any>;
  ResourceSpecificationVersion: string;
}
 
export interface ValidationError {
  readonly value: JsonValue<any>;
  readonly message: string;
}
 
export class CfnSpecValidator {
  public static validate(spec: CfnSpec) {
    const ret = new CfnSpecValidator(spec);
    ret.validateSpec();
    return ret.errors;
  }
 
  public readonly errors = new Array<ValidationError>();
  private readonly root: JsonValue<CfnSpec>;
 
  constructor(spec: CfnSpec) {
    this.root = JsonValue.of(spec);
  }
 
  public validateSpec() {
    this.assert(this.root.get('PropertyTypes'), isObject, (propTypes) => {
      this.validateMap(propTypes, (propType) => this.validatePropertyType(propType));
    });
 
    this.assert(this.root.get('ResourceTypes'), isObject, (resTypes) => {
      this.validateMap(resTypes, (propType) => this.validateResourceType(propType));
    });
  }
 
  /**
   * Property types are extremely weird
   *
   * Nominally, they define "records" that have a `Properties` field with the defined
   * properties.
   *
   * However, they are also commonly used as aliases for other types, meaning they have
   * the same type-indicating fields as individual property *fields* would have.
   *
   * Also also, it seems to be quite common to have them empty--have no fields at all.
   * This seems to be taken as an alias for an unstructured `Json` type. It's probably
   * just a mistake, but unfortunately a mistake that S3 is participating in, so if we
   * fail on that we won't be able to consume updates to S3's schema. Our codegen is
   * ready to deal with this and just renders it to an empty struct.
   */
  private validatePropertyType(propType: JsonValue<Record<string, any>>) {
    // If the only set of properties is "Documentation", we take this to be an alias
    // for an empty struct and allow it. I feel icky allowing this, but it seems to
    // be pragmatic for now.
    Iif (Object.keys(propType.value).join(',') === 'Documentation') {
      return;
    }
 
    const properties = propType.get('Properties');
    if (properties.hasValue) {
      this.assert(properties, isObject, (props) => {
        this.validateProperties(props);
      });
    } else E{
      this.validateType(propType, 'if a property type doesn\'t have "Properties", it ');
    }
  }
 
  private validateResourceType(resType: JsonValue<any>) {
    this.assertOptional(resType.get('Properties'), isObject, (props) => {
      this.validateProperties(props);
    });
 
    this.assertOptional(resType.get('Attributes'), isObject, (attrs) => {
      this.validateMap(attrs, attr => {
        this.validateType(attr);
      });
    });
  }
 
  private validateProperties(properties: JsonValue<Record<string, any>>) {
    this.validateMap(properties, prop => {
      this.validateType(prop);
 
      this.assertOptional(prop.get('UpdateType'), (x: any) => {
        Iif (!['Mutable', 'Immutable', 'Conditional'].includes(x)) {
          throw new Error(`invalid value for enum: '${x}'`);
        }
      });
    });
  }
 
  /**
   * Validate the type
   *
   * There must be:
   * - Either Type or PrimitiveType
   * - Only if Type is List or Map, there will be either an ItemType or a PrimitiveItemType
   * - Non-primitive Types must correspond to a property type
   */
  private validateType(typedObject: JsonValue<Record<string, any>>, errorPrefix = '') {
    const type = typedObject.get('Type');
    const primitiveType = typedObject.get('PrimitiveType');
 
    if (type.hasValue === primitiveType.hasValue) {
      this.report(typedObject, `${errorPrefix}must have exactly one of 'Type', 'PrimitiveType', found: ${JSON.stringify({
        Type: type.valueOrUndefined,
        PrimitiveType: primitiveType.valueOrUndefined,
      })}`);
    }
 
    this.assertOptional(primitiveType, isValidPrimitive);
 
    let isCollectionType = false;
    const itemType = typedObject.get('ItemType');
    const primitiveItemType = typedObject.get('PrimitiveItemType');
 
    if (type.hasValue) {
      isCollectionType = COLLECTION_TYPES.includes(type.value);
      if (isCollectionType) {
        if (itemType.hasValue === primitiveItemType.hasValue) {
          this.report(typedObject, `must have exactly one of 'ItemType', 'PrimitiveItemType', found: ${JSON.stringify({
            ItemType: itemType.valueOrUndefined,
            PrimitiveItemType: primitiveItemType.valueOrUndefined,
          })}`);
        }
 
        this.assertOptional(primitiveItemType, isValidPrimitive);
        if (itemType.hasValue) {
          this.assertValidPropertyTypeReference(itemType);
        }
      } else {
        this.assertValidPropertyTypeReference(type);
      }
    }
 
    if (!isCollectionType) {
      if (itemType.hasValue || primitiveItemType.hasValue) {
        this.report(typedObject, 'only \'List\' or \'Map\' types can have \'ItemType\', \'PrimitiveItemType\'');
      }
    }
 
    const dupes = typedObject.get('DuplicatesAllowed');
    Iif (dupes.hasValue && !isCollectionType) {
      this.report(dupes, 'occurs on non-collection type');
    }
  }
 
  private assertValidPropertyTypeReference(typeName: JsonValue<string>) {
    Iif (BUILTIN_COMPLEX_TYPES.includes(typeName.value)) {
      return;
    }
 
    const cfnName = typeName.path[1]; // AWS::Xyz::Resource[.Property]
    const namespace = cfnName.split('.')[0];
 
    const propTypeName = `${namespace}.${typeName.value}`;
    if (!this.root.get('PropertyTypes').get(propTypeName).hasValue) {
      this.report(typeName, `unknown property type name '${typeName.value}' (missing definition for '${propTypeName}')`);
    }
  }
 
  private assertOptional<A, B extends A>(x: JsonValue<A>, pred: (x: A) => asserts x is B, block?: (x: JsonValue<B>) => void): boolean {
    return x.hasValue ? this.assert(x, pred, block) : true;
  }
 
  private assert<A, B extends A>(x: JsonValue<A>, pred: (x: A) => asserts x is B, block?: (x: JsonValue<B>) => void): boolean {
    try {
      pred(x.value);
      if (block) {
        block(new JsonValue(x.value, x.path));
      }
      return true;
    } catch (e) {
      this.report(x, e.message);
      return false;
    }
  }
 
  private validateMap<A>(x: JsonValue<Record<string, A>>, block: (x: JsonValue<A>) => void) {
    for (const key in x.value) {
      block(x.get(key));
    }
  }
 
  private report(value: JsonValue<any>, message: string) {
    this.errors.push({ value, message });
  }
}
 
function isObject(x: any): asserts x is Record<string, any> {
  Iif (x == null || typeof x !== 'object' || Array.isArray(x)) {
    throw new Error(`expected object, found '${x}'`);
  }
}
 
const COLLECTION_TYPES = ['List', 'Map'];
const BUILTIN_COMPLEX_TYPES = ['Tag'];
 
function isValidPrimitive(x: any): asserts x is string {
  const primitives = ['String', 'Long', 'Integer', 'Double', 'Boolean', 'Timestamp', 'Json'];
 
  Iif (!primitives.includes(x)) {
    throw new Error(`must be one of ${primitives.join(', ')}, got: ${x}`);
  }
}
 
interface JsonValue<A> {
  readonly path: string[];
  readonly pathValue: any;
  readonly hasValue: boolean;
  readonly value: A;
  readonly valueOrUndefined: A | undefined;
  get<K extends keyof A>(k: K): JsonValue<A[K]>;
}
 
class JsonValue<A> implements JsonValue<A> {
  public static of<B>(x: B): JsonValue<B> {
    return new JsonValue(x, []);
  }
 
  public readonly hasValue: boolean = true;
  public readonly valueOrUndefined: A | undefined = this.value;
  public readonly pathValue: any = this.value;
 
  constructor(public readonly value: A, public readonly path: string[]) {
  }
 
  public get<K extends keyof A>(k: K): JsonValue<A[K]> {
    Iif (!this.value || typeof this.value !== 'object' || Array.isArray(this.value)) {
      return new ErrorValue(`expected object, found ${this.value}`, this.path, this.value);
    }
    const ret = this.value[k];
    if (ret === undefined) {
      return new ErrorValue(`missing required key '${k}'`, this.path, this.value);
    }
    return new JsonValue(ret, [...this.path, `${k}`]);
  }
}
 
class ErrorValue<A> implements JsonValue<A> {
  public readonly hasValue = false;
  public readonly valueOrUndefined: A | undefined = undefined;
 
  constructor(private readonly error: string, public readonly path: string[], public readonly pathValue: any) {
  }
 
  public get<K extends keyof A>(_k: K): JsonValue<A[K]> {
    return this as any;
  }
 
  public get value(): A {
    throw new Error(this.error);
  }
}
 
export function formatErrorInContext(error: ValidationError) {
  let reportValue = error.value.pathValue;
  for (let i = error.value.path.length; i > 0; i--) {
    reportValue = { [error.value.path[i - 1]]: reportValue };
  }
 
  const formattedLines = JSON.stringify(reportValue, undefined, 2).split('\n');
 
  const indent = 2 * (error.value.path.length + 1);
 
  // Insert the error message at line N with an appropriate indent
  formattedLines.splice(error.value.path.length + 1, 0, `\n!!!${' '.repeat(indent - 3)}${error.message} !!!\n`);
 
  return formattedLines.join('\n');
}
 
async function main(args: string[]) {
  const spec = await fs.readJson(args[0]);
  const errors = CfnSpecValidator.validate(spec);
  Iif (errors.length !== 0) {
    for (const error of errors) {
      console.error(formatErrorInContext(error));
    }
    process.exitCode = 1;
  }
}
 
Iif (require.main === module) {
  main(process.argv.slice(2)).catch(e => {
    process.exitCode = 1;
    // eslint-disable-next-line no-console
    console.error(e.message);
  });
}