Skip to content

Commit

Permalink
fix: message-examples rule and check unused security schemes in 2.x.x (
Browse files Browse the repository at this point in the history
  • Loading branch information
magicmatatjahu authored Feb 3, 2023
1 parent eb36c8c commit 6b43317
Show file tree
Hide file tree
Showing 11 changed files with 14,919 additions and 138 deletions.
14,559 changes: 14,444 additions & 115 deletions package-lock.json

Large diffs are not rendered by default.

41 changes: 39 additions & 2 deletions src/ruleset/functions/documentStructure.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,48 @@ import { createRulesetFunction } from '@stoplight/spectral-core';
import { schema as schemaFn } from '@stoplight/spectral-functions';
import { aas2_0, aas2_1, aas2_2, aas2_3, aas2_4, aas2_5, aas2_6 } from '../formats';

// import type { ErrorObject } from 'ajv';
import type { ErrorObject } from 'ajv';
import type { IFunctionResult, Format } from '@stoplight/spectral-core';

type AsyncAPIVersions = keyof typeof specs;

function shouldIgnoreError(error: ErrorObject): boolean {
return (
// oneOf is a fairly error as we have 2 options to choose from for most of the time.
error.keyword === 'oneOf' ||
// the required $ref is entirely useless, since aas-schema rules operate on resolved content, so there won't be any $refs in the document
(error.keyword === 'required' && error.params.missingProperty === '$ref')
);
}

// ajv throws a lot of errors that have no understandable context, e.g. errors related to the fact that a value doesn't meet the conditions of some sub-schema in `oneOf`, `anyOf` etc.
// for this reason, we filter these unnecessary errors and leave only the most important ones (usually the first occurring in the list of errors).
function prepareResults(errors: ErrorObject[]): void {
// Update additionalProperties errors to make them more precise and prevent them from being treated as duplicates
for (let i = 0; i < errors.length; i++) {
const error = errors[i];

if (error.keyword === 'additionalProperties') {
error.instancePath = `${error.instancePath}/${String(error.params['additionalProperty'])}`;
} else if (error.keyword === 'required' && error.params.missingProperty === '$ref') {
errors.splice(i, 1);
i--;
}
}

for (let i = 0; i < errors.length; i++) {
const error = errors[i];

if (i + 1 < errors.length && errors[i + 1].instancePath === error.instancePath) {
errors.splice(i + 1, 1);
i--;
} else if (i > 0 && shouldIgnoreError(error) && errors[i - 1].instancePath.startsWith(error.instancePath)) {
errors.splice(i, 1);
i--;
}
}
}

function getCopyOfSchema(version: AsyncAPIVersions): Record<string, unknown> {
return JSON.parse(JSON.stringify(specs[version])) as Record<string, unknown>;
}
Expand Down Expand Up @@ -88,7 +125,7 @@ export const documentStructure = createRulesetFunction<unknown, { resolved: bool
return;
}

const errors = schemaFn(targetVal, { allErrors: true, schema }, context);
const errors = schemaFn(targetVal, { allErrors: true, schema, prepareResults: options.resolved ? prepareResults : undefined }, context);
if (!Array.isArray(errors)) {
return;
}
Expand Down
9 changes: 8 additions & 1 deletion src/ruleset/functions/unusedComponent.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { unreferencedReusableObject } from '@stoplight/spectral-functions';
import { createRulesetFunction } from '@stoplight/spectral-core';
import { aas2 } from '../formats';
import { isObject } from '../../utils';

import type { IFunctionResult } from '@stoplight/spectral-core';
Expand All @@ -22,6 +23,12 @@ export const unusedComponent = createRulesetFunction<{ components: Record<string

const results: IFunctionResult[] = [];
Object.keys(components).forEach(componentType => {
// if component type is `securitySchemes` and we operate on AsyncAPI 2.x.x skip validation
// security schemes in 2.x.x are referenced by keys, not by object ref - for this case we have a separate `asyncapi2-unused-securityScheme` rule
if (componentType === 'securitySchemes' && aas2(targetVal, null)) {
return;
}

const value = components[componentType];
if (!isObject(value)) {
return;
Expand All @@ -39,4 +46,4 @@ export const unusedComponent = createRulesetFunction<{ components: Record<string
});
return results;
},
);
);
1 change: 1 addition & 0 deletions src/ruleset/ruleset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ export const coreRuleset = {
},
},
},
// enable after fixing https://github.com/asyncapi/spec-json-schemas/issues/296
// 'asyncapi-document-unresolved': {
// description: 'Checking if the AsyncAPI document has valid unresolved structure.',
// message: '{{error}}',
Expand Down
29 changes: 25 additions & 4 deletions src/ruleset/v2/functions/messageExamples.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,23 @@ import type { IFunctionResult, RulesetFunctionContext } from '@stoplight/spectra
import type { JSONSchema7 } from 'json-schema';
import type { v2 } from 'spec-types';

