Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
5 changes: 5 additions & 0 deletions .changeset/fix-github-url-parsing.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@asyncapi/cli": patch
---

Fix GitHub URL parsing for branch names containing slashes and file extension detection for multi-dot filenames
5 changes: 5 additions & 0 deletions .changeset/fix-request-body-validation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@asyncapi/cli": patch
---

Fix request body validation to support all content types and not skip validation when condition callback is used
40 changes: 26 additions & 14 deletions src/apps/api/middlewares/validation.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
/**
* Create AJV's validator function for given path in the OpenAPI document.
*/
async function compileAjv(options: ValidationMiddlewareOptions) {

Check failure on line 35 in src/apps/api/middlewares/validation.middleware.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this function to reduce its Cognitive Complexity from 16 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=asyncapi_cli&issues=AZ5JoffWR2__0CCSgsjI&open=AZ5JoffWR2__0CCSgsjI&pullRequest=2207
const appOpenAPI = await getAppOpenAPI();
const paths = appOpenAPI.paths || {};

Expand All @@ -57,7 +57,20 @@
return;
}

let schema = requestBody.content['application/json'].schema;
const content = requestBody.content;
if (!content) {
return;
}

// Try to find schema across all content types, not just application/json
let schema: any;
const contentTypes = Object.keys(content);
for (const contentType of contentTypes) {
if (content[contentType]?.schema) {
schema = content[contentType].schema;
break;
}
}
if (!schema) {
return;
}
Expand Down Expand Up @@ -167,22 +180,21 @@
res: Response,
next: NextFunction,
): Promise<void> => {
// Check if the condition is met
if (options.condition && !options.condition(req)) {
return next();
}
// Check if the condition is met for body validation
const skipBodyValidation = options.condition && !options.condition(req);

try {
if (!validate) {
throw new ProblemException({
type: 'invalid-request-body',
title: 'Invalid Request Body',
status: 422,
detail: `Request body validation is not supported for "${options.path}" path with "${options.method}" method.`,
});
if (!skipBodyValidation) {
if (!validate) {
throw new ProblemException({
type: 'invalid-request-body',
title: 'Invalid Request Body',
status: 422,
detail: `Request body validation is not supported for "${options.path}" path with "${options.method}" method.`,
});
}
await validateRequestBody(validate, req.body);
}

await validateRequestBody(validate, req.body);
} catch (error: unknown) {
if (error instanceof ProblemException) {
return next(error);
Expand Down
2 changes: 1 addition & 1 deletion src/apps/cli/commands/new/file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ export default class NewFile extends Command {
if (!fileName.includes('.')) {
fileNameToWriteToDisk = `${fileName}.yaml`;
} else {
const extension = fileName.split('.')[1];
const extension = fileName.split('.').pop() ?? '';

if (extension === 'yml' || extension === 'yaml' || extension === 'json') {
fileNameToWriteToDisk = fileName;
Expand Down
2 changes: 1 addition & 1 deletion src/domains/models/SpecificationFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ export async function fileExists(name: string): Promise<boolean> {
return true;
}

const extension = name.split('.')[1];
const extension = name.split('.').pop() ?? '';

const allowedExtenstion = ['yml', 'yaml', 'json'];

Expand Down
22 changes: 20 additions & 2 deletions src/domains/services/validation.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,12 +69,30 @@ const convertGitHubWebUrl = (url: string): string => {
const urlWithoutFragment = url.split('#')[0];

// Handle GitHub web URLs like: https://github.com/owner/repo/blob/branch/path
// Branch names can contain slashes (e.g. feature/new-validation)
// eslint-disable-next-line no-useless-escape
const githubWebPattern = /^https:\/\/github\.com\/([^\/]+)\/([^\/]+)\/blob\/([^\/]+)\/(.+)$/;
const githubWebPattern = /^https:\/\/github\.com\/([^\/]+)\/([^\/]+)\/blob\/(.+)$/;
const match = urlWithoutFragment.match(githubWebPattern);

if (match) {
const [, owner, repo, branch, filePath] = match;
const [, owner, repo, branchAndPath] = match;
// Split on the first '/' after the branch name segment to separate branch from file path.
// Since branch names can contain '/', we need to find where the branch ends and the file path begins.
// We try progressively longer prefixes until the GitHub API confirms a valid path.
// Simple heuristic: try each possible split point from left to right.
const segments = branchAndPath.split('/');
// Try each possible split: branch = segments[0..i], filePath = segments[i+1..]
for (let i = 0; i < segments.length - 1; i++) {
const branch = segments.slice(0, i + 1).join('/');
const filePath = segments.slice(i + 1).join('/');
// If the filePath contains a dot (likely a file), use this split
if (filePath.includes('.')) {
return `https://api.github.com/repos/${owner}/${repo}/contents/${filePath}?ref=${branch}`;
}
}
// Fallback: treat everything after the first segment as filePath
const branch = segments[0];
const filePath = segments.slice(1).join('/');
return `https://api.github.com/repos/${owner}/${repo}/contents/${filePath}?ref=${branch}`;
}

Expand Down
33 changes: 31 additions & 2 deletions test/unit/services/validation.service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,14 +244,43 @@ describe('ValidationService', () => {
};

const result = await validationService.validateDocument(specFile, options);
// The validation succeeds means the validation command is successfully executed it is independent whether
// the document is valid or not
// The validation succeeds means the validation command is successfully executed it is independent whether
// the document is valid or not
expect(result.success).to.equal(true);
if (result.success) {
expect(result.data).to.have.property('status');
expect(result.data).to.have.property('diagnostics');
expect(result.data?.diagnostics).to.be.an('array');
}
});

it('should correctly parse GitHub URLs with slash-based branch names', async () => {
const specWithSlashBranch = `{
"asyncapi": "2.6.0",
"info": { "title": "Test", "version": "1.0.0" },
"channels": {
"user/event": {
"publish": {
"message": {
"payload": {
"$ref": "https://github.com/private-org/private-repo/blob/feature/new-validation/schema.yaml#/payload"
}
}
}
}
}
}`;
const specFile = new Specification(specWithSlashBranch);
const options = { 'diagnostics-format': 'stylish' as const };

const result = await validationService.validateDocument(specFile, options);
expect(result.success).to.equal(true);
if (result.success) {
const invalidRefDiagnostic = result.data?.diagnostics?.find((d: any) => d.code === 'invalid-ref');
// eslint-disable-next-line no-unused-expressions
expect(invalidRefDiagnostic).to.exist;
expect(invalidRefDiagnostic?.message).to.include('feature/new-validation');
}
});
});
});
Loading