-
Notifications
You must be signed in to change notification settings - Fork 658
fix(boto3): Fix botocore SigV4 failures caused by post-sign trace propagation #7050
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
pabloDeputter
wants to merge
39
commits into
master
Choose a base branch
from
pablo/fix-botocore-sigv4-trace-propagation
base: master
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.
+727
−5
Open
Changes from all commits
Commits
Show all changes
39 commits
Select commit
Hold shift + click to select a range
abc57bc
fix(boto3): Inject trace headers before SigV4 signing
pabloDeputter 78f1ee6
fix(stdlib): Preserve signed headers during trace propagation
pabloDeputter 88fdd7d
test(boto3): add tests covering trace propagation + SigV4 signing
pabloDeputter a1e5f9c
test(boto3): inline span_streaming logic
pabloDeputter 4ba8901
test(stdlib): cover httplib SigV4 trace header preservation
pabloDeputter 92672ca
test(boto3): Add `server_close()` in test cleanup
pabloDeputter 37fa9ff
fix(stdlib): clarify comment
pabloDeputter e675673
fix(stdlib): Move trace header generation into `endheaders()`
pabloDeputter 14bad29
fix(stdlib): Replace `return set()` with `continue` to avoid skipping…
pabloDeputter 90a77d6
fix(stdlib): Move `get_aws_sigv4_signed_headers` to `sentry_sdk.utils…
pabloDeputter f2d0cee
fix(stdlib): Make mypy happy
pabloDeputter e6e9e5e
fix(stdlib): Capture internal exceptions in `endheaders()`
pabloDeputter 3f4dacc
test(utils): Add test for `get_aws_sigv4_signed_headers`
pabloDeputter 6d7301c
fix(aiohttp): Preserve SigV4 signed headers
pabloDeputter a0c1ad2
test(aiohttp): Add tests related to SigV4 issues
pabloDeputter e40e931
test(boto3): Add signed header assertions to tests
pabloDeputter af905db
test(httplib): Add tests for SigV4 signed headers
pabloDeputter 09f8c44
fix(aiohttp): Do `request.rel_url` instead of `request.url` so py3.7-…
pabloDeputter e07978e
fix(aiohttp): Use `raw_path` instead of `rel_url` to avoid encoding i…
pabloDeputter 08dc4d2
ref(boto3): Clarify logic in `replace_header()`
pabloDeputter 079cf17
ref(utils): Remove bytes parsing from `get_aws_sigv4_signed_headers()…
pabloDeputter ebcce02
ref(utils): `get_aws_sigv4_signed_headers()` now takes in `authorizat…
pabloDeputter 484a941
chore(stdlib): Track headers during request construction
pabloDeputter 35ff7b4
linting
pabloDeputter 355be07
fix(stdlib): Fix renaming issue
pabloDeputter 5ab6ccb
ref(utils): Remove unused `Mapping` import
pabloDeputter f04bd51
ref(stdlib): Fix another typo
pabloDeputter 28e33cc
revert aiohttp changes
alexander-alderman-webb 6ff70c4
limit changes to botocore connection classes
alexander-alderman-webb 8003db0
merge master
alexander-alderman-webb b68e9f7
formatting
alexander-alderman-webb 3ce7587
make mypy happy
alexander-alderman-webb 628543e
clean up trace_url on endheaders
alexander-alderman-webb a739e84
(ref): Make `get_aws_sigv4_signed_headers` private; renamed to `_get_…
pabloDeputter 3d44029
(tests): Move tests using `AWSHTTPConnection` to `test_aws_http_conne…
pabloDeputter c706b7b
remove tracking of uncessary headers
pabloDeputter 1ee3b58
ruff fix
pabloDeputter 8762b88
resolve PR comments
pabloDeputter 98195e9
pr comments: made logic a bit easier and more clariyfing comments
pabloDeputter 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
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 |
|---|---|---|
|
|
@@ -10,7 +10,7 @@ | |
| from sentry_sdk.integrations import Integration | ||
| from sentry_sdk.scope import add_global_event_processor, should_send_default_pii | ||
| from sentry_sdk.traces import StreamedSpan | ||
| from sentry_sdk.tracing import Span | ||
| from sentry_sdk.tracing import BAGGAGE_HEADER_NAME, SENTRY_TRACE_HEADER_NAME, Span | ||
| from sentry_sdk.tracing_utils import ( | ||
| EnvironHeaders, | ||
| add_http_breadcrumb, | ||
|
|
@@ -20,6 +20,8 @@ | |
| ) | ||
| from sentry_sdk.utils import ( | ||
| SENSITIVE_DATA_SUBSTITUTE, | ||
| _get_aws_sigv4_signed_headers_from_authorization_header, | ||
| _get_aws_sigv4_signed_headers_from_url_query_string, | ||
| capture_internal_exceptions, | ||
| ensure_integration_enabled, | ||
| is_sentry_url, | ||
|
|
@@ -29,7 +31,7 @@ | |
| ) | ||
|
|
||
| if TYPE_CHECKING: | ||
| from typing import Any, Callable, Dict, List, Optional, Union | ||
| from typing import Any, Callable, Dict, List, Optional, Set, Union | ||
|
|
||
| from sentry_sdk._types import Event, Hint | ||
|
|
||
|
|
@@ -40,6 +42,14 @@ | |
| "build": sys.version, | ||
| } | ||
|
|
||
| _SENTRY_HEADER_NAMES = frozenset((BAGGAGE_HEADER_NAME, SENTRY_TRACE_HEADER_NAME)) | ||
|
|
||
| try: | ||
| from botocore.awsrequest import AWSHTTPConnection, AWSHTTPSConnection | ||
| except ImportError: | ||
| AWSHTTPConnection = None # type: ignore[misc,assignment] | ||
| AWSHTTPSConnection = None # type: ignore[misc,assignment] | ||
|
|
||
|
|
||
| class StdlibIntegration(Integration): | ||
| identifier = "stdlib" | ||
|
|
@@ -73,6 +83,164 @@ def _complete_span(span: "Union[Span, StreamedSpan]") -> None: | |
| add_http_request_source(span) | ||
|
|
||
|
|
||
| def _get_wrapped_putheader( | ||
| original_putheader: "Callable[..., Any]", | ||
| ) -> "Callable[..., Any]": | ||
| """Record existing `sentry-trace` and SigV4-signed propagation headers to skip.""" | ||
|
|
||
| def putheader(self: "HTTPConnection", header: "Any", *values: "Any") -> "Any": | ||
| rv = original_putheader(self, header, *values) | ||
|
|
||
| headers_to_skip: "Optional[Set[str]]" = getattr( | ||
| self, "_sentrysdk_headers_to_skip", None | ||
| ) | ||
| if headers_to_skip is None: | ||
| return rv | ||
|
|
||
| if isinstance(header, bytes): | ||
| normalized_header = header.decode("ascii", "ignore").lower() | ||
| elif isinstance(header, str): | ||
| normalized_header = header.lower() | ||
| else: | ||
| return rv | ||
|
|
||
| # existing `sentry-trace`: skip so it is not duplicated. | ||
| if normalized_header == SENTRY_TRACE_HEADER_NAME: | ||
| headers_to_skip.add(normalized_header) | ||
|
|
||
| if normalized_header == "authorization" and values: | ||
| with capture_internal_exceptions(): | ||
| authorization = values[0] | ||
| if isinstance(authorization, bytes): | ||
| authorization = authorization.decode("latin-1") | ||
| # `SignedHeaders` lists fields covered by SigV4. | ||
| signed_headers = ( | ||
| _get_aws_sigv4_signed_headers_from_authorization_header( | ||
| authorization | ||
| ) | ||
| ) | ||
| # skip signed `sentry-trace` and `baggage`. | ||
| headers_to_skip.update( | ||
| _SENTRY_HEADER_NAMES.intersection(signed_headers) | ||
| ) | ||
|
|
||
| return rv | ||
|
|
||
| return putheader | ||
|
|
||
|
|
||
| def _get_wrapped_endheaders( | ||
| original_endheaders: "Callable[..., Any]", | ||
| ) -> "Callable[..., Any]": | ||
| """ | ||
| Add unsigned propagation headers immediately before sending. | ||
|
|
||
| `sentry-trace`: add if missing; leave an existing or signed value as-is. | ||
| `baggage`: add if missing; append if unsigned since multiple fields are | ||
| allowed and combined (https://www.w3.org/TR/baggage/#baggage-http-header-format); | ||
| leave a signed value as-is since it is part of the SigV4 signature. | ||
| """ | ||
|
|
||
| def endheaders(self: "HTTPConnection", *args: "Any", **kwargs: "Any") -> "Any": | ||
| real_url = getattr(self, "_sentrysdk_real_url", None) | ||
| span = getattr(self, "_sentrysdk_span", None) | ||
|
|
||
| try: | ||
| if real_url is not None: | ||
| with capture_internal_exceptions(): | ||
| headers_to_skip = getattr(self, "_sentrysdk_headers_to_skip", None) | ||
|
|
||
| if headers_to_skip is not None: | ||
| # presigned URLs list signed names in the query string. | ||
| query_signed_headers = ( | ||
| _get_aws_sigv4_signed_headers_from_url_query_string( | ||
| real_url | ||
| ) | ||
| ) | ||
| headers_to_skip.update( | ||
| _SENTRY_HEADER_NAMES.intersection(query_signed_headers) | ||
| ) | ||
|
|
||
| for ( | ||
| header_name, | ||
| header_value, | ||
| ) in sentry_sdk.get_current_scope().iter_trace_propagation_headers( | ||
| span=span | ||
| ): | ||
| # skip signed headers and an existing `sentry-trace`. | ||
| if header_name.lower() in headers_to_skip: | ||
| continue | ||
|
|
||
| logger.debug( | ||
| "[Tracing] Adding `{key}` header {value} to outgoing request to {real_url}.".format( | ||
| key=header_name, | ||
| value=header_value, | ||
| real_url=real_url, | ||
| ) | ||
| ) | ||
| self.putheader(header_name, header_value) | ||
| return original_endheaders(self, *args, **kwargs) | ||
| finally: | ||
| self._sentrysdk_real_url = None # type: ignore[attr-defined] | ||
|
|
||
| return endheaders | ||
|
|
||
|
|
||
| def _get_wrapped_putrequest( | ||
| original_putrequest: "Callable[..., Any]", | ||
| ) -> "Callable[..., Any]": | ||
| """Start `headers_to_skip` before headers are written.""" | ||
|
|
||
| def putrequest( | ||
| self: "HTTPConnection", method: str, url: str, *args: "Any", **kwargs: "Any" | ||
| ) -> "Any": | ||
| # existing `sentry-trace` and SigV4-signed propagation headers are skipped. | ||
| self._sentrysdk_headers_to_skip = set() # type: ignore[attr-defined] | ||
|
|
||
| try: | ||
| rv = original_putrequest(self, method, url, *args, **kwargs) | ||
| except BaseException: | ||
| # do not leave partial request state on a reusable connection when | ||
| # the underlying request setup fails. | ||
| self._sentrysdk_headers_to_skip = None # type: ignore[attr-defined] | ||
| raise | ||
|
|
||
| return rv | ||
|
|
||
| return putrequest | ||
|
|
||
|
|
||
| def _patch_aws_connection() -> None: | ||
| """ | ||
| Patch AWS connection classes so trace propagation does not break SigV4. | ||
|
|
||
| Botocore signs the request before headers reach HTTPConnection. Wait until | ||
| `endheaders()` to add unsigned propagation headers, after `putheader()` has | ||
| recorded existing `sentry-trace` and signed field names. | ||
| """ | ||
| if AWSHTTPConnection is not None: | ||
| AWSHTTPConnection.putheader = _get_wrapped_putheader( # type: ignore[method-assign] | ||
| AWSHTTPConnection.putheader | ||
| ) | ||
| AWSHTTPConnection.endheaders = _get_wrapped_endheaders( # type: ignore[method-assign] | ||
| AWSHTTPConnection.endheaders | ||
| ) | ||
| AWSHTTPConnection.putrequest = _get_wrapped_putrequest( # type: ignore[method-assign] | ||
| AWSHTTPConnection.putrequest | ||
| ) | ||
|
|
||
| if AWSHTTPSConnection is not None: | ||
| AWSHTTPSConnection.putheader = _get_wrapped_putheader( # type: ignore[method-assign] | ||
| AWSHTTPSConnection.putheader | ||
| ) | ||
| AWSHTTPSConnection.endheaders = _get_wrapped_endheaders( # type: ignore[method-assign] | ||
| AWSHTTPSConnection.endheaders | ||
| ) | ||
| AWSHTTPSConnection.putrequest = _get_wrapped_putrequest( # type: ignore[method-assign] | ||
| AWSHTTPSConnection.putrequest | ||
| ) | ||
|
|
||
|
|
||
| def _install_httplib() -> None: | ||
|
sentry-warden[bot] marked this conversation as resolved.
|
||
| real_putrequest = HTTPConnection.putrequest | ||
| real_getresponse = HTTPConnection.getresponse | ||
|
|
@@ -189,7 +357,11 @@ def putrequest( | |
|
|
||
| rv = real_putrequest(self, method, url, *args, **kwargs) | ||
|
|
||
| if should_propagate_trace(client, real_url): | ||
| # if `_sentrysdk_headers_to_skip` is set, inject headers in `endheaders()` | ||
| # after botocore has supplied the final headers. | ||
| if should_propagate_trace(client, real_url) and not hasattr( | ||
| self, "_sentrysdk_headers_to_skip" | ||
| ): | ||
| for ( | ||
| key, | ||
| value, | ||
|
|
@@ -202,6 +374,8 @@ def putrequest( | |
| ) | ||
| ) | ||
| self.putheader(key, value) | ||
| elif should_propagate_trace(client, real_url): | ||
| self._sentrysdk_real_url = real_url # type: ignore[attr-defined] | ||
|
|
||
| self._sentrysdk_span = span # type: ignore[attr-defined] | ||
| self._sentrysdk_breadcrumb = breadcrumb # type: ignore[attr-defined] | ||
|
|
@@ -286,6 +460,9 @@ def close(self: "HTTPResponse") -> None: | |
| _complete_span(span) | ||
|
|
||
| HTTPConnection.putrequest = putrequest # type: ignore[method-assign] | ||
| # patch `HTTPConnection.putrequest()` first. urllib3 < 1.25.9 inherits it, so | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'd also add a note that once |
||
| # wrapping AWS classes first would skip URL and span recording. | ||
| _patch_aws_connection() | ||
| HTTPConnection.getresponse = getresponse # type: ignore[method-assign] | ||
| HTTPResponse.read = read # type: ignore[method-assign] | ||
| HTTPResponse.close = close # type: ignore[assignment,method-assign] | ||
|
|
||
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.
Uh oh!
There was an error while loading. Please reload this page.