function serializeSchema(schema: unknown, type: 'payload' | 'headers'): any {
if (!schema && typeof schema !== 'boolean') { // if schema is falsy then
if (type === 'headers') { // object for headers
schema = { type: 'object' };
} else { // anything for payload
schema = {};
}
} else if (typeof schema === 'boolean') { // spectral cannot handle boolean schemas
if (schema === true) {
schema = {}; // everything
} else {
schema = { not: {} }; // nothing
}
}
return schema;
}

function getMessageExamples(message: v2.MessageObject): Array<{ path: JsonPath; value: v2.MessageExampleObject }> {
if (!Array.isArray(message.examples)) {
return [];
Expand Down Expand Up @@ -59,18 +76,22 @@ export const messageExamples = createRulesetFunction<v2.MessageObject, null>(
if (!targetVal.examples) return;

const results: IFunctionResult[] = [];
const payloadSchema = serializeSchema(targetVal.payload, 'payload');
const headersSchema = serializeSchema(targetVal.headers, 'headers');
for (const example of getMessageExamples(targetVal)) {
const { path, value } = example;

// validate payload
if (example.value.payload !== undefined) {
const errors = validate(example.value.payload, example.path, 'payload', targetVal.payload, ctx);
if (value.payload !== undefined) {
const errors = validate(value.payload, path, 'payload', payloadSchema, ctx);
if (Array.isArray(errors)) {
results.push(...errors);
}
}

// validate headers
if (example.value.headers !== undefined) {
const errors = validate(example.value.headers, example.path, 'headers', targetVal.headers, ctx);
if (value.headers !== undefined) {
const errors = validate(value.headers, path, 'headers', headersSchema, ctx);
if (Array.isArray(errors)) {
results.push(...errors);
}
Expand Down
62 changes: 62 additions & 0 deletions src/ruleset/v2/functions/unusedSecuritySchemes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { createRulesetFunction } from '@stoplight/spectral-core';
import { getAllOperations } from '../utils';
import { isObject } from '../../../utils';

import type { IFunctionResult } from '@stoplight/spectral-core';
import type { v2 } from '../../../spec-types';

export const unusedSecuritySchemes = createRulesetFunction<v2.AsyncAPIObject, null>(
{
input: {
type: 'object',
properties: {
components: {
type: 'object',
},
},
required: ['components'],
},
options: null,
},
(targetVal) => {
const securitySchemes = targetVal.components?.securitySchemes;
if (!isObject(securitySchemes)) {
return;
}

const usedSecuritySchemes: string[] = [];
// collect all security requirements from servers
if (isObject(targetVal.servers)) {
Object.values(targetVal.servers).forEach(server => {
if (Array.isArray(server.security)) {
server.security.forEach(requirements => {
usedSecuritySchemes.push(...Object.keys(requirements));
});
}
});
}
// collect all security requirements from operations
const operations = getAllOperations(targetVal);
for (const { operation } of operations) {
if (Array.isArray(operation.security)) {
operation.security.forEach(requirements => {
usedSecuritySchemes.push(...Object.keys(requirements));
});
}
}

const usedSecuritySchemesSet = new Set(usedSecuritySchemes);
const securitySchemesKinds = Object.keys(securitySchemes);

const results: IFunctionResult[] = [];
securitySchemesKinds.forEach(securitySchemeKind => {
if (!usedSecuritySchemesSet.has(securitySchemeKind)) {
results.push({
message: 'Potentially unused security scheme has been detected in AsyncAPI document.',
path: ['components', 'securitySchemes', securitySchemeKind],
});
}
});
return results;
},
);
15 changes: 15 additions & 0 deletions src/ruleset/v2/ruleset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { operationIdUniqueness } from './functions/operationIdUniqueness';
import { schemaValidation } from './functions/schemaValidation';
import { security } from './functions/security';
import { serverVariables } from './functions/serverVariables';
import { unusedSecuritySchemes } from './functions/unusedSecuritySchemes';
import { uniquenessTags } from '../functions/uniquenessTags';
import { asyncApi2SchemaParserRule } from '../../schema-parser/spectral-rule-v2';

Expand Down Expand Up @@ -347,5 +348,19 @@ export const v2RecommendedRuleset = {
},
},
},

/**
* Component Object rules
*/
'asyncapi2-unused-securityScheme': {
description: 'Potentially unused security scheme has been detected in AsyncAPI document.',
recommended: true,
resolved: false,
severity: 'info',
given: '$',
then: {
function: unusedSecuritySchemes,
},
},
},
};
33 changes: 33 additions & 0 deletions test/ruleset/rules/asyncapi-unused-component.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,4 +160,37 @@ testRule('asyncapi-unused-component', [
},
],
},

{
name: 'possible component is unused - skip security schemes',
document: {
asyncapi: '2.0.0',
channels: {
someChannel: {
publish: {
message: {
$ref: '#/components/messages/someMessage'
}
}
}
},
components: {
messages: {
someMessage: {
payload: {
$ref: '#/components/schemas/someSchema',
}
},
},
schemas: {
someSchema: {},
},
securitySchemes: {
unusedScheme1: {},
unusedScheme2: {},
}
}
},
errors: [],
},
]);
Loading

0 comments on commit 6b43317

Please sign in to comment.