[BUG][Java][okhttp-gson] useOneOfDiscriminatorLookup is ignored in validateJsonElement causing multi-match failure when disallowAdditionalPropertiesIfNotPresent=false

未关闭
#25,735 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

难度
2/5
预计耗时
1-3 小时
新手友好度
48/100
Issue 类型
缺陷
描述清晰度
描述清楚
活跃度
活跃
技术栈
java
领域
backend

调研方向

Read modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/oneof_model.mustache, especially validateJsonElement(), and compare its discriminator handling with modules/openapi-generator/src/main/resources/Java/libraries/okhttp/oneof_model.mustache. Check the existing Java generator tests for okhttp-gson oneOf validation, then confirm the supplied Cat payload validates through the discriminator mapping when both options are enabled.

由索引模型根据 Issue 内容生成。

描述

Issue: Bug
Bug Report Checklist
  • Have you provided a full/minimal spec to reproduce the issue?
  • Have you validated the input using an OpenAPI validator?
  • Have you tested with the latest master to confirm the issue still exists?
  • Have you searched for related issues/PRs?
  • What's the actual output vs expected output?
  • [Optional] Sponsorship to speed up the bug fix or feature request (example)
Description

When generating a Java client using the default okhttp-gson library with:

  • useOneOfDiscriminatorLookup=true
  • disallowAdditionalPropertiesIfNotPresent=false

Validating a oneOf model payload using validateJsonElement fails with:
IOException: The JSON string is invalid for Pet with oneOf schemas: Cat, Dog. 2 class(es) match the result, expected 1.

Root Cause

In Java/libraries/okhttp-gson/oneof_model.mustache, discriminator lookup logic exists in the Gson TypeAdapter.read() method, allowing deserialization to fast-path directly to the mapped model.
https://github.com/OpenAPITools/openapi-generator/blob/cff025891c06ff5d9680027b7df8fe1e420a2e1d/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/oneof_model.mustache#L137-L160

  1. validateJsonElement(JsonElement jsonElement) lacks this discriminator check. It iterates through all oneOf schemas sequentially and increments validCount for each schema that passes validation.

  2. When disallowAdditionalPropertiesIfNotPresent=false, schemas accept undeclared properties. If branches share required fields (such as the discriminator field itself) while variant-specific fields are optional, a payload intended for one branch (e.g. {"petType":"cat","hunts":true}) is also considered valid by other branches (e.g. Dog, where bark is optional and hunts is treated as an allowed additional property).

  3. As a result, both Cat and Dog validate successfully (validCount = 2), triggering the validCount != 1 error.

  4. In the newer generic okhttp library (modules/openapi-generator/src/main/resources/Java/libraries/okhttp/oneof_model.mustache), this discriminator check is already implemented inside validateJsonElement(). It simply needs to be ported to okhttp-gson.

openapi-generator version

Master / 7.x

OpenAPI declaration file content or url
openapi: 3.0.3
info:
  title: OneOf Discriminator Validation Bug
  version: 1.0.0
paths:
  /pet:
    post:
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Pet'
      responses:
        '200':
          description: OK
components:
  schemas:
    Pet:
      type: object
      discriminator:
        propertyName: petType
        mapping:
          cat: '#/components/schemas/Cat'
          dog: '#/components/schemas/Dog'
      oneOf:
        - $ref: '#/components/schemas/Cat'
        - $ref: '#/components/schemas/Dog'
    Cat:
      type: object
      required:
        - petType
      properties:
        petType:
          type: string
        hunts:
          type: boolean
    Dog:
      type: object
      required:
        - petType
      properties:
        petType:
          type: string
        bark:
          type: boolean
Generation Details

Command line used for generation

$ java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generate \
  -g java \
  --library okhttp-gson \
  --additional-properties useOneOfDiscriminatorLookup=true,disallowAdditionalPropertiesIfNotPresent=false \
  -i spec.yaml \
  -o out/
Steps to reproduce

Run the following test against the generated client:

package org.openapitools.client.model;

import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;

import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import org.junit.jupiter.api.Test;

public class PetTest {
    @Test
    public void testPet() {
        String json = "{\"petType\":\"cat\",\"hunts\":true}";
        JsonElement element = JsonParser.parseString(json);
        assertDoesNotThrow(() -> Pet.validateJsonElement(element));
    }
}
Expected behavior

Because useOneOfDiscriminatorLookup=true is configured, Pet.validateJsonElement(element) should inspect the discriminator field petType, resolve the mapping (cat -> Cat), validate only against Cat.validateJsonElement(element), and return without error.

Actual behavior

Pet.validateJsonElement(element) does not check the discriminator. It validates both Cat and Dog. Since additional properties are allowed, both schemas accept the JSON payload, resulting in validCount = 2 and throwing:
java.io.IOException: The JSON string is invalid for Pet with oneOf schemas: Cat, Dog. 2 class(es) match the result, expected 1. Detailed failure message for oneOf schemas: []. JSON: {"petType":"cat","hunts":true}

Suggest a fix

In oneof_model.mustache, add the {{#useOneOfDiscriminatorLookup}} block to validateJsonElement (matching modules/openapi-generator/src/main/resources/Java/libraries/okhttp/oneof_model.mustache):

    public static void validateJsonElement(JsonElement jsonElement) throws IOException {
        // validate oneOf schemas one by one
        int validCount = 0;
        ArrayList<String> errorMessages = new ArrayList<>();
        {{#useOneOfDiscriminatorLookup}}
        {{#discriminator}}
        JsonObject jsonObject = jsonElement.getAsJsonObject();
        if (jsonObject.get("{{{propertyBaseName}}}") == null) {
            throw new IOException("Failed to deserialize as the discriminator field '{{{propertyBaseName}}}' is missing.");
        }
        String discriminatorValue = jsonObject.get("{{{propertyBaseName}}}").getAsString();
        {{#mappedModels}}
        if ("{{{mappingName}}}".equals(discriminatorValue)) {
            {{{modelName}}}.validateJsonElement(jsonElement);
            return;
        }
        {{/mappedModels}}
        {{/discriminator}}
        {{/useOneOfDiscriminatorLookup}}
        {{#composedSchemas}}
        {{#oneOf}}

I'll create a pull request to fix this.

主要语言
Java
星标
26.9k
派生
7.8k
平均合并
2 天 23 分钟
30 天内合并 PR
177

环境准备

在 Codespaces 中打开

在浏览器里用你自己的 GitHub 账号启动这个项目的开发容器。

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

OpenAPITools/openapi-generator 的其他 Issue

查看 OpenAPITools/openapi-generator 的全部 Issue

相似的 Issue

更多 Java Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。