- 
                Notifications
    
You must be signed in to change notification settings  - Fork 10.5k
 
          feat: analyzer and codeFix for kestrel setup ListenOptions.Listen(IPAddress.Any) usage
          #58872
        
          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
      
      
            DeagleGross
  merged 6 commits into
  dotnet:main
from
DeagleGross:dmkorolev/analyzers/listenoptions
  
      
      
   
  Nov 13, 2024 
      
    
  
     Merged
                    Changes from all commits
      Commits
    
    
            Show all changes
          
          
            6 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      065fc23
              
                init the analyzer
              
              
                DeagleGross 4f98258
              
                + code fix
              
              
                DeagleGross 969d8a6
              
                address PR comments (x1)
              
              
                DeagleGross 9acd514
              
                support local variable usage
              
              
                DeagleGross 67213af
              
                cleanup comment
              
              
                DeagleGross a39c0c8
              
                rename the analyzer
              
              
                DeagleGross 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
    
  
  
    
              
        
          
          
            143 changes: 143 additions & 0 deletions
          
          143 
        
  src/Framework/AspNetCoreAnalyzers/src/Analyzers/Kestrel/ListenOnIPv6AnyAnalyzer.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,143 @@ | ||
| // 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.Diagnostics; | ||
| using Microsoft.CodeAnalysis; | ||
| using System.Collections.Immutable; | ||
| using Microsoft.CodeAnalysis.CSharp; | ||
| using Microsoft.CodeAnalysis.Operations; | ||
| using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
| using System.Linq; | ||
| 
     | 
||
| namespace Microsoft.AspNetCore.Analyzers.Kestrel; | ||
| 
     | 
||
| [DiagnosticAnalyzer(LanguageNames.CSharp)] | ||
| public class ListenOnIPv6AnyAnalyzer : DiagnosticAnalyzer | ||
| { | ||
| public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => [ DiagnosticDescriptors.KestrelShouldListenOnIPv6AnyInsteadOfIpAny ]; | ||
| 
     | 
||
| public override void Initialize(AnalysisContext context) | ||
| { | ||
| context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); | ||
| context.EnableConcurrentExecution(); | ||
| 
     | 
||
| context.RegisterSyntaxNodeAction(KestrelServerOptionsListenInvocation, SyntaxKind.InvocationExpression); | ||
| } | ||
| 
     | 
||
| private void KestrelServerOptionsListenInvocation(SyntaxNodeAnalysisContext context) | ||
| { | ||
| // fail fast before accessing SemanticModel | ||
| if (context.Node is not InvocationExpressionSyntax | ||
| { | ||
| Expression: MemberAccessExpressionSyntax | ||
| { | ||
| Name: IdentifierNameSyntax { Identifier.ValueText: "Listen" } | ||
| } | ||
| } kestrelOptionsListenExpressionSyntax) | ||
| { | ||
| return; | ||
| } | ||
| 
     | 
||
| var nodeOperation = context.SemanticModel.GetOperation(context.Node, context.CancellationToken); | ||
| if (!IsKestrelServerOptionsType(nodeOperation, out var kestrelOptionsListenInvocation)) | ||
| { | ||
| return; | ||
| } | ||
| 
     | 
||
| var addressArgument = kestrelOptionsListenInvocation?.Arguments.FirstOrDefault(); | ||
| if (!IsIPAddressType(addressArgument?.Parameter)) | ||
| { | ||
| return; | ||
| } | ||
| 
     | 
||
| var args = kestrelOptionsListenExpressionSyntax.ArgumentList; | ||
| var ipAddressArgumentSyntax = args.Arguments.FirstOrDefault(); | ||
| if (ipAddressArgumentSyntax is null) | ||
| { | ||
| return; | ||
| } | ||
| 
     | 
||
| // explicit usage like `options.Listen(IPAddress.Any, ...)` | ||
| if (ipAddressArgumentSyntax is ArgumentSyntax | ||
| { | ||
| Expression: MemberAccessExpressionSyntax | ||
| { | ||
| Name: IdentifierNameSyntax { Identifier.ValueText: "Any" } | ||
| } | ||
| }) | ||
| { | ||
| context.ReportDiagnostic(Diagnostic.Create(DiagnosticDescriptors.KestrelShouldListenOnIPv6AnyInsteadOfIpAny, ipAddressArgumentSyntax.GetLocation())); | ||
| } | ||
| 
     | 
||
| // usage via local variable like | ||
| // ``` | ||
| // var myIp = IPAddress.Any; | ||
| // options.Listen(myIp, ...); | ||
| // ``` | ||
| if (addressArgument!.Value is ILocalReferenceOperation localReferenceOperation) | ||
| { | ||
| var localVariableDeclaration = localReferenceOperation.Local.DeclaringSyntaxReferences.FirstOrDefault(); | ||
| if (localVariableDeclaration is null) | ||
| { | ||
| return; | ||
| } | ||
| 
     | 
||
| var localVarSyntax = localVariableDeclaration.GetSyntax(context.CancellationToken); | ||
| if (localVarSyntax is VariableDeclaratorSyntax | ||
| { | ||
| Initializer.Value: MemberAccessExpressionSyntax | ||
| { | ||
| Name.Identifier.ValueText: "Any" | ||
| } | ||
| }) | ||
| { | ||
| context.ReportDiagnostic(Diagnostic.Create(DiagnosticDescriptors.KestrelShouldListenOnIPv6AnyInsteadOfIpAny, ipAddressArgumentSyntax.GetLocation())); | ||
| } | ||
| } | ||
| } | ||
| 
     | 
