Skip to content

Support additionnalProperties: false in OneOf #668

Closed

Description

@LelouBil

If I have an openApi schema that has additionalProperties: false, and I send a request with extra fields, it should be refused..

After more research, I found out this is the job of the request validator. But It doesn't change what happens about OneOf.

For methods like AsSomeType() generated in case of a OneOf

Is currently deserialized like this :

        var body MyElement
	err := json.Unmarshal(t.union, &body)
	return body, err

And it should be deserialized like this (if the target schema has additionalProperties set to false) :

        var body MyElement

	dec := json.NewDecoder(bytes.NewReader(t.union))
	dec.DisallowUnknownFields()
	err := dec.Decode(&body)
	
	return body, err

Activity

  1. changed the title [-]Support additionalProperties: false in the strict server generation + in OneOf[/-] [+]Improve OneOf Matching[/+] on Jul 7, 2022
  2. Warboss-rus commented on Jul 27, 2022

    @Warboss-rus
    Contributor

    This change will break anyOf, which is handled by the same code and extracts partial data from union.
    Also, ignoring unknown fileds is useful for backwards compatibility, as we can add new fields without using entirely new API version, so making it default to fail is not a good idea.
    And finally, it is a breaking change, since it will also disallow unknown fields in all underlying objects, not just the top level of union object.
    If you really need it, I think it should be an option that is off by default.

  3. LelouBil commented on Jul 27, 2022

    @LelouBil
    ContributorAuthor

    Well, I (sort of) solved my actual problem an other way.

    My actual problem was that I had a base schema, a second schema extending the first one using allOf, and a third schema that is a oneOf that could be either the base or the extended.

    I had put additionalProperties: false in both the base and the extended.

    My actual problem was that AsBase() never returned an error because the additionalProperties was not being used.

    I don't know if that's a propre use of additionalProperties, but in the end I solved my problem using the ValueByDiscriminator method, which I discovered later because it was not being generated with my spec at first.

  4. LelouBil commented on Jul 27, 2022

    @LelouBil
    ContributorAuthor

    Regarding this actual issue I think the deserialization should honor the additionalProperties value if the oneOf variant (I'm not sue how that should be done according to the OpenApi spec)

  5. LelouBil commented on Jul 27, 2022

    @LelouBil
    ContributorAuthor

    The current default configuration for the Java client of the Openapi Generator (which I am using on the other side of my application) is currently configured to honor additionalProperties during oneOf matching searching :

    https://github.com/OpenAPITools/openapi-generator/blob/b6ca40031a6225441a627cb5a311eff4c9d5eeef/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/pojo.mustache#L437-L457

    https://github.com/OpenAPITools/openapi-generator/blob/32d15100b0622c5e57ac131615e057a58aecef8e/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/oneof_model.mustache#L101-L112

    The oneOf class calls validateJsonObject successfully on the possible matches, and validateJsonObject is set up to fail if an extra property is present while additionalProperties is set to false

  6. LelouBil commented on Jul 27, 2022

    @LelouBil
    ContributorAuthor
  7. chanced commented on Jul 27, 2022

    @chanced

    Deserialization shouldn't. That's a validation rule which should be handled through evaluation with json schema.

  8. changed the title [-]Improve OneOf Matching[/-] [+]Support additionnalProperties: false in OneOf[/+] on Jul 27, 2022
  9. enricoribelli commented on Dec 1, 2023

    @enricoribelli

    Well, I (sort of) solved my actual problem an other way.

    My actual problem was that I had a base schema, a second schema extending the first one using allOf, and a third schema that is a oneOf that could be either the base or the extended.

    I had put additionalProperties: false in both the base and the extended.

    My actual problem was that AsBase() never returned an error because the additionalProperties was not being used.

    I don't know if that's a propre use of additionalProperties, but in the end I solved my problem using the ValueByDiscriminator method, which I discovered later because it was not being generated with my spec at first.

    I am having the same problem that the ValueByDiscriminator method (and others that should appear when using anyOf in the schema) is not being generated. How did you make it happen?

  10. pawankumargyg commented on Jun 26, 2024

    @pawankumargyg

    We encountered a similar issue with our spec validations in version 6.4.0. Our setup included a base schema with various schemas extending it, utilized as oneOf. Unfortunately, using additionalProperties or discriminator did not resolve the problem. To address this, we devised a workaround: we applied pattern matching to the property value used for discriminator mapping for each schema within oneOf. This approach allowed us to pass validation without altering our model generations.

    Here is an example spec works for us

    BaseSchema:
        type: object
        property:
            p1: string
            P2: string
    Schema1:
       allOf:
          - $ref: <BaseSchema>
        type: object
        property:
           p1: string
           patternOnP1: '^you have for this schema$'
    Schema2:
       allOf:
          - $ref: <BaseSchema>
        type: object
        property:
           p3: string
           patternOnP1: '^you have for this schema$'
    ActualObjectWithOneOf:
       oneOf:
          - $ref: Schema1
          -  $ref Schema2
         discriminator:
             propertyName: p1
            mapping:
              value1: Schema1
              value2: Schema2
    

    In our experience, additionalProperties doesn't work well with schema inheritance and composition. It operates on a per-schema basis and fails to comprehend the final merged schema.

  11. mromaszewicz commented on Sep 26, 2026

    @mromaszewicz
    Member

    This is now supported on main, with the new schema-merging-behavior: v3 (#2580). When a oneOf or anyOf variant has additionalProperties: false, its As* method checks the union's top-level keys before decoding, and returns an error for a key the variant doesn't allow:

    // Subject is oneOf [Base, Extended], and Base has additionalProperties: false.
    // For {"id": "2", "extra": "more"}:
    _, err := subject.AsBase()
    // err: Base doesn't allow the property "extra"

    A variant allows the keys it declares, and those the rest of the object declares: the union's own properties, its discriminator, and, in an allOf of several unions, the other unions' variants. Only the top level is checked, rather than using DisallowUnknownFields, so nested objects that allow extra properties still accept them. ValueByDiscriminator() goes through As*, so it returns the error too. To keep the old behavior, set output-options.lenient-union-accessors: true.

    To try it, set this in your configuration:

    compatibility:
      schema-merging-behavior: v3

    There's no release with v3 yet, so you'll need the latest main, for example go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen@main --config=config.yaml spec.yaml. docs/schema-merging.md describes how v3 differs from v2. v3 is an option for now, and we plan to make it the default once it has been tested for a while, so we're eager to hear your feedback: whether it works with your specs, and anything it generates that you didn't expect.


    This message was generated by AI.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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