Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
136 changes: 136 additions & 0 deletions tools/spectral/ipa/__tests__/collectionIdentifierCamelCase.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import testRule from './__helpers__/testRule';
import { DiagnosticSeverity } from '@stoplight/types';

testRule('xgen-IPA-102-collection-identifier-camelCase', [
{
name: 'valid camelCase identifiers',
document: {
paths: {
'/api/v2/atlas/test': {},
'/users': {},
'/resourceGroups': {},
'/userProfiles': {},
'/api/v1/test': {},
},
},
errors: [],
},
{
name: 'valid camelCase with path parameters',
document: {
paths: {
'/resourceGroups/{groupId}': {},
'/users/{userId}/userProfiles': {},
},
},
errors: [],
},
{
name: 'valid paths with custom methods (only checking identifier part)',
document: {
paths: {
'/resources:any_Custom_Method': {},
'/users/{userId}/data/:AnyOtherMethod': {},
},
},
errors: [],
},
{
name: 'invalid PascalCase instead of camelCase',
document: {
paths: {
'/Resources': {},
},
},
errors: [
{
code: 'xgen-IPA-102-collection-identifier-camelCase',
message:
"Collection identifiers must be in camelCase. Path segment 'Resources' in path '/Resources' is not in camelCase. http://go/ipa/102",
path: ['paths', '/Resources'],
severity: DiagnosticSeverity.Warning,
},
],
},
{
name: 'invalid with snake_case instead of camelCase',
document: {
paths: {
'/resource_groups': {},
},
},
errors: [
{
code: 'xgen-IPA-102-collection-identifier-camelCase',
message:
"Collection identifiers must be in camelCase. Path segment 'resource_groups' in path '/resource_groups' is not in camelCase. http://go/ipa/102",
path: ['paths', '/resource_groups'],
severity: DiagnosticSeverity.Warning,
},
Comment on lines +57 to +68
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Q: If the path is for example /resource_groups/{id}/resource_keys, will there be two errors, one for resource_groups and one for resource_keys?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Single violation with 2 errors.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cool, could you add a test case for it?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Extended multiple test cases.

],
},
{
name: 'invalid with kebab-case instead of camelCase',
document: {
paths: {
'/resource-groups': {},
},
},
errors: [
{
code: 'xgen-IPA-102-collection-identifier-camelCase',
message:
"Collection identifiers must be in camelCase. Path segment 'resource-groups' in path '/resource-groups' is not in camelCase. http://go/ipa/102",
path: ['paths', '/resource-groups'],
severity: DiagnosticSeverity.Warning,
},
],
},
{
name: 'invalid resource path with invalid casing but valid custom method',
document: {
paths: {
'/Resources:createResource': {},
},
},
errors: [
{
code: 'xgen-IPA-102-collection-identifier-camelCase',
message:
"Collection identifiers must be in camelCase. Path segment 'Resources' in path '/Resources:createResource' is not in camelCase. http://go/ipa/102",
path: ['paths', '/Resources:createResource'],
severity: DiagnosticSeverity.Warning,
},
],
},
{
name: 'invalid with consecutive uppercase letters',
document: {
paths: {
'/resourcesAPI': {},
},
},
errors: [
{
code: 'xgen-IPA-102-collection-identifier-camelCase',
message:
"Collection identifiers must be in camelCase. Path segment 'resourcesAPI' in path '/resourcesAPI' is not in camelCase. http://go/ipa/102",
path: ['paths', '/resourcesAPI'],
severity: DiagnosticSeverity.Warning,
},
],
},
{
name: 'valid with path-level exception',
document: {
paths: {
'/resource_groups': {
'x-xgen-IPA-exception': {
'xgen-IPA-102-collection-identifier-camelCase': 'Legacy API path that cannot be changed',
},
},
},
},
errors: [],
},
]);
21 changes: 21 additions & 0 deletions tools/spectral/ipa/rulesets/IPA-102.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,26 @@
# http://go/ipa/102

rules:
xgen-IPA-102-collection-identifier-camelCase:
description: >-
Collection identifiers must be in camelCase. Logic includes:<br/>
- All path segments that are not path parameters<br/>
- Only the resource identifier part before any colon in custom method paths (e.g., 'resource' in '/resource:customMethod')<br/>
- Path parameters should also follow camelCase naming<br/>
- Certain values can be exempted via the ignoredValues configuration (e.g., 'v1', 'v2') that can be supplied as `ignoredValues`
argument to the rule<br/>
- Paths with x-xgen-IPA-exception for this rule are excluded from validation<br/>
http://go/ipa/102
message: '{{error}} http://go/ipa/102'
severity: warn
given: $.paths
then:
field: '@key'
function: collectionIdentifierCamelCase
functionOptions:
# Contains list of ignored path params
ignoredValues: ['v2', 'v1']

