Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@
<Compile Include="..\Datadog.Trace\Ci\TestStatus.cs" Link="Ci\%(Filename)%(Extension)" />
<Compile Include="..\Datadog.Trace\ClrProfiler\AutoInstrumentation\ManualInstrumentation\TracerSettingKeyConstants.cs" Link="Configuration\%(Filename)%(Extension)" />
<Compile Include="..\Datadog.Trace\ClrProfiler\AutoInstrumentation\ManualInstrumentation\IntegrationSettingsSerializationHelper.cs" Link="Configuration\%(Filename)%(Extension)" />
<Compile Include="..\Datadog.Trace\Configuration\DeprecationMessages.cs" Link="Configuration\%(Filename)%(Extension)" />
<Compile Include="..\Datadog.Trace\Configuration\DeprecationMessages.cs"
Link="Configuration\%(Filename)%(Extension)" />
<Compile Include="..\Datadog.Trace\DuckTyping\DuckAsClassAttribute.cs" Link="DuckTyping\%(Filename)%(Extension)" />
<Compile Include="..\Datadog.Trace\HttpHeaderNames.cs" />
<Compile Include="..\Datadog.Trace\IDatadogOpenTracingTracer.cs" />
Expand Down

Large diffs are not rendered by default.

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;
}
}
}
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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,10 @@ internal static class ProcessConfiguration

if (logDirectory == null)
{
#pragma warning disable 618 // ProfilerLogPath is deprecated but still supported
var nativeLogFile = config.WithKeys(ConfigurationKeys.ProfilerLogPath).AsString();
#pragma warning restore 618
// ProfilerLogPath is deprecated but still supported. For now, we bypass the WithKeys analyzer, but later we want to pull deprecations differently as part of centralized file
Copy link
Member

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?

Copy link
Contributor Author

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 😅

#pragma warning disable DD0008, 618
var nativeLogFile = config.WithKeys(ConfigurationKeys.TraceLogPath).AsString();
#pragma warning restore DD0008, 618
if (!string.IsNullOrEmpty(nativeLogFile))
{
logDirectory = Path.GetDirectoryName(nativeLogFile);
Expand Down
2 changes: 1 addition & 1 deletion tracer/src/Datadog.Trace/AppSec/SecuritySettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ public SecuritySettings(IConfigurationSource? source, IConfigurationTelemetry te
UserEventsAutoInstrumentationMode = UserTrackingIdentMode;
}

ApiSecurityEnabled = config.WithKeys(ConfigurationKeys.AppSec.ApiSecurityEnabled, "DD_EXPERIMENTAL_API_SECURITY_ENABLED")
ApiSecurityEnabled = config.WithKeys(ConfigurationKeys.AppSec.ApiSecurityEnabled)
.AsBool(true);

ApiSecuritySampleDelay = config.WithKeys(ConfigurationKeys.AppSec.ApiSecuritySampleDelay)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ internal static bool TryLoadJsonConfigurationFile(IConfigurationSource configura

// if environment variable is not set, look for default file name in the current directory
var configurationFileName = new ConfigurationBuilder(configurationSource, telemetry)
.WithKeys(ConfigurationKeys.ConfigurationFileName, "DD_DOTNET_TRACER_CONFIG_FILE")
.WithKeys(ConfigurationKeys.ConfigurationFileName)
.AsString(
getDefaultValue: () => Path.Combine(baseDirectory ?? GetCurrentDirectory(), "datadog.json"),
validator: null);
Expand Down
Loading
Loading