1

Is there a way to check correctness of traceparent http header using Azure API Management policies before is forwarded to backend service?

Znas Me
  • 190
  • 1
  • 15

2 Answers2

3

The best that I could find is to create API management policy with regular expression. It will find most of invalid cases, expect some of corner cases. If invalid http traceparent header supplied then 400 - bad request, response is returned.

    <choose>
        <when condition="@(!Regex.IsMatch(context.Request.Headers.GetValueOrDefault("traceparent",""), @"^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$", RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(500)))">
            <return-response>
                <set-status code="400" reason="Bad request - Missing or invalid traceparent http header" />
                <set-header name="Content-Type" exists-action="override">
                    <value>application/json</value>
                </set-header>
                <set-body>@(new JObject(new JProperty("statusCode", 400), new JProperty("message", "Missing or invalid &apos;traceparent&apos; http header for distributed tracing. More information how to supply one at https://www.w3.org/TR/trace-context-1/")).ToString())</set-body>
            </return-response>
        </when>
    </choose>
Pang
  • 9,564
  • 146
  • 81
  • 122
Znas Me
  • 190
  • 1
  • 15
0

Only manually. You can use choose policy with a policy expression where you get value of the header and validate it using C# code. And then take different actions depending on whether you deem it valid or not.

Vitaliy Kurokhtin
  • 7,205
  • 1
  • 19
  • 18
  • I was hoping that I do not need to add manually code in API Management. Can you point me somewhere where I find example how to validate traceparent header, because C# is not my primary language. Pretty much sure behind the scene, somewhere in Azure ecosystem, exactly the same validation is performed. – Znas Me Mar 18 '20 at 17:57