Skip to content

fix: Improve handling of OpenAPI tag references #2325

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 15, 2025
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
23 changes: 20 additions & 3 deletions src/Microsoft.OpenApi/Models/OpenApiOperation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.OpenApi.Exceptions;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Models.Interfaces;
using Microsoft.OpenApi.Models.References;
Expand Down Expand Up @@ -86,7 +87,7 @@
/// <summary>
/// REQUIRED. The list of possible responses as they are returned from executing this operation.
/// </summary>
public OpenApiResponses? Responses { get; set; } = new();
public OpenApiResponses? Responses { get; set; } = [];

/// <summary>
/// A map of possible out-of band callbacks related to the parent operation.
Expand Down Expand Up @@ -182,7 +183,7 @@
// tags
writer.WriteOptionalCollection(
OpenApiConstants.Tags,
Tags,
VerifyTagReferences(Tags),
callback);

// summary
Expand Down Expand Up @@ -236,7 +237,7 @@
// tags
writer.WriteOptionalCollection(
OpenApiConstants.Tags,
Tags,
VerifyTagReferences(Tags),
(w, t) => t.SerializeAsV2(w));

// summary
Expand Down Expand Up @@ -355,5 +356,21 @@

writer.WriteEndObject();
}

private static HashSet<OpenApiTagReference>? VerifyTagReferences(HashSet<OpenApiTagReference>? tags)
{
if (tags?.Count > 0)
{
foreach (var tag in tags)
{
if (tag.Target is null)
{
throw new OpenApiException($"The OpenAPI tag reference '{tag.Reference.Id}' does reference a valid tag.");
}
}
Comment on lines +364 to +370

Check notice

Code scanning / CodeQL

Missed opportunity to use Where Note

This foreach loop
implicitly filters its target sequence
- consider filtering the sequence explicitly using '.Where(...)'.
}

return tags;
}
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.OpenApi.Interfaces;
Expand Down
15 changes: 14 additions & 1 deletion src/Microsoft.OpenApi/OpenApiTagComparer.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using Microsoft.OpenApi.Models.Interfaces;
using Microsoft.OpenApi.Models.References;

namespace Microsoft.OpenApi;

Expand Down Expand Up @@ -31,6 +32,10 @@ public bool Equals(IOpenApiTag? x, IOpenApiTag? y)
{
return true;
}
if (x is OpenApiTagReference referenceX && y is OpenApiTagReference referenceY)
{
return StringComparer.Equals(referenceX.Name ?? referenceX.Reference.Id, referenceY.Name ?? referenceY.Reference.Id);
}
return StringComparer.Equals(x.Name, y.Name);
}

Expand All @@ -41,5 +46,13 @@ public bool Equals(IOpenApiTag? x, IOpenApiTag? y)
internal static readonly StringComparer StringComparer = StringComparer.Ordinal;

