Skip to content
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

Add an analyzer to prevent use of some internal shared source types #6642

Merged
merged 20 commits into from
Aug 11, 2023
Merged
Show file tree
Hide file tree
Changes from 10 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System.Collections.Generic;
using System.Threading.Tasks;
using Xunit;
using Verifier = Azure.ClientSdk.Analyzers.Tests.AzureAnalyzerVerifier<Azure.ClientSdk.Analyzers.BannedTypesAnalyzer>;

namespace Azure.ClientSdk.Analyzers.Tests
{
public class AZC0020Tests
{
private List<(string fileName, string source)> _sharedSourceFiles;

public AZC0020Tests()
{
_sharedSourceFiles = new List<(string fileName, string source)>() {

("MutableJsonDocument.cs", @"
namespace Azure.Core.Json
{
internal sealed partial class MutableJsonDocument
{
}
}
"),

("MutableJsonElement.cs", @"
namespace Azure.Core.Json
{
internal sealed partial class MutableJsonElement
{
}
}
")
};
}

[Fact]
public async Task AZC0020ProducedForMutableJsonDocumentUsage()
{
string code = @"
using Azure.Core.Json;

namespace LibraryNamespace
{
public class Model
{
MutableJsonDocument {|AZC0020:_document|};
annelo-msft marked this conversation as resolved.
Show resolved Hide resolved
}
}";
await Verifier.VerifyAnalyzerAsync(code, _sharedSourceFiles);
}

[Fact]
public async Task AZC0020ProducedForMutableJsonElementUsage()
{
string code = @"
using Azure.Core.Json;

namespace LibraryNamespace
{
public class Model
{
MutableJsonElement {|AZC0020:_element|};
}
}";
await Verifier.VerifyAnalyzerAsync(code, _sharedSourceFiles);
annelo-msft marked this conversation as resolved.
Show resolved Hide resolved
}

[Fact]
public async Task AZC0020NotProducedForAllowedTypeUsage()
{
string code = @"
using System.Text.Json;

namespace LibraryNamespace
{
public class Model
{
JsonElement _element;
}
}";
await Verifier.VerifyAnalyzerAsync(code, _sharedSourceFiles);
}

[Fact]
public async Task AZC0020NotProducedForTypeWithBannedNameButAllowedNamespace()
{
string code = @"
namespace LibraryNamespace
{
public class MutableJsonDocument
{
}
public class Model
{
MutableJsonDocument _document;
}
}";
await Verifier.VerifyAnalyzerAsync(code, _sharedSourceFiles);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
Expand All @@ -11,16 +12,16 @@
using Microsoft.CodeAnalysis.Testing;
using Microsoft.CodeAnalysis.Testing.Verifiers;

namespace Azure.ClientSdk.Analyzers.Tests
namespace Azure.ClientSdk.Analyzers.Tests
{
public static class AzureAnalyzerVerifier<TAnalyzer> where TAnalyzer : DiagnosticAnalyzer, new()
{
private static readonly ReferenceAssemblies DefaultReferenceAssemblies =
ReferenceAssemblies.Default.AddPackages(ImmutableArray.Create(
new PackageIdentity("Azure.Core", "1.26.0"),
new PackageIdentity("Microsoft.Bcl.AsyncInterfaces", "1.1.0"),
new PackageIdentity("System.Text.Json", "4.6.0"),
new PackageIdentity("Newtonsoft.Json", "12.0.3"),
new PackageIdentity("System.Text.Json", "4.6.0"),
new PackageIdentity("System.Threading.Tasks.Extensions", "4.5.3")));

public static CSharpAnalyzerTest<TAnalyzer, XUnitVerifier> CreateAnalyzer(string source, LanguageVersion languageVersion = LanguageVersion.Latest)
Expand All @@ -37,7 +38,7 @@ public static CSharpAnalyzerTest<TAnalyzer, XUnitVerifier> CreateAnalyzer(string
TestBehaviors = TestBehaviors.SkipGeneratedCodeCheck
};

public static Task VerifyAnalyzerAsync(string source, LanguageVersion languageVersion = LanguageVersion.Latest)
public static Task VerifyAnalyzerAsync(string source, LanguageVersion languageVersion = LanguageVersion.Latest)
=> CreateAnalyzer(source, languageVersion).RunAsync(CancellationToken.None);

public static Task VerifyAnalyzerAsync(string source, params DiagnosticResult[] diagnostics)
Expand All @@ -47,6 +48,16 @@ public static Task VerifyAnalyzerAsync(string source, params DiagnosticResult[]
return test.RunAsync(CancellationToken.None);
}

public static Task VerifyAnalyzerAsync(string source, List<(string fileName, string source)> files)
{
var test = CreateAnalyzer(source);
foreach (var file in files)
{
test.TestState.Sources.Add(file);
}
return test.RunAsync(CancellationToken.None);
}

public static DiagnosticResult Diagnostic(string expectedDescriptor) => AnalyzerVerifier<TAnalyzer>.Diagnostic(expectedDescriptor);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;

namespace Azure.ClientSdk.Analyzers
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class BannedTypesAnalyzer : SymbolAnalyzerBase
{
private static HashSet<string> BannedTypes = new HashSet<string>()
{
"Azure.Core.Json.MutableJsonDocument",
"Azure.Core.Json.MutableJsonElement",
"Azure.Core.Json.MutableJsonChange",
"Azure.Core.Json.MutableJsonChangeKind",
};

private static readonly string BannedTypesMessageArgs = string.Join(", ", BannedTypes);

public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(Descriptors.AZC0020);

public override SymbolKind[] SymbolKinds { get; } = new[]
{
SymbolKind.Method,
SymbolKind.Field,
SymbolKind.Property,
SymbolKind.Parameter,
SymbolKind.Event,
SymbolKind.NamedType,
};

public override void Analyze(ISymbolAnalysisContext context)
{
if (IsAzureCore(context.Symbol.ContainingAssembly))
{
return;
}

switch (context.Symbol)
{
case IParameterSymbol parameterSymbol:
CheckType(context, parameterSymbol.Type, parameterSymbol);
break;
case IMethodSymbol methodSymbol:
CheckType(context, methodSymbol.ReturnType, methodSymbol);
annelo-msft marked this conversation as resolved.
Show resolved Hide resolved
break;
case IEventSymbol eventSymbol:
CheckType(context, eventSymbol.Type, eventSymbol);
break;
case IPropertySymbol propertySymbol:
CheckType(context, propertySymbol.Type, propertySymbol);
break;
case IFieldSymbol fieldSymbol:
CheckType(context, fieldSymbol.Type, fieldSymbol);
break;
annelo-msft marked this conversation as resolved.
Show resolved Hide resolved
case INamedTypeSymbol namedTypeSymbol:
CheckType(context, namedTypeSymbol.BaseType, namedTypeSymbol);
foreach (var iface in namedTypeSymbol.Interfaces)
{
CheckType(context, iface, namedTypeSymbol);
}
break;
}
}

private static void CheckType(ISymbolAnalysisContext context, ITypeSymbol type, ISymbol symbol)
{
if (type is INamedTypeSymbol namedTypeSymbol)
{
if (IsBannedType(namedTypeSymbol))
{
context.ReportDiagnostic(Diagnostic.Create(Descriptors.AZC0020, symbol.Locations.First(), BannedTypesMessageArgs), symbol);
}

if (namedTypeSymbol.IsGenericType)
{
foreach (var typeArgument in namedTypeSymbol.TypeArguments)
{
CheckType(context, typeArgument, symbol);
}
}
}
}

private static bool IsBannedType(INamedTypeSymbol namedTypeSymbol)
{
return BannedTypes.Contains($"{namedTypeSymbol.ContainingNamespace}.{namedTypeSymbol.Name}");
}

private static bool IsAzureCore(IAssemblySymbol assembly)
{
return assembly.Name.Equals("Azure.Core");
annelo-msft marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,14 @@ internal class Descriptors
nameof(AZC0018),
"Do ensure protocol method take a RequestContext parameter called context and not take models as parameter type or return type.",
"Protocol method should have requestContext as the last parameter and don't have model as parameter type or return type.",
"Usage", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: null);
"Usage", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: null);

public static DiagnosticDescriptor AZC0020 = new DiagnosticDescriptor(
annelo-msft marked this conversation as resolved.
Show resolved Hide resolved
nameof(AZC0020),
"Avoid using banned types in public APIs",
"The Azure.Core internal shared source types {0} should not be used outside of the Azure.Core library.",
"Usage",
DiagnosticSeverity.Warning, true);
#endregion

#region General
Expand Down