diff --git a/README.md b/README.md
index a4cf4171e..9bebdc649 100644
--- a/README.md
+++ b/README.md
@@ -84,6 +84,23 @@ var (openApiDocument, _) = await OpenApiDocument.LoadAsync("https://raw.githubus
var outputString = await openApiDocument.SerializeAsJsonAsync(OpenApiSpecVersion.OpenApi2_0);
```
+## JSON Schema dialects
+
+For OpenAPI 3.1 and 3.2, the reader selects a schema's dialect from its explicit `$schema`, its enclosing schema's dialect, the document's `jsonSchemaDialect`, or the OpenAPI default, in that order. The OpenAPI base dialect and JSON Schema draft 2020-12 use the existing version-specific schema readers. Unrecognized keywords remain available through `UnrecognizedKeywords`; unsupported dialects produce a diagnostic without discarding the schema.
+
+External dialect resolution is opt-in through asynchronous loading:
+
+```C#
+var result = await OpenApiDocument.LoadAsync(stream, OpenApiConstants.Json,
+ new OpenApiReaderSettings { LoadExternalRefs = true });
+```
+
+This also enables ordinary external references. For an unknown dialect, the reader follows its meta-schema's `$schema` chain to a supported dialect using `CustomExternalLoader` or the default HTTP/file loader. Resolution is cached per document read, detects cycles, and is limited to 16 parent links per chain (including cached links) and 1 MiB per response. Cancellation is passed to the configured loader and stream reads. Failed or unsupported chains retain their diagnostic.
+
+Non-empty dialect URI fragments select a JSON Pointer target or a schema named by `$anchor` or `$dynamicAnchor` within the loaded resource. Fragment lookup traverses recognized schema locations only; missing or ambiguous targets and locations defined by unknown custom vocabularies retain the unsupported-dialect diagnostic. Named-anchor lookup stops at nested non-empty `$id` declarations; it does not build an embedded-resource index.
+
+This does not add parsers for other JSON Schema drafts or custom vocabularies. Writing still follows the requested OpenAPI output version rather than dispatching on the schema dialect.
+
# Validating/Testing OpenAPI descriptions
[Microsoft.OpenApi.Hidi](https://www.nuget.org/packages/Microsoft.OpenApi.Hidi) is a command line tool for validating and transforming OpenAPI descriptions.
The OpenAPI.NET v3-compatible tool is maintained in [OpenAPI.NET.OData's main branch](https://github.com/microsoft/OpenAPI.NET.OData/tree/main/src/Microsoft.OpenApi.Hidi).
diff --git a/src/Microsoft.OpenApi/Interfaces/IOpenApiVersionService.cs b/src/Microsoft.OpenApi/Interfaces/IOpenApiVersionService.cs
index 01f728ef1..5e4077cdb 100644
--- a/src/Microsoft.OpenApi/Interfaces/IOpenApiVersionService.cs
+++ b/src/Microsoft.OpenApi/Interfaces/IOpenApiVersionService.cs
@@ -31,6 +31,15 @@ internal interface IOpenApiVersionService
/// Instance of OpenApiDocument populated with data from JsonNode
OpenApiDocument LoadDocument(JsonNode jsonNode, Uri location, ParsingContext context);
+ ///
+ /// Converts a JSON Schema node into an OpenAPI schema using this version's parsing rules.
+ ///
+ /// The JSON Schema node.
+ /// The host document instance.
+ /// The current parsing context.
+ /// The parsed schema.
+ IOpenApiSchema LoadSchema(JsonNode node, OpenApiDocument doc, ParsingContext context);
+
///
/// Gets the description and summary scalar values in a reference object for V3.1 support
///
diff --git a/src/Microsoft.OpenApi/Reader/BaseOpenApiVersionService.cs b/src/Microsoft.OpenApi/Reader/BaseOpenApiVersionService.cs
index fb21d57b3..5b7ec1a4d 100644
--- a/src/Microsoft.OpenApi/Reader/BaseOpenApiVersionService.cs
+++ b/src/Microsoft.OpenApi/Reader/BaseOpenApiVersionService.cs
@@ -29,6 +29,17 @@ protected BaseOpenApiVersionService(OpenApiDiagnostic diagnostic)
}
return default;
}
+
+ public virtual IOpenApiSchema LoadSchema(JsonNode node, OpenApiDocument doc, ParsingContext context)
+ {
+ if (Loaders.TryGetValue(typeof(OpenApiSchema), out var loader) && loader(node, doc, context) is IOpenApiSchema schema)
+ {
+ return schema;
+ }
+
+ throw new InvalidOperationException($"No schema loader is registered for {GetType().Name}.");
+ }
+
public virtual string? GetReferenceScalarValues(JsonObject jsonObject, string scalarValue)
{
if (jsonObject.Any(static x => !"$ref".Equals(x.Key, StringComparison.OrdinalIgnoreCase)) &&
diff --git a/src/Microsoft.OpenApi/Reader/JsonNodeHelper.cs b/src/Microsoft.OpenApi/Reader/JsonNodeHelper.cs
index db285f078..dec92ad1f 100644
--- a/src/Microsoft.OpenApi/Reader/JsonNodeHelper.cs
+++ b/src/Microsoft.OpenApi/Reader/JsonNodeHelper.cs
@@ -28,11 +28,30 @@ public static List CreateList(this JsonNode? node, Func()
- .Select(n => map(n, hostDocument, context))
- .Where(static i => i != null)
- .ToList();
+ var list = new List();
+ for (var index = 0; index < jsonArray.Count; index++)
+ {
+ if (jsonArray[index] is not JsonObject jsonObject)
+ {
+ continue;
+ }
+
+ try
+ {
+ context.StartObject(index.ToString(CultureInfo.InvariantCulture));
+ var value = map(jsonObject, hostDocument, context);
+ if (value != null)
+ {
+ list.Add(value);
+ }
+ }
+ finally
+ {
+ context.EndObject();
+ }
+ }
+
+ return list;
}
public static List CreateListOfAny(this JsonNode? node, ParsingContext context)
@@ -102,7 +121,7 @@ public static Dictionary CreateMap(this JsonNode? node, Func k.key, v => v.value);
}
- public static Dictionary CreateSimpleMap(this JsonNode? node, Func map, ParsingContext context)
+ public static Dictionary CreateSimpleMap(this JsonNode? node, Func map, ParsingContext context, bool reportConversionErrors = false)
{
if (node is not JsonObject jsonMap)
{
@@ -121,6 +140,10 @@ public static Dictionary CreateSimpleMap(this JsonNode? node, Func
return (key, value: map(jsonNode));
}
+ catch (Exception exception) when (reportConversionErrors && exception is FormatException or OverflowException)
+ {
+ throw new OpenApiReaderException(exception.Message, exception) { Pointer = context.GetLocation() };
+ }
finally
{
context.EndObject();
@@ -161,8 +184,18 @@ public static Dictionary> CreateArrayMap(this JsonNode? no
return nodes.ToDictionary(kvp => kvp.key, kvp => kvp.values);
}
- public static string? GetScalarValue(this JsonNode? node)
+ public static string? GetScalarValue(this JsonNode? node, bool requireString = false)
{
+ if (requireString)
+ {
+ if (!TryGetStringValue(node, out var stringValue))
+ {
+ throw new OpenApiException("Expected string value.");
+ }
+
+ return stringValue;
+ }
+
if (node.IsJsonNullSentinel())
{
return null;
@@ -178,6 +211,47 @@ public static Dictionary> CreateArrayMap(this JsonNode? no
return jsonObject.TryGetPropertyValue("$ref", out var refNode) ? refNode?.GetScalarValue() : null;
}
+ public static string? GetReferencePointer(this JsonObject jsonObject, ParsingContext context, bool preserveInvalidProperties = false)
+ {
+ if (!preserveInvalidProperties)
+ {
+ return jsonObject.GetReferencePointer();
+ }
+
+ if (!jsonObject.TryGetPropertyValue(OpenApiConstants.DollarRef, out var refNode))
+ {
+ return null;
+ }
+
+ try
+ {
+ var pointer = refNode.GetScalarValue(requireString: true);
+ if (pointer is not null)
+ {
+ ValidateReferencePointerFormat(pointer);
+ }
+
+ return pointer;
+ }
+ catch (OpenApiException exception)
+ {
+ // $ref is consumed before ParseMap, so recover only this keyword's
+ // extraction/format failure and let the ordinary map retain its raw value.
+ try
+ {
+ context.StartObject(OpenApiConstants.DollarRef);
+ exception.Pointer = context.GetLocation();
+ context.Diagnostic.Errors.Add(new(exception));
+ }
+ finally
+ {
+ context.EndObject();
+ }
+
+ return null;
+ }
+ }
+
public static void ValidateReferencePointerFormat(string pointer)
{
var hashIndex = pointer.IndexOf('#');
@@ -194,11 +268,13 @@ public static void ValidateReferencePointerFormat(string pointer)
/// Returns the value of $dynamicRef if $ref is absent. Used to create a schema reference
/// for bare $dynamicRef schemas (no $ref) so they participate in reference resolution.
///
- public static string? GetDynamicReferencePointer(this JsonObject jsonObject)
+ public static string? GetDynamicReferencePointer(this JsonObject jsonObject, bool preserveInvalidProperties = false)
{
if (jsonObject.TryGetPropertyValue("$ref", out _))
return null;
- return jsonObject.TryGetPropertyValue("$dynamicRef", out var dynRefNode) ? dynRefNode?.GetScalarValue() : null;
+ return jsonObject.TryGetPropertyValue("$dynamicRef", out var dynRefNode)
+ ? GetSchemaKeywordValue(dynRefNode, preserveInvalidProperties)
+ : null;
}
///
@@ -236,9 +312,26 @@ public static bool IsFragmentOnlyDynamicRef(string? dynamicRef)
return hashIndex > 0 ? dynamicRef.Substring(0, hashIndex) : null;
}
- public static string? GetJsonSchemaIdentifier(this JsonObject jsonObject)
+ public static string? GetJsonSchemaIdentifier(this JsonObject jsonObject, bool preserveInvalidProperties = false)
+ {
+ return jsonObject.TryGetPropertyValue("$id", out var idNode)
+ ? GetSchemaKeywordValue(idNode, preserveInvalidProperties)
+ : null;
+ }
+
+ private static string? GetSchemaKeywordValue(JsonNode? node, bool preserveInvalidProperties)
+ {
+ // The fixed-field handler reports invalid values during ParseMap. Do not
+ // interpret them as a reference or identifier before that handler can run.
+ return preserveInvalidProperties
+ ? TryGetStringValue(node, out var value) ? value : null
+ : node?.GetScalarValue();
+ }
+
+ private static bool TryGetStringValue(JsonNode? node, out string? value)
{
- return jsonObject.TryGetPropertyValue("$id", out var idNode) ? idNode?.GetScalarValue() : null;
+ value = null;
+ return !node.IsJsonNullSentinel() && node is JsonValue jsonValue && jsonValue.TryGetValue(out value);
}
public static void ParseMap(
@@ -248,7 +341,8 @@ public static void ParseMap(
PatternFieldMap patternFieldMap,
OpenApiDocument hostDocument,
ParsingContext context,
- Action? unrecognizedProperty = null)
+ Action? unrecognizedProperty = null,
+ bool preserveInvalidProperties = false)
{
if (JsonObject == null)
{
@@ -257,7 +351,7 @@ public static void ParseMap(
foreach (var propertyNode in JsonObject)
{
- ParseField(propertyNode.Key, propertyNode.Value ?? JsonNullSentinel.JsonNull, domainObject, fixedFieldMap, patternFieldMap, hostDocument, context, unrecognizedProperty);
+ ParseField(propertyNode.Key, propertyNode.Value ?? JsonNullSentinel.JsonNull, domainObject, fixedFieldMap, patternFieldMap, hostDocument, context, unrecognizedProperty, preserveInvalidProperties);
}
}
@@ -269,7 +363,8 @@ private static void ParseField(
PatternFieldMap patternFields,
OpenApiDocument hostDocument,
ParsingContext context,
- Action? unrecognizedProperty)
+ Action? unrecognizedProperty,
+ bool preserveInvalidProperties)
{
if (fixedFields.TryGetValue(name, out var fixedFieldMap))
{
@@ -281,11 +376,26 @@ private static void ParseField(
catch (OpenApiReaderException ex)
{
context.Diagnostic.Errors.Add(new(ex));
+ if (preserveInvalidProperties)
+ {
+ unrecognizedProperty?.Invoke(parentInstance, name, value);
+ }
}
catch (OpenApiException ex)
{
ex.Pointer = context.GetLocation();
context.Diagnostic.Errors.Add(new(ex));
+ if (preserveInvalidProperties)
+ {
+ unrecognizedProperty?.Invoke(parentInstance, name, value);
+ }
+ }
+ catch (Exception ex) when (preserveInvalidProperties && unrecognizedProperty is not null && value is JsonValue &&
+ ex is FormatException or OverflowException)
+ {
+ // Scalar conversions belong to this field; nested schemas can use a different dialect.
+ context.Diagnostic.Errors.Add(new OpenApiError(context.GetLocation(), ex.Message));
+ unrecognizedProperty(parentInstance, name, value);
}
finally
{
@@ -305,11 +415,19 @@ private static void ParseField(
catch (OpenApiReaderException ex)
{
context.Diagnostic.Errors.Add(new(ex));
+ if (preserveInvalidProperties)
+ {
+ unrecognizedProperty?.Invoke(parentInstance, name, value);
+ }
}
catch (OpenApiException ex)
{
ex.Pointer = context.GetLocation();
context.Diagnostic.Errors.Add(new(ex));
+ if (preserveInvalidProperties)
+ {
+ unrecognizedProperty?.Invoke(parentInstance, name, value);
+ }
}
finally
{
diff --git a/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs b/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs
index 6b7a5fb9d..ee95d119d 100644
--- a/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs
+++ b/src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs
@@ -1,13 +1,13 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
+using System;
using System.IO;
-using System.Text.Json.Nodes;
+using System.Linq;
using System.Text.Json;
+using System.Text.Json.Nodes;
using System.Threading;
using System.Threading.Tasks;
-using System.Linq;
-using System;
namespace Microsoft.OpenApi.Reader
{
@@ -108,6 +108,12 @@ public ReadResult Read(JsonNode jsonNode,
{
Document = document,
Diagnostic = diagnostic,
+ UnsupportedSchemaDialects = settings.LoadExternalRefs
+ ? context.SchemaDialectService?.UnsupportedDialects.ToArray()
+ : null,
+ UnsupportedSchemaDialectErrors = settings.LoadExternalRefs
+ ? context.SchemaDialectService?.UnsupportedDialectErrors.ToArray()
+ : null,
};
}
diff --git a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs
index 2abd04873..342757b01 100644
--- a/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs
+++ b/src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs
@@ -2,9 +2,11 @@
// Licensed under the MIT license.
using System;
+using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
+using System.Runtime.CompilerServices;
using System.Security;
using System.Text;
using System.Threading;
@@ -253,6 +255,7 @@ private static async Task InternalLoadAsync(Stream input, string for
if (settings.LoadExternalRefs)
{
+ await ResolveJsonSchemaDialectsAsync(readResult, location, settings, cancellationToken).ConfigureAwait(false);
var diagnosticExternalRefs = await LoadExternalRefsAsync(readResult.Document, settings, format, cancellationToken).ConfigureAwait(false);
// Merge diagnostics of external reference
if (diagnosticExternalRefs != null)
@@ -262,9 +265,55 @@ private static async Task InternalLoadAsync(Stream input, string for
}
}
+ readResult.UnsupportedSchemaDialects = null;
+ readResult.UnsupportedSchemaDialectErrors = null;
+
return readResult;
}
+ private static async Task ResolveJsonSchemaDialectsAsync(
+ ReadResult readResult,
+ Uri location,
+ OpenApiReaderSettings settings,
+ CancellationToken cancellationToken)
+ {
+ if (readResult.Document is null ||
+ readResult.Diagnostic is null ||
+ readResult.UnsupportedSchemaDialectErrors is null ||
+ readResult.UnsupportedSchemaDialects is not { Count: > 0 } unsupportedDialects)
+ {
+ return;
+ }
+
+ var loader = settings.CustomExternalLoader ?? new DefaultStreamLoader(settings.HttpClient);
+ var resolver = new JsonSchemaDialectResolver(loader, location);
+ var dialectMappings = await resolver.ResolveAsync(unsupportedDialects, cancellationToken).ConfigureAwait(false);
+ // Both supported dialects use the current OpenAPI version service, which is also
+ // the fallback used during parsing. Resolving an alias therefore only removes its
+ // unsupported-dialect errors; reparsing would rerun callbacks and replace custom readers' results.
+ // Dialects requiring different parsing rules will need a different resolution approach.
+ var resolvedErrors = new HashSet(readResult.UnsupportedSchemaDialectErrors
+ .Where(item => dialectMappings.ContainsKey(item.Dialect))
+ .Select(item => item.Error), DiagnosticReferenceEqualityComparer.Instance);
+ if (resolvedErrors.Count > 0)
+ {
+ readResult.Diagnostic.Errors = readResult.Diagnostic.Errors
+ .Where(error => !resolvedErrors.Contains(error))
+ .ToList();
+ }
+ }
+
+ private sealed class DiagnosticReferenceEqualityComparer : IEqualityComparer
+ {
+ internal static DiagnosticReferenceEqualityComparer Instance { get; } = new();
+
+ public bool Equals(OpenApiError? x, OpenApiError? y)
+ => ReferenceEquals(x, y);
+
+ public int GetHashCode(OpenApiError obj)
+ => RuntimeHelpers.GetHashCode(obj);
+ }
+
private static async Task LoadExternalRefsAsync(OpenApiDocument? document, OpenApiReaderSettings settings, string? format = null, CancellationToken token = default)
{
// Load this document into the workspace
diff --git a/src/Microsoft.OpenApi/Reader/ParsingContext.cs b/src/Microsoft.OpenApi/Reader/ParsingContext.cs
index 2cf72c074..44c2716d8 100644
--- a/src/Microsoft.OpenApi/Reader/ParsingContext.cs
+++ b/src/Microsoft.OpenApi/Reader/ParsingContext.cs
@@ -29,6 +29,7 @@ public class ParsingContext
internal JsonNode? JsonNode { get; set; }
internal List Tags { get; private set; } = new();
+ internal JsonSchemaDialectService? SchemaDialectService { get; private set; }
///
/// The base url for the document
@@ -85,12 +86,14 @@ public OpenApiDocument Parse(JsonNode jsonNode, Uri location)
break;
case string version when version.is3_1():
VersionService = new OpenApiV31VersionService(Diagnostic);
+ SchemaDialectService = new JsonSchemaDialectService(VersionService, GetJsonSchemaDialect(jsonNode), Diagnostic);
doc = VersionService.LoadDocument(jsonNode, location, this);
this.Diagnostic.SpecificationVersion = OpenApiSpecVersion.OpenApi3_1;
ValidateRequiredFields(doc, version);
break;
case string version when version.is3_2():
VersionService = new OpenApiV32VersionService(Diagnostic);
+ SchemaDialectService = new JsonSchemaDialectService(VersionService, GetJsonSchemaDialect(jsonNode), Diagnostic);
doc = VersionService.LoadDocument(jsonNode, location, this);
this.Diagnostic.SpecificationVersion = OpenApiSpecVersion.OpenApi3_2;
ValidateRequiredFields(doc, version);
@@ -126,10 +129,12 @@ public OpenApiDocument Parse(JsonNode jsonNode, Uri location)
break;
case OpenApiSpecVersion.OpenApi3_1:
this.VersionService = new OpenApiV31VersionService(Diagnostic);
+ SchemaDialectService = new JsonSchemaDialectService(VersionService, openApiDocument.JsonSchemaDialect, Diagnostic);
element = this.VersionService.LoadElement(jsonNode, openApiDocument, this);
break;
case OpenApiSpecVersion.OpenApi3_2:
this.VersionService = new OpenApiV32VersionService(Diagnostic);
+ SchemaDialectService = new JsonSchemaDialectService(VersionService, openApiDocument.JsonSchemaDialect, Diagnostic);
element = this.VersionService.LoadElement(jsonNode, openApiDocument, this);
break;
}
@@ -155,6 +160,15 @@ private static string GetVersion(JsonNode jsonNode)
return versionNode?.GetScalarValue()?.Replace("\"", string.Empty) ?? throw new OpenApiException("Version node not found.");
}
+ private static Uri? GetJsonSchemaDialect(JsonNode jsonNode)
+ {
+ var dialectNode = new JsonPointer("/jsonSchemaDialect").Find(jsonNode);
+ return dialectNode is JsonValue &&
+ Uri.TryCreate(dialectNode.GetScalarValue(), UriKind.Absolute, out var dialect)
+ ? dialect
+ : null;
+ }
+
///
/// Service providing all Version specific conversion functions
///
diff --git a/src/Microsoft.OpenApi/Reader/ReadResult.cs b/src/Microsoft.OpenApi/Reader/ReadResult.cs
index 7710110dd..6317b4b3c 100644
--- a/src/Microsoft.OpenApi/Reader/ReadResult.cs
+++ b/src/Microsoft.OpenApi/Reader/ReadResult.cs
@@ -1,12 +1,18 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
+using System;
+using System.Collections.Generic;
+
namespace Microsoft.OpenApi.Reader;
///
/// Container object used for returning the result of reading an OpenAPI description.
///
public class ReadResult
{
+ internal IReadOnlyCollection? UnsupportedSchemaDialects { get; set; }
+ internal IReadOnlyCollection<(Uri Dialect, OpenApiError Error)>? UnsupportedSchemaDialectErrors { get; set; }
+
///
/// The parsed OpenApiDocument. Null will be returned if the document could not be parsed.
///
@@ -24,4 +30,3 @@ public void Deconstruct(out OpenApiDocument? document, out OpenApiDiagnostic? di
diagnostic = Diagnostic;
}
}
-
diff --git a/src/Microsoft.OpenApi/Reader/Services/DefaultStreamLoader.cs b/src/Microsoft.OpenApi/Reader/Services/DefaultStreamLoader.cs
index fb6d86bab..2630ef484 100644
--- a/src/Microsoft.OpenApi/Reader/Services/DefaultStreamLoader.cs
+++ b/src/Microsoft.OpenApi/Reader/Services/DefaultStreamLoader.cs
@@ -28,7 +28,7 @@ public DefaultStreamLoader(HttpClient httpClient)
///
public async Task LoadAsync(Uri baseUrl, Uri uri, CancellationToken cancellationToken = default)
{
- var absoluteUri = baseUrl.AbsoluteUri.Equals(OpenApiConstants.BaseRegistryUri) switch
+ var absoluteUri = uri.IsAbsoluteUri ? uri : baseUrl.AbsoluteUri.Equals(OpenApiConstants.BaseRegistryUri) switch
{
true => new Uri(Path.Combine(Directory.GetCurrentDirectory(), uri.ToString())),
_ => new Uri(baseUrl, uri),
diff --git a/src/Microsoft.OpenApi/Reader/Services/JsonSchemaDialectResolver.cs b/src/Microsoft.OpenApi/Reader/Services/JsonSchemaDialectResolver.cs
new file mode 100644
index 000000000..4537a1552
--- /dev/null
+++ b/src/Microsoft.OpenApi/Reader/Services/JsonSchemaDialectResolver.cs
@@ -0,0 +1,312 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Net.Http;
+using System.Security;
+using System.Text.Json;
+using System.Text.Json.Nodes;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace Microsoft.OpenApi.Reader;
+
+///
+/// Resolves unknown JSON Schema dialects to parsing rules already known by the reader.
+///
+internal sealed class JsonSchemaDialectResolver
+{
+ internal const int MaxResolutionDepth = 16;
+ internal const int MaxMetaSchemaSize = 1024 * 1024;
+
+ private readonly IStreamLoader _loader;
+ private readonly Uri _baseUrl;
+ private readonly Dictionary _metaSchemaDialects = new(StringComparer.Ordinal);
+
+ internal JsonSchemaDialectResolver(IStreamLoader loader, Uri baseUrl)
+ {
+ _loader = loader;
+ _baseUrl = baseUrl;
+ }
+
+ internal async Task> ResolveAsync(
+ IEnumerable dialects,
+ CancellationToken cancellationToken)
+ {
+ var result = new Dictionary(new DialectUriEqualityComparer());
+ foreach (var dialect in dialects)
+ {
+ if (await ResolveAsync(dialect, cancellationToken).ConfigureAwait(false) is { } knownDialect)
+ {
+ result[dialect] = knownDialect;
+ }
+ }
+
+ return result;
+ }
+
+ private async Task ResolveAsync(Uri dialect, CancellationToken cancellationToken)
+ {
+ var visited = new HashSet(StringComparer.Ordinal);
+ var current = dialect;
+
+ for (var depth = 0; depth < MaxResolutionDepth; depth++)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ if (JsonSchemaDialectService.IsKnownDialect(current))
+ {
+ return current;
+ }
+
+ var key = GetDialectKey(current);
+ if (!visited.Add(key))
+ {
+ return null;
+ }
+
+ // Cached parent links still count toward this chain's depth limit.
+ if (!_metaSchemaDialects.TryGetValue(key, out var parentDialect))
+ {
+ parentDialect = await LoadParentDialectAsync(current, cancellationToken).ConfigureAwait(false);
+ _metaSchemaDialects[key] = parentDialect;
+ }
+
+ if (parentDialect is null)
+ {
+ return null;
+ }
+
+ current = parentDialect;
+ }
+
+ if (JsonSchemaDialectService.IsKnownDialect(current))
+ {
+ return current;
+ }
+
+ return null;
+ }
+
+ private async Task LoadParentDialectAsync(Uri dialect, CancellationToken cancellationToken)
+ {
+ try
+ {
+ using var input = await _loader.LoadAsync(_baseUrl, dialect, cancellationToken).ConfigureAwait(false);
+ if (input.CanSeek && input.Length - input.Position > MaxMetaSchemaSize)
+ {
+ return null;
+ }
+
+ using var buffer = new MemoryStream();
+ var bytes = new byte[81920];
+ var totalBytesRead = 0;
+ int bytesRead;
+ while ((bytesRead = await input.ReadAsync(bytes, 0, bytes.Length, cancellationToken).ConfigureAwait(false)) > 0)
+ {
+ if (bytesRead > MaxMetaSchemaSize - totalBytesRead)
+ {
+ return null;
+ }
+
+ await buffer.WriteAsync(bytes, 0, bytesRead, cancellationToken).ConfigureAwait(false);
+ totalBytesRead += bytesRead;
+ }
+
+ buffer.Position = 0;
+ var metaSchema = await JsonNode.ParseAsync(buffer, cancellationToken: cancellationToken).ConfigureAwait(false);
+ return FindParentDialect(metaSchema, dialect, cancellationToken);
+ }
+ catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
+ {
+ return null;
+ }
+ catch (Exception exception) when (exception is IOException or HttpRequestException or JsonException or OpenApiException or
+ ArgumentException or InvalidOperationException or SecurityException or UnauthorizedAccessException or UriFormatException)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ return null;
+ }
+ }
+
+ private static Uri? FindParentDialect(JsonNode? metaSchema, Uri dialect, CancellationToken cancellationToken)
+ {
+ var fragment = dialect.Fragment.Length == 0 ? string.Empty : Uri.UnescapeDataString(dialect.Fragment.Substring(1));
+ var isPointer = fragment.StartsWith("/", StringComparison.Ordinal);
+ var isAnchor = fragment.Length > 0 && !isPointer;
+ if (isAnchor && (!IsAnchorName(fragment) || metaSchema is JsonObject root && HasInvalidIdentifier(root, dialect)))
+ {
+ return null;
+ }
+
+ Uri? result = null;
+ var found = false;
+ foreach (var (schema, pointer, effectiveDialect) in EnumerateSchemas(metaSchema, string.Empty, null, isAnchor, cancellationToken))
+ {
+ var matches = isAnchor
+ ? schema is JsonObject jsonObject &&
+ (HasAnchor(jsonObject, OpenApiConstants.Anchor, fragment) || HasAnchor(jsonObject, OpenApiConstants.DynamicAnchor, fragment))
+ : string.Equals(pointer, fragment, StringComparison.Ordinal);
+ if (!matches)
+ {
+ continue;
+ }
+
+ if (found)
+ {
+ // Plain-name fragments must identify one schema in the current resource.
+ return null;
+ }
+
+ found = true;
+ result = effectiveDialect;
+ if (!isAnchor)
+ {
+ return result;
+ }
+ }
+
+ return result;
+ }
+
+ private static IEnumerable<(JsonNode Schema, string Pointer, Uri? Dialect)> EnumerateSchemas(
+ JsonNode? node,
+ string pointer,
+ Uri? inheritedDialect,
+ bool restrictToResource,
+ CancellationToken cancellationToken)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ if (!IsSchema(node))
+ {
+ yield break;
+ }
+
+ var effectiveDialect = inheritedDialect;
+ if (node is JsonObject schema)
+ {
+ // Anchors belong to their nearest resource root, not to enclosing resources.
+ if (restrictToResource && pointer.Length > 0 && schema.TryGetPropertyValue("$id", out var identifier) &&
+ (identifier is not JsonValue idValue || !idValue.TryGetValue(out var id) || !string.IsNullOrEmpty(id)))
+ {
+ yield break;
+ }
+
+ if (schema.TryGetPropertyValue(OpenApiConstants.DollarSchema, out var dialectNode))
+ {
+ effectiveDialect = dialectNode is JsonValue value && value.TryGetValue(out var declaredDialect) &&
+ Uri.TryCreate(declaredDialect, UriKind.Absolute, out var parentDialect) ? parentDialect : null;
+ }
+ }
+
+ yield return (node!, pointer, effectiveDialect);
+ if (node is not JsonObject jsonObject)
+ {
+ yield break;
+ }
+
+ foreach (var (child, childPointer) in EnumerateChildSchemas(jsonObject, pointer))
+ {
+ foreach (var descendant in EnumerateSchemas(child, childPointer, effectiveDialect, restrictToResource, cancellationToken))
+ {
+ yield return descendant;
+ }
+ }
+ }
+
+ private static IEnumerable<(JsonNode Schema, string Pointer)> EnumerateChildSchemas(JsonObject schema, string pointer)
+ {
+ // Only locations with known schema semantics are traversed. Examples and custom
+ // vocabulary payloads cannot safely be interpreted as schemas or anchor declarations.
+ foreach (var property in schema)
+ {
+ var propertyPointer = pointer + "/" + property.Key;
+ switch (property.Key)
+ {
+ case "$defs" or "properties" or "patternProperties" or "dependentSchemas" when property.Value is JsonObject map:
+ foreach (var child in map)
+ {
+ if (IsSchema(child.Value))
+ {
+ yield return (child.Value!, propertyPointer + "/" + OpenApiVisitorBase.EncodeJsonPointerSegment(child.Key));
+ }
+ }
+ break;
+ case "allOf" or "anyOf" or "oneOf" or "prefixItems" when property.Value is JsonArray array:
+ for (var index = 0; index < array.Count; index++)
+ {
+ if (IsSchema(array[index]))
+ {
+ yield return (array[index]!, propertyPointer + "/" + index.ToString(CultureInfo.InvariantCulture));
+ }
+ }
+ break;
+ case "items" or "not" or "contains" or "propertyNames" or "additionalProperties" or
+ "unevaluatedProperties" or "unevaluatedItems" or "contentSchema" or "if" or "then" or "else":
+ if (IsSchema(property.Value))
+ {
+ yield return (property.Value!, propertyPointer);
+ }
+ break;
+ }
+ }
+ }
+
+ private static bool IsSchema(JsonNode? node) => node is JsonObject || node is JsonValue value && value.TryGetValue(out _);
+
+ private static bool HasAnchor(JsonObject schema, string keyword, string anchor) =>
+ schema.TryGetPropertyValue(keyword, out var node) && node is JsonValue value &&
+ value.TryGetValue(out var name) && string.Equals(name, anchor, StringComparison.Ordinal);
+
+ private static bool HasInvalidIdentifier(JsonObject schema, Uri dialect) =>
+ schema.TryGetPropertyValue("$id", out var node) &&
+ (node is not JsonValue value || !value.TryGetValue(out var id) ||
+ !string.IsNullOrEmpty(id) && (!Uri.TryCreate(dialect, id, out var identifier) || identifier.Fragment.Length > 1));
+
+ private static bool IsAnchorName(string name)
+ {
+ for (var index = 0; index < name.Length; index++)
+ {
+ var character = name[index];
+ if (!(character is >= 'A' and <= 'Z' or >= 'a' and <= 'z' or '_' ||
+ index > 0 && character is >= '0' and <= '9' or '-' or '.'))
+ {
+ return false;
+ }
+ }
+
+ return name.Length > 0;
+ }
+
+ private static string GetDialectKey(Uri dialect)
+ {
+ var value = dialect.AbsoluteUri;
+ return value.EndsWith("#", StringComparison.Ordinal) ? value.Substring(0, value.Length - 1) : value;
+ }
+
+ private sealed class DialectUriEqualityComparer : IEqualityComparer
+ {
+ public bool Equals(Uri? x, Uri? y)
+ {
+ if (ReferenceEquals(x, y))
+ {
+ return true;
+ }
+
+ if (x is null || y is null)
+ {
+ return false;
+ }
+
+ return StringComparer.Ordinal.Equals(GetDialectKey(x), GetDialectKey(y));
+ }
+
+ public int GetHashCode(Uri obj)
+ {
+ return StringComparer.Ordinal.GetHashCode(GetDialectKey(obj));
+ }
+ }
+}
diff --git a/src/Microsoft.OpenApi/Reader/Services/JsonSchemaDialectService.cs b/src/Microsoft.OpenApi/Reader/Services/JsonSchemaDialectService.cs
new file mode 100644
index 000000000..a802944af
--- /dev/null
+++ b/src/Microsoft.OpenApi/Reader/Services/JsonSchemaDialectService.cs
@@ -0,0 +1,117 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+using System;
+using System.Collections.Generic;
+using System.Text.Json.Nodes;
+
+namespace Microsoft.OpenApi.Reader;
+
+///
+/// Selects the version service used to parse JSON Schema dialects.
+///
+internal sealed class JsonSchemaDialectService
+{
+ internal static readonly Uri OpenApiBaseDialect = new("https://spec.openapis.org/oas/3.1/dialect/base");
+ internal static readonly Uri JsonSchemaDraft202012 = new("https://json-schema.org/draft/2020-12/schema");
+
+ private readonly Uri? _documentDialect;
+ private readonly IOpenApiVersionService _fallbackVersionService;
+ private readonly OpenApiDiagnostic _diagnostic;
+ private readonly Dictionary _versionServices = new(StringComparer.Ordinal);
+ private readonly Dictionary _unsupportedDialects = new(StringComparer.Ordinal);
+ private readonly List<(Uri Dialect, OpenApiError Error)> _unsupportedDialectErrors = new();
+ private readonly HashSet _reportedDocumentDialects = new(StringComparer.Ordinal);
+ private readonly Stack _dialectScopes = new();
+
+ internal JsonSchemaDialectService(
+ IOpenApiVersionService versionService,
+ Uri? documentDialect,
+ OpenApiDiagnostic diagnostic)
+ {
+ _fallbackVersionService = versionService;
+ _documentDialect = documentDialect;
+ _diagnostic = diagnostic;
+
+ RegisterDialect(OpenApiBaseDialect, versionService);
+ RegisterDialect(JsonSchemaDraft202012, versionService);
+ }
+
+ internal IReadOnlyCollection UnsupportedDialects => _unsupportedDialects.Values;
+ internal IReadOnlyCollection<(Uri Dialect, OpenApiError Error)> UnsupportedDialectErrors => _unsupportedDialectErrors;
+ internal bool IsUsingFallback => _dialectScopes.Count > 0 &&
+ !_versionServices.ContainsKey(GetDialectKey(_dialectScopes.Peek()));
+
+ internal IOpenApiSchema LoadSchema(JsonNode node, OpenApiDocument hostDocument, ParsingContext context)
+ {
+ var declaredDialect = GetDeclaredDialect(node);
+ var inheritedDialect = _dialectScopes.Count > 0 ? _dialectScopes.Peek() : null;
+ var effectiveDialect = declaredDialect ?? inheritedDialect ?? _documentDialect ?? OpenApiBaseDialect;
+
+ if (!_versionServices.TryGetValue(GetDialectKey(effectiveDialect), out var versionService))
+ {
+ versionService = _fallbackVersionService;
+ _unsupportedDialects[GetDialectKey(effectiveDialect)] = effectiveDialect;
+
+ // Report the point where an unsupported dialect enters the schema tree. Descendants
+ // inherit that result and do not need to repeat the same diagnostic.
+ if (declaredDialect is not null)
+ {
+ AddUnsupportedDialectError(effectiveDialect, context.GetLocation());
+ }
+ else if (inheritedDialect is null && _documentDialect is not null &&
+ _reportedDocumentDialects.Add(GetDialectKey(effectiveDialect)))
+ {
+ AddUnsupportedDialectError(effectiveDialect, $"#/{OpenApiConstants.JsonSchemaDialect}");
+ }
+ }
+
+ _dialectScopes.Push(effectiveDialect);
+ try
+ {
+ return versionService.LoadSchema(node, hostDocument, context);
+ }
+ finally
+ {
+ _dialectScopes.Pop();
+ }
+ }
+
+ private void AddUnsupportedDialectError(Uri dialect, string pointer)
+ {
+ var error = new OpenApiError(pointer, $"The JSON Schema dialect '{dialect}' is not supported.");
+ _diagnostic.Errors.Add(error);
+ _unsupportedDialectErrors.Add((dialect, error));
+ }
+
+ internal static bool IsKnownDialect(Uri dialect)
+ {
+ var key = GetDialectKey(dialect);
+ return string.Equals(key, GetDialectKey(OpenApiBaseDialect), StringComparison.Ordinal) ||
+ string.Equals(key, GetDialectKey(JsonSchemaDraft202012), StringComparison.Ordinal);
+ }
+
+ private void RegisterDialect(Uri dialect, IOpenApiVersionService versionService)
+ {
+ _versionServices[GetDialectKey(dialect)] = versionService;
+ }
+
+ private static Uri? GetDeclaredDialect(JsonNode node)
+ {
+ if (node is not JsonObject jsonObject ||
+ !jsonObject.TryGetPropertyValue(OpenApiConstants.DollarSchema, out var dialectNode) ||
+ dialectNode is not JsonValue)
+ {
+ return null;
+ }
+
+ var value = dialectNode.GetScalarValue();
+ return Uri.TryCreate(value, UriKind.Absolute, out var dialect) ? dialect : null;
+ }
+
+ private static string GetDialectKey(Uri dialect)
+ {
+ var value = dialect.AbsoluteUri;
+ return value.EndsWith("#", StringComparison.Ordinal) ? value.Substring(0, value.Length - 1) : value;
+ }
+}
diff --git a/src/Microsoft.OpenApi/Reader/V31/OpenApiSchemaDeserializer.cs b/src/Microsoft.OpenApi/Reader/V31/OpenApiSchemaDeserializer.cs
index 52ca0912b..7c8a3fb3c 100644
--- a/src/Microsoft.OpenApi/Reader/V31/OpenApiSchemaDeserializer.cs
+++ b/src/Microsoft.OpenApi/Reader/V31/OpenApiSchemaDeserializer.cs
@@ -26,7 +26,7 @@ internal static partial class OpenApiV31Deserializer
},
{
"$id",
- (o, n, _, _) => o.Id = n.GetScalarValue()
+ (o, n, _, c) => o.Id = n.GetScalarValue(requireString: c.SchemaDialectService?.IsUsingFallback == true)
},
{
"$comment",
@@ -34,11 +34,12 @@ internal static partial class OpenApiV31Deserializer
},
{
"$vocabulary",
- (o, n, _, c) => o.Vocabulary = n.CreateSimpleMap(LoadBool, c).ToDictionary(kvp => kvp.Key, kvp => kvp.Value ?? false)
+ (o, n, _, c) => o.Vocabulary = n.CreateSimpleMap(LoadBool, c,
+ reportConversionErrors: c.SchemaDialectService?.IsUsingFallback == true).ToDictionary(kvp => kvp.Key, kvp => kvp.Value ?? false)
},
{
"$dynamicRef",
- (o, n, _, _) => o.DynamicRef = n.GetScalarValue()
+ (o, n, _, c) => o.DynamicRef = n.GetScalarValue(requireString: c.SchemaDialectService?.IsUsingFallback == true)
},
{
"$dynamicAnchor",
@@ -412,6 +413,12 @@ internal static partial class OpenApiV31Deserializer
};
public static IOpenApiSchema LoadSchema(JsonNode node, OpenApiDocument hostDocument, ParsingContext context)
+ {
+ return context.SchemaDialectService?.LoadSchema(node, hostDocument, context) ??
+ LoadSchemaCore(node, hostDocument, context);
+ }
+
+ internal static IOpenApiSchema LoadSchemaCore(JsonNode node, OpenApiDocument hostDocument, ParsingContext context)
{
// Handle boolean schemas (true/false) for JSON Schema 2020-12 compatibility
if (node is JsonValue jsonValue && jsonValue.TryGetValue(out var boolValue))
@@ -428,9 +435,10 @@ public static IOpenApiSchema LoadSchema(JsonNode node, OpenApiDocument hostDocum
var jsonObject = node.CheckMapNode(OpenApiConstants.Schema, context);
- var pointer = jsonObject.GetReferencePointer();
- var dynamicPointer = jsonObject.GetDynamicReferencePointer();
- var identifier = jsonObject.GetJsonSchemaIdentifier();
+ var preserveInvalidProperties = context.SchemaDialectService?.IsUsingFallback == true;
+ var pointer = jsonObject.GetReferencePointer(context, preserveInvalidProperties);
+ var dynamicPointer = jsonObject.GetDynamicReferencePointer(preserveInvalidProperties);
+ var identifier = jsonObject.GetJsonSchemaIdentifier(preserveInvalidProperties);
if (pointer != null)
{
@@ -446,7 +454,7 @@ public static IOpenApiSchema LoadSchema(JsonNode node, OpenApiDocument hostDocum
schema.UnrecognizedKeywords ??= new Dictionary(StringComparer.Ordinal);
schema.UnrecognizedKeywords[name] = value;
}
- });
+ }, preserveInvalidProperties: context.SchemaDialectService?.IsUsingFallback == true);
result.Reference.ApplySchemaMetadata(referenceMetadata, jsonObject);
result.Reference.SetJsonPointerPath(pointer, nodeLocation);
@@ -470,7 +478,7 @@ public static IOpenApiSchema LoadSchema(JsonNode node, OpenApiDocument hostDocum
schema.UnrecognizedKeywords ??= new Dictionary(StringComparer.Ordinal);
schema.UnrecognizedKeywords[name] = value;
}
- });
+ }, preserveInvalidProperties: context.SchemaDialectService?.IsUsingFallback == true);
result.Reference.ApplySchemaMetadata(referenceMetadata, jsonObject);
result.Reference.SetJsonPointerPath(dynamicPointer, nodeLocation);
return result;
@@ -483,7 +491,7 @@ public static IOpenApiSchema LoadSchema(JsonNode node, OpenApiDocument hostDocum
{
schema.UnrecognizedKeywords ??= new Dictionary(StringComparer.Ordinal);
schema.UnrecognizedKeywords[name] = value;
- });
+ }, preserveInvalidProperties: context.SchemaDialectService?.IsUsingFallback == true);
if (!string.IsNullOrEmpty(identifier) && hostDocument.Workspace is not null)
{
diff --git a/src/Microsoft.OpenApi/Reader/V31/OpenApiV31VersionService.cs b/src/Microsoft.OpenApi/Reader/V31/OpenApiV31VersionService.cs
index 8bd6530f6..faa597d33 100644
--- a/src/Microsoft.OpenApi/Reader/V31/OpenApiV31VersionService.cs
+++ b/src/Microsoft.OpenApi/Reader/V31/OpenApiV31VersionService.cs
@@ -60,6 +60,12 @@ public override OpenApiDocument LoadDocument(JsonNode jsonNode, Uri location, Pa
{
return OpenApiV31Deserializer.LoadOpenApi(jsonNode, location, context);
}
+
+ public override IOpenApiSchema LoadSchema(JsonNode node, OpenApiDocument doc, ParsingContext context)
+ {
+ return OpenApiV31Deserializer.LoadSchemaCore(node, doc, context);
+ }
+
internal override Dictionary> Loaders => _loaders;
}
diff --git a/src/Microsoft.OpenApi/Reader/V32/OpenApiSchemaDeserializer.cs b/src/Microsoft.OpenApi/Reader/V32/OpenApiSchemaDeserializer.cs
index b038fa6e5..796eea00c 100644
--- a/src/Microsoft.OpenApi/Reader/V32/OpenApiSchemaDeserializer.cs
+++ b/src/Microsoft.OpenApi/Reader/V32/OpenApiSchemaDeserializer.cs
@@ -26,7 +26,7 @@ internal static partial class OpenApiV32Deserializer
},
{
"$id",
- (o, n, _, _) => o.Id = n.GetScalarValue()
+ (o, n, _, c) => o.Id = n.GetScalarValue(requireString: c.SchemaDialectService?.IsUsingFallback == true)
},
{
"$comment",
@@ -34,11 +34,12 @@ internal static partial class OpenApiV32Deserializer
},
{
"$vocabulary",
- (o, n, _, c) => o.Vocabulary = n.CreateSimpleMap(LoadBool, c).ToDictionary(kvp => kvp.Key, kvp => kvp.Value ?? false)
+ (o, n, _, c) => o.Vocabulary = n.CreateSimpleMap(LoadBool, c,
+ reportConversionErrors: c.SchemaDialectService?.IsUsingFallback == true).ToDictionary(kvp => kvp.Key, kvp => kvp.Value ?? false)
},
{
"$dynamicRef",
- (o, n, _, _) => o.DynamicRef = n.GetScalarValue()
+ (o, n, _, c) => o.DynamicRef = n.GetScalarValue(requireString: c.SchemaDialectService?.IsUsingFallback == true)
},
{
"$dynamicAnchor",
@@ -412,6 +413,12 @@ internal static partial class OpenApiV32Deserializer
};
public static IOpenApiSchema LoadSchema(JsonNode node, OpenApiDocument hostDocument, ParsingContext context)
+ {
+ return context.SchemaDialectService?.LoadSchema(node, hostDocument, context) ??
+ LoadSchemaCore(node, hostDocument, context);
+ }
+
+ internal static IOpenApiSchema LoadSchemaCore(JsonNode node, OpenApiDocument hostDocument, ParsingContext context)
{
// Handle boolean schemas (true/false) for JSON Schema 2020-12 compatibility
if (node is JsonValue jsonValue && jsonValue.TryGetValue(out var boolValue))
@@ -428,9 +435,10 @@ public static IOpenApiSchema LoadSchema(JsonNode node, OpenApiDocument hostDocum
var jsonObject = node.CheckMapNode(OpenApiConstants.Schema, context);
- var pointer = jsonObject.GetReferencePointer();
- var dynamicPointer = jsonObject.GetDynamicReferencePointer();
- var identifier = jsonObject.GetJsonSchemaIdentifier();
+ var preserveInvalidProperties = context.SchemaDialectService?.IsUsingFallback == true;
+ var pointer = jsonObject.GetReferencePointer(context, preserveInvalidProperties);
+ var dynamicPointer = jsonObject.GetDynamicReferencePointer(preserveInvalidProperties);
+ var identifier = jsonObject.GetJsonSchemaIdentifier(preserveInvalidProperties);
if (pointer != null)
{
@@ -446,7 +454,7 @@ public static IOpenApiSchema LoadSchema(JsonNode node, OpenApiDocument hostDocum
schema.UnrecognizedKeywords ??= new Dictionary(StringComparer.Ordinal);
schema.UnrecognizedKeywords[name] = value;
}
- });
+ }, preserveInvalidProperties: context.SchemaDialectService?.IsUsingFallback == true);
result.Reference.ApplySchemaMetadata(referenceMetadata, jsonObject);
result.Reference.SetJsonPointerPath(pointer, nodeLocation);
@@ -470,7 +478,7 @@ public static IOpenApiSchema LoadSchema(JsonNode node, OpenApiDocument hostDocum
schema.UnrecognizedKeywords ??= new Dictionary(StringComparer.Ordinal);
schema.UnrecognizedKeywords[name] = value;
}
- });
+ }, preserveInvalidProperties: context.SchemaDialectService?.IsUsingFallback == true);
result.Reference.ApplySchemaMetadata(referenceMetadata, jsonObject);
result.Reference.SetJsonPointerPath(dynamicPointer, nodeLocation);
return result;
@@ -483,7 +491,7 @@ public static IOpenApiSchema LoadSchema(JsonNode node, OpenApiDocument hostDocum
{
schema.UnrecognizedKeywords ??= new Dictionary(StringComparer.Ordinal);
schema.UnrecognizedKeywords[name] = value;
- });
+ }, preserveInvalidProperties: context.SchemaDialectService?.IsUsingFallback == true);
if (!string.IsNullOrEmpty(identifier) && hostDocument.Workspace is not null)
{
diff --git a/src/Microsoft.OpenApi/Reader/V32/OpenApiV32VersionService.cs b/src/Microsoft.OpenApi/Reader/V32/OpenApiV32VersionService.cs
index 35a869a3a..2ba6ed1b0 100644
--- a/src/Microsoft.OpenApi/Reader/V32/OpenApiV32VersionService.cs
+++ b/src/Microsoft.OpenApi/Reader/V32/OpenApiV32VersionService.cs
@@ -60,8 +60,13 @@ public override OpenApiDocument LoadDocument(JsonNode jsonNode, Uri location, Pa
{
return OpenApiV32Deserializer.LoadOpenApi(jsonNode, location, context);
}
+
+ public override IOpenApiSchema LoadSchema(JsonNode node, OpenApiDocument doc, ParsingContext context)
+ {
+ return OpenApiV32Deserializer.LoadSchemaCore(node, doc, context);
+ }
+
internal override Dictionary> Loaders => _loaders;
}
}
-
diff --git a/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/JsonSchemaDialectArrayLocationRegressionTests.cs b/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/JsonSchemaDialectArrayLocationRegressionTests.cs
new file mode 100644
index 000000000..a6317589d
--- /dev/null
+++ b/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/JsonSchemaDialectArrayLocationRegressionTests.cs
@@ -0,0 +1,297 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Microsoft.OpenApi.Reader;
+using Xunit;
+
+namespace Microsoft.OpenApi.Readers.Tests.OpenApiReaderTests;
+
+public class JsonSchemaDialectArrayLocationRegressionTests
+{
+ private const string UnsupportedDialect = "https://example.com/custom-dialect";
+ private const string KnownDialect = "https://json-schema.org/draft/2020-12/schema";
+ private const string ItemPointer = "#/components/schemas/Item";
+
+ public static IEnumerable