xgen-IPA-102-path-alternate-resource-name-path-param:
description: 'Paths should alternate between resource names and path params. http://go/ipa/102'
message: '{{error}} http://go/ipa/102'
Expand All @@ -23,3 +43,4 @@ rules:
functions:
- collectionIdentifierPattern
- eachPathAlternatesBetweenResourceNameAndPathParam
- collectionIdentifierCamelCase
9 changes: 5 additions & 4 deletions tools/spectral/ipa/rulesets/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,11 @@ For rule definitions, see [IPA-005.yaml](https://github.com/mongodb/openapi/blob

For rule definitions, see [IPA-102.yaml](https://github.com/mongodb/openapi/blob/main/tools/spectral/ipa/rulesets/IPA-102.yaml).

| Rule Name | Description | Severity |
| ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | -------- |
| xgen-IPA-102-path-alternate-resource-name-path-param | Paths should alternate between resource names and path params. http://go/ipa/102 | error |
| xgen-IPA-102-collection-identifier-pattern | Collection identifiers must begin with a lowercase letter and contain only ASCII letters and numbers. http://go/ipa/102 | warn |
| Rule Name | Description | Severity |
| ---------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- |
| xgen-IPA-102-path-alternate-resource-name-path-param | Paths should alternate between resource names and path params. http://go/ipa/102 | error |
| xgen-IPA-102-collection-identifier-camelCase | Collection identifiers must be in camelCase. Logic includes:<br/> - All path segments that are not path parameters<br/> - Only the resource identifier part before any colon in custom method paths (e.g., 'resource' in '/resource:customMethod')<br/> - Path parameters should also follow camelCase naming<br/> - Certain values can be exempted via the ignoredValues configuration (e.g., 'v1', 'v2') that can be supplied as `ignoredValues` argument to the rule<br/> - Paths with x-xgen-IPA-exception for this rule are excluded from validation<br/> http://go/ipa/102 | warn |
| xgen-IPA-102-collection-identifier-pattern | Collection identifiers must begin with a lowercase letter and contain only ASCII letters and numbers. http://go/ipa/102 | warn |

### IPA-104

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import {
collectAdoption,
collectAndReturnViolation,
collectException,
handleInternalError,
} from './utils/collectionUtils.js';
import { hasException } from './utils/exceptions.js';
import { isPathParam } from './utils/componentUtils.js';
import { casing } from '@stoplight/spectral-functions';

const RULE_NAME = 'xgen-IPA-102-collection-identifier-camelCase';
const ERROR_MESSAGE = 'Collection identifiers must be in camelCase.';

/**
* Checks if collection identifiers in paths follow camelCase convention
*
* @param {object} input - The path key from the OpenAPI spec
* @param {object} options - Rule configuration options
* @param {object} context - The context object containing the path and documentInventory
*/
export default (input, options, { path, documentInventory }) => {
const oas = documentInventory.resolved;
const pathKey = input;

// Check for exception at the path level
if (hasException(oas.paths[input], RULE_NAME)) {
collectException(oas.paths[input], RULE_NAME, path);
return;
}

// Extract ignored values from options
const ignoredValues = options?.ignoredValues || [];

const violations = checkViolations(pathKey, path, ignoredValues);
if (violations.length > 0) {
return collectAndReturnViolation(path, RULE_NAME, violations);
}

return collectAdoption(path, RULE_NAME);
};

function checkViolations(pathKey, path, ignoredValues = []) {
const violations = [];
try {
const pathSegments = pathKey.split('/');

pathSegments.forEach((segment) => {
// Skip path parameter validation if it matches the expected format
if (isPathParam(segment)) {
// Extract parameter name without brackets
const paramName = segment.slice(1, segment.indexOf('}'));
// Check if it's a valid camelCase parameter name
if (casing(paramName, { type: 'camel', disallowDigits: true })) {
violations.push({
message: `${ERROR_MESSAGE} Path parameter '${paramName}' in path '${pathKey}' is not in camelCase.`,
path: [...path, pathKey],
});
}
return;
}

// Skip validation for ignored values
if (ignoredValues.includes(segment)) {
return;
}

// For regular path segments, check if they contain custom method indicators
// If they do, only validate the identifier part (before the colon)
const colonIndex = segment.indexOf(':');
let identifier = segment;

if (colonIndex !== -1) {
// Only check the identifier part before the colon
identifier = segment.substring(0, colonIndex);
}

// Skip empty identifiers
if (identifier.length === 0) {
return;
}

// Skip validation for ignored values at the identifier level too
if (ignoredValues.includes(identifier)) {
return;
}

// Check if it's in camelCase using the casing function
if (casing(identifier, { type: 'camel', disallowDigits: true })) {
violations.push({
message: `${ERROR_MESSAGE} Path segment '${identifier}' in path '${pathKey}' is not in camelCase.`,
path: [...path, pathKey],
});
}
});
} catch (e) {
handleInternalError(RULE_NAME, [...path, pathKey], e);
}

return violations;
}
11 changes: 11 additions & 0 deletions tools/spectral/ipa/rulesets/functions/utils/schemaUtils.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,19 @@
/**
* Checks if the object has results property
* @param {*} schema
* @returns true if schema object returns results property (pagination), false otherwise
*/
export function schemaIsPaginated(schema) {
const fields = Object.keys(schema);
return fields.includes('properties') && Object.keys(schema['properties']).includes('results');
}

/**
* Checks if schema is an array type of schema
*
* @param {*} schema
* @returns
*/
export function schemaIsArray(schema) {
const fields = Object.keys(schema);
return fields.includes('type') && schema['type'] === 'array';
Expand Down
Loading