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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
([#4078](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/4171))
- `opentelemetry-instrumentation-aiohttp-server`: fix HTTP error inconsistencies
([#4175](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/4175))
- `opentelemetry-instrumentation-aws-lambda`, `opentelemetry-instrumentation`: fix improper handling of header casing
([#4216](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/4216))

### Breaking changes

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ def custom_event_context_extractor(lambda_event):
from opentelemetry.context.context import Context
from opentelemetry.instrumentation.aws_lambda.package import _instruments
from opentelemetry.instrumentation.aws_lambda.version import __version__
from opentelemetry.instrumentation.cidict import CIDict
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from opentelemetry.instrumentation.utils import unwrap
from opentelemetry.metrics import MeterProvider, get_meter_provider
Expand Down Expand Up @@ -176,7 +177,9 @@ def _default_event_context_extractor(lambda_event: Any) -> Context:
)
if not isinstance(headers, dict):
headers = {}
return get_global_textmap().extract(headers)
return get_global_textmap().extract(
Copy link
Contributor

@xrmx xrmx Feb 20, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When I did this in another code base I've only done the header normalization for v1 using this to decide if that was the case:

def should_normalize(event):
    request_context = event.get("requestContext", {})
    return ("elb" in request_context or "requestId" in request_context) and "http" not in request_context

Maybe here it would be impractical since we are picking more stuff from the headers.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We'd want to normalize regardless, no? For example, even if you're using API GW v2, it's possible that a caller still might not provide headers as lowercase.

CIDict(headers),
)


def _determine_parent_context(
Expand Down Expand Up @@ -216,20 +219,21 @@ def _set_api_gateway_v1_proxy_attributes(
span.set_attribute(HTTP_METHOD, lambda_event.get("httpMethod"))

if lambda_event.get("headers"):
if "User-Agent" in lambda_event["headers"]:
headers = CIDict(lambda_event["headers"])
if "User-Agent" in headers:
span.set_attribute(
HTTP_USER_AGENT,
lambda_event["headers"]["User-Agent"],
headers["User-Agent"],
)
if "X-Forwarded-Proto" in lambda_event["headers"]:
if "X-Forwarded-Proto" in headers:
span.set_attribute(
HTTP_SCHEME,
lambda_event["headers"]["X-Forwarded-Proto"],
headers["X-Forwarded-Proto"],
)
if "Host" in lambda_event["headers"]:
if "Host" in headers:
span.set_attribute(
NET_HOST_NAME,
lambda_event["headers"]["Host"],
headers["Host"],
)
if "resource" in lambda_event:
span.set_attribute(HTTP_ROUTE, lambda_event["resource"])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,36 @@ def custom_event_context_extractor(lambda_event):
expected_baggage=MOCK_W3C_BAGGAGE_VALUE,
propagators="tracecontext,baggage",
),
TestCase(
name="case_insensitive_headers_uppercase",
custom_extractor=None,
context={
"headers": {
TraceContextTextMapPropagator._TRACEPARENT_HEADER_NAME.upper(): MOCK_W3C_TRACE_CONTEXT_SAMPLED,
TraceContextTextMapPropagator._TRACESTATE_HEADER_NAME.upper(): f"{MOCK_W3C_TRACE_STATE_KEY}={MOCK_W3C_TRACE_STATE_VALUE},foo=1,bar=2",
}
},
expected_traceid=MOCK_W3C_TRACE_ID,
expected_parentid=MOCK_W3C_PARENT_SPAN_ID,
expected_trace_state_len=3,
expected_state_value=MOCK_W3C_TRACE_STATE_VALUE,
xray_traceid=MOCK_XRAY_TRACE_CONTEXT_NOT_SAMPLED,
),
TestCase(
name="case_insensitive_headers_mixedcase",
custom_extractor=None,
context={
"headers": {
"TraceParent": MOCK_W3C_TRACE_CONTEXT_SAMPLED,
"tRaCeStAtE": f"{MOCK_W3C_TRACE_STATE_KEY}={MOCK_W3C_TRACE_STATE_VALUE},foo=1,bar=2",
}
},
expected_traceid=MOCK_W3C_TRACE_ID,
expected_parentid=MOCK_W3C_PARENT_SPAN_ID,
expected_trace_state_len=3,
expected_state_value=MOCK_W3C_TRACE_STATE_VALUE,
xray_traceid=MOCK_XRAY_TRACE_CONTEXT_NOT_SAMPLED,
),
]
for test in tests:
with self.subTest(test_name=test.name):
Expand Down Expand Up @@ -400,6 +430,57 @@ def test_lambda_no_error_with_invalid_flush_timeout(self):

test_env_patch.stop()

def test_api_gateway_v1_attributes_case_insensitivity(self):
AwsLambdaInstrumentor().instrument()

mock_execute_lambda(
{
"httpMethod": "GET",
"headers": {
"user-agent": "lowercase-agent",
"host": "lowercase-host",
"x-forwarded-proto": "http",
},
"resource": "/test",
"requestContext": {
"version": "1.0",
},
}
)

spans = self.memory_exporter.get_finished_spans()
self.assertEqual(len(spans), 1)
span = spans[0]
self.assertEqual(
span.attributes.get(HTTP_USER_AGENT), "lowercase-agent"
)
self.assertEqual(span.attributes.get(NET_HOST_NAME), "lowercase-host")
self.assertEqual(span.attributes.get(HTTP_SCHEME), "http")

self.memory_exporter.clear()

mock_execute_lambda(
{
"httpMethod": "GET",
"headers": {
"uSeR-aGeNt": "mixed-agent",
"hOsT": "mixed-host",
"X-fOrWaRdEd-PrOtO": "https",
},
"resource": "/test",
"requestContext": {
"version": "1.0",
},
}
)

spans = self.memory_exporter.get_finished_spans()
self.assertEqual(len(spans), 1)
span = spans[0]
self.assertEqual(span.attributes.get(HTTP_USER_AGENT), "mixed-agent")
self.assertEqual(span.attributes.get(NET_HOST_NAME), "mixed-host")
self.assertEqual(span.attributes.get(HTTP_SCHEME), "https")

def test_lambda_handles_multiple_consumers(self):
test_env_patch = mock.patch.dict(
"os.environ",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
# Copyright The OpenTelemetry Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import annotations

from typing import (
Any,
Generic,
Iterable,
Iterator,
Mapping,
MutableMapping,
Optional,
Tuple,
TypeVar,
Union,
)

KT = TypeVar("KT")
VT = TypeVar("VT")


class CIDict(MutableMapping[KT, VT], Generic[KT, VT]):
def __init__(
self,
data: Optional[Union[Mapping[KT, VT], Iterable[Tuple[KT, VT]]]] = None,
) -> None:
self._data: dict[KT, Tuple[KT, VT]] = {}
if data is None:
data = {}
self.update(data)

@staticmethod
def _normalize_key(key: KT) -> KT:
if isinstance(key, str):
return key.lower() # type: ignore
return key

def _get_entry(self, key: KT) -> Tuple[KT, VT]:
normalized_key = self._normalize_key(key)
if normalized_key in self._data:
return self._data[normalized_key]
raise KeyError(repr(key))

def original_key(self, key: KT) -> KT:
return self._get_entry(key)[0]

def normalized_items(self) -> Iterable[Tuple[KT, VT]]:
return ((key, value[1]) for key, value in self._data.items())

def __setitem__(self, key: KT, value: VT, /) -> None:
self._data[self._normalize_key(key)] = (key, value)

def __delitem__(self, key: KT, /) -> None:
try:
del self._data[self._normalize_key(key)]
except KeyError:
raise KeyError(repr(key)) from None

def __getitem__(self, key: KT, /) -> VT:
return self._get_entry(key)[1]

def __len__(self) -> int:
return len(self._data)

def __iter__(self) -> Iterator[KT]:
return (key for key, _ in self._data.values())

def __repr__(self) -> str:
return f"{self.__class__.__name__}({dict(self.items())!r})"

def __eq__(self, other: Any) -> bool:
if isinstance(other, CIDict):
return dict(self.normalized_items()) == dict(
other.normalized_items()
)
if not isinstance(other, Mapping):
return False
ciother: CIDict[Any, Any] = CIDict(other)
return dict(self.normalized_items()) == dict(
ciother.normalized_items()
)
Loading