All files / src/plugins/validation/2and3/semantic-validators schema-ibm.js

98.37% Statements 181/184
93% Branches 186/200
100% Functions 21/21
100% Lines 173/173

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 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626                                      29x 29x 29x 29x   29x 135x   135x   135x   135x 5473x                                       5473x           5473x         1468x 1510x 4x 8x   1506x 12x 27x   1494x 5x 7x     1489x     1468x           135x   135x 1489x   1489x   1489x 1489x 22x   22x         1467x 1456x 1456x 1456x               1467x 1449x 1449x 1449x               1467x 1454x 1454x 1454x                 1489x 1489x                   135x           1489x 300x       1189x 1189x 160x 1x                 1189x 1189x 1189x           1189x 1x                   1189x 179x     1010x 1010x 1010x             1010x               1010x 593x   1010x   196x       1x                 196x   9x       4x                 9x   356x       11x                 356x     7x 1x             7x     264x 1x             264x     161x 1x             161x         11x 2x           9x 2x                   11x 1x             11x     6x                                   1489x               1489x 1489x 60x               1489x 1239x       250x   566x     524x   516x     516x 516x 88x               428x 428x 1x                         22x 13x       9x 9x     9x   9x 9x 6x 2x                                               1449x 1215x       234x 234x 550x     549x   549x 549x 1x             548x                                   1456x 1218x       238x 553x     552x   551x 551x 551x   551x 551x 21x                       22x 17x     5x 15x 15x 12x 12x 12x 4x                                                 1454x 1370x     84x 257x 257x 227x 227x 227x 227x 227x 4x                           7x 7x           7x                         1489x   250x   566x 518x 149x   10x 3x 3x             10x               369x   343x                    
// invalid_type_format_pair:
// Schemas need to have properly matching type/format pairs
 
// snake_case_only:
// Property names and enum values MUST be lower snake case.
// https://pages.github.ibm.com/CloudEngineering/api_handbook/design/terminology.html#formatting
 
// no_schema_description:
// Schema objects should have a description
 
// no_property_description:
// Properties within schema objects should have descriptions
 
// description_mentions_json:
// Schema property descriptions should not state that model will be a JSON object
 
// array_of_arrays:
// Schema properties that are arrays should avoid having items that are also arrays
 
const forIn = require('lodash/forIn');
const includes = require('lodash/includes');
const { checkCase, walk } = require('../../../utils');
const MessageCarrier = require('../../../utils/messageCarrier');
 
