[BUG][Java][okhttp-gson] useOneOfDiscriminatorLookup is ignored in validateJsonElement causing multi-match failure when disallowAdditionalPropertiesIfNotPresent=false
Maintainer thường phản hồi trong vòng 1 ngày
Chưa có ai nhận issue này.
Đánh giá
- Độ khó
- 2/5
- Thời gian dự kiến
- 1-3 giờ
- Mức phù hợp với người mới
- 48/100
Hướng nghiên cứu
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.
Do mô hình lập chỉ mục viết ra từ nội dung của issue.
Mô tả
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=truedisallowAdditionalPropertiesIfNotPresent=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
-
validateJsonElement(JsonElement jsonElement)lacks this discriminator check. It iterates through alloneOfschemas sequentially and incrementsvalidCountfor each schema that passes validation. -
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, wherebarkis optional andhuntsis treated as an allowed additional property). -
As a result, both
CatandDogvalidate successfully (validCount = 2), triggering thevalidCount != 1error. -
In the newer generic
okhttplibrary (modules/openapi-generator/src/main/resources/Java/libraries/okhttp/oneof_model.mustache), this discriminator check is already implemented insidevalidateJsonElement(). It simply needs to be ported tookhttp-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.
- Ngôn ngữ chính
- Java
- Star
- 26.9k
- Fork
- 7.8k
- Merge trung bình
- 2 ngày 23 phút
- Pull request đã merge (30 ngày)
- 177
Chuẩn bị môi trường
Khởi chạy dev container của dự án ngay trên trình duyệt, bằng tài khoản GitHub của bạn.
- Có Dockerfile hoặc tệp Docker Compose
- Có mẫu pull request
- Đọc hướng dẫn đóng góp
Bắt đầu từ đâu
- Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
- Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
- Fork repository và làm thay đổi trên một nhánh.
- Mở pull request có tham chiếu số hiệu của issue.
Issue khác của OpenAPITools/openapi-generator
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 70/100
OpenAPITools/openapi-generator#25768 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Enhancement: Feature
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 70/100
OpenAPITools/openapi-generator#25753 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
[BUG][RUBY-NEXTGEN] A non-String value in a pattern-constrained attribute raises NoMethodErrorCó thể đã có người làm @Inf1mum đã nhận 3 ngày trước. Đang mở
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 76/100
OpenAPITools/openapi-generator#25724 · 1 bình luận ·
Maintainer thường phản hồi trong vòng 1 ngày
-
[BUG][RUBY-NEXTGEN] Response#to_hash is advertised and raises when the data is an ArrayCó thể đã có người làm @Inf1mum đã nhận 3 ngày trước. Đang mở
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 77/100
OpenAPITools/openapi-generator#25723 · 1 bình luận ·
Maintainer thường phản hồi trong vòng 1 ngày
-
[BUG][RUBY-NEXTGEN] A JSON string response raises ApiError because the body is parsed twiceCó thể đã có người làm @Inf1mum đã nhận 2 ngày trước. Đang mở
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 77/100
OpenAPITools/openapi-generator#25719 · 1 bình luận ·
Maintainer thường phản hồi trong vòng 1 ngày
Tất cả issue của OpenAPITools/openapi-generator
Issue tương tự
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 62/100
eclipse-tradista/tradista#371 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Failed to start Rescue missionĐang mởcritical
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 68/100
mars-sim/mars-sim#2199 · 2 bình luận ·
Maintainer thường phản hồi trong vòng 1 ngày
-
[BUG-02] Endpoints /assistente/relatorio/*/preview retornam 404 ("Ver na tela" dos relatórios)Đang mở
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 65/100
projeto-ong-amar/projeto-ong-amar-backend#26 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 72/100
primefaces/primefaces#15568 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
崩溃日志只按 CRLF 分行Đang mở
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 72/100
PCL-Community/PCL-CE#3872 ·
Maintainer thường phản hồi trong vòng 1 ngày