||
| private static bool IsIPAddressType(IParameterSymbol? parameter) => parameter is | ||
| { | ||
| Type: // searching type `System.Net.IPAddress` | ||
| { | ||
| Name: "IPAddress", | ||
| ContainingNamespace: { Name: "Net", ContainingNamespace: { Name: "System", ContainingNamespace.IsGlobalNamespace: true } } | ||
| } | ||
| }; | ||
| 
     | 
||
| private static bool IsKestrelServerOptionsType(IOperation? operation, out IInvocationOperation? kestrelOptionsListenInvocation) | ||
| { | ||
| var result = operation is IInvocationOperation // searching type `Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions` | ||
| { | ||
| TargetMethod: { Name: "Listen" }, | ||
| Instance.Type: | ||
| { | ||
| Name: "KestrelServerOptions", | ||
| ContainingNamespace: | ||
| { | ||
| Name: "Core", | ||
| ContainingNamespace: | ||
| { | ||
| Name: "Kestrel", | ||
| ContainingNamespace: | ||
| { | ||
| Name: "Server", | ||
| ContainingNamespace: | ||
| { | ||
| Name: "AspNetCore", | ||
| ContainingNamespace: | ||
| { | ||
| Name: "Microsoft", | ||
| ContainingNamespace.IsGlobalNamespace: true | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| }; | ||
| 
     | 
||
| kestrelOptionsListenInvocation = result ? (IInvocationOperation)operation! : null; | ||
| return result; | ||
| } | ||
| } | ||
  
    
      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
    
  
  
    
              
        
          
          
            79 changes: 79 additions & 0 deletions
          
          79 
        
  src/Framework/AspNetCoreAnalyzers/src/CodeFixes/Kestrel/ListenOnIPv6AnyFixer.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,79 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
| 
     | 
||
| using System.Composition; | ||
| using Microsoft.CodeAnalysis.CodeFixes; | ||
| using Microsoft.CodeAnalysis; | ||
| using System.Collections.Immutable; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.AspNetCore.Analyzers; | ||
| using Microsoft.CodeAnalysis.CodeActions; | ||
| using Microsoft.CodeAnalysis.Editing; | ||
| using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
| using Microsoft.CodeAnalysis.CSharp; | ||
| 
     | 
||
| namespace Microsoft.AspNetCore.Fixers.Kestrel; | ||
| 
     | 
||
| [ExportCodeFixProvider(LanguageNames.CSharp), Shared] | ||
| public class ListenOnIPv6AnyFixer : CodeFixProvider | ||
| { | ||
| public override ImmutableArray<string> FixableDiagnosticIds => [ DiagnosticDescriptors.KestrelShouldListenOnIPv6AnyInsteadOfIpAny.Id ]; | ||
| 
     | 
||
| public sealed override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; | ||
| 
     | 
||
| public override Task RegisterCodeFixesAsync(CodeFixContext context) | ||
| { | ||
| foreach (var diagnostic in context.Diagnostics) | ||
| { | ||
| context.RegisterCodeFix( | ||
| CodeAction.Create( | ||
| "Consider using IPAddress.IPv6Any instead of IPAddress.Any", | ||
| async cancellationToken => | ||
| { | ||
| var editor = await DocumentEditor.CreateAsync(context.Document, cancellationToken).ConfigureAwait(false); | ||
| var root = await context.Document.GetSyntaxRootAsync(cancellationToken); | ||
| if (root is null) | ||
| { | ||
| return context.Document; | ||
| } | ||
| 
     | 
||
| var argumentSyntax = root.FindNode(diagnostic.Location.SourceSpan).FirstAncestorOrSelf<ArgumentSyntax>(); | ||
| if (argumentSyntax is null) | ||
| { | ||
| return context.Document; | ||
| } | ||
| 
     | 
||
| // get to the `Listen(IPAddress.Any, ...)` invocation | ||
| if (argumentSyntax.Parent?.Parent is not InvocationExpressionSyntax { ArgumentList.Arguments.Count: > 1 } invocationExpressionSyntax) | ||
| { | ||
| return context.Document; | ||
| } | ||
| if (invocationExpressionSyntax.Expression is not MemberAccessExpressionSyntax memberAccessExpressionSyntax) | ||
| { | ||
| return context.Document; | ||
| } | ||
| 
     | 
||
| var instanceVariableInvoked = memberAccessExpressionSyntax.Expression; | ||
| var adjustedArgumentList = invocationExpressionSyntax.ArgumentList.RemoveNode(invocationExpressionSyntax.ArgumentList.Arguments.First(), SyntaxRemoveOptions.KeepLeadingTrivia); | ||
| if (adjustedArgumentList is null || adjustedArgumentList.Arguments.Count == 0) | ||
| { | ||
| return context.Document; | ||
| } | ||
| 
     | 
||
| // changing invocation from `<variable>.Listen(IPAddress.Any, ...)` to `<variable>.ListenAnyIP(...)` | ||
| editor.ReplaceNode( | ||
| invocationExpressionSyntax, | ||
| invocationExpressionSyntax | ||
| .WithExpression(SyntaxFactory.ParseExpression($"{instanceVariableInvoked.ToString()}.ListenAnyIP")) | ||
| .WithArgumentList(adjustedArgumentList!) | ||
| .WithLeadingTrivia(invocationExpressionSyntax.GetLeadingTrivia()) | ||
| ); | ||
| return editor.GetChangedDocument(); | ||
| }, | ||
| equivalenceKey: DiagnosticDescriptors.KestrelShouldListenOnIPv6AnyInsteadOfIpAny.Id), | ||
| diagnostic); | ||
| } | ||
| 
     | 
||
| return Task.CompletedTask; | ||
| } | ||
| } | 
        
          
          
            90 changes: 90 additions & 0 deletions
          
          90 
        
  src/Framework/AspNetCoreAnalyzers/test/Kestrel/ListenOnIPv6AnyAnalyzerAndFixerTests.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,90 @@ | ||
| // 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.Generic; | ||
| using System.Text; | ||
| using Microsoft.CodeAnalysis.Testing; | ||
| using VerifyCS = Microsoft.AspNetCore.Analyzers.Verifiers.CSharpCodeFixVerifier< | ||
| Microsoft.AspNetCore.Analyzers.Kestrel.ListenOnIPv6AnyAnalyzer, | ||
| Microsoft.AspNetCore.Fixers.Kestrel.ListenOnIPv6AnyFixer>; | ||
| 
     | 
||
| namespace Microsoft.AspNetCore.Analyzers.Kestrel; | ||
| 
     | 
||
| public class ListenOnIPv6AnyAnalyzerAndFixerTests | ||
| { | ||
| [Fact] | ||
| public async Task ReportsDiagnostic_IPAddressAsLocalVariable_OuterScope() | ||
| { | ||
| var source = GetKestrelSetupSource("myIp", extraOuterCode: "var myIp = IPAddress.Any;"); | ||
| await VerifyCS.VerifyAnalyzerAsync(source, codeSampleDiagnosticResult); | ||
| } | ||
| 
     | 
||
| [Fact] | ||
| public async Task ReportsDiagnostic_IPAddressAsLocalVariable() | ||
| { | ||
| var source = GetKestrelSetupSource("myIp", extraInlineCode: "var myIp = IPAddress.Any;"); | ||
| await VerifyCS.VerifyAnalyzerAsync(source, codeSampleDiagnosticResult); | ||
| } | ||
| 
     | 
||
| [Fact] | ||
| public async Task ReportsDiagnostic_ExplicitUsage() | ||
| { | ||
| var source = GetKestrelSetupSource("IPAddress.Any"); | ||
| await VerifyCS.VerifyAnalyzerAsync(source, codeSampleDiagnosticResult); | ||
| } | ||
| 
     | 
||
| [Fact] | ||
| public async Task CodeFix_ExplicitUsage() | ||
| { | ||
| var source = GetKestrelSetupSource("IPAddress.Any"); | ||
| var fixedSource = GetCorrectedKestrelSetup(); | ||
| await VerifyCS.VerifyCodeFixAsync(source, codeSampleDiagnosticResult, fixedSource); | ||
| } | ||
| 
     | 
||
| [Fact] | ||
| public async Task CodeFix_IPAddressAsLocalVariable() | ||
| { | ||
| var source = GetKestrelSetupSource("IPAddress.Any", extraInlineCode: "var myIp = IPAddress.Any;"); | ||
| var fixedSource = GetCorrectedKestrelSetup(extraInlineCode: "var myIp = IPAddress.Any;"); | ||
| await VerifyCS.VerifyCodeFixAsync(source, codeSampleDiagnosticResult, fixedSource); | ||
| } | ||
| 
     | 
||
| private static DiagnosticResult codeSampleDiagnosticResult | ||
| = new DiagnosticResult(DiagnosticDescriptors.KestrelShouldListenOnIPv6AnyInsteadOfIpAny).WithLocation(0); | ||
| 
     | 
||
| static string GetKestrelSetupSource(string ipAddressArgument, string extraInlineCode = null, string extraOuterCode = null) | ||
| => GetCodeSample($$"""Listen({|#0:{{ipAddressArgument}}|}, """, extraInlineCode, extraOuterCode); | ||
| 
     | 
||
| static string GetCorrectedKestrelSetup(string extraInlineCode = null, string extraOuterCode = null) | ||
| => GetCodeSample("ListenAnyIP(", extraInlineCode, extraOuterCode); | ||
| 
     | 
||
| static string GetCodeSample(string invocation, string extraInlineCode = null, string extraOuterCode = null) => $$""" | ||
| using Microsoft.Extensions.Hosting; | ||
| using Microsoft.AspNetCore.Hosting; | ||
| using Microsoft.AspNetCore.Server.Kestrel.Core; | ||
| using System.Net; | ||
| 
     | 
||
| {{extraOuterCode}} | ||
| 
     | 
||
| var hostBuilder = new HostBuilder() | ||
| .ConfigureWebHost(webHost => | ||
| { | ||
| webHost.UseKestrel().ConfigureKestrel(options => | ||
| { | ||
| {{extraInlineCode}} | ||
| 
     | 
||
| options.ListenLocalhost(5000); | ||
| options.ListenAnyIP(5000); | ||
| options.{{invocation}}5000, listenOptions => | ||
| { | ||
| listenOptions.UseHttps(); | ||
| listenOptions.Protocols = HttpProtocols.Http1AndHttp2AndHttp3; | ||
| }); | ||
| }); | ||
| }); | ||
| 
     | 
||
| var host = hostBuilder.Build(); | ||
| host.Run(); | ||
| """; | ||
| } | 
  
    
      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
    
  
  
    
              
      
      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.