Validate that oneOf and anyOf compositions define a discriminator

IN
6d ago
+269-6

What

Adds a new style rule for the concern raised in #806: a schema that composes alternative models with oneOf or anyOf should define a discriminator, so that API consumers can tell the possible object types apart (see the Swagger documentation on inheritance and polymorphism referenced in the issue).

Rule semantics

  • Every schema of components/schemas that declares a non-empty oneOf or anyOf and has no discriminator is reported:
    *ERROR* in Model 'MyComposition', field 'discriminator' -> A schema with a oneOf or anyOf composition should define a discriminator
  • The discriminator is considered defined when the composing schema carries a discriminator object, as documented by the Swagger reference (the discriminator lives on the schema that carries oneOf/anyOf).
  • allOf is out of scope: it describes a merged model rather than a set of alternatives, and the referenced documentation limits the use of the discriminator to oneOf and anyOf.
  • The check is limited to the named schemas of components/schemas, like the existing model rules; covering inline compositions (e.g. in responses) could be a follow-up.

Config

New option validateModelDiscriminator (boolean, default true), following the repo convention of enabling all rules by default:

  • documented in the README options table
  • wired through the gradle plugin task and the maven plugin mojo
  • usable in the CLI options file (parsed by name, like the other options)

Tests

  • testModelDiscriminatorValidation (parameterized): oneOf without a discriminator is reported when the rule is on and stays silent when the flag is off
  • testModelDiscriminatorValidationSuccessWhenDiscriminatorIsDefined: a oneOf schema with a discriminator produces no error
  • testModelDiscriminatorValidationReportsAnyOfComposition: anyOf compositions are covered too
  • testModelDiscriminatorValidationIgnoresAllOfComposition: allOf is not reported
  • ValidatorParametersTest covers the new default; ErrorAggregatorTest covers the new error; the CLI default.json fixture was updated accordingly

./gradlew spotlessApply test passes on all modules (lib, cli, gradle-plugin, maven-plugin).

Fixes #806


Summary by cubic

Adds a model validation rule that flags named schemas in components/schemas with a non-empty oneOf or anyOf composition that don't define a discriminator, so consumers can tell the possible object types apart.

New Features

  • New validateModelDiscriminator option (defaults to true) exposed through the CLI, Gradle, and Maven plugins.
  • Only named schemas in components/schemas are checked; inline and empty compositions are not reported.
  • allOf is ignored since it describes a merged model rather than a set of alternatives.