- 
                Notifications
    You must be signed in to change notification settings 
- Fork 150
[ConfigRegistry] 4/5 Aliases handling and analyzers to prevent using any string key #7689
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
          
     Open
      
      
            anna-git
  wants to merge
  7
  commits into
  anna/config-inversion-configuration-aliases-switch-3
  
    
      
        
          
  
    
      Choose a base branch
      
     
    
      
        
      
      
        
          
          
        
        
          
            
              
              
              
  
           
        
        
          
            
              
              
           
        
       
     
  
        
          
            
          
            
          
        
       
    
      
from
anna/config-inversion-configuration-analyzers-4
  
      
      
   
  
    
  
  
  
 
  
      
    base: anna/config-inversion-configuration-aliases-switch-3
Could not load branches
            
              
  
    Branch not found: {{ refName }}
  
            
                
      Loading
              
            Could not load tags
            
            
              Nothing to show
            
              
  
            
                
      Loading
              
            Are you sure you want to change the base?
            Some commits from the old base branch may be removed from the timeline,
            and old review comments may become outdated.
          
          
  
     Open
                    Changes from all commits
      Commits
    
    
            Show all changes
          
          
            7 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      f0b8304
              
                Source generator for ConfigurationKey switcher for aliases
              
              
                anna-git 9d9afd0
              
                Handle aliases in ConfigurationBuilder.cs and remove overloads for fa…
              
              
                anna-git d3f8788
              
                Special case for IntegrationSettings.cs keys
              
              
                anna-git 6a597b5
              
                Adapt config tests
              
              
                anna-git 28bfb8a
              
                 special case for logging factory..
              
              
                anna-git 0688fef
              
                Platform key analyzer
              
              
                anna-git dcd2f3c
              
                Add analyzer to enforce ConfigurationBuilder only with configuration …
              
              
                anna-git 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
    
  
  
    
              
        
          
  
    
      
          
            386 changes: 386 additions & 0 deletions
          
          386 
        
  tracer/src/Datadog.Trace.SourceGenerators/Configuration/ConfigKeyAliasesSwitcherGenerator.cs
  
  
      
      
   
        
      
      
    Large diffs are not rendered by default.
      
      Oops, something went wrong.
      
    
  
        
          
  
    
      
          
            227 changes: 227 additions & 0 deletions
          
          227 
        
  ...adog.Trace.Tools.Analyzers/ConfigurationAnalyzers/ConfigurationBuilderWithKeysAnalyzer.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,227 @@ | ||
| // <copyright file="ConfigurationBuilderWithKeysAnalyzer.cs" company="Datadog"> | ||
| // Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. | ||
| // This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. | ||
| // </copyright> | ||
|  | ||
| using System.Collections.Immutable; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CSharp; | ||
| using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
| using Microsoft.CodeAnalysis.Diagnostics; | ||
|  | ||
| namespace Datadog.Trace.Tools.Analyzers.ConfigurationAnalyzers | ||
| { | ||
| /// <summary> | ||
| /// Analyzer to ensure that ConfigurationBuilder.WithKeys method calls only accept string constants | ||
| /// from PlatformKeys or ConfigurationKeys classes, not hardcoded strings or variables. | ||
| /// </summary> | ||
| [DiagnosticAnalyzer(LanguageNames.CSharp)] | ||
| public class ConfigurationBuilderWithKeysAnalyzer : DiagnosticAnalyzer | ||
| { | ||
| /// <summary> | ||
| /// Diagnostic descriptor for when WithKeys or Or is called with a hardcoded string instead of a constant from PlatformKeys or ConfigurationKeys. | ||
| /// </summary> | ||
| public static readonly DiagnosticDescriptor UseConfigurationConstantsRule = new( | ||
| id: "DD0007", | ||
| title: "Use configuration constants instead of hardcoded strings in WithKeys/Or calls", | ||
| messageFormat: "{0} method should use constants from PlatformKeys or ConfigurationKeys classes instead of hardcoded string '{1}'", | ||
| category: "Usage", | ||
| defaultSeverity: DiagnosticSeverity.Error, | ||
| isEnabledByDefault: true, | ||
| description: "ConfigurationBuilder.WithKeys and HasKeys.Or method calls should only accept string constants from PlatformKeys or ConfigurationKeys classes to ensure consistency and avoid typos."); | ||
|  | ||
| /// <summary> | ||
| /// Diagnostic descriptor for when WithKeys or Or is called with a variable instead of a constant from PlatformKeys or ConfigurationKeys. | ||
| /// </summary> | ||
| public static readonly DiagnosticDescriptor UseConfigurationConstantsNotVariablesRule = new( | ||
| id: "DD0008", | ||
| title: "Use configuration constants instead of variables in WithKeys/Or calls", | ||
| messageFormat: "{0} method should use constants from PlatformKeys or ConfigurationKeys classes instead of variable '{1}'", | ||
| category: "Usage", | ||
| defaultSeverity: DiagnosticSeverity.Error, | ||
| isEnabledByDefault: true, | ||
| description: "ConfigurationBuilder.WithKeys and HasKeys.Or method calls should only accept string constants from PlatformKeys or ConfigurationKeys classes, not variables or computed values."); | ||
|  | ||
| /// <summary> | ||
| /// Gets the supported diagnostics | ||
| /// </summary> | ||
| public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => | ||
| ImmutableArray.Create(UseConfigurationConstantsRule, UseConfigurationConstantsNotVariablesRule); | ||
|  | ||
| /// <summary> | ||
| /// Initialize the analyzer | ||
| /// </summary> | ||
| /// <param name="context">context</param> | ||
| public override void Initialize(AnalysisContext context) | ||
| { | ||
| context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); | ||
| context.EnableConcurrentExecution(); | ||
| context.RegisterSyntaxNodeAction(AnalyzeInvocationExpression, SyntaxKind.InvocationExpression); | ||
| } | ||
|  | ||
| private static void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext context) | ||
| { | ||
| var invocation = (InvocationExpressionSyntax)context.Node; | ||
|  | ||
| // Check if this is a WithKeys or Or method call | ||
| var methodName = GetConfigurationMethodName(invocation, context.SemanticModel); | ||
| if (methodName == null) | ||
| { | ||
| return; | ||
| } | ||
|  | ||
| // Analyze each argument to the method | ||
| var argumentList = invocation.ArgumentList; | ||
| if (argumentList?.Arguments.Count > 0) | ||
| { | ||
| var argument = argumentList.Arguments[0]; // Both WithKeys and Or take a single string argument | ||
| AnalyzeConfigurationArgument(context, argument, methodName); | ||
| } | ||
| } | ||
|  | ||
| private static string GetConfigurationMethodName(InvocationExpressionSyntax invocation, SemanticModel semanticModel) | ||
| { | ||
| if (invocation.Expression is MemberAccessExpressionSyntax memberAccess) | ||
| { | ||
| var methodName = memberAccess.Name.Identifier.ValueText; | ||
|  | ||
| // Check if the method being called is "WithKeys" or "Or" | ||
| const string withKeysMethodName = "WithKeys"; | ||
| const string orMethodName = "Or"; | ||
| if (methodName is withKeysMethodName or orMethodName) | ||
| { | ||
| // Get the symbol info for the method | ||
| var symbolInfo = semanticModel.GetSymbolInfo(memberAccess); | ||
| if (symbolInfo.Symbol is IMethodSymbol method) | ||
| { | ||
| var containingType = method.ContainingType?.Name; | ||
| var containingNamespace = method.ContainingNamespace?.ToDisplayString(); | ||
|  | ||
| // Check if this is the ConfigurationBuilder.WithKeys method | ||
| if (methodName == withKeysMethodName && | ||
| containingType == "ConfigurationBuilder" && | ||
| containingNamespace == "Datadog.Trace.Configuration.Telemetry") | ||
| { | ||
| return withKeysMethodName; | ||
| } | ||
|  | ||
| // Check if this is the HasKeys.Or method | ||
| if (methodName == orMethodName && | ||
| containingType == "HasKeys" && | ||
| containingNamespace == "Datadog.Trace.Configuration.Telemetry") | ||
| { | ||
| return orMethodName; | ||
| } | ||
| } | ||
| } | ||
| } | ||
|  | ||
| return null; | ||
| } | ||
|  | ||
| private static void AnalyzeConfigurationArgument(SyntaxNodeAnalysisContext context, ArgumentSyntax argument, string methodName) | ||
| { | ||
| var expression = argument.Expression; | ||
|  | ||
| switch (expression) | ||
| { | ||
| case LiteralExpressionSyntax literal when literal.Token.IsKind(SyntaxKind.StringLiteralToken): | ||
| // This is a hardcoded string literal - report diagnostic | ||
| var literalValue = literal.Token.ValueText; | ||
| var diagnostic = Diagnostic.Create( | ||
| UseConfigurationConstantsRule, | ||
| literal.GetLocation(), | ||
| methodName, | ||
| literalValue); | ||
| context.ReportDiagnostic(diagnostic); | ||
| break; | ||
|  | ||
| case MemberAccessExpressionSyntax memberAccess: | ||
| // Check if this is accessing a constant from PlatformKeys or ConfigurationKeys | ||
| if (!IsValidConfigurationConstant(memberAccess, context.SemanticModel)) | ||
| { | ||
| // This is accessing something else - report diagnostic | ||
| var memberName = memberAccess.ToString(); | ||
| var memberDiagnostic = Diagnostic.Create( | ||
| UseConfigurationConstantsNotVariablesRule, | ||
| memberAccess.GetLocation(), | ||
| methodName, | ||
| memberName); | ||
| context.ReportDiagnostic(memberDiagnostic); | ||
| } | ||
|  | ||
| break; | ||
|  | ||
| case IdentifierNameSyntax identifier: | ||
| // This is a variable or local constant - report diagnostic | ||
| var identifierName = identifier.Identifier.ValueText; | ||
| var variableDiagnostic = Diagnostic.Create( | ||
| UseConfigurationConstantsNotVariablesRule, | ||
| identifier.GetLocation(), | ||
| methodName, | ||
| identifierName); | ||
| context.ReportDiagnostic(variableDiagnostic); | ||
| break; | ||
|  | ||
| default: | ||
| // Any other expression type (method calls, computed values, etc.) - report diagnostic | ||
| var expressionText = expression.ToString(); | ||
| var defaultDiagnostic = Diagnostic.Create( | ||
| UseConfigurationConstantsNotVariablesRule, | ||
| expression.GetLocation(), | ||
| methodName, | ||
| expressionText); | ||
| context.ReportDiagnostic(defaultDiagnostic); | ||
| break; | ||
| } | ||
| } | ||
|  | ||
| private static bool IsValidConfigurationConstant(MemberAccessExpressionSyntax memberAccess, SemanticModel semanticModel) | ||
| { | ||
| var symbolInfo = semanticModel.GetSymbolInfo(memberAccess); | ||
| if (symbolInfo.Symbol is IFieldSymbol field) | ||
| { | ||
| // Check if this is a const string field | ||
| if (field.IsConst && field.Type?.SpecialType == SpecialType.System_String) | ||
| { | ||
| var containingType = field.ContainingType; | ||
| if (containingType != null) | ||
| { | ||
| // Check if the containing type is PlatformKeys or ConfigurationKeys (or their nested classes) | ||
| return IsValidConfigurationClass(containingType); | ||
| } | ||
| } | ||
| } | ||
|  | ||
| return false; | ||
| } | ||
|  | ||
| private static bool IsValidConfigurationClass(INamedTypeSymbol typeSymbol) | ||
| { | ||
| // Check if this is PlatformKeys or ConfigurationKeys class or their nested classes | ||
| var currentType = typeSymbol; | ||
| while (currentType != null) | ||
| { | ||
| var typeName = currentType.Name; | ||
| var namespaceName = currentType.ContainingNamespace?.ToDisplayString(); | ||
|  | ||
| // Check for PlatformKeys class | ||
| if (typeName == "PlatformKeys" && namespaceName == "Datadog.Trace.Configuration") | ||
| { | ||
| return true; | ||
| } | ||
|  | ||
| // Check for ConfigurationKeys class | ||
| if (typeName == "ConfigurationKeys" && namespaceName == "Datadog.Trace.Configuration") | ||
| { | ||
| return true; | ||
| } | ||
|  | ||
| // Check nested classes within PlatformKeys or ConfigurationKeys | ||
| currentType = currentType.ContainingType; | ||
| } | ||
|  | ||
| return false; | ||
| } | ||
| } | ||
| } | 
        
          
  
    
      
          
            126 changes: 126 additions & 0 deletions
          
          126 
        
  tracer/src/Datadog.Trace.Tools.Analyzers/ConfigurationAnalyzers/PlatformKeysAnalyzer.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,126 @@ | ||
