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
8 changes: 8 additions & 0 deletions aiohttp/web_log.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,12 @@ def compile_format(self, log_format: str) -> tuple[str, list[KeyMethod]]:
# can repeat the same key more than once
methods = list()

# Protect literal "%%" (an escaped percent sign) before atom processing
# so the second "%" is not mistaken for the start of an atom and is not
# re-escaped into an invalid "%%%" format by the cleanup pass below.
sentinel = "\x00"
log_format = log_format.replace("%%", sentinel)

for atom in self.FORMAT_RE.findall(log_format):
if atom[1] == "":
format_key1 = self.LOG_FORMAT_MAP[atom[0]]
Expand All @@ -121,6 +127,8 @@ def compile_format(self, log_format: str) -> tuple[str, list[KeyMethod]]:

log_format = self.FORMAT_RE.sub(r"%s", log_format)
log_format = self.CLEANUP_RE.sub(r"%\1", log_format)
# Restore protected "%%" as a percent-format escape for a literal "%".
log_format = log_format.replace(sentinel, "%%")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Null separators become percent signs

If an app uses null characters to separate fields in log_format, this replacement changes them to percent signs too. For example, "%a\x00%s" now writes % between the address and status, so readers that split on null characters lose the field boundaries. Choose a marker absent from the input, or handle %% without a marker.

return log_format, methods

@staticmethod
Expand Down
19 changes: 18 additions & 1 deletion tests/test_web_log.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,27 @@ def test_access_logger_format() -> None:
log_format = '%T "%{ETag}o" %X {X} %%P'
mock_logger = mock.Mock()
access_logger = AccessLogger(mock_logger, log_format)
expected = '%s "%s" %%X {X} %%%s'
expected = '%s "%s" %%X {X} %%P'
assert expected == access_logger._log_format


def test_access_logger_format_literal_percent() -> None:
"""A literal ``%%`` compiles to a valid percent-escape and logs correctly.

Regression test for https://github.com/aio-libs/aiohttp/issues/14390
"""
mock_logger = mock.Mock()
access_logger = AccessLogger(mock_logger, "%a %s 100%%")
assert "%s %s 100%%" == access_logger._log_format

request = mock.Mock(remote="127.0.0.1", headers={})
response = mock.Mock(status=200, headers={})
access_logger.log(request, response, 0.1)
# The escaped "%%" renders as a single "%" and no error is raised.
mock_logger.info.assert_called_once()
mock_logger.exception.assert_not_called()


@pytest.mark.skipif(
IS_PYPY,
reason="""
Expand Down
Loading