Define Kubernetes Custom Resource requiring one of the following fields or no fields

2/24/2021

I try to define a new Custom Resource, requiring it to have one of (1) field A, (2) field B, or (3) empty body.

For example: {A: 1}, {B: 1}, {} are OK, but {A:1, B:2} is not.

Here is the definition of my Custom Resource in form of OpenApi schema:

foo:
  type: object
  properties:
    a:
     type: int
    b:
     type: int
  oneOf:
    - required: ["a"]
    - required: ["b"]
    # no sure how to include the empty body

How should I include the empty body in the oneOf constraint?

-- Augustin Pan
kubernetes
kubernetes-custom-resources
openapi

1 Answer

2/24/2021

OpenAPI 3.1

You can use 'null' (with quotes).

oneOf:
  - type: 'null'

Or an object with a property of type null.

oneOf:
  - NullObjectExample:
    type: object
    properties:
      prop1:
        type: 'null'

OpenAPI 3.0

There is no null type, but you can use a nullable string. You may want to add a description stating this is expected to be null at all times.

oneOf:
  - type: string
    nullable: true

Or again, an object with a nullable string property.

oneOf:
  - NullObjectExample:
    type: object
    properties:
      prop1:
        type: string
        nullable: true

Why No Empty Object

In addition to not making intent clear, this presents a possible security vulnerability. See this page for an explanation. In short:

If you do not clearly define the schema and you leave properties of a JSON payload empty, you effectively allow attackers to pass in any data. This means that you are opening your backend to various attacks, such as SQL injection.

-- Software2
Source: StackOverflow