Coverage for src/governed_harness/api/access_log.py: 95%

18 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-12 16:06 +0000

1"""Access log of ``harness api serve`` without query strings (#174). 

2 

3uvicorn writes the request target with its query string to the access log. The API accepts the 

4token only in the ``Authorization`` header, but a client that sends ``?token=...`` by mistake 

5would still get it written in clear, so the query string is dropped before any handler formats 

6the record: the line keeps the client, method, path, HTTP version and status.""" 

7 

8from __future__ import annotations 

9 

10import copy 

11import logging 

12from typing import Any 

13 

14ACCESS_LOGGER = "uvicorn.access" 

15 

16 

17class StripQueryFilter(logging.Filter): 

18 """Remove the query string from the request target of a uvicorn access record.""" 

19 

20 def filter(self, record: logging.LogRecord) -> bool: 

21 args = record.args 

22 if isinstance(args, tuple) and len(args) >= 3 and isinstance(args[2], str): 22 ↛ 24line 22 didn't jump to line 24 because the condition on line 22 was always true

23 record.args = (*args[:2], args[2].split("?", 1)[0], *args[3:]) 

24 return True 

25 

26 

27def log_config() -> dict[str, Any]: 

28 """uvicorn's default logging configuration with the query filter on the access logger.""" 

29 from uvicorn.config import LOGGING_CONFIG 

30 

31 config = copy.deepcopy(LOGGING_CONFIG) 

32 config.setdefault("filters", {})["strip_query"] = {"()": StripQueryFilter} 

33 access = config["loggers"].setdefault(ACCESS_LOGGER, {}) 

34 access["filters"] = [*access.get("filters", []), "strip_query"] 

35 return config