module.exports.validate = function({ jsSpec, isOAS3 }, config) {
  const messages = new MessageCarrier();
 
  config = config.schemas;
 
  const schemas = [];
 
  walk(jsSpec, [], function(obj, path) {
    const current = path[path.length - 1];
 
    /*
      Collect all schemas for later analysis.  The logic should capture the following:
      - Swagger2
        - Everything in the top-level "definitions" object
        - Properties within all models
        - The schema for all body parameters,
            both in operations and the top-level "parameters" object
        - The schema for all responses,
            both in operations and the top-level "responses" object
      - OpenAPI 3
        - Everything in the "schemas" section of the top-level "components" object
        - Properties within all models
        - The schema for all parameters (that have a schema),
            both in operations and the "parameters" section of the top-level "components" object
        - The schema for all media type objects (any object within a "content" property)
            This includes responses, request bodies, parameters (with content rather than schema),
            both at the operation level and within the top-level "components" object
    */
    const modelLocations = [
      'definitions',
      'schemas',
      'properties',
      'parameters'
    ];
    if (
      current === 'schema' ||
      current === 'items' ||
      modelLocations.includes(path[path.length - 2])
    ) {
      const pushLeafSchemas = (obj, path) => {
        if (obj.allOf && Array.isArray(obj.allOf)) {
          obj.allOf.forEach((e, i) =>
            pushLeafSchemas(e, [...path, 'allOf', i])
          );
        } else if (isOAS3 && obj.oneOf && Array.isArray(obj.oneOf)) {
          obj.oneOf.forEach((e, i) =>
            pushLeafSchemas(e, [...path, 'oneOf', i])
          );
        } else if (isOAS3 && obj.anyOf && Array.isArray(obj.anyOf)) {
          obj.anyOf.forEach((e, i) =>
            pushLeafSchemas(e, [...path, 'anyOf', i])
          );
        } else {
          schemas.push({ schema: obj, path });
        }
      };
      pushLeafSchemas(obj, path);
    }
  });
 
  // Collect the properties info. Pass it to checkProperties to catch
  // properties that have the same name but an inconsistent type.
  const propertiesToCompare = {};
 
  schemas.forEach(({ schema, path }) => {
    generateFormatErrors(schema, path, config, isOAS3, messages);
 
    generateDescriptionWarnings(schema, path, config, isOAS3, messages);
 
    const checkStatus = config.snake_case_only;
    if (checkStatus !== 'off') {
      checkPropNames(schema, path, config, messages);
 
      checkEnumValues(schema, path, config, messages);
    } else {
      // optional support for property_case_convention, property_case_collision, and enum_case_convention
      // in config.  In the else block because support should be mutually exclusive
      // with config.snake_case_only since it is overlapping functionality
      if (config.property_case_convention) {
        const checkCaseStatus = config.property_case_convention[0];
        Eif (checkCaseStatus !== 'off') {
          checkPropNamesCaseConvention(
            schema,
            path,
            config.property_case_convention,
            messages
          );
        }
      }
      if (config.property_case_collision) {
        const checkCaseStatus = config.property_case_collision;
        Eif (checkCaseStatus !== 'off') {
          checkPropNamesCaseCollision(
            schema,
            path,
            config.property_case_collision,
            messages
          );
        }
      }
      if (config.enum_case_convention) {
        const checkCaseStatus = config.enum_case_convention[0];
        Eif (checkCaseStatus !== 'off') {
          checkEnumCaseConvention(
            schema,
            path,
            config.enum_case_convention,
            messages
          );
        }
      }
    }
    Eif (config.inconsistent_property_type !== 'off') {
      checkProperties(
        schema,
        propertiesToCompare,
        path,
        config.inconsistent_property_type,
        messages
      );
    }
  });
 
  return messages;
};
 
// Flag as an error any property that does not have a recognized "type" and "format" according to the
// [Swagger 2.0 spec](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types)
function generateFormatErrors(schema, contextPath, config, isOAS3, messages) {
  if (schema.$ref) {
    return;
  }
 
  // Special case: check for arrays of arrays
  let checkStatus = config.array_of_arrays;
  if (checkStatus !== 'off' && schema.type === 'array' && schema.items) {
    if (schema.items.type === 'array') {
      messages.addMessage(
        contextPath.concat(['items', 'type']),
        'Array properties should avoid having items of type array.',
        checkStatus,
        'array_of_arrays'
      );
    }
  }
 
  checkStatus = config.invalid_type_format_pair;
  Eif (checkStatus !== 'off') {
    typeFormatErrors(schema, contextPath, isOAS3, messages, checkStatus);
  }
}
 
function typeFormatErrors(obj, path, isOAS3, messages, checkStatus) {
  // error if format defined but not type
  if (!obj.type && obj.format) {
    messages.addMessage(
      path.concat(['format']),
      'Format defined without a type.',
      checkStatus,
      'invalid_type_format_pair'
    );
  }
 
  // we will check ref in defintions section
  // only proceed if type defined
  if (obj.$ref || !obj.type) {
    return;
  }
 
  const validIntegerFormats = ['int32', 'int64'];
  const validNumberFormats = ['float', 'double'];
  const validStringFormats = [
    'byte',
    'binary',
    'date',
    'date-time',
    'password'
  ];
  const validTypes = [
    'integer',
    'number',
    'string',
    'boolean',
    'object',
    'array'
  ];
  if (!isOAS3) {
    validTypes.push('file');
  }
  switch (obj.type) {
    case 'integer':
      if (
        obj.format &&
        !includes(validIntegerFormats, obj.format.toLowerCase())
      ) {
        messages.addMessage(
          path.concat(['type']),
          `Schema of type integer should use one of the following formats: ${validIntegerFormats.join(
            ', '
          )}.`,
          checkStatus,
          'invalid_type_format_pair'
        );
      }
      break;
    case 'number':
      if (
        obj.format &&
        !includes(validNumberFormats, obj.format.toLowerCase())
      ) {
        messages.addMessage(
          path.concat(['type']),
          `Schema of type number should use one of the following formats: ${validNumberFormats.join(
            ', '
          )}.`,
          checkStatus,
          'invalid_type_format_pair'
        );
      }
      break;
    case 'string':
      if (
        obj.format &&
        !includes(validStringFormats, obj.format.toLowerCase())
      ) {
        messages.addMessage(
          path.concat(['type']),
          `Schema of type string should use one of the following formats: ${validStringFormats.join(
            ', '
          )}.`,
          checkStatus,
          'invalid_type_format_pair'
        );
      }
      break;
    case 'boolean':
      // No valid formats for boolean, format should be undefined
      if (obj.format !== undefined) {
        messages.addMessage(
          path.concat(['type']),
          `Schema of type boolean should not have a format.`,
          checkStatus,
          'invalid_type_format_pair'
        );
      }
      break;
    case 'object':
      // No valid format pairings for object, format should be undefined
      if (obj.format !== undefined) {
        messages.addMessage(
          path.concat(['type']),
          'Schema of type object should not have a format.',
          checkStatus,
          'invalid_type_format_pair'
        );
      }
      break;
    case 'array':
      // No valid format pairings for array, format should be undefined
      if (obj.format !== undefined) {
        messages.addMessage(
          path.concat(['type']),
          'Schema of type array should not have a format.',
          checkStatus,
          'invalid_type_format_pair'
        );
      }
      break;
    case 'file':
      // schemas of type file are allowed in swagger2 for responses and parameters
      // of type 'formData'
      // note: type file is only allowed for root schemas (not properties, etc.)
      if (isOAS3 || (!obj.in && !isRootSchema(path))) {
        messages.addMessage(
          path.concat(['type']),
          'File type only valid for swagger2 and must be used as root schema.',
          checkStatus,
          'invalid_type_format_pair'
        );
      } else if (obj.in && obj.in !== 'formData') {
        messages.addMessage(
          path.concat(['type']),
          'File type parameter must use in: formData.',
          checkStatus,
          'invalid_type_format_pair'
        );
      }
      // Format should not be defined for schema of type file.
      // Error reported in addition to potential error above.
      // Only check for swagger2 because type file should not be used in OAS3.
      if (!isOAS3 && obj.format !== undefined) {
        messages.addMessage(
          path.concat(['type']),
          'Schema of type file should not have a format.',
          checkStatus,
          'invalid_type_format_pair'
        );
      }
      break;
    default:
      // invalid type
      messages.addMessage(
        path.concat(['type']),
        `Invalid type. Valid types are: ${validTypes.join(', ')}.`,
        checkStatus,
        'invalid_type_format_pair'
      );
  }
}
 