/// <inheritdoc/>
public int GetHashCode(IOpenApiTag obj) => string.IsNullOrEmpty(obj?.Name) ? 0 : StringComparer.GetHashCode(obj!.Name);
public int GetHashCode(IOpenApiTag obj)
{
string? value = obj?.Name;
if (value is null && obj is OpenApiTagReference reference)
{
value = reference.Reference.Id;
}
return string.IsNullOrEmpty(value) ? 0 : StringComparer.GetHashCode(value);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ public async Task CopiesOverAllReferencedComponentsToTheSubsetDocumentCorrectly(
var openApiOperationTags = doc?.Paths["/items"].Operations?[HttpMethod.Get].Tags?.ToArray();
Assert.NotNull(openApiOperationTags);
Assert.Single(openApiOperationTags);
Assert.True(openApiOperationTags[0].UnresolvedReference);
Assert.NotNull(openApiOperationTags[0].Target);

var predicate = OpenApiFilterService.CreatePredicate(operationIds: operationIds);
if (doc is not null)
Expand All @@ -271,7 +271,7 @@ public async Task CopiesOverAllReferencedComponentsToTheSubsetDocumentCorrectly(
var trimmedOpenApiOperationTags = subsetOpenApiDocument.Paths?["/items"].Operations?[HttpMethod.Get].Tags?.ToArray();
Assert.NotNull(trimmedOpenApiOperationTags);
Assert.Single(trimmedOpenApiOperationTags);
Assert.True(trimmedOpenApiOperationTags[0].UnresolvedReference);
Assert.NotNull(trimmedOpenApiOperationTags[0].Target);

// Finally try to write the trimmed document as v3 document
var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture);
Expand Down Expand Up @@ -302,7 +302,8 @@ public void ReturnsPathParametersOnSlicingBasedOnOperationIdsOrTags(string? oper
// Assert
foreach (var pathItem in subsetOpenApiDocument.Paths)
{
Assert.True(pathItem.Value.Parameters!.Count != 0);
Assert.NotNull(pathItem.Value.Parameters);
Assert.NotEmpty(pathItem.Value.Parameters);
Assert.Single(pathItem.Value.Parameters!);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,3 +81,5 @@ components:
value:
name: "New Item"

tags:
- name: list.items
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,8 @@ components:
in: header
security:
- api_key: [ ]
tags:
- name: pets
webhooks:
newPetAlert:
post:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,5 +122,8 @@ components:
ExtraInfo:
type: string

tags:
- name: pets

security:
- api_key: []
30 changes: 30 additions & 0 deletions test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Collections.Generic;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
using Microsoft.OpenApi.Exceptions;
using Microsoft.OpenApi.Extensions;
using Microsoft.OpenApi.Models;
using Microsoft.OpenApi.Models.Interfaces;
Expand Down Expand Up @@ -859,5 +860,34 @@ public void OpenApiOperationCopyConstructorWithAnnotationsSucceeds()

Assert.NotEqual(baseOperation.Metadata["key1"], actualOperation.Metadata["key1"]);
}

[Theory]
[InlineData(OpenApiSpecVersion.OpenApi2_0)]
[InlineData(OpenApiSpecVersion.OpenApi3_0)]
[InlineData(OpenApiSpecVersion.OpenApi3_1)]
public async Task SerializeAsJsonAsyncThrowsIfTagReferenceIsUnresolved(OpenApiSpecVersion version)
{
var document = new OpenApiDocument()
{
Tags =
[
new() { Name = "one" },
new() { Name = "three" }
]
};

var operation = new OpenApiOperation()
{
Tags =
[
new OpenApiTagReference("one", document),
new OpenApiTagReference("two", document),
new OpenApiTagReference("three", document)
]
};

var exception = await Assert.ThrowsAsync<OpenApiException>(() => operation.SerializeAsJsonAsync(version));
Assert.Equal("The OpenAPI tag reference 'two' does reference a valid tag.", exception.Message);
}
}
}
114 changes: 114 additions & 0 deletions test/Microsoft.OpenApi.Tests/OpenApiTagComparerTests.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.OpenApi.Models;
using Microsoft.OpenApi.Models.References;
using Xunit;

namespace Microsoft.OpenApi.Tests;

public class OpenApiTagComparerTests
{
private readonly OpenApiTagComparer _comparer = OpenApiTagComparer.Instance;

[Fact]
public void Defensive()
{
Expand All @@ -16,13 +20,15 @@ public void Defensive()
Assert.Equal(0, _comparer.GetHashCode(null));
Assert.Equal(0, _comparer.GetHashCode(new OpenApiTag()));
}

[Fact]
public void SameNamesAreEqual()
{
var openApiTag1 = new OpenApiTag { Name = "tag" };
var openApiTag2 = new OpenApiTag { Name = "tag" };
Assert.True(_comparer.Equals(openApiTag1, openApiTag2));
}

[Fact]
public void SameInstanceAreEqual()
{
Expand All @@ -37,4 +43,112 @@ public void DifferentCasingAreNotEquals()
var openApiTag2 = new OpenApiTag { Name = "TAG" };
Assert.False(_comparer.Equals(openApiTag1, openApiTag2));
}

[Fact]
public void WorksCorrectlyWithHashSetOfTags()
{
var tags = new HashSet<OpenApiTag>(_comparer)
{
new() { Name = "one" },
new() { Name = "two" },
new() { Name = "two" },
new() { Name = "three" }
};

Assert.Equal(["one", "two", "three"], [.. tags.Select(t => t.Name)]);
}

[Fact]
public void SameReferenceInstanceAreEqual()
{
var openApiTag = new OpenApiTagReference("tag");
Assert.True(_comparer.Equals(openApiTag, openApiTag));
}

[Fact]
public void SameReferenceIdsAreEqual()
{
var openApiTag1 = new OpenApiTagReference("tag");
var openApiTag2 = new OpenApiTagReference("tag");
Assert.True(_comparer.Equals(openApiTag1, openApiTag2));
}

[Fact]
public void SameReferenceIdAreEqualWithValidTagReferences()
{
var document = new OpenApiDocument
{
Tags = [new() { Name = "tag" }]
};

var openApiTag1 = new OpenApiTagReference("tag", document);
var openApiTag2 = new OpenApiTagReference("tag", document);
Assert.True(_comparer.Equals(openApiTag1, openApiTag2));
}

[Fact]
public void DifferentReferenceIdAreNotEqualWithValidTagReferences()
{
var document = new OpenApiDocument
{
Tags =
[
new() { Name = "one" },
new() { Name = "two" },
]
};

var openApiTag1 = new OpenApiTagReference("one", document);
var openApiTag2 = new OpenApiTagReference("two", document);
Assert.False(_comparer.Equals(openApiTag1, openApiTag2));
}

[Fact]
public void DifferentCasingReferenceIdsAreNotEqual()
{
var openApiTag1 = new OpenApiTagReference("tag");
var openApiTag2 = new OpenApiTagReference("TAG");
Assert.False(_comparer.Equals(openApiTag1, openApiTag2));
}

[Fact] // See https://github.com/microsoft/OpenAPI.NET/issues/2319
public void WorksCorrectlyWithHashSetOfReferences()
{
// The document intentionally does not contain the actual tags
var document = new OpenApiDocument();

var tags = new HashSet<OpenApiTagReference>(_comparer)
{
new("one", document),
new("two", document),
new("two", document),
new("three", document)
};

Assert.Equal(["one", "two", "three"], [..tags.Select(t => t.Reference.Id)]);
}

[Fact]
public void WorksCorrectlyWithHashSetOfReferencesToValidTags()
{
var document = new OpenApiDocument
{
Tags =
[
new() { Name = "one" },
new() { Name = "two" },
new() { Name = "three" }
]
};

var tags = new HashSet<OpenApiTagReference>(_comparer)
{
new("one", document),
new("two", document),
new("two", document),
new("three", document)
};

Assert.Equal(["one", "two", "three"], [.. tags.Select(t => t.Reference.Id)]);
}
}