Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: validate API requests and responses according to the OpenApi spec #1579

Merged
merged 1 commit into from
Aug 26, 2024
Merged
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
feat: validate API requests and responses according to the OpenApi spec
Signed-off-by: Philippe Martin <[email protected]>
  • Loading branch information
feloy committed Aug 22, 2024
commit bbae16afc99d431905cca485b0d2a013c7454208
2 changes: 2 additions & 0 deletions packages/backend/package.json
Original file line number Diff line number Diff line change
@@ -71,6 +71,7 @@
"dependencies": {
"@huggingface/gguf": "^0.1.9",
"express": "^4.19.2",
"express-openapi-validator": "^5.3.1",
"isomorphic-git": "^1.27.1",
"mustache": "^4.2.0",
"openai": "^4.56.0",
@@ -82,6 +83,7 @@
},
"devDependencies": {
"@podman-desktop/api": "1.12.0",
"@rollup/plugin-replace": "^5.0.7",
"@types/express": "^4.17.21",
"@types/js-yaml": "^4.0.9",
"@types/mustache": "^4.2.5",
9 changes: 8 additions & 1 deletion packages/backend/src/managers/apiServer.spec.ts
Original file line number Diff line number Diff line change
@@ -114,9 +114,16 @@ test('/api/version endpoint when getting package.json file fails', async () => {
expect(res.body.errors[0]).toEqual('an error getting package file');
});

test('/api/version endpoint with unexpected param', async () => {
expect(server.getListener()).toBeDefined();
const res = await request(server.getListener()!).get('/api/version?wrongParam').expect(400);
expect(res.body.message).toEqual(`Unknown query parameter 'wrongParam'`);
});

test('/api/wrongEndpoint', async () => {
expect(server.getListener()).toBeDefined();
await request(server.getListener()!).get('/api/wrongEndpoint').expect(404);
const res = await request(server.getListener()!).get('/api/wrongEndpoint').expect(404);
expect(res.body.message).toEqual('not found');
});

test('/', async () => {
27 changes: 26 additions & 1 deletion packages/backend/src/managers/apiServer.ts
Original file line number Diff line number Diff line change
@@ -17,7 +17,7 @@
***********************************************************************/

import type { Disposable } from '@podman-desktop/api';
import type { Request, Response } from 'express';
import type { NextFunction, Request, Response } from 'express';
import express from 'express';
import type { Server } from 'http';
import path from 'node:path';
@@ -30,6 +30,8 @@ import type { components } from '../../src-generated/openapi';
import type { ModelInfo } from '@shared/src/models/IModelInfo';
import type { ConfigurationRegistry } from '../registries/ConfigurationRegistry';
import { getFreeRandomPort } from '../utils/ports';
import * as OpenApiValidator from 'express-openapi-validator';
import type { HttpError, OpenApiRequest } from 'express-openapi-validator/dist/framework/types';

const SHOW_API_INFO_COMMAND = 'ai-lab.show-api-info';
const SHOW_API_ERROR_COMMAND = 'ai-lab.show-api-error';
@@ -68,6 +70,29 @@ export class ApiServer implements Disposable {
const router = express.Router();
router.use(express.json());

// validate requests / responses based on openapi spec
router.use(
OpenApiValidator.middleware({
apiSpec: this.getSpecFile(),
validateRequests: true,
validateResponses: {
onError: (error, body, req) => {
console.error(`Response body fails validation: `, error);
console.error(`Emitted from:`, req.originalUrl);
console.error(body);
},
},
}),
);

router.use((err: HttpError, _req: OpenApiRequest, res: Response, _next: NextFunction) => {
// format errors from validator
res.status(err.status || 500).json({
message: err.message,
errors: err.errors,
});
});

// declare routes
router.get('/version', this.getVersion.bind(this));
router.get('/tags', this.getModels.bind(this));
13 changes: 13 additions & 0 deletions packages/backend/vite.config.js
Original file line number Diff line number Diff line change
@@ -18,6 +18,7 @@

import {join} from 'path';
import {builtinModules} from 'module';
import replace from '@rollup/plugin-replace';

const PACKAGE_ROOT = __dirname;

@@ -59,6 +60,18 @@ const config = {
emptyOutDir: true,
reportCompressedSize: false,
},
plugins: [
// This is to apply the patch https://github.com/JS-DevTools/ono/pull/20
// can be removed when the patch is merged
replace({
delimiters: ['', ''],
preventAssignment: true,
values: {
'if (typeof module === "object" && typeof module.exports === "object") {':
'if (typeof module === "object" && typeof module.exports === "object" && typeof module.exports.default === "object") {',
},
}),
],
};

export default config;
Loading