Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
45 changes: 38 additions & 7 deletions src/util/apiUtil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,45 @@ import yaml from "js-yaml"

export const validateYamlInput = (input: string): input is string => {
try {
//Parse the yaml to verify
yaml.load(input);
} catch (e) {
const parsed = yaml.load(input); // Parsar YAML till ett JSON-objekt

if (typeof parsed !== 'object' || parsed === null) {
throw new RapLPBaseApiError(
"Could not validate Yaml",
"Parsed YAML is not a valid object",
ERROR_TYPE.BAD_REQUEST);
}

// Kontrollera att alla nödvändiga toppnivånycklar finns
const requiredKeys = ['openapi', 'info', 'paths'];
const missingKeys = requiredKeys.filter(key => !(key in parsed));

if (missingKeys.length > 0) {
throw new RapLPBaseApiError(
"Missing required top-level keys",
`Missing required top-level keys: ${missingKeys.join(', ')}`,
ERROR_TYPE.BAD_REQUEST);
}
} catch (error) {
// Handle YAML parsing error
throw new RapLPBaseApiError("Could not validate Yaml", "Invalid YAML", ERROR_TYPE.BAD_REQUEST);
if (error instanceof yaml.YAMLException) {
throw new RapLPBaseApiError(
"Could not validate Yaml",
`YAML Syntax Error: ${error.message}`,
ERROR_TYPE.BAD_REQUEST);
} else if (error instanceof RapLPBaseApiError) {
throw error
} else {
throw new RapLPBaseApiError(
"Failed to validate yaml",
`Could not vaildate yaml: ${error}`,
ERROR_TYPE.INTERNAL_SERVER_ERROR
)
}

}

return true
return true;
}

export function decodeBase64String(base64YamlFile: string) {
Expand All @@ -40,6 +71,6 @@ export async function processApiSpec(enabledRulesAndCategorys: { rules: Record<s
* @returns Boolean
*/
export function hasOwnProperty<X extends {}, Y extends PropertyKey>
(obj: X, prop: Y): obj is X & Record<Y, unknown> {
return obj.hasOwnProperty(prop)
(obj: X, prop: Y): obj is X & Record<Y, unknown> {
return obj.hasOwnProperty(prop)
}
18 changes: 14 additions & 4 deletions tests/integration/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,12 @@ describe("API Test", () => {
var app: any

beforeAll(async () => {
app = await startServer();
const mockArgs = {
enableUrlValidation: false,
urlValidationConfigFile: 'custom-config.json',
};

app = await startServer(mockArgs);
api = new ValidateApi(new Configuration({ basePath: "http://localhost:3000/api/v1" }))
})

Expand All @@ -40,22 +45,27 @@ describe("API Test", () => {

it("Assert that the error handler is intercepting faults", async () => {
const data = readFileSync(path.resolve(__dirname, "../../apis/dok-api.yaml"))
Copy link
Collaborator

@brorlarsnicklas brorlarsnicklas Dec 6, 2024

Choose a reason for hiding this comment

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

data används aldrig?

const missingTopLevelKeysYaml = `
name: Jane Smith
age: 25
occupation: Designer
`;

const response = await request(app)
.post("/api/v1/validation/validate")
.set('Content-Type', 'application/json')
.send({
yaml: data.toString("base64") + "123qwdsdfgaerg39e4rg",
yaml: Buffer.from(missingTopLevelKeysYaml).toString('base64'),
categories: []
})


expect(response.status).toBe(400)
expect(response.body).toMatchObject({
type: "about:blank",
title: "Could not validate Yaml",
title: "Missing required top-level keys",
status: 400,
detail: "Invalid YAML",
detail: "Missing required top-level keys: openapi, info, paths",
instance: "/api/v1/validation/validate"
})

Expand Down
82 changes: 82 additions & 0 deletions tests/unit/api/apiUtil.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@

import { validateYamlInput } from "../../../src/util/apiUtil.ts"
import { RapLPBaseApiError } from "../../../src/util/RapLPBaseApiErrorHandling.ts";

describe('validateYamlInput', () => {
test('should return true for valid YAML string with all top-level keys', () => {
const validYaml = `
openapi: 3.0.3
info: some info
paths:
`;

const result = validateYamlInput(validYaml);
expect(result).toBe(true);
});

test('should throw error for missing top-level keys', () => {
const missingTopLevelKeysYaml = `
name: Jane Smith
age: 25
occupation: Designer
`;

try {
validateYamlInput(missingTopLevelKeysYaml);
} catch (error) {
if (error instanceof RapLPBaseApiError) {
expect(error.title).toBe("Missing required top-level keys");
expect(error.message).toContain("Missing required top-level keys: openapi, info, paths");
}
}
});


test('should throw error for invalid YAML string', () => {
// Invalid YAML: Missing colon after 'age'
const invalidYaml = `
name: Jane Smith
age 25
occupation: Designer
`;

try {
validateYamlInput(invalidYaml);
} catch (error) {
if (error instanceof RapLPBaseApiError) {
expect(error.title).toBe("Could not validate Yaml");
expect(error.message).toContain("YAML Syntax Error:");
}
}

});

test('should throw error for malformed YAML', () => {
// Completely malformed YAML
const malformedYaml = `Just
some
random: text: that is not YAML.`;

try {
validateYamlInput(malformedYaml);
} catch (error) {
if (error instanceof RapLPBaseApiError) {
expect(error.title).toBe("Could not validate Yaml");
expect(error.message).toContain("YAML Syntax Error:");
}
}
});

test('should throw error for empty string', () => {
const emptyYaml = "";

try {
validateYamlInput(emptyYaml);
} catch (error) {
if (error instanceof RapLPBaseApiError) {
expect(error.title).toBe("Could not validate Yaml");
expect(error.message).toContain("Parsed YAML is not a valid object");
}
}
});
});