| // <copyright file="PlatformKeysAnalyzer.cs" company="Datadog"> | ||
| // Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. | ||
| // This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. | ||
| // </copyright> | ||
|  | ||
| #nullable enable | ||
| using System; | ||
| using System.Collections.Immutable; | ||
| using System.Linq; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.Diagnostics; | ||
|  | ||
| namespace Datadog.Trace.Tools.Analyzers.ConfigurationAnalyzers; | ||
|  | ||
| /// <summary> | ||
| /// DD0010: Invalid PlatformKeys constant naming | ||
| /// | ||
| /// Ensures that constants in the PlatformKeys class do not start with reserved prefixes: | ||
| /// - OTEL (OpenTelemetry prefix) | ||
| /// - DD_ (Datadog configuration prefix) | ||
| /// - _DD_ (Internal Datadog configuration prefix) | ||
| /// - DATADOG_ (Older Datadog configuration prefix) | ||
| /// | ||
| /// Platform keys should represent environment variables from external platforms/services, | ||
| /// not Datadog-specific or OpenTelemetry configuration keys. | ||
| /// </summary> | ||
| [DiagnosticAnalyzer(LanguageNames.CSharp)] | ||
| public sealed class PlatformKeysAnalyzer : DiagnosticAnalyzer | ||
| { | ||
| /// <summary> | ||
| /// The diagnostic ID displayed in error messages | ||
| /// </summary> | ||
| public const string DiagnosticId = "DD0010"; | ||
|  | ||
| private const string PlatformKeysClassName = "PlatformKeys"; | ||
| private const string PlatformKeysNamespace = "Datadog.Trace.Configuration"; | ||
|  | ||
| private static readonly string[] ForbiddenPrefixes = { "OTEL", "DD_", "_DD_", "DATADOG_ " }; | ||
|  | ||
| private static readonly DiagnosticDescriptor Rule = new( | ||
| DiagnosticId, | ||
| title: "Invalid PlatformKeys constant naming", | ||
| messageFormat: "PlatformKeys constant '{0}' should not start with '{1}'. Platform keys should represent external environment variables, not Datadog or OpenTelemetry configuration keys. Use ConfigurationKeys instead.", | ||
| category: "CodeQuality", | ||
| defaultSeverity: DiagnosticSeverity.Error, | ||
| isEnabledByDefault: true, | ||
| description: "Constants in PlatformKeys class should not start with OTEL, DD_, or _DD_ prefixes as these are reserved for OpenTelemetry and Datadog configuration keys. Platform keys should represent environment variables from external platforms and services."); | ||
|  | ||
| /// <inheritdoc /> | ||
| public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(Rule); | ||
|  | ||
| /// <inheritdoc /> | ||
| public override void Initialize(AnalysisContext context) | ||
| { | ||
| context.EnableConcurrentExecution(); | ||
| context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); | ||
| context.RegisterSymbolAction(AnalyzeNamedType, SymbolKind.NamedType); | ||
| } | ||
|  | ||
| private static void AnalyzeNamedType(SymbolAnalysisContext context) | ||
| { | ||
| var namedTypeSymbol = (INamedTypeSymbol)context.Symbol; | ||
|  | ||
| // Check if this is the PlatformKeys class in the correct namespace | ||
| if (!IsPlatformKeysClass(namedTypeSymbol)) | ||
| { | ||
| return; | ||
| } | ||
|  | ||
| // Analyze all const fields in the PlatformKeys class and its nested classes | ||
| AnalyzeConstFields(context, namedTypeSymbol); | ||
| } | ||
|  | ||
| private static bool IsPlatformKeysClass(INamedTypeSymbol namedTypeSymbol) | ||
| { | ||
| // Check if this is the PlatformKeys class (including partial classes) | ||
| if (namedTypeSymbol.Name != PlatformKeysClassName) | ||
| { | ||
| return false; | ||
| } | ||
|  | ||
| // Check if it's in the correct namespace | ||
| var containingNamespace = namedTypeSymbol.ContainingNamespace; | ||
| return containingNamespace?.ToDisplayString() == PlatformKeysNamespace; | ||
| } | ||
|  | ||
| private static void AnalyzeConstFields(SymbolAnalysisContext context, INamedTypeSymbol typeSymbol) | ||
| { | ||
| // Analyze const fields in the current type | ||
| foreach (var member in typeSymbol.GetMembers()) | ||
| { | ||
| if (member is IFieldSymbol { IsConst: true, Type.SpecialType: SpecialType.System_String } field) | ||
| { | ||
| AnalyzeConstField(context, field); | ||
| } | ||
| else if (member is INamedTypeSymbol nestedType) | ||
| { | ||
| // Recursively analyze nested classes (like Aws, AzureAppService, etc.) | ||
| AnalyzeConstFields(context, nestedType); | ||
| } | ||
| } | ||
| } | ||
|  | ||
| private static void AnalyzeConstField(SymbolAnalysisContext context, IFieldSymbol field) | ||
| { | ||
| if (field.ConstantValue is not string constantValue) | ||
| { | ||
| return; | ||
| } | ||
|  | ||
| // Check if the constant value starts with any forbidden prefix (case-insensitive) | ||
| var forbiddenPrefix = ForbiddenPrefixes.FirstOrDefault(prefix => constantValue.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)); | ||
| if (forbiddenPrefix == null) | ||
| { | ||
| return; | ||
| } | ||
|  | ||
| var diagnostic = Diagnostic.Create( | ||
| Rule, | ||
| field.Locations.FirstOrDefault(), | ||
| constantValue, | ||
| forbiddenPrefix); | ||
|  | ||
| context.ReportDiagnostic(diagnostic); | ||
| } | ||
| } | 
  
    
      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
    
  
  
    
              
      
      Oops, something went wrong.
        
    
  
      
      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.
  
    
  
    
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Later, as in later in this config stack, or as in after that?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
later as later in config registry v2 😅