Skip to content

Commit

Permalink
Merge pull request #71 from tlinhart/log-new-header-value
Browse files Browse the repository at this point in the history
Use new header value in failed validation warning
  • Loading branch information
sondrelg authored Feb 24, 2023
2 parents 17f0b1a + 20e2e9b commit 860f4d5
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 3 deletions.
6 changes: 5 additions & 1 deletion asgi_correlation_id/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,14 @@ async def __call__(self, scope: 'Scope', receive: 'Receive', send: 'Send') -> No
headers = MutableHeaders(scope=scope)
header_value = headers.get(self.header_name.lower())

validation_failed = False
if not header_value:
# Generate request ID if none was found
id_value = self.generator()
elif self.validator and not self.validator(header_value):
# Also generate a request ID if one was found, but it was deemed invalid
validation_failed = True
id_value = self.generator()
logger.warning(FAILED_VALIDATION_MESSAGE, header_value)
else:
# Otherwise, use the found request ID
id_value = header_value
Expand All @@ -69,6 +70,9 @@ async def __call__(self, scope: 'Scope', receive: 'Receive', send: 'Send') -> No
if self.transformer:
id_value = self.transformer(id_value)

if validation_failed is True:
logger.warning(FAILED_VALIDATION_MESSAGE, id_value)

# Update the request headers if needed
if id_value != header_value and self.update_request_header is True:
headers[self.header_name] = id_value
Expand Down
5 changes: 3 additions & 2 deletions tests/test_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,9 @@ async def test_view() -> dict:

async with AsyncClient(app=app, base_url='http://test') as client:
response = await client.get('test', headers={'X-Request-ID': value})
assert response.headers['X-Request-ID'] != value
assert caplog.messages[0] == FAILED_VALIDATION_MESSAGE.replace('%s', value)
new_value = response.headers['X-Request-ID']
assert new_value != value
assert caplog.messages[0] == FAILED_VALIDATION_MESSAGE.replace('%s', new_value)


@pytest.mark.parametrize('app', apps)
Expand Down

0 comments on commit 860f4d5

Please sign in to comment.