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
8 changes: 8 additions & 0 deletions VERSIONHISTORY.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
# Version History

## V5.8.5

V5.8.5 fixes how V4 code generation finds a `$dynamicAnchor` when a `$ref` pointer reaches into an embedded resource.

### Bug fixes

- **In V4, a `$ref` whose pointer reaches into an embedded resource enters only that resource.** A reference such as `"$ref": "bar#/$defs/item"`, where `item` has its own `$id`, lands in the `item` resource. The generator put `bar` into the dynamic scope as well, so a `$dynamicRef` inside `item` could resolve to a `$dynamicAnchor` that only `bar` declares, and validate against the wrong schema. The scope now holds the resource the reference lands in, as the specification and V5 require. The JSON-Schema-Test-Suite's optional draft 2020-12 test "$dynamicRef skips over intermediate resources - pointer reference across resource boundary", which V4 excluded with both answers wrong, now runs and passes.

## V5.8.4

V5.8.4 is the first release published to NuGet.org since V5.8.0, and it publishes with NuGet.org Trusted Publishing. V5.8.1, V5.8.2 and V5.8.3 were tagged, and have GitHub releases, but their packages were never published to NuGet.org: the API key the release build used had expired, so each tag build's push was refused. Those versions are skipped on NuGet.org. V5.8.4 has no changes of its own beyond how it is published, so it ships everything in the three, which are listed below:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ await typeBuilderContext.SchemaRegistry.ResolveBaseReference(
return;
}

baseSchemaForReference = GetResourceSchema(typeBuilderContext.SchemaRegistry, baseSchemaForReferenceLocation, baseSchemaForReference);
typeBuilderContext.EnterReferenceScope(baseSchemaForReferenceLocation, baseSchemaForReference, schemaForRefPointer);
TypeDeclaration subschemaTypeDeclaration = await typeBuilderContext.BuildTypeDeclarationForCurrentScope(cancellationToken);

Expand Down Expand Up @@ -219,6 +220,7 @@ await typeBuilderContext.SchemaRegistry.ResolveBaseReference(
return;
}

baseSchemaForReference = GetResourceSchema(typeBuilderContext.SchemaRegistry, baseSchemaForReferenceLocation, baseSchemaForReference);
typeBuilderContext.EnterReferenceScope(baseSchemaForReferenceLocation, baseSchemaForReference, schemaForRefPointer);
TypeDeclaration subschemaTypeDeclaration = await typeBuilderContext.BuildTypeDeclarationForCurrentScope(cancellationToken);

Expand Down Expand Up @@ -309,6 +311,7 @@ await typeBuilderContext.SchemaRegistry.ResolveBaseReference(
return;
}

baseSchemaForReference = GetResourceSchema(typeBuilderContext.SchemaRegistry, baseSchemaForReferenceLocation, baseSchemaForReference);
typeBuilderContext.EnterReferenceScope(baseSchemaForReferenceLocation, baseSchemaForReference, schemaForRefPointer);
TypeDeclaration subschemaTypeDeclaration = await typeBuilderContext.BuildTypeDeclarationForCurrentScope(cancellationToken);

Expand Down Expand Up @@ -344,7 +347,9 @@ public static (JsonReference Location, JsonReference Pointer) GetPointerForRefer
// If we've already located it, this must be the thing.
if (schemaRegistry.TryGetLocatedSchema(new JsonReference(baseSchemaForReferenceLocation.Uri, reference.Fragment), out _))
{
schemaForRefPointer = new JsonReference([], reference.Fragment);
// The pointer may cross into an embedded resource (a subschema with its own id). The reference
// then lands in that resource, not in the one the pointer started from, so re-base on it.
return RebaseOnInnermostResource(schemaRegistry, baseSchemaForReferenceLocation, reference.Fragment);
}
else
{
Expand Down Expand Up @@ -473,6 +478,86 @@ public static Dictionary<string, TKeyword> For(IVocabulary vocabulary)
}
}

/// <summary>
/// Gets the located schema of the resource at a base location, so that the scope a reference enters is the
/// resource the reference landed in, and not the resource it was resolved from.
/// </summary>
/// <param name="schemaRegistry">The schema registry.</param>
/// <param name="resourceLocation">The location of the resource.</param>
/// <param name="fallback">The located schema to use if no schema is registered at the location.</param>
/// <returns>The located schema for the resource.</returns>
/// <remarks>
/// The dynamic scope is the list of resources entered during evaluation. If a reference such as
/// <c>bar#/$defs/item</c> lands in an embedded resource (<c>item</c>), <c>bar</c> must not be in the
/// dynamic scope, or a <c>$dynamicRef</c> would find <c>bar</c>'s dynamic anchors.
/// </remarks>
private static LocatedSchema GetResourceSchema(JsonSchemaRegistry schemaRegistry, JsonReference resourceLocation, LocatedSchema fallback)
{
if (fallback.Location == resourceLocation)
{
return fallback;
}

return schemaRegistry.TryGetLocatedSchema(resourceLocation, out LocatedSchema? resourceSchema)
? resourceSchema
: fallback;
}

/// <summary>
/// Re-bases a pointer that has already been located on the innermost resource it passes through.
/// </summary>
/// <param name="schemaRegistry">The schema registry.</param>
/// <param name="baseSchemaForReferenceLocation">The location of the resource the pointer starts from.</param>
/// <param name="fragment">The pointer fragment, with its leading <c>#</c>.</param>
/// <returns>The location of the innermost resource and the pointer relative to it; or the inputs unchanged if
/// the pointer does not pass through an embedded resource.</returns>
private static (JsonReference Location, JsonReference Pointer) RebaseOnInnermostResource(
JsonSchemaRegistry schemaRegistry,
JsonReference baseSchemaForReferenceLocation,
ReadOnlySpan<char> fragment)
{
JsonReference unchangedPointer = new([], fragment);
JsonReference resourceLocation = baseSchemaForReferenceLocation;
string[] segments = fragment.ToString().Split('/');
var currentBuilder = new StringBuilder();
bool found = false;
bool rebased = false;
foreach (string segment in segments)
{
if (currentBuilder.Length > 0)
{
currentBuilder.Append('/');
}

// The segments are still pointer-encoded, which is how the registry keys its locations.
currentBuilder.Append(segment);
found = schemaRegistry.TryGetLocatedSchema(resourceLocation.WithFragment(currentBuilder.ToString()), out LocatedSchema? locatedSchema);
if (found &&
currentBuilder.Length > 1 &&
Scope.ShouldEnterScope(locatedSchema!.Schema, locatedSchema.Vocabulary, out string? scopeName))
{
JsonReference scopeLocation = resourceLocation.Apply(new JsonReference(scopeName));
if (scopeLocation.HasFragment)
{
// A plain-name scope (an anchor-style id) does not start a new resource.
continue;
}

resourceLocation = scopeLocation;
currentBuilder.Clear();
currentBuilder.Append('#');
rebased = true;
}
}

if (!rebased || !found)
{
return (baseSchemaForReferenceLocation, unchangedPointer);
}

return (resourceLocation, new JsonReference(currentBuilder.ToString()));
}

private static bool TryResolvePointer(
JsonSchemaRegistry schemaRegistry,
JsonReference baseSchemaForReferenceLocation,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
// <auto-generated/>
#nullable enable

using System.Text.Json;
using Corvus.Json;
using Corvus.Json.Specs.Tests.Infrastructure;
using Drivers;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace JsonSchemaTestSuite.Draft202012.Optional.DynamicRef;

[TestCategory("Draft202012")]
[TestClass]
public class SuiteDynamicRefSkipsOverIntermediateResourcesPointerReferenceAcrossResourceBoundary
{
private static Fixture? s_fixture;

[ClassInitialize]
public static async Task ClassInit(TestContext _)
{
s_fixture = new Fixture();
await s_fixture.InitializeAsync();
}

[ClassCleanup]
public static void ClassCleanupMethod()
{
if (s_fixture is not null)
{
s_fixture.Dispose();
s_fixture = null;
}
}

[TestMethod]
public void TestIntegerPropertyPasses()
{
using var doc = JsonDocument.Parse("{ \"bar-item\": { \"content\": 42 } }");
IJsonValue instance = JsonSchemaBuilderDriver.CreateInstance(s_fixture!.GeneratedType, doc.RootElement);
Assert.IsTrue(instance.Validate(ValidationContext.ValidContext).IsValid);
}

[TestMethod]
public void TestStringPropertyFails()
{
using var doc = JsonDocument.Parse("{ \"bar-item\": { \"content\": \"value\" } }");
IJsonValue instance = JsonSchemaBuilderDriver.CreateInstance(s_fixture!.GeneratedType, doc.RootElement);
Assert.IsFalse(instance.Validate(ValidationContext.ValidContext).IsValid);
}

public class Fixture : IDisposable
{
private JsonSchemaBuilderDriver? _driver;

public global::System.Type GeneratedType { get; private set; } = null!;

public async Task InitializeAsync()
{
_driver = DriverFactory.CreateDraft202012Driver();
GeneratedType = await _driver.GenerateTypeForJsonSchemaTestSuite(
"optional/dynamicRef.json",
"#/0/schema",
"JsonSchemaTestSuiteDraft202012OptionalDynamicRef",
"DynamicRefSkipsOverIntermediateResourcesPointerReferenceAcrossResourceBoundary",
validateFormat: false,
optionalAsNullable: false,
useImplicitOperatorString: false);
}

public void Dispose()
{
_driver?.Dispose();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,11 @@ public static IEnumerable<TestGroup> ProvideTestGroups()

string json = File.ReadAllText(file);
using JsonDocument doc = JsonDocument.Parse(json);
if (doc.RootElement.ValueKind != JsonValueKind.Array)
{
// Not a test file: a schema that other tests load by path (e.g. issue957-swagger.json).
continue;
}

int suiteIndex = 0;
foreach (JsonElement testSuiteElement in doc.RootElement.EnumerateArray())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -267,15 +267,6 @@
}
]
},
{
"file": "optional/dynamicRef.json",
"suites": [
{
"name": "$dynamicRef skips over intermediate resources - pointer reference across resource boundary",
"reason": "V4 engine limitation with dynamic-ref."
}
]
},
{
"file": "optional/format/time.json",
"suites": [
Expand Down
Loading