// http://watson-developer-cloud.github.io/api-guidelines/swagger-coding-style#models
function generateDescriptionWarnings(
  schema,
  contextPath,
  config,
  isOAS3,
  messages
) {
  // determine if this is a top-level schema
  const isTopLevelSchema = isOAS3
    ? contextPath.length === 3 &&
      contextPath[0] === 'components' &&
      contextPath[1] === 'schemas'
    : contextPath.length === 2 && contextPath[0] === 'definitions';
 
  // Check description in schema only for "top level" schema
  const hasDescription =
    schema.description && schema.description.toString().trim().length;
  if (isTopLevelSchema && !hasDescription) {
    messages.addMessage(
      contextPath,
      'Schema must have a non-empty description.',
      config.no_schema_description,
      'no_schema_description'
    );
  }
 
  if (!schema.properties) {
    return;
  }
 
  // verify that every property of the model has a description
  forIn(schema.properties, (property, propName) => {
    // if property is defined by a ref, it does not need a description
    if (!property || property.$ref || propName.slice(0, 2) === 'x-') return;
 
    // if property has a allOf, anyOf, or oneOf schema, it does not needs a description
    if (property.allOf || property.anyOf || property.oneOf) return;
 
    const path = contextPath.concat(['properties', propName, 'description']);
 
    const hasDescription =
      property.description && property.description.toString().trim().length;
    if (!hasDescription) {
      messages.addMessage(
        path,
        'Schema properties must have a description with content in it.',
        config.no_property_description,
        'no_property_description'
      );
    } else {
      // if the property does have a description, "Avoid describing a model as a 'JSON object' since this will be incorrect for some SDKs."
      const mentionsJSON = includes(property.description.toLowerCase(), 'json');
      if (mentionsJSON) {
        messages.addMessage(
          path,
          'Not all languages use JSON, so descriptions should not state that the model is a JSON object.',
          config.description_mentions_json,
          'description_mentions_json'
        );
      }
    }
  });
}
 
// https://pages.github.ibm.com/CloudEngineering/api_handbook/design/terminology.html#formatting
function checkPropNames(schema, contextPath, config, messages) {
  if (!schema.properties) {
    return;
  }
 
  // flag any property whose name is not "lower snake case"
  forIn(schema.properties, (property, propName) => {
    Iif (propName.slice(0, 2) === 'x-') return;
 
    // Skip snake_case_only checks for deprecated properties
    Iif (property.deprecated === true) return;
 
    const checkStatus = config.snake_case_only || 'off';
    if (checkStatus.match('error|warning')) {
      if (!checkCase(propName, 'lower_snake_case')) {
        messages.addMessage(
          contextPath.concat(['properties', propName]),
          'Property names must be lower snake case.',
          checkStatus,
          'snake_case_only'
        );
      }
    }
  });
}
 
/**
 * Check that property names follow the specified case convention
 * @param schema
 * @param contextPath
 * @param checkStatus a string, 'off' | 'warning' | 'error'
 * @param messages
 */
function checkPropNamesCaseCollision(
  schema,
  contextPath,
  checkStatus,
  messages
) {
  if (!schema.properties) {
    return;
  }
 
  // flag any property whose name is identical to another property in a different case
  const prevProps = [];
  forIn(schema.properties, (property, propName) => {
    if (propName.slice(0, 2) === 'x-') return;
 
    // Skip case_convention checks for deprecated properties
    Iif (propName.deprecated === true) return;
 
    const caselessPropName = propName.replace(/[_-]/g, '').toLowerCase();
    if (prevProps.includes(caselessPropName)) {
      messages.addMessage(
        contextPath.concat(['properties', propName]),
        `Property name is identical to another property except for the naming convention: ${propName}`,
        checkStatus,
        'property_case_collision'
      );
    } else {
      prevProps.push(caselessPropName);
    }
  });
}
 
/**
 * Check that property names follow the specified case convention
 * @param schema
 * @param contextPath
 * @param caseConvention an array, [0]='off' | 'warning' | 'error'. [1]='lower_snake_case' etc.
 * @param messages
 */
