Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ This format is based on [Keep a Changelog](http://keepachangelog.com/).
This project does not adhere to [Semantic Versioning](https://semver.org/) and minor version changes can have incompatible API changes. These incompatible API changes will largely affect those who have custom validator or walker implementations. Those who just use the library to validate using the standard JSON Schema Draft specifications may not need changes.
## [Unreleased]

- Prevent descendant discriminator state from leaking between `oneOf` and `anyOf` branches in OpenAPI 3.0. [#1378](https://github.com/networknt/json-schema-validator/issues/1378)

## 3.0.9- 2026-11-03

### Breaking changes
Expand Down
15 changes: 15 additions & 0 deletions src/main/java/com/networknt/schema/ExecutionContext.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;

import com.networknt.schema.annotation.Annotations;
Expand Down Expand Up @@ -193,6 +194,20 @@ public Map<NodePath, DiscriminatorState> getDiscriminatorMapping() {
return discriminatorMapping;
}

/**
* Discards discriminator state newly recorded below an alternative branch.
* A branch of oneOf or anyOf is an alternative, so discriminator state below
* the validator's location must not reach a sibling branch. State at the
* validator's own location and state present before the branch are retained.
*
* @param location the validator's instance location
* @param before discriminator locations present before evaluating the branch
*/
public void discardDiscriminatorsBelow(NodePath location, Set<NodePath> before) {
discriminatorMapping.keySet().removeIf(path -> !before.contains(path)
&& path.getNameCount() > location.getNameCount() && path.startsWith(location));
}

/**
* This is used during the execution to determine if the validator should fail fast.
* <p>
Expand Down
12 changes: 12 additions & 0 deletions src/main/java/com/networknt/schema/keyword/AnyOfValidator.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@
package com.networknt.schema.keyword;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import tools.jackson.databind.JsonNode;
import com.networknt.schema.Error;
Expand Down Expand Up @@ -74,6 +76,8 @@ protected void validate(ExecutionContext executionContext, JsonNode node, JsonNo
int schemaIndex = 0;
executionContext.setFailFast(false);
for (Schema schema : this.schemas) {
Set<NodePath> before = this.schemaContext.isDiscriminatorKeywordEnabled()
? new HashSet<>(executionContext.getDiscriminatorMapping().keySet()) : null;
subSchemaErrors.clear(); // Reuse and clear for each run
executionContext.evaluationPathAddLast(schemaIndex);
try {
Expand All @@ -85,6 +89,9 @@ protected void validate(ExecutionContext executionContext, JsonNode node, JsonNo
} finally {
executionContext.evaluationPathRemoveLast();
}
if (before != null) {
executionContext.discardDiscriminatorsBelow(instanceLocation, before);
}
schemaIndex++;

// check if any validation errors have occurred
Expand Down Expand Up @@ -195,12 +202,17 @@ public void walk(ExecutionContext executionContext, JsonNode node, JsonNode root
}
int schemaIndex = 0;
for (Schema schema : this.schemas) {
Set<NodePath> before = this.schemaContext.isDiscriminatorKeywordEnabled()
? new HashSet<>(executionContext.getDiscriminatorMapping().keySet()) : null;
executionContext.evaluationPathAddLast(schemaIndex);
try {
schema.walk(executionContext, node, rootNode, instanceLocation, false);
} finally {
executionContext.evaluationPathRemoveLast();
}
if (before != null) {
executionContext.discardDiscriminatorsBelow(instanceLocation, before);
}
schemaIndex++;
}
}
Expand Down
12 changes: 12 additions & 0 deletions src/main/java/com/networknt/schema/keyword/OneOfValidator.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@
package com.networknt.schema.keyword;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import tools.jackson.databind.JsonNode;
import com.networknt.schema.Error;
Expand Down Expand Up @@ -86,6 +88,8 @@ protected void validate(ExecutionContext executionContext, JsonNode node, JsonNo
try {
executionContext.setFailFast(false);
for (Schema schema : this.schemas) {
Set<NodePath> before = this.schemaContext.isDiscriminatorKeywordEnabled()
? new HashSet<>(executionContext.getDiscriminatorMapping().keySet()) : null;
subSchemaErrors.clear();
executionContext.evaluationPathAddLast(schemaIndex);
try {
Expand All @@ -97,6 +101,9 @@ protected void validate(ExecutionContext executionContext, JsonNode node, JsonNo
} finally {
executionContext.evaluationPathRemoveLast();
}
if (before != null) {
executionContext.discardDiscriminatorsBelow(instanceLocation, before);
}
schemaIndex++;

// check if any validation errors have occurred
Expand Down Expand Up @@ -256,12 +263,17 @@ public void walk(ExecutionContext executionContext, JsonNode node, JsonNode root
} else {
int schemaIndex = 0;
for (Schema schema : this.schemas) {
Set<NodePath> before = this.schemaContext.isDiscriminatorKeywordEnabled()
? new HashSet<>(executionContext.getDiscriminatorMapping().keySet()) : null;
executionContext.evaluationPathAddLast(schemaIndex);
try {
schema.walk(executionContext, node, rootNode, instanceLocation, false);
} finally {
executionContext.evaluationPathRemoveLast();
}
if (before != null) {
executionContext.discardDiscriminatorsBelow(instanceLocation, before);
}
schemaIndex++;
}
}
Expand Down
49 changes: 49 additions & 0 deletions src/test/java/com/networknt/schema/Issue1378Test.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* Copyright (c) 2026 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.networknt.schema;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;

import java.nio.charset.StandardCharsets;
import java.util.Map;

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

import com.networknt.schema.dialect.Dialects;

class Issue1378Test {
@ParameterizedTest
@ValueSource(strings = { "oneOf", "anyOf" })
void nestedDiscriminatorsStayWithinAlternativeBranches(String keyword) throws Exception {
String doc;
try (var input = getClass().getResourceAsStream("/schema/issue1378.json")) {
doc = new String(input.readAllBytes(), StandardCharsets.UTF_8);
}
// Change only the outer alternative; keep both nested oneOf schemas intact.
doc = doc.replaceFirst("oneOf", keyword);
String document = doc;
SchemaRegistry registry = SchemaRegistry.withDialect(Dialects.getOpenApi30(),
builder -> builder.schemas(Map.of("https://example.com/openapi.json", document)));
Schema schema = registry.getSchema(
SchemaLocation.of("https://example.com/openapi.json#/components/schemas/Container"));
assertEquals(0, schema.validate("{\"kind\":\"B\",\"items\":[{\"type\":\"x\",\"value\":\"hello\"}]}", InputFormat.JSON).size());
assertFalse(schema.validate("{\"kind\":\"B\",\"items\":[{\"type\":\"x\",\"value\":42}]}", InputFormat.JSON).isEmpty());
assertEquals(0, schema.validate("{\"kind\":\"B\",\"items\":[{\"type\":\"y\",\"count\":1}]}", InputFormat.JSON).size());
assertEquals(0, schema.validate("{\"kind\":\"A\",\"items\":[{\"type\":\"x\",\"values\":[\"a\"]}]}", InputFormat.JSON).size());
}
}
88 changes: 88 additions & 0 deletions src/test/resources/schema/issue1378.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
{
"openapi": "3.0.3",
"info": { "title": "discriminator repro", "version": "1" },
"paths": {},
"components": {
"schemas": {
"Container": {
"oneOf": [
{ "$ref": "#/components/schemas/KindA" },
{ "$ref": "#/components/schemas/KindB" }
]
},
"KindA": {
"type": "object",
"required": ["kind", "items"],
"properties": {
"kind": { "type": "string", "enum": ["A"] },
"items": {
"type": "array",
"items": {
"oneOf": [
{ "$ref": "#/components/schemas/XList" },
{ "$ref": "#/components/schemas/YItem" }
],
"discriminator": {
"propertyName": "type",
"mapping": {
"x": "#/components/schemas/XList",
"y": "#/components/schemas/YItem"
}
}
}
}
}
},
"KindB": {
"type": "object",
"required": ["kind", "items"],
"properties": {
"kind": { "type": "string", "enum": ["B"] },
"items": {
"type": "array",
"items": {
"oneOf": [
{ "$ref": "#/components/schemas/XString" },
{ "$ref": "#/components/schemas/YItem" }
],
"discriminator": {
"propertyName": "type",
"mapping": {
"x": "#/components/schemas/XString",
"y": "#/components/schemas/YItem"
}
}
}
}
}
},
"XList": {
"type": "object",
"required": ["type", "values"],
"properties": {
"type": { "type": "string" },
"values": { "type": "array", "items": { "type": "string" } }
},
"additionalProperties": false
},
"XString": {
"type": "object",
"required": ["type", "value"],
"properties": {
"type": { "type": "string" },
"value": { "type": "string" }
},
"additionalProperties": false
},
"YItem": {
"type": "object",
"required": ["type", "count"],
"properties": {
"type": { "type": "string" },
"count": { "type": "integer" }
},
"additionalProperties": false
}
}
}
}
Loading