-
Notifications
You must be signed in to change notification settings - Fork 10.4k
Add an analyzer that complains when using using model binding attributes with a minimal action delegate #35359
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
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
23 changes: 23 additions & 0 deletions
23
src/Framework/Analyzer/src/Microsoft.AspNetCore.App.Analyzers.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
<PropertyGroup> | ||
<Description>CSharp Analyzers for ASP.NET Core.</Description> | ||
<IsShippingPackage>false</IsShippingPackage> | ||
<AddPublicApiAnalyzers>false</AddPublicApiAnalyzers> | ||
<TargetFramework>netstandard2.0</TargetFramework> | ||
<IncludeBuildOutput>false</IncludeBuildOutput> | ||
<Nullable>Enable</Nullable> | ||
<RootNamespace>Microsoft.AspNetCore.Analyzers</RootNamespace> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<Reference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" PrivateAssets="All" /> | ||
|
||
<InternalsVisibleTo Include="Microsoft.AspNetCore.App.Analyzers.Test" /> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<Compile Include="$(SharedSourceRoot)IsExternalInit.cs" LinkBase="Shared" /> | ||
<Compile Include="$(SharedSourceRoot)Roslyn\CodeAnalysisExtensions.cs" LinkBase="Shared" /> | ||
</ItemGroup> | ||
|
||
</Project> |
20 changes: 20 additions & 0 deletions
20
src/Framework/Analyzer/src/MinimalActions/DiagnosticDescriptors.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using Microsoft.CodeAnalysis; | ||
|
||
namespace Microsoft.AspNetCore.Analyzers.MinimalActions | ||
{ | ||
[System.Diagnostics.CodeAnalysis.SuppressMessage("MicrosoftCodeAnalysisReleaseTracking", "RS2008:Enable analyzer release tracking")] | ||
internal static class DiagnosticDescriptors | ||
{ | ||
internal static readonly DiagnosticDescriptor DoNotUseModelBindingAttributesOnMinimalActionParameters = new( | ||
"ASP0003", | ||
"Do not use model binding attributes with Map actions", | ||
"{0} should not be specified for a {1} delegate parameter", | ||
BrennanConroy marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"Usage", | ||
DiagnosticSeverity.Warning, | ||
isEnabledByDefault: true, | ||
helpLinkUri: "https://aka.ms/aspnet/analyzers"); | ||
} | ||
} |
43 changes: 43 additions & 0 deletions
43
src/Framework/Analyzer/src/MinimalActions/DisallowMvcBindArgumentsOnParameters.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System.Linq; | ||
using Microsoft.CodeAnalysis; | ||
using Microsoft.CodeAnalysis.Diagnostics; | ||
using Microsoft.CodeAnalysis.Operations; | ||
|
||
namespace Microsoft.AspNetCore.Analyzers.MinimalActions; | ||
|
||
public partial class MinimalActionAnalyzer : DiagnosticAnalyzer | ||
{ | ||
private static void DisallowMvcBindArgumentsOnParameters( | ||
in OperationAnalysisContext context, | ||
WellKnownTypes wellKnownTypes, | ||
IInvocationOperation invocation, | ||
IMethodSymbol methodSymbol) | ||
{ | ||
foreach (var parameter in methodSymbol.Parameters) | ||
{ | ||
var modelBindingAttribute = parameter.GetAttributes(wellKnownTypes.IBinderTypeProviderMetadata).FirstOrDefault() ?? | ||
parameter.GetAttributes(wellKnownTypes.BindAttribute).FirstOrDefault(); | ||
|
||
if (modelBindingAttribute is not null) | ||
{ | ||
var location = Location.None; | ||
if (!parameter.DeclaringSyntaxReferences.IsEmpty) | ||
{ | ||
var syntax = parameter.DeclaringSyntaxReferences[0].GetSyntax(context.CancellationToken); | ||
location = syntax.GetLocation(); | ||
} | ||
|
||
var methodName = invocation.TargetMethod.Name; | ||
|
||
context.ReportDiagnostic(Diagnostic.Create( | ||
DiagnosticDescriptors.DoNotUseModelBindingAttributesOnMinimalActionParameters, | ||
location, | ||
modelBindingAttribute.AttributeClass.Name, | ||
methodName)); | ||
} | ||
} | ||
} | ||
} |
72 changes: 72 additions & 0 deletions
72
src/Framework/Analyzer/src/MinimalActions/MinimalActionAnalyzer.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System; | ||
using System.Collections.Immutable; | ||
using System.Linq; | ||
using Microsoft.CodeAnalysis; | ||
using Microsoft.CodeAnalysis.Diagnostics; | ||
using Microsoft.CodeAnalysis.Operations; | ||
|
||
namespace Microsoft.AspNetCore.Analyzers.MinimalActions; | ||
|
||
[DiagnosticAnalyzer(LanguageNames.CSharp)] | ||
public partial class MinimalActionAnalyzer : DiagnosticAnalyzer | ||
{ | ||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(new[] | ||
{ | ||
DiagnosticDescriptors.DoNotUseModelBindingAttributesOnMinimalActionParameters, | ||
}); | ||
|
||
public override void Initialize(AnalysisContext context) | ||
{ | ||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); | ||
context.EnableConcurrentExecution(); | ||
|
||
context.RegisterCompilationStartAction(static compilationStartAnalysisContext => | ||
{ | ||
var compilation = compilationStartAnalysisContext.Compilation; | ||
if (!WellKnownTypes.TryCreate(compilation, out var wellKnownTypes)) | ||
{ | ||
return; | ||
} | ||
|
||
compilationStartAnalysisContext.RegisterOperationAction(operationAnalysisContext => | ||
{ | ||
var invocation = (IInvocationOperation)operationAnalysisContext.Operation; | ||
var targetMethod = invocation.TargetMethod; | ||
if (IsMapActionInvocation(wellKnownTypes, invocation, targetMethod)) | ||
{ | ||
return; | ||
} | ||
|
||
var delegateCreation = invocation.Arguments[2].Descendants().OfType<IDelegateCreationOperation>().FirstOrDefault(); | ||
if (delegateCreation is null) | ||
{ | ||
return; | ||
} | ||
|
||
if (delegateCreation.Target.Kind == OperationKind.AnonymousFunction) | ||
{ | ||
var lambda = ((IAnonymousFunctionOperation)delegateCreation.Target); | ||
DisallowMvcBindArgumentsOnParameters(in operationAnalysisContext, wellKnownTypes, invocation, lambda.Symbol); | ||
} | ||
else if (delegateCreation.Target.Kind == OperationKind.MethodReference) | ||
{ | ||
var methodReference = (IMethodReferenceOperation)delegateCreation.Target; | ||
DisallowMvcBindArgumentsOnParameters(in operationAnalysisContext, wellKnownTypes, invocation, methodReference.Method); | ||
} | ||
}, OperationKind.Invocation); | ||
}); | ||
} | ||
|
||
private static bool IsMapActionInvocation( | ||
WellKnownTypes wellKnownTypes, | ||
IInvocationOperation invocation, | ||
IMethodSymbol targetMethod) | ||
{ | ||
return !targetMethod.Name.StartsWith("Map", StringComparison.Ordinal) || | ||
!SymbolEqualityComparer.Default.Equals(wellKnownTypes.MinimalActionEndpointRouteBuilderExtensions, targetMethod.ContainingType) || | ||
invocation.Arguments.Length != 3; | ||
} | ||
} |
47 changes: 47 additions & 0 deletions
47
src/Framework/Analyzer/src/MinimalActions/WellKnownTypes.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System.Diagnostics.CodeAnalysis; | ||
using Microsoft.CodeAnalysis; | ||
|
||
namespace Microsoft.AspNetCore.Analyzers.MinimalActions; | ||
|
||
internal sealed class WellKnownTypes | ||
{ | ||
public static bool TryCreate(Compilation compilation, [NotNullWhen(true)] out WellKnownTypes? wellKnownTypes) | ||
{ | ||
wellKnownTypes = default; | ||
const string MinimalActionEndpointRouteBuilderExtensions = "Microsoft.AspNetCore.Builder.MinimalActionEndpointRouteBuilderExtensions"; | ||
if (compilation.GetTypeByMetadataName(MinimalActionEndpointRouteBuilderExtensions) is not { } minimalActionEndpointRouteBuilderExtensions) | ||
{ | ||
return false; | ||
} | ||
|
||
const string IBinderTypeProviderMetadata = "Microsoft.AspNetCore.Mvc.ModelBinding.IBinderTypeProviderMetadata"; | ||
if (compilation.GetTypeByMetadataName(IBinderTypeProviderMetadata) is not { } ibinderTypeProviderMetadata) | ||
{ | ||
return false; | ||
} | ||
|
||
// There isn't a good way to distinguish BindAttribute from other allowed | ||
// MVC's attributes like From*. | ||
const string BindAttribute = "Microsoft.AspNetCore.Mvc.BindAttribute"; | ||
if (compilation.GetTypeByMetadataName(BindAttribute) is not { } bindAttribute) | ||
{ | ||
return false; | ||
} | ||
|
||
wellKnownTypes = new WellKnownTypes | ||
{ | ||
MinimalActionEndpointRouteBuilderExtensions = minimalActionEndpointRouteBuilderExtensions, | ||
IBinderTypeProviderMetadata = ibinderTypeProviderMetadata, | ||
BindAttribute = bindAttribute, | ||
}; | ||
|
||
return true; | ||
} | ||
|
||
public ITypeSymbol MinimalActionEndpointRouteBuilderExtensions { get; private init; } | ||
public INamedTypeSymbol IBinderTypeProviderMetadata { get; private init; } | ||
public INamedTypeSymbol BindAttribute { get; private init; } | ||
} |
20 changes: 20 additions & 0 deletions
20
src/Framework/Analyzer/test/Microsoft.AspNetCore.App.Analyzers.Test.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
|
||
<PropertyGroup> | ||
<TargetFramework>$(DefaultNetCoreTargetFramework)</TargetFramework> | ||
<PreserveCompilationContext>true</PreserveCompilationContext> | ||
<RootNamespace>Microsoft.AspNetCore.Analyzers</RootNamespace> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<None Include="xunit.runner.json" CopyToOutputDirectory="PreserveNewest" /> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<ProjectReference Include="..\src\Microsoft.AspNetCore.App.Analyzers.csproj" /> | ||
<ProjectReference Include="$(RepoRoot)src\Analyzers\Microsoft.AspNetCore.Analyzer.Testing\src\Microsoft.AspNetCore.Analyzer.Testing.csproj" /> | ||
<Reference Include="Microsoft.AspNetCore" /> | ||
<Reference Include="Microsoft.AspNetCore.Mvc" /> | ||
</ItemGroup> | ||
|
||
</Project> |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.