function checkPropNamesCaseConvention(
  schema,
  contextPath,
  caseConvention,
  messages
) {
  if (!schema.properties || !caseConvention) {
    return;
  }
 
  // flag any property whose name does not follow the case convention
  forIn(schema.properties, (property, propName) => {
    if (propName.slice(0, 2) === 'x-') return;
 
    // Skip case_convention checks for deprecated properties
    if (property.deprecated === true) return;
 
    const checkStatus = caseConvention[0] || 'off';
    Eif (checkStatus.match('error|warning')) {
      const caseConventionValue = caseConvention[1];
 
      const isCorrectCase = checkCase(propName, caseConventionValue);
      if (!isCorrectCase) {
        messages.addMessage(
          contextPath.concat(['properties', propName]),
          `Property names must follow case convention: ${caseConventionValue}`,
          checkStatus,
          'property_case_convention'
        );
      }
    }
  });
}
 
function checkEnumValues(schema, contextPath, config, messages) {
  if (!schema.enum) {
    return;
  }
 
  for (let i = 0; i < schema.enum.length; i++) {
    const enumValue = schema.enum[i];
    if (typeof enumValue === 'string') {
      const checkStatus = config.snake_case_only || 'off';
      Eif (checkStatus.match('error|warning')) {
        if (!checkCase(enumValue, 'lower_snake_case')) {
          messages.addMessage(
            contextPath.concat(['enum', i.toString()]),
            'Enum values must be lower snake case.',
            checkStatus,
            'snake_case_only'
          );
        }
      }
    }
  }
}
 
/**
 * Check that enum values follow the specified case convention
 * @param schema
 * @param contextPath
 * @param caseConvention an array, [0]='off' | 'warning' | 'error'. [1]='lower_snake_case' etc.
 * @param messages
 */
function checkEnumCaseConvention(
  schema,
  contextPath,
  caseConvention,
  messages
) {
  if (!schema.enum || !caseConvention) {
    return;
  }
 
  for (let i = 0; i < schema.enum.length; i++) {
    const enumValue = schema.enum[i];
    if (typeof enumValue === 'string') {
      const checkStatus = caseConvention[0] || 'off';
      Eif (checkStatus.match('error|warning')) {
        const caseConventionValue = caseConvention[1];
        const isCorrectCase = checkCase(enumValue, caseConventionValue);
        if (!isCorrectCase) {
          messages.addMessage(
            contextPath.concat(['enum', i.toString()]),
            `Enum values must follow case convention: ${caseConventionValue}`,
            checkStatus,
            'enum_case_convention'
          );
        }
      }
    }
  }
}
 
// NOTE: this function is Swagger 2 specific and would need to be adapted to be used with OAS
function isRootSchema(path) {
  const current = path[path.length - 1];
  const parent = path[path.length - 2];
 
  // `schema` can only exist in parameter or response objects
  // root schemas can also appear under a variable key in the `definitions` section
  // if it is the top level `definitions` section (rather than some property named "definitions"),
  // the path length will be 2
  return (
    current === 'schema' || (parent === 'definitions' && path.length === 2)
  );
}
 
// Flag any properties that have the same name but an inconsistent type.
function checkProperties(
  schema,
  propertiesToCompare,
  contextPath,
  configOption,
  messages
) {
  if (!schema.properties) return;
 
  for (const [key, value] of Object.entries(schema.properties)) {
    // skips properties that use $ref
    if (value.type) {
      if (propertiesToCompare[key]) {
        if (propertiesToCompare[key].type !== value.type) {
          // First property that appeared in API def, should only print once.
          if (!propertiesToCompare[key].printed) {
            propertiesToCompare[key].printed = true;
            messages.addMessage(
              propertiesToCompare[key].path,
              `Property has inconsistent type: ${key}.`,
              configOption[0],
              'inconsistent_property_type'
            );
          }
          messages.addMessage(
            contextPath.concat(['properties', key]).join('.'),
            `Property has inconsistent type: ${key}.`,
            configOption[0],
            'inconsistent_property_type'
          );
        }
      } else {
        if (configOption && configOption[1] && !configOption[1].includes(key)) {
          // add property if the name is not excluded
          propertiesToCompare[key] = {
            type: value.type,
            path: contextPath.concat(['properties', key]).join('.'),
            printed: false
          };
        }
      }
    }
  }
}