Skip to content

Feature request: Sanitize the string generated by Tracing decorator #740

@hjgraca

Description

@hjgraca

Use case

Currently the string that gets generated from the decorated methods with Tracing does not get sanitized and might fail silently to add traces to X-Ray due to invalid characters

In the following example with top level statements the generated string is ## <<Main>$>g__Handler|0_0 which breaks the accepted characters for segment name defined in the X-Ray documentation.

using System.Text.Json;
using Amazon.Lambda.Core;
using Amazon.Lambda.RuntimeSupport;
using Amazon.Lambda.Serialization.SystemTextJson;
using AWS.Lambda.Powertools.Tracing;


await LambdaBootstrapBuilder.Create((Func<string, ILambdaContext, Task<string>>)Handler, new DefaultLambdaJsonSerializer())
        .Build()
        .RunAsync();

[Tracing(SegmentName = "My Handler")]
async Task<string> Handler(string input, ILambdaContext context)
{
    
    string json = await CreateAnonObjectAsJson(input);

    return await Task.FromResult(json);
}

[Tracing(SegmentName = "My Mehod")]
async Task<string> CreateAnonObjectAsJson(string input)
{
    var val = new
    {
        input,
        utcDate = DateTime.UtcNow.ToString("s"),
        date = DateTime.Now.ToString("s"),
    };

    string json = JsonSerializer.Serialize(val, new JsonSerializerOptions { WriteIndented = true });

    return json;
}

Solution/User Experience

We will tackle this issue in two ways:

  1. Add a summary to the SegmentName property that shows what are the accepted characters
  2. Sanitize the string generated by the handler/methods to remove unsupported characters

Summary

    /// <summary>
    ///     Set custom segment name for the operation.
    ///     The default is '## {MethodName}'.
    ///
    ///     The logical name of the service that handled the request, up to 200 characters. 
    ///     Names can contain Unicode letters, numbers, and whitespace, and the following symbols: \_, ., :, /, %, &amp;, #, =, +, \\, -, @
    /// </summary>
    public string SegmentName { get; set; } = "";

Sanitize

using System.Text.RegularExpressions;

public static string SanitizeString(string input)
{
    // Define a regular expression pattern to match allowed characters
    string pattern = @"[^a-zA-Z0-9\s_\.\:/%&#=+\-@]";
    
    // Replace any character that does not match the pattern with an empty string
    return Regex.Replace(input, pattern, string.Empty);
}

Alternative solutions

Acknowledgment

Metadata

Metadata

Assignees

Labels

feature-requestNew or enhancements to existing featurespending-releaseFix or implementation already in dev waiting to be released

Type

No type

Projects

Status

✅ Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions