Skip to content

Don't validate readOnly properties when writing, and writeOnly when reading #104

@bertramakers

Description

@bertramakers

Given a schema like:

{
  "type": "object",
  "properties": {
    "readAndWrite": {"type": "string"},
    "readOnly": {"type": "string", "readOnly": true},
    "writeOnly": {"type": "string", "writeOnly": true}
  },
  "required": ["readAndWrite", "readOnly", "writeOnly"]
}

And data like this (for example on an incoming HTTP request, so when "writing"):

{
  "readAndWrite": "...",
  "writeOnly": "..."
}

Opis\JsonSchema\Validator::validate() will return a validation result with an error like:

The required properties (readOnly) are missing

Is it possible to set some kind of "read" or "write" context on the validator, to ignore either writeOnly or readOnly properties in some situations?

We have two reasons to mark some read-only properties as required in our schemas:

  • We do not only use JSON schema to validate incoming data, but we also want to validate the JSON that we return in response bodies, so we can pro-actively find implementation bugs. And some read-only properties must always be included in the response/read context.
  • So integrators can see what properties will always be included in a read context.

Additionally even if we don't make any read-only property required, we also just don't want to validate their type and value if they happen to be included in a write context. Because an API client might fetch a resource, alter some (write-able) properties, and send the data back including the read-only properties which might be stale by the time that they send their data. Or they might always include a read-only property in their request by accident. Either way we ignore those properties in write contexts, so we also want to ignore them in the validation. Which seems to be a valid implementation according to:

If "readOnly" has a value of boolean true, it indicates that the value of the instance is managed exclusively by the owning authority, and attempts by an application to modify the value of this property are expected to be ignored or rejected by that owning authority.

https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.9.4

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions