Skip to content

[Feature]: strict validation of additionalProperties #1080

Description

@number492

Suggested Behavior

I would like to request a new configurable behaviour:
When additionalProperties is false or undefined on an object in the schema, I would like validation to fail (with a descriptive error message) if the object in the request/response contains any property not explicitly defined in the schema.

Example schema:

openapi: 3.1.0
info:
title: My API
version: 1.0.0
servers:
- url: https://api.example.com/v1
paths:
/posts:
post:
summary: Create a new post
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/Post'
/comments:
post:
summary: Create a new comment
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/Comment'
/tags:
post:
summary: Create a new tag
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/Tag'
components:
schemas:
Post:
type: object
required:
- title
- body
properties:
title:
type: string
body:
type: string
additionalProperties: true
Comment:
type: object
required:
- text
properties:
text:
type: string
additionalProperties: false
Tag:
type: object
required:
- name
properties:
name:
type: string

Example POST body to https://api.example.com/v1/tags:

{
"name": "Tag Name",
"sneaky_property": "this should not be allowed"
}

Example ValidationError:

"Validation of object {'name': 'Tag Name', 'sneaky_property': 'this should not be allowed'} failed: additional properties are not allowed ('sneaky_property' was unexpected)"

I have an implementation of this where I'm overrriding ObjectCaster._cast_proparties (sic!) and making a check there. This worked fine so far, but injecting this into oas30_casters_dict and friends, and then assembling the relevant classes to build a custom V30RequestValidator is not trivial. Also, 0.22.0 broke my implementation and so far I couldn't figure out where.

I could provide my implementation, which is not guaranteed to fit the current architecture, and tests currently only exist in proprietary code.

Why is this needed?

Loose third-party schemas could be made more strict, and by extension more secure, if this validation behaviour could be configured during run time.

References

No response

Would you like to implement a feature?

None

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions