Skip to content
Open
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
14 changes: 12 additions & 2 deletions src/Microsoft.OpenApi/Services/OpenApiVisitorBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Text.Json.Nodes;
Expand All @@ -27,7 +28,16 @@ public abstract class OpenApiVisitorBase
/// <param name="segment">Identifier for context</param>
public virtual void Enter(string segment)
{
this._path.Push(segment);
if (string.IsNullOrEmpty(segment))
{
this._path.Push(string.Empty);
return;
}
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP1_0_OR_GREATER
this._path.Push(segment.Replace("~", "~0", StringComparison.Ordinal).Replace("/", "~1", StringComparison.OrdinalIgnoreCase));
#else
this._path.Push(segment.Replace("~", "~0").Replace("/", "~1"));
#endif
}

/// <summary>
Expand All @@ -41,7 +51,7 @@ public virtual void Exit()
/// <summary>
/// Pointer to source of validation error in document
/// </summary>
public string PathString { get => "#/" + String.Join("/", _path.Reverse()); }
public string PathString { get => "#/" + string.Join("/", _path.Reverse()); }

/// <summary>
/// Visits <see cref="OpenApiDocument"/>
Expand Down
15 changes: 3 additions & 12 deletions src/Microsoft.OpenApi/Services/OpenApiWalker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -485,7 +485,7 @@

_visitor.Visit(pathItem);

if (pathItem != null)

Check warning on line 488 in src/Microsoft.OpenApi/Services/OpenApiWalker.cs

View workflow job for this annotation

GitHub Actions / Build

Change this condition so that it does not always evaluate to 'True'.

Check warning on line 488 in src/Microsoft.OpenApi/Services/OpenApiWalker.cs

View workflow job for this annotation

GitHub Actions / Build

Change this condition so that it does not always evaluate to 'True'.

Check warning on line 488 in src/Microsoft.OpenApi/Services/OpenApiWalker.cs

View workflow job for this annotation

GitHub Actions / Build

