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

Support OpenAPI writeOnly properties #76 #84

Merged
merged 3 commits into from
Oct 22, 2019
Merged
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
24 changes: 24 additions & 0 deletions src/middlewares/ajv/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,30 @@ function createAjv(
};
}

return () => true;
},
});
} else {
// response
ajv.removeKeyword('writeOnly');
ajv.addKeyword('writeOnly', {
modifying: true,
compile: sch => {
if (sch) {
return function validate(data, path, obj, propName) {
const isValid = !(sch === true && data != null);
(<any>validate).errors = [
{
keyword: 'writeOnly',
dataPath: path,
message: `is write-only`,
params: { writeOnly: propName },
},
];
return isValid;
};
}

return () => true;
},
});
Expand Down
124 changes: 124 additions & 0 deletions test/resources/write.only.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
openapi: '3.0.0'
info:
version: 1.0.0
title: Swagger Petstore
description: A sample API
termsOfService: http://swagger.io/terms/
license:
name: Apache 2.0
url: https://www.apache.org/licenses/LICENSE-2.0.html
servers:
- url: http://petstore.swagger.io/v1

paths:
/products/inlined:
post:
description: create products
operationId: createProductsInline
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
id:
type: string
readOnly: true
name:
type: string
price:
type: number
created_at:
type: string
format: date-time
readOnly: true
responses:
'200':
description: pet response
content:
application/json:
schema:
$ref: '#/components/schemas/Product'

/products/nested:
post:
description: create products
operationId: createProductsNested
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/ProductNested'
responses:
'200':
description: pet response
content:
application/json:
schema:
$ref: '#/components/schemas/ProductNested'

components:
schemas:
Product:
type: object
properties:
id:
type: string
readOnly: true
name:
type: string
price:
type: number
role:
type: string
enum:
- admin
- user
writeOnly: true
created_at:
type: string
format: date-time
readOnly: true

# TODO add nested test
ProductNested:
type: object
properties:
id:
type: string
readOnly: true
name:
type: string
price:
type: number
created_at:
type: string
format: date-time
readOnly: true
role:
type: string
enum:
- admin
- user
writeOnly: true
reviews:
type: array
items:
$ref: '#/components/schemas/Review'

Review:
type: object
properties:
id:
type: integer
readOnly: true
role_x:
type: string
enum:
- admin
- user
writeOnly: true
rating:
type: integer
138 changes: 138 additions & 0 deletions test/write.only.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import * as path from 'path';
import * as express from 'express';
import { expect } from 'chai';
import * as request from 'supertest';
import { createApp } from './common/app';

const packageJson = require('../package.json');

describe(packageJson.name, () => {
let app = null;

before(async () => {
// Set up the express app
const apiSpec = path.join('test', 'resources', 'write.only.yaml');
app = await createApp({ apiSpec, validateResponses: true }, 3005, app =>
app
.post(`${app.basePath}/products/inlined`, (req, res) => {
const body = req.body;
const excludeWriteOnly = req.query.exclude_write_only;
if (excludeWriteOnly) {
delete body.role;
}
res.json(body);
})
.post(`${app.basePath}/products/nested`, (req, res) => {
const body = req.body;
const excludeWriteOnly = req.query.exclude_write_only;
body.id = 'test';
body.created_at = new Date().toISOString();
body.reviews = body.reviews.map(r => ({
...(excludeWriteOnly ? {} : { role_x: 'admin' }),
rating: r.rating || 2,
}));

if (excludeWriteOnly) {
delete body.role;
}
res.json(body);
}),
);
});

after(() => {
app.server.close();
});

it('should not allow ready only inlined properties in requests', async () =>
request(app)
.post(`${app.basePath}/products/inlined`)
.set('content-type', 'application/json')
.send({
name: 'some name',
price: 10.99,
created_at: new Date().toUTCString(),
})
.expect(400)
.then(r => {
const body = r.body;
// id is a readonly property and should not be allowed in the request
expect(body.message).to.contain('created_at');
}));

it('should not allow write only inlined properties in responses', async () =>
request(app)
.post(`${app.basePath}/products/inlined`)
.set('content-type', 'application/json')
.send({
name: 'some name',
role: 'admin',
price: 10.99,
})
.expect(500)
.then(r => {
const body = r.body;
expect(body.message).to.contain('role');
expect(body.errors[0].path).to.contain('.response.role');
expect(body.errors[0].message).to.contain('write-only');
}));

it('should return 200 if no write-only properties are in the responses', async () =>
request(app)
.post(`${app.basePath}/products/inlined`)
.query({
exclude_write_only: true,
})
.set('content-type', 'application/json')
.send({
name: 'some name',
role: 'admin',
price: 10.99,
})
.expect(200));

it('should not allow write only properties in responses (nested schema $refs)', async () =>
request(app)
.post(`${app.basePath}/products/nested`)
.set('content-type', 'application/json')
.send({
name: 'some name',
price: 10.99,
reviews: [
{
rating: 5,
},
],
})
.expect(500)
.then(r => {
const body = r.body;
expect(body.message).to.contain('role_x');
expect(body.errors[0].path).to.contain('.response.reviews[0].role_x');
expect(body.errors[0].message).to.contain('write-only');
}));

it('should not allow read only properties in requests (deep nested schema $refs)', async () =>
request(app)
.post(`${app.basePath}/products/nested`)
.query({
exclude_write_only: true,
})
.set('content-type', 'application/json')
.send({
name: 'some name',
price: 10.99,
reviews: [
{
id: 99,
role_x: 'admin',
rating: 5,
},
],
})
.expect(400)
.then(r => {
const body = r.body;
expect(body.message).to.contain('request.body.reviews[0].id');
}));
});