Change this condition so that it does not always evaluate to 'True'.
{
if (pathItem.Parameters is { } parameters)
{
Expand Down Expand Up @@ -835,7 +835,7 @@
/// <summary>
/// Visits <see cref="IOpenApiMediaType"/> and child objects
/// </summary>
internal void Walk(IOpenApiMediaType mediaType, bool isComponent = false)

Check warning on line 838 in src/Microsoft.OpenApi/Services/OpenApiWalker.cs

View workflow job for this annotation

GitHub Actions / Build

This method signature overlaps the one defined on line 811, the default parameter value can't be used.

Check warning on line 838 in src/Microsoft.OpenApi/Services/OpenApiWalker.cs

View workflow job for this annotation

GitHub Actions / Build

This method signature overlaps the one defined on line 811, the default parameter value can't be used.

Check warning on line 838 in src/Microsoft.OpenApi/Services/OpenApiWalker.cs

View workflow job for this annotation

GitHub Actions / Build

This method signature overlaps the one defined on line 811, the default parameter value can't be used.
{
if (mediaType == null)
{
Expand Down Expand Up @@ -1297,15 +1297,6 @@
}
}

private static string ReplaceSlashes(string value)
{
#if NET8_0_OR_GREATER
return value.Replace("/", "~1", StringComparison.Ordinal);
#else
return value.Replace("/", "~1");
#endif
}

/// <summary>
/// Adds a segment to the context path to enable pointing to the current location in the document
/// </summary>
Expand All @@ -1315,7 +1306,7 @@
/// <param name="walk">An action that walks objects within the context.</param>
private void WalkItem<T>(string context, T state, Action<OpenApiWalker, T> walk)
{
_visitor.Enter(ReplaceSlashes(context));
_visitor.Enter(context);
walk(this, state);
_visitor.Exit();
}
Expand All @@ -1330,7 +1321,7 @@
/// <param name="walk">An action that walks objects within the context.</param>
private void WalkItem<T>(string context, T state, Action<OpenApiWalker, T, bool> walk, bool isComponent)
{
_visitor.Enter(ReplaceSlashes(context));
_visitor.Enter(context);
walk(this, state, isComponent);
_visitor.Exit();
}
Expand All @@ -1351,7 +1342,7 @@
{
if (state != null && state.Count > 0)
{
_visitor.Enter(ReplaceSlashes(context));
_visitor.Enter(context);

foreach (var item in state)
{
Expand Down
43 changes: 33 additions & 10 deletions src/Microsoft.OpenApi/Validations/Rules/OpenApiDocumentRules.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
// Licensed under the MIT license.

using System;
using System.Collections.Generic;
using System.Linq;

namespace Microsoft.OpenApi
{
Expand Down Expand Up @@ -74,28 +76,49 @@ private void ValidateSchemaReference(OpenApiSchemaReference reference)
{
if (reference.RecursiveTarget is null)
{
var segments = GetSegments().ToArray();
EnterSegments(segments);
// The reference was not followed to a valid schema somewhere in the document
context.Enter(GetSegment());
context.CreateWarning(ruleName, string.Format(SRResource.Validation_SchemaReferenceDoesNotExist, reference.Reference.ReferenceV3));
context.Exit();
ExitSegments(segments.Length);
}
}
catch (InvalidOperationException ex)
{
context.Enter(GetSegment());
var segments = GetSegments().ToArray();
EnterSegments(segments);
context.CreateWarning(ruleName, ex.Message);
context.Exit();
ExitSegments(segments.Length);
}

string GetSegment()
void ExitSegments(int length)
{
// Trim off the leading "#/" as the context is already at the root of the document
return
#if NET8_0_OR_GREATER
$"{PathString[2..]}/$ref";
for (var i = 0; i < length; i++)
{
context.Exit();
}
}

void EnterSegments(string[] segments)
{
foreach (var segment in segments)
{
context.Enter(segment);
}
}

IEnumerable<string> GetSegments()
{
foreach (var segment in this.PathString.Substring(2).Split('/'))
{
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP1_0_OR_GREATER
yield return segment.Replace("~1", "/", StringComparison.OrdinalIgnoreCase).Replace("~0", "~", StringComparison.OrdinalIgnoreCase);
#else
PathString.Substring(2) + "/$ref";
yield return segment.Replace("~1", "/").Replace("~0", "~");
#endif
}
yield return "$ref";
// Trim off the leading "#/" as the context is already at the root of the document
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
using System.Collections.Generic;
using Xunit;

namespace Microsoft.OpenApi.Tests.Services;

public class OpenApiVisitorBaseTests
{
[Fact]
public void EncodesReservedCharacters()
{
// Given
var openApiDocument = new OpenApiDocument
{
Info = new()
{
Title = "foo",
Version = "1.2.2"
},
Paths = new()
{
},
Components = new()
{
Schemas = new Dictionary<string, IOpenApiSchema>()
{
["Pet~"] = new OpenApiSchema()
{
Type = JsonSchemaType.Object
},
["Pet/"] = new OpenApiSchema()
{
Type = JsonSchemaType.Object
},
}
}
};
var visitor = new LocatorVisitor();

// When
visitor.Visit(openApiDocument);

// Then
Assert.Equivalent(
new List<string>
{
"#/components/schemas/Pet~0",
"#/components/schemas/Pet~1"
}, visitor.Locations);
}

private class LocatorVisitor : OpenApiVisitorBase
{
public List<string> Locations { get; } = new List<string>();

public override void Visit(IOpenApiSchema openApiSchema)
{
Locations.Add(this.PathString);
}
public override void Visit(OpenApiComponents components)
{
Enter("schemas");
if (components.Schemas != null)
{
foreach (var schemaKvp in components.Schemas)
{
Enter(schemaKvp.Key);
this.Visit(schemaKvp.Value);
Exit();
}
}
Exit();
}
public override void Visit(OpenApiDocument doc)
{
Enter("components");
Visit(doc.Components);
Exit();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ public static void GetOperationWithRequestBodyIsInvalid()
Assert.NotNull(warnings);
var warning = Assert.Single(warnings);
Assert.Equal("GET operations should not have a request body.", warning.Message);
Assert.Equal("#/paths//people/get/requestBody", warning.Pointer);
Assert.Equal("#/paths/~1people/get/requestBody", warning.Pointer);
}

[Fact]
Expand Down
Loading