log-redaction 0.1.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,40 @@
1
+ node_modules
2
+ dist
3
+ coverage
4
+ *.log
5
+ .DS_Store
6
+
7
+ # Dart
8
+ .dart_tool/
9
+ .packages
10
+ pubspec.lock
11
+
12
+ # Local env files
13
+ .env
14
+ .vercel
15
+ .tsconfig.tsbuildinfo
16
+
17
+ # Python
18
+ __pycache__/
19
+ *.py[cod]
20
+ .venv/
21
+ .pytest_cache/
22
+
23
+ # Zotero plugin
24
+ *.xpi
25
+
26
+ # Tool state
27
+ .omc/
28
+ .opencode/
29
+ .sisyphus/
30
+
31
+ # oh-my-agent runtime (local artifacts — do not commit)
32
+ .agents/oma-config.local.cue
33
+ .agents/oma-config.local.yaml
34
+ .antigravitycli/
35
+ .agents/results/
36
+ .agents/state/
37
+ .agents/backup/
38
+ docs/plans/
39
+ .migration-backup/
40
+ .qwen/tmp/
@@ -0,0 +1,8 @@
1
+ # Changelog
2
+
3
+ ## [0.1.1](https://github.com/gracefullight/pkgs/compare/log-redaction@0.1.0...log-redaction@0.1.1) (2026-12-03)
4
+
5
+
6
+ ### Features
7
+
8
+ * **log-redaction:** add log-redaction python package ([#71](https://github.com/gracefullight/pkgs/issues/71)) ([6355071](https://github.com/gracefullight/pkgs/commit/63550719d9e8d1188b9e51df94a4f82053f16979))
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Eunkwang Shin
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,173 @@
1
+ Metadata-Version: 2.5
2
+ Name: log-redaction
3
+ Version: 0.1.1
4
+ Summary: Credential redaction for structlog and standard-library logs
5
+ Project-URL: Homepage, https://github.com/gracefullight/pkgs/tree/main/packages/log-redaction#readme
6
+ Project-URL: Repository, https://github.com/gracefullight/pkgs
7
+ Project-URL: Issues, https://github.com/gracefullight/pkgs/issues
8
+ Project-URL: Changelog, https://github.com/gracefullight/pkgs/blob/main/packages/log-redaction/CHANGELOG.md
9
+ Author-email: Eunkwang Shin <gracefullight.dev@gmail.com>
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: litestar,logging,redaction,security,structlog
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Topic :: System :: Logging
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.12
23
+ Provides-Extra: litestar
24
+ Requires-Dist: litestar<3,>=2.0.0; extra == 'litestar'
25
+ Provides-Extra: structlog
26
+ Requires-Dist: structlog>=24.1.0; extra == 'structlog'
27
+ Description-Content-Type: text/markdown
28
+
29
+ # log-redaction
30
+
31
+ **English** | [한국어](./README.ko.md)
32
+
33
+ [![PyPI version](https://img.shields.io/pypi/v/log-redaction.svg)](https://pypi.org/project/log-redaction/)
34
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
35
+
36
+ Mask credentials in Python logs. It covers structlog events, standard-library log records and exception tracebacks. The core has no dependencies.
37
+
38
+ ## Features
39
+
40
+ - **Text redaction** - `redact_text` masks credentials in URLs, form bodies and exception messages
41
+ - **structlog processor** - `redact_processor` masks sensitive keys and nested strings in the event dict
42
+ - **stdlib formatter** - `RedactingFormatter` redacts the final formatted line, traceback included
43
+ - **One-call install** - `install_log_redaction` swaps the formatter on every root handler
44
+ - **Litestar plugin** - `LogRedactionPlugin` wires all of this in at application startup
45
+
46
+ ## Installation
47
+
48
+ ```bash
49
+ uv add log-redaction
50
+ # Optional integrations
51
+ uv add "log-redaction[structlog]"
52
+ uv add "log-redaction[litestar]"
53
+ ```
54
+
55
+ Requires Python 3.12 or newer.
56
+
57
+ ## What gets masked
58
+
59
+ Two kinds of parameter names are masked.
60
+
61
+ | Kind | Where | Default names |
62
+ |------|-------|---------------|
63
+ | Secret names | Anywhere: `access_token=abc` | `access_token`, `refresh_token`, `id_token`, `client_secret`, `fb_exchange_token`, `th_exchange_token`, `revoke_token`, `input_token`, `api_key`, `apikey`, `authorization`, `password`, `secret`, `token`, `AWSAccessKeyId`, `X-Goog-Signature`, `X-Amz-Signature`, `X-Amz-Credential` |
64
+ | Query-only names | Only after `?` or `&`: `?code=abc` | `code`, `auth`, `key`, `session`, `sig`, `signature`, `search` |
65
+
66
+ Query-only names stay readable in ordinary log lines, so `code=502` or `key=contents.brief.system` keep their diagnostic value. Slack incoming webhook URLs are always masked.
67
+
68
+ The structlog processor also masks the values of sensitive keys. These are the secret names plus `password_hash`, `webhook`, `webhook_url`, `bearer`, `credential`, `credentials`, `private_key` and `system_token`. Matching is case-insensitive.
69
+
70
+ ## Usage
71
+
72
+ ### Text
73
+
74
+ ```python
75
+ from log_redaction import redact_text
76
+
77
+ redact_text("GET https://graph.example.com/me?access_token=abc&fields=id")
78
+ # 'GET https://graph.example.com/me?access_token=***REDACTED***&fields=id'
79
+
80
+ redact_text("upstream failed code=502")
81
+ # 'upstream failed code=502'
82
+ ```
83
+
84
+ ### structlog
85
+
86
+ Put the processor immediately before the renderer.
87
+
88
+ ```python
89
+ import structlog
90
+ from log_redaction import redact_processor
91
+
92
+ structlog.configure(
93
+ processors=[
94
+ structlog.stdlib.add_log_level,
95
+ structlog.processors.TimeStamper(fmt="iso"),
96
+ redact_processor,
97
+ structlog.processors.JSONRenderer(),
98
+ ],
99
+ )
100
+ ```
101
+
102
+ ### Standard library logging
103
+
104
+ Call `install_log_redaction` after `logging.basicConfig`. It keeps each root handler's format string and date format.
105
+
106
+ ```python
107
+ import logging
108
+ from log_redaction import install_log_redaction
109
+
110
+ logging.basicConfig(format="%(levelname)s %(message)s", level=logging.INFO)
111
+ install_log_redaction()
112
+ ```
113
+
114
+ To attach the formatter yourself, use `RedactingFormatter`. It takes the same arguments as `logging.Formatter`.
115
+
116
+ ```python
117
+ from log_redaction import RedactingFormatter
118
+
119
+ handler.setFormatter(RedactingFormatter("%(asctime)s %(message)s"))
120
+ ```
121
+
122
+ ### Litestar
123
+
124
+ ```python
125
+ from litestar import Litestar
126
+ from log_redaction.litestar import LogRedactionPlugin
127
+
128
+ app = Litestar(route_handlers=[...], plugins=[LogRedactionPlugin()])
129
+ ```
130
+
131
+ At startup the plugin inserts the processor before the structlog renderer (the last processor in the chain), unless it is already there. It then installs `RedactingFormatter` on every root handler. Configure structlog and stdlib logging before the app starts. Without structlog installed, only the formatter is installed.
132
+
133
+ ### Custom name lists
134
+
135
+ `Redactor` takes the name lists as keyword arguments. Each argument replaces its default list.
136
+
137
+ ```python
138
+ from log_redaction import DEFAULT_QUERY_SECRET_NAMES, RedactingFormatter, Redactor
139
+ from log_redaction.litestar import LogRedactionPlugin
140
+
141
+ redactor = Redactor(
142
+ query_secret_names=(*DEFAULT_QUERY_SECRET_NAMES, "phone"),
143
+ )
144
+
145
+ redactor.redact_text("/users?phone=01000000000") # text
146
+ redactor # structlog processor
147
+ RedactingFormatter("%(message)s", redactor=redactor) # stdlib formatter
148
+ LogRedactionPlugin(redactor) # Litestar plugin
149
+ ```
150
+
151
+ | Argument | Default | Meaning |
152
+ |----------|---------|---------|
153
+ | `secret_names` | `DEFAULT_SECRET_NAMES` | Masked anywhere |
154
+ | `query_secret_names` | `DEFAULT_QUERY_SECRET_NAMES` | Masked only after `?` or `&` |
155
+ | `sensitive_keys` | `DEFAULT_SENSITIVE_KEYS` | Extra structlog keys to mask, on top of `secret_names` |
156
+
157
+ `install_log_redaction(redactor)` accepts a redactor as well.
158
+
159
+ ## API
160
+
161
+ | Name | Description |
162
+ |------|-------------|
163
+ | `MASK` | Replacement string, `***REDACTED***` |
164
+ | `redact_text(value)` | Mask credentials in a string |
165
+ | `redact_processor(logger, method_name, event_dict)` | structlog processor |
166
+ | `RedactingFormatter(..., redactor=None)` | `logging.Formatter` that redacts its output |
167
+ | `install_log_redaction(redactor=None)` | Replace the formatter on every root handler |
168
+ | `Redactor(*, secret_names, query_secret_names, sensitive_keys)` | Redaction with custom lists; the instance is a structlog processor |
169
+ | `log_redaction.litestar.LogRedactionPlugin(redactor=None)` | Litestar `InitPlugin` |
170
+
171
+ ## License
172
+
173
+ MIT
@@ -0,0 +1,145 @@
1
+ # log-redaction
2
+
3
+ [English](./README.md) | **한국어**
4
+
5
+ [![PyPI version](https://img.shields.io/pypi/v/log-redaction.svg)](https://pypi.org/project/log-redaction/)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
+
8
+ Python 로그에 섞인 자격증명을 마스킹합니다. structlog 이벤트, 표준 라이브러리 로그 레코드, 예외 트레이스백을 모두 덮습니다. 코어는 의존성이 없습니다.
9
+
10
+ ## 기능
11
+
12
+ - **문자열 리댁션** - `redact_text`가 URL, 폼 바디, 예외 메시지에 섞인 자격증명을 마스킹합니다
13
+ - **structlog 프로세서** - `redact_processor`가 이벤트 딕셔너리의 민감 키와 중첩 문자열을 마스킹합니다
14
+ - **stdlib 포매터** - `RedactingFormatter`가 트레이스백을 포함해 최종 포맷 결과를 리댁션합니다
15
+ - **한 번에 설치** - `install_log_redaction`이 모든 root 핸들러의 포매터를 교체합니다
16
+ - **Litestar 플러그인** - `LogRedactionPlugin`이 애플리케이션 시작 시 위 설정을 연결합니다
17
+
18
+ ## 설치
19
+
20
+ ```bash
21
+ uv add log-redaction
22
+ # 선택 통합
23
+ uv add "log-redaction[structlog]"
24
+ uv add "log-redaction[litestar]"
25
+ ```
26
+
27
+ Python 3.12 이상이 필요합니다.
28
+
29
+ ## 마스킹 대상
30
+
31
+ 파라미터 이름을 두 종류로 나눠 마스킹합니다.
32
+
33
+ | 종류 | 위치 | 기본 이름 |
34
+ |------|------|-----------|
35
+ | 비밀 이름 | 어디서든: `access_token=abc` | `access_token`, `refresh_token`, `id_token`, `client_secret`, `fb_exchange_token`, `th_exchange_token`, `revoke_token`, `input_token`, `api_key`, `apikey`, `authorization`, `password`, `secret`, `token`, `AWSAccessKeyId`, `X-Goog-Signature`, `X-Amz-Signature`, `X-Amz-Credential` |
36
+ | 쿼리 한정 이름 | `?` 또는 `&` 뒤에서만: `?code=abc` | `code`, `auth`, `key`, `session`, `sig`, `signature`, `search` |
37
+
38
+ 쿼리 한정 이름은 평범한 로그 줄에서 그대로 남습니다. 그래서 `code=502`, `key=contents.brief.system` 같은 진단 정보를 잃지 않습니다. Slack incoming webhook URL은 항상 마스킹합니다.
39
+
40
+ structlog 프로세서는 민감 키의 값도 마스킹합니다. 민감 키는 비밀 이름에 `password_hash`, `webhook`, `webhook_url`, `bearer`, `credential`, `credentials`, `private_key`, `system_token`을 더한 것입니다. 대소문자는 구분하지 않습니다.
41
+
42
+ ## 사용법
43
+
44
+ ### 문자열
45
+
46
+ ```python
47
+ from log_redaction import redact_text
48
+
49
+ redact_text("GET https://graph.example.com/me?access_token=abc&fields=id")
50
+ # 'GET https://graph.example.com/me?access_token=***REDACTED***&fields=id'
51
+
52
+ redact_text("upstream failed code=502")
53
+ # 'upstream failed code=502'
54
+ ```
55
+
56
+ ### structlog
57
+
58
+ 프로세서를 렌더러 바로 앞에 둡니다.
59
+
60
+ ```python
61
+ import structlog
62
+ from log_redaction import redact_processor
63
+
64
+ structlog.configure(
65
+ processors=[
66
+ structlog.stdlib.add_log_level,
67
+ structlog.processors.TimeStamper(fmt="iso"),
68
+ redact_processor,
69
+ structlog.processors.JSONRenderer(),
70
+ ],
71
+ )
72
+ ```
73
+
74
+ ### 표준 라이브러리 logging
75
+
76
+ `logging.basicConfig` 다음에 `install_log_redaction`을 호출합니다. 각 root 핸들러의 포맷 문자열과 날짜 포맷은 유지됩니다.
77
+
78
+ ```python
79
+ import logging
80
+ from log_redaction import install_log_redaction
81
+
82
+ logging.basicConfig(format="%(levelname)s %(message)s", level=logging.INFO)
83
+ install_log_redaction()
84
+ ```
85
+
86
+ 포매터를 직접 붙이려면 `RedactingFormatter`를 씁니다. 인자는 `logging.Formatter`와 같습니다.
87
+
88
+ ```python
89
+ from log_redaction import RedactingFormatter
90
+
91
+ handler.setFormatter(RedactingFormatter("%(asctime)s %(message)s"))
92
+ ```
93
+
94
+ ### Litestar
95
+
96
+ ```python
97
+ from litestar import Litestar
98
+ from log_redaction.litestar import LogRedactionPlugin
99
+
100
+ app = Litestar(route_handlers=[...], plugins=[LogRedactionPlugin()])
101
+ ```
102
+
103
+ 플러그인은 시작 시 structlog 렌더러(체인의 마지막 프로세서) 바로 앞에 프로세서를 넣습니다. 이미 들어 있으면 넣지 않습니다. 이어서 모든 root 핸들러에 `RedactingFormatter`를 설치합니다. structlog와 stdlib logging은 앱이 시작되기 전에 설정해 두세요. structlog가 설치되어 있지 않으면 포매터만 설치합니다.
104
+
105
+ ### 이름 목록 바꾸기
106
+
107
+ `Redactor`는 이름 목록을 키워드 인자로 받습니다. 각 인자는 해당 기본 목록을 대체합니다.
108
+
109
+ ```python
110
+ from log_redaction import DEFAULT_QUERY_SECRET_NAMES, RedactingFormatter, Redactor
111
+ from log_redaction.litestar import LogRedactionPlugin
112
+
113
+ redactor = Redactor(
114
+ query_secret_names=(*DEFAULT_QUERY_SECRET_NAMES, "phone"),
115
+ )
116
+
117
+ redactor.redact_text("/users?phone=01000000000") # 문자열
118
+ redactor # structlog 프로세서
119
+ RedactingFormatter("%(message)s", redactor=redactor) # stdlib 포매터
120
+ LogRedactionPlugin(redactor) # Litestar 플러그인
121
+ ```
122
+
123
+ | 인자 | 기본값 | 의미 |
124
+ |------|--------|------|
125
+ | `secret_names` | `DEFAULT_SECRET_NAMES` | 어디서든 마스킹 |
126
+ | `query_secret_names` | `DEFAULT_QUERY_SECRET_NAMES` | `?` 또는 `&` 뒤에서만 마스킹 |
127
+ | `sensitive_keys` | `DEFAULT_SENSITIVE_KEYS` | `secret_names`에 더해 마스킹할 structlog 키 |
128
+
129
+ `install_log_redaction(redactor)`도 redactor를 받습니다.
130
+
131
+ ## API
132
+
133
+ | 이름 | 설명 |
134
+ |------|------|
135
+ | `MASK` | 대체 문자열 `***REDACTED***` |
136
+ | `redact_text(value)` | 문자열의 자격증명 마스킹 |
137
+ | `redact_processor(logger, method_name, event_dict)` | structlog 프로세서 |
138
+ | `RedactingFormatter(..., redactor=None)` | 출력을 리댁션하는 `logging.Formatter` |
139
+ | `install_log_redaction(redactor=None)` | 모든 root 핸들러의 포매터 교체 |
140
+ | `Redactor(*, secret_names, query_secret_names, sensitive_keys)` | 목록을 바꾼 리댁션. 인스턴스가 곧 structlog 프로세서 |
141
+ | `log_redaction.litestar.LogRedactionPlugin(redactor=None)` | Litestar `InitPlugin` |
142
+
143
+ ## 라이선스
144
+
145
+ MIT
@@ -0,0 +1,145 @@
1
+ # log-redaction
2
+
3
+ **English** | [한국어](./README.ko.md)
4
+
5
+ [![PyPI version](https://img.shields.io/pypi/v/log-redaction.svg)](https://pypi.org/project/log-redaction/)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
+
8
+ Mask credentials in Python logs. It covers structlog events, standard-library log records and exception tracebacks. The core has no dependencies.
9
+
10
+ ## Features
11
+
12
+ - **Text redaction** - `redact_text` masks credentials in URLs, form bodies and exception messages
13
+ - **structlog processor** - `redact_processor` masks sensitive keys and nested strings in the event dict
14
+ - **stdlib formatter** - `RedactingFormatter` redacts the final formatted line, traceback included
15
+ - **One-call install** - `install_log_redaction` swaps the formatter on every root handler
16
+ - **Litestar plugin** - `LogRedactionPlugin` wires all of this in at application startup
17
+
18
+ ## Installation
19
+
20
+ ```bash
21
+ uv add log-redaction
22
+ # Optional integrations
23
+ uv add "log-redaction[structlog]"
24
+ uv add "log-redaction[litestar]"
25
+ ```
26
+
27
+ Requires Python 3.12 or newer.
28
+
29
+ ## What gets masked
30
+
31
+ Two kinds of parameter names are masked.
32
+
33
+ | Kind | Where | Default names |
34
+ |------|-------|---------------|
35
+ | Secret names | Anywhere: `access_token=abc` | `access_token`, `refresh_token`, `id_token`, `client_secret`, `fb_exchange_token`, `th_exchange_token`, `revoke_token`, `input_token`, `api_key`, `apikey`, `authorization`, `password`, `secret`, `token`, `AWSAccessKeyId`, `X-Goog-Signature`, `X-Amz-Signature`, `X-Amz-Credential` |
36
+ | Query-only names | Only after `?` or `&`: `?code=abc` | `code`, `auth`, `key`, `session`, `sig`, `signature`, `search` |
37
+
38
+ Query-only names stay readable in ordinary log lines, so `code=502` or `key=contents.brief.system` keep their diagnostic value. Slack incoming webhook URLs are always masked.
39
+
40
+ The structlog processor also masks the values of sensitive keys. These are the secret names plus `password_hash`, `webhook`, `webhook_url`, `bearer`, `credential`, `credentials`, `private_key` and `system_token`. Matching is case-insensitive.
41
+
42
+ ## Usage
43
+
44
+ ### Text
45
+
46
+ ```python
47
+ from log_redaction import redact_text
48
+
49
+ redact_text("GET https://graph.example.com/me?access_token=abc&fields=id")
50
+ # 'GET https://graph.example.com/me?access_token=***REDACTED***&fields=id'
51
+
52
+ redact_text("upstream failed code=502")
53
+ # 'upstream failed code=502'
54
+ ```
55
+
56
+ ### structlog
57
+
58
+ Put the processor immediately before the renderer.
59
+
60
+ ```python
61
+ import structlog
62
+ from log_redaction import redact_processor
63
+
64
+ structlog.configure(
65
+ processors=[
66
+ structlog.stdlib.add_log_level,
67
+ structlog.processors.TimeStamper(fmt="iso"),
68
+ redact_processor,
69
+ structlog.processors.JSONRenderer(),
70
+ ],
71
+ )
72
+ ```
73
+
74
+ ### Standard library logging
75
+
76
+ Call `install_log_redaction` after `logging.basicConfig`. It keeps each root handler's format string and date format.
77
+
78
+ ```python
79
+ import logging
80
+ from log_redaction import install_log_redaction
81
+
82
+ logging.basicConfig(format="%(levelname)s %(message)s", level=logging.INFO)
83
+ install_log_redaction()
84
+ ```
85
+
86
+ To attach the formatter yourself, use `RedactingFormatter`. It takes the same arguments as `logging.Formatter`.
87
+
88
+ ```python
89
+ from log_redaction import RedactingFormatter
90
+
91
+ handler.setFormatter(RedactingFormatter("%(asctime)s %(message)s"))
92
+ ```
93
+
94
+ ### Litestar
95
+
96
+ ```python
97
+ from litestar import Litestar
98
+ from log_redaction.litestar import LogRedactionPlugin
99
+
100
+ app = Litestar(route_handlers=[...], plugins=[LogRedactionPlugin()])
101
+ ```
102
+
103
+ At startup the plugin inserts the processor before the structlog renderer (the last processor in the chain), unless it is already there. It then installs `RedactingFormatter` on every root handler. Configure structlog and stdlib logging before the app starts. Without structlog installed, only the formatter is installed.
104
+
105
+ ### Custom name lists
106
+
107
+ `Redactor` takes the name lists as keyword arguments. Each argument replaces its default list.
108
+
109
+ ```python
110
+ from log_redaction import DEFAULT_QUERY_SECRET_NAMES, RedactingFormatter, Redactor
111
+ from log_redaction.litestar import LogRedactionPlugin
112
+
113
+ redactor = Redactor(
114
+ query_secret_names=(*DEFAULT_QUERY_SECRET_NAMES, "phone"),
115
+ )
116
+
117
+ redactor.redact_text("/users?phone=01000000000") # text
118
+ redactor # structlog processor
119
+ RedactingFormatter("%(message)s", redactor=redactor) # stdlib formatter
120
+ LogRedactionPlugin(redactor) # Litestar plugin
121
+ ```
122
+
123
+ | Argument | Default | Meaning |
124
+ |----------|---------|---------|
125
+ | `secret_names` | `DEFAULT_SECRET_NAMES` | Masked anywhere |
126
+ | `query_secret_names` | `DEFAULT_QUERY_SECRET_NAMES` | Masked only after `?` or `&` |
127
+ | `sensitive_keys` | `DEFAULT_SENSITIVE_KEYS` | Extra structlog keys to mask, on top of `secret_names` |
128
+
129
+ `install_log_redaction(redactor)` accepts a redactor as well.
130
+
131
+ ## API
132
+
133
+ | Name | Description |
134
+ |------|-------------|
135
+ | `MASK` | Replacement string, `***REDACTED***` |
136
+ | `redact_text(value)` | Mask credentials in a string |
137
+ | `redact_processor(logger, method_name, event_dict)` | structlog processor |
138
+ | `RedactingFormatter(..., redactor=None)` | `logging.Formatter` that redacts its output |
139
+ | `install_log_redaction(redactor=None)` | Replace the formatter on every root handler |
140
+ | `Redactor(*, secret_names, query_secret_names, sensitive_keys)` | Redaction with custom lists; the instance is a structlog processor |
141
+ | `log_redaction.litestar.LogRedactionPlugin(redactor=None)` | Litestar `InitPlugin` |
142
+
143
+ ## License
144
+
145
+ MIT
@@ -0,0 +1,269 @@
1
+ """Redact credentials in structured and standard-library logs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import re
7
+ from collections.abc import Iterable, Mapping
8
+ from typing import Any, Literal, override
9
+
10
+ MASK = "***REDACTED***"
11
+
12
+ # Parameter names fall into two groups.
13
+ #
14
+ # Names that identify a credential on their own. They are masked wherever
15
+ # they appear.
16
+ DEFAULT_SECRET_NAMES: tuple[str, ...] = (
17
+ # OAuth / Meta Graph
18
+ "access_token",
19
+ "refresh_token",
20
+ "id_token",
21
+ "client_secret",
22
+ "fb_exchange_token",
23
+ "th_exchange_token",
24
+ "revoke_token",
25
+ "input_token",
26
+ # Generic
27
+ "api_key",
28
+ "apikey",
29
+ "authorization",
30
+ "password",
31
+ "secret",
32
+ "token",
33
+ # Signed URLs (Azure SAS / AWS / GCS)
34
+ "AWSAccessKeyId",
35
+ "X-Goog-Signature",
36
+ "X-Amz-Signature",
37
+ "X-Amz-Credential",
38
+ )
39
+
40
+ # Names that are credentials only in query-string position.
41
+ #
42
+ # As URL parameters, ``code``/``key``/``sig`` carry an OAuth authorization
43
+ # code, an API key or a SAS signature. In an ordinary log line they are
44
+ # diagnostic fields (``code=502``, ``key=contents.brief.system``). Masking by
45
+ # name alone would erase the identifiers needed to correlate an incident, so
46
+ # these names are masked only after ``?`` or ``&``.
47
+ DEFAULT_QUERY_SECRET_NAMES: tuple[str, ...] = (
48
+ "code",
49
+ "auth",
50
+ "key",
51
+ "session",
52
+ "sig",
53
+ "signature",
54
+ # Search URLs can carry names and phone numbers.
55
+ "search",
56
+ )
57
+
58
+ # Extra structlog ``event_dict`` keys to mask, on top of the secret names.
59
+ #
60
+ # Query-only names are deliberately absent: here they are structured log
61
+ # fields, not URL parameters, and they carry diagnostic information.
62
+ DEFAULT_SENSITIVE_KEYS: tuple[str, ...] = (
63
+ "password_hash",
64
+ "webhook",
65
+ "webhook_url",
66
+ "bearer",
67
+ "credential",
68
+ "credentials",
69
+ "private_key",
70
+ "system_token",
71
+ )
72
+
73
+ # End a value only at characters that act as delimiters in URLs and logs.
74
+ _VALUE = r"([^&\s\"'<>|\\}\]]+)"
75
+
76
+ # A Slack incoming webhook URL is itself the credential.
77
+ _SLACK_WEBHOOK_RE = re.compile(
78
+ r"(https://hooks\.slack\.com/services/)\S+",
79
+ re.IGNORECASE,
80
+ )
81
+
82
+ _MAX_DEPTH = 6
83
+
84
+
85
+ def _names_alternation(names: tuple[str, ...]) -> str:
86
+ """Sort longest first so ``api_key`` wins over ``key``."""
87
+ return "|".join(re.escape(n) for n in sorted(names, key=len, reverse=True))
88
+
89
+
90
+ class Redactor:
91
+ """Mask credentials using configurable name lists.
92
+
93
+ Every argument defaults to the built-in list, so ``Redactor()`` behaves
94
+ exactly like the module-level helpers.
95
+
96
+ Args:
97
+ secret_names: Parameter names masked wherever they appear.
98
+ query_secret_names: Parameter names masked only after ``?`` or ``&``.
99
+ sensitive_keys: Extra structlog keys whose values are masked. The
100
+ secret names are always masked as keys too.
101
+ """
102
+
103
+ def __init__(
104
+ self,
105
+ *,
106
+ secret_names: Iterable[str] = DEFAULT_SECRET_NAMES,
107
+ query_secret_names: Iterable[str] = DEFAULT_QUERY_SECRET_NAMES,
108
+ sensitive_keys: Iterable[str] = DEFAULT_SENSITIVE_KEYS,
109
+ ) -> None:
110
+ secret = tuple(secret_names)
111
+ query = tuple(query_secret_names)
112
+ # ``(?<![A-Za-z0-9_-])`` stops ``api_key=`` from partially matching
113
+ # as ``key=``.
114
+ self._secret_param_re = (
115
+ re.compile(
116
+ r"(?<![A-Za-z0-9_-])("
117
+ + _names_alternation(secret)
118
+ + r")="
119
+ + _VALUE,
120
+ re.IGNORECASE,
121
+ )
122
+ if secret
123
+ else None
124
+ )
125
+ # Query position only: capture the delimiter (``?``/``&``) and keep it.
126
+ self._query_secret_re = (
127
+ re.compile(
128
+ r"([?&])(" + _names_alternation(query) + r")=" + _VALUE,
129
+ re.IGNORECASE,
130
+ )
131
+ if query
132
+ else None
133
+ )
134
+ self._sensitive_keys = frozenset(name.lower() for name in secret) | frozenset(
135
+ key.lower() for key in sensitive_keys
136
+ )
137
+
138
+ def redact_text(self, value: str) -> str:
139
+ """Mask credentials embedded in a string.
140
+
141
+ Covers URL query strings (``?access_token=abc``), form-encoded bodies
142
+ and URLs inside exception messages. Returns the input unchanged when
143
+ it holds no credential.
144
+ """
145
+ if not value:
146
+ return value
147
+ redacted = value
148
+ if self._secret_param_re is not None:
149
+ redacted = self._secret_param_re.sub(rf"\1={MASK}", redacted)
150
+ if self._query_secret_re is not None:
151
+ # Keep the delimiter (``?code=`` becomes ``?code=***``).
152
+ redacted = self._query_secret_re.sub(rf"\1\2={MASK}", redacted)
153
+ return _SLACK_WEBHOOK_RE.sub(rf"\1{MASK}", redacted)
154
+
155
+ def _is_sensitive_key(self, key: object) -> bool:
156
+ return isinstance(key, str) and key.lower() in self._sensitive_keys
157
+
158
+ def _redact_value(self, value: object, *, depth: int = 0) -> object:
159
+ """Walk dicts and lists, masking sensitive keys and redacting strings."""
160
+ if depth > _MAX_DEPTH: # Guard against cycles and huge structures.
161
+ return value
162
+ if isinstance(value, str):
163
+ return self.redact_text(value)
164
+ if isinstance(value, dict):
165
+ return {
166
+ k: (
167
+ MASK
168
+ if self._is_sensitive_key(k)
169
+ else self._redact_value(v, depth=depth + 1)
170
+ )
171
+ for k, v in value.items()
172
+ }
173
+ if isinstance(value, list):
174
+ return [self._redact_value(item, depth=depth + 1) for item in value]
175
+ if isinstance(value, tuple):
176
+ # A namedtuple cannot be rebuilt with type(value)(list), so it
177
+ # becomes a plain tuple.
178
+ return tuple(self._redact_value(item, depth=depth + 1) for item in value)
179
+ return value
180
+
181
+ def __call__(
182
+ self,
183
+ logger: Any,
184
+ method_name: str,
185
+ event_dict: Mapping[str, Any],
186
+ ) -> dict[str, Any]:
187
+ """structlog processor that redacts ``event_dict`` before rendering.
188
+
189
+ Place it immediately before the final renderer in the processor chain.
190
+ """
191
+ return {
192
+ k: MASK if self._is_sensitive_key(k) else self._redact_value(v)
193
+ for k, v in event_dict.items()
194
+ }
195
+
196
+
197
+ _DEFAULT_REDACTOR = Redactor()
198
+
199
+
200
+ def redact_text(value: str) -> str:
201
+ """Mask credentials embedded in a string, using the default lists."""
202
+ return _DEFAULT_REDACTOR.redact_text(value)
203
+
204
+
205
+ def redact_processor(
206
+ logger: Any,
207
+ method_name: str,
208
+ event_dict: Mapping[str, Any],
209
+ ) -> dict[str, Any]:
210
+ """structlog processor using the default lists.
211
+
212
+ Place it immediately before the final renderer in the processor chain.
213
+ """
214
+ return _DEFAULT_REDACTOR(logger, method_name, event_dict)
215
+
216
+
217
+ class RedactingFormatter(logging.Formatter):
218
+ """Formatter that redacts the final string, message and traceback alike.
219
+
220
+ Attached to a handler, it covers stdlib loggers (httpx and others),
221
+ third-party libraries and exception tracebacks, which a structlog
222
+ processor alone cannot reach.
223
+ """
224
+
225
+ def __init__(
226
+ self,
227
+ fmt: str | None = None,
228
+ datefmt: str | None = None,
229
+ style: Literal["%", "{", "$"] = "%",
230
+ validate: bool = True,
231
+ *,
232
+ defaults: Mapping[str, Any] | None = None,
233
+ redactor: Redactor | None = None,
234
+ ) -> None:
235
+ super().__init__(fmt, datefmt, style, validate, defaults=defaults)
236
+ self._redactor = redactor or _DEFAULT_REDACTOR
237
+
238
+ @override
239
+ def format(self, record: logging.LogRecord) -> str:
240
+ return self._redactor.redact_text(super().format(record))
241
+
242
+
243
+ def install_log_redaction(redactor: Redactor | None = None) -> None:
244
+ """Replace the formatter of every root handler with a redacting one.
245
+
246
+ Call it **after** ``logging.basicConfig``.
247
+ """
248
+ for handler in logging.getLogger().handlers:
249
+ existing = handler.formatter
250
+ handler.setFormatter(
251
+ RedactingFormatter(
252
+ fmt=getattr(existing, "_fmt", None) or "%(message)s",
253
+ datefmt=getattr(existing, "datefmt", None),
254
+ redactor=redactor,
255
+ )
256
+ )
257
+
258
+
259
+ __all__ = [
260
+ "DEFAULT_QUERY_SECRET_NAMES",
261
+ "DEFAULT_SECRET_NAMES",
262
+ "DEFAULT_SENSITIVE_KEYS",
263
+ "MASK",
264
+ "RedactingFormatter",
265
+ "Redactor",
266
+ "install_log_redaction",
267
+ "redact_processor",
268
+ "redact_text",
269
+ ]
@@ -0,0 +1,59 @@
1
+ """Litestar plugin that wires log redaction in at application startup.
2
+
3
+ Requires the ``litestar`` extra. structlog is optional: when it is not
4
+ installed, only the stdlib formatter is installed.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import TYPE_CHECKING, Any, override
10
+
11
+ from litestar.plugins import InitPlugin
12
+
13
+ from log_redaction import Redactor, install_log_redaction, redact_processor
14
+
15
+ if TYPE_CHECKING:
16
+ from litestar.config.app import AppConfig
17
+
18
+
19
+ class LogRedactionPlugin(InitPlugin):
20
+ """Install log redaction when the application starts.
21
+
22
+ On startup it inserts the redaction processor immediately before the
23
+ structlog renderer (the last processor in the chain), unless it is
24
+ already there, and installs ``RedactingFormatter`` on every root logging
25
+ handler. Configure structlog and stdlib logging before the app starts.
26
+
27
+ Args:
28
+ redactor: Redactor with custom name lists. Defaults to the built-in
29
+ lists.
30
+ """
31
+
32
+ def __init__(self, redactor: Redactor | None = None) -> None:
33
+ self._redactor = redactor
34
+
35
+ @override
36
+ def on_app_init(self, app_config: AppConfig) -> AppConfig:
37
+ app_config.on_startup.append(self._install)
38
+ return app_config
39
+
40
+ def _install(self) -> None:
41
+ processor: Any = self._redactor or redact_processor
42
+ _insert_before_renderer(processor)
43
+ install_log_redaction(self._redactor)
44
+
45
+
46
+ def _insert_before_renderer(processor: Any) -> None:
47
+ try:
48
+ import structlog
49
+ except ImportError:
50
+ return
51
+
52
+ processors = list(structlog.get_config()["processors"])
53
+ if processor in processors:
54
+ return
55
+ processors.insert(max(len(processors) - 1, 0), processor)
56
+ structlog.configure(processors=processors)
57
+
58
+
59
+ __all__ = ["LogRedactionPlugin"]
File without changes
@@ -0,0 +1,49 @@
1
+ [project]
2
+ name = "log-redaction"
3
+ version = "0.1.1"
4
+ description = "Credential redaction for structlog and standard-library logs"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ authors = [{ name = "Eunkwang Shin", email = "gracefullight.dev@gmail.com" }]
9
+ requires-python = ">=3.12"
10
+ dependencies = []
11
+ keywords = ["logging", "redaction", "structlog", "litestar", "security"]
12
+ classifiers = [
13
+ "Development Status :: 4 - Beta",
14
+ "Intended Audience :: Developers",
15
+ "Programming Language :: Python :: 3",
16
+ "Programming Language :: Python :: 3 :: Only",
17
+ "Programming Language :: Python :: 3.12",
18
+ "Programming Language :: Python :: 3.13",
19
+ "Programming Language :: Python :: 3.14",
20
+ "Topic :: System :: Logging",
21
+ "Typing :: Typed",
22
+ ]
23
+
24
+ [project.optional-dependencies]
25
+ structlog = ["structlog>=24.1.0"]
26
+ litestar = ["litestar>=2.0.0,<3"]
27
+
28
+ [project.urls]
29
+ Homepage = "https://github.com/gracefullight/pkgs/tree/main/packages/log-redaction#readme"
30
+ Repository = "https://github.com/gracefullight/pkgs"
31
+ Issues = "https://github.com/gracefullight/pkgs/issues"
32
+ Changelog = "https://github.com/gracefullight/pkgs/blob/main/packages/log-redaction/CHANGELOG.md"
33
+
34
+ [dependency-groups]
35
+ dev = ["pytest>=8.4.0"]
36
+
37
+ [build-system]
38
+ requires = ["hatchling>=1.27.0"]
39
+ build-backend = "hatchling.build"
40
+
41
+ [tool.hatch.build.targets.wheel]
42
+ packages = ["log_redaction"]
43
+
44
+ [tool.hatch.build.targets.sdist]
45
+ include = ["log_redaction", "tests", "README.md", "README.ko.md", "LICENSE", "CHANGELOG.md"]
46
+
47
+ [tool.pytest.ini_options]
48
+ addopts = "--import-mode=importlib"
49
+ testpaths = ["tests"]
@@ -0,0 +1,76 @@
1
+ """LogRedactionPlugin wires redaction in at application startup."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import logging
7
+ from collections.abc import Iterator
8
+
9
+ import pytest
10
+ import structlog
11
+ from litestar import Litestar
12
+ from litestar.testing import TestClient
13
+
14
+ from log_redaction import MASK, RedactingFormatter, Redactor, redact_processor
15
+ from log_redaction.litestar import LogRedactionPlugin
16
+
17
+
18
+ @pytest.fixture
19
+ def root_stream() -> Iterator[io.StringIO]:
20
+ root = logging.getLogger()
21
+ saved = root.handlers[:]
22
+ stream = io.StringIO()
23
+ handler = logging.StreamHandler(stream)
24
+ handler.setFormatter(logging.Formatter("%(levelname)s %(message)s"))
25
+ root.handlers = [handler]
26
+ try:
27
+ yield stream
28
+ finally:
29
+ root.handlers = saved
30
+ structlog.reset_defaults()
31
+
32
+
33
+ def test_plugin_inserts_processor_and_installs_formatter(
34
+ root_stream: io.StringIO,
35
+ ) -> None:
36
+ renderer = structlog.processors.JSONRenderer()
37
+ structlog.configure(processors=[structlog.processors.add_log_level, renderer])
38
+ # logging_config=None keeps Litestar from replacing the root handlers.
39
+ app = Litestar(plugins=[LogRedactionPlugin()], logging_config=None)
40
+
41
+ # Nothing changes until the app starts.
42
+ assert redact_processor not in structlog.get_config()["processors"]
43
+
44
+ with TestClient(app):
45
+ processors = structlog.get_config()["processors"]
46
+ assert processors[-2:] == [redact_processor, renderer]
47
+
48
+ handler = logging.getLogger().handlers[0]
49
+ assert isinstance(handler.formatter, RedactingFormatter)
50
+ logging.getLogger("httpx").warning("GET /cb?access_token=abc")
51
+
52
+ assert root_stream.getvalue() == f"WARNING GET /cb?access_token={MASK}\n"
53
+
54
+
55
+ def test_plugin_does_not_insert_processor_twice(root_stream: io.StringIO) -> None:
56
+ renderer = structlog.processors.JSONRenderer()
57
+ structlog.configure(processors=[redact_processor, renderer])
58
+
59
+ app = Litestar(plugins=[LogRedactionPlugin()], logging_config=None)
60
+
61
+ with TestClient(app):
62
+ assert structlog.get_config()["processors"] == [redact_processor, renderer]
63
+
64
+
65
+ def test_plugin_uses_given_redactor(root_stream: io.StringIO) -> None:
66
+ renderer = structlog.processors.JSONRenderer()
67
+ structlog.configure(processors=[renderer])
68
+ redactor = Redactor(query_secret_names=("phone",))
69
+
70
+ app = Litestar(plugins=[LogRedactionPlugin(redactor)], logging_config=None)
71
+
72
+ with TestClient(app):
73
+ assert structlog.get_config()["processors"] == [redactor, renderer]
74
+ logging.getLogger("app").warning("/users?phone=010")
75
+
76
+ assert root_stream.getvalue() == f"WARNING /users?phone={MASK}\n"
@@ -0,0 +1,182 @@
1
+ """Redaction regression tests (2026-07-20 security review).
2
+
3
+ These pin the shape of lines that actually reached production logs. Even if
4
+ the root fixes (Bearer headers, POST bodies) are reverted, no credential may
5
+ remain in the logs.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+ import sys
12
+
13
+ import pytest
14
+
15
+ from log_redaction import (
16
+ MASK,
17
+ RedactingFormatter,
18
+ redact_processor,
19
+ redact_text,
20
+ )
21
+
22
+ # Synthetic sentinel, not a real Threads token (real tokens are 180+ chars).
23
+ _TOKEN = "FAKE-SENTINEL-not-a-real-threads-token-0002"
24
+
25
+
26
+ @pytest.mark.parametrize(
27
+ "line",
28
+ [
29
+ # The exact line httpx logged at INFO
30
+ f'HTTP Request: GET https://graph.threads.net/v1.0/me?fields=id&access_token={_TOKEN} "HTTP/1.1 200 OK"',
31
+ # Long-lived exchange that also carried the app secret
32
+ f"HTTP Request: GET https://graph.threads.net/access_token?grant_type=th_exchange_token&client_secret=APPSECRET&access_token={_TOKEN}",
33
+ # httpx.HTTPStatusError.__str__ embeds the URL
34
+ f"Client error '400 Bad Request' for url 'https://graph.threads.net/v1.0/me?access_token={_TOKEN}'",
35
+ # Instagram / Facebook
36
+ f"HTTP Request: GET https://graph.instagram.com/me?fields=id,username&access_token={_TOKEN}",
37
+ f"HTTP Request: GET https://graph.facebook.com/v18.0/me/accounts?access_token={_TOKEN}",
38
+ ],
39
+ )
40
+ def test_credentials_never_survive_redaction(line: str) -> None:
41
+ out = redact_text(line)
42
+ assert _TOKEN not in out
43
+ assert "APPSECRET" not in out
44
+ assert MASK in out
45
+
46
+
47
+ def test_slack_webhook_url_is_redacted() -> None:
48
+ out = redact_text(
49
+ "HTTP Request: POST https://hooks.slack.com/services/T01/B02/zzSECRETzz"
50
+ )
51
+ assert "zzSECRETzz" not in out
52
+ assert MASK in out
53
+
54
+
55
+ @pytest.mark.parametrize(
56
+ "benign",
57
+ [
58
+ "status_code=400 error_code=rate_limited",
59
+ "job_id=abc retry_count=2 prompt_keys=threads.reply,threads.topic",
60
+ '{"event": "job_failed", "status_code": 400, "kind": "contents.publish"}',
61
+ ],
62
+ )
63
+ def test_benign_fields_are_not_over_redacted(benign: str) -> None:
64
+ """Harmless fields stay intact so debugging value is not lost."""
65
+ assert redact_text(benign) == benign
66
+
67
+
68
+ def test_structlog_processor_masks_keys_and_nested_strings() -> None:
69
+ out = redact_processor(
70
+ logging.getLogger("t"),
71
+ "info",
72
+ {
73
+ "event": "threads_call",
74
+ "access_token": _TOKEN,
75
+ "url": f"https://graph.threads.net/v1.0/me?access_token={_TOKEN}",
76
+ "nested": {"client_secret": "APPSECRET", "kind": "publish"},
77
+ "kind": "publish",
78
+ },
79
+ )
80
+ assert out["access_token"] == MASK
81
+ assert _TOKEN not in str(out["url"])
82
+ assert out["nested"]["client_secret"] == MASK
83
+ # Harmless fields are kept
84
+ assert out["kind"] == "publish"
85
+ assert out["nested"]["kind"] == "publish"
86
+
87
+
88
+ def test_formatter_redacts_exception_traceback() -> None:
89
+ """Traceback path, which a structlog processor cannot reach."""
90
+ try:
91
+ raise RuntimeError(
92
+ f"upstream failed: https://graph.threads.net/v1.0/me?access_token={_TOKEN}"
93
+ )
94
+ except RuntimeError:
95
+ record = logging.LogRecord(
96
+ name="t",
97
+ level=logging.ERROR,
98
+ pathname=__file__,
99
+ lineno=1,
100
+ msg="boom",
101
+ args=(),
102
+ exc_info=sys.exc_info(),
103
+ )
104
+
105
+ formatted = RedactingFormatter("%(message)s").format(record)
106
+ assert _TOKEN not in formatted
107
+ assert MASK in formatted
108
+
109
+
110
+ def test_httpx_style_lazy_args_are_redacted() -> None:
111
+ """httpx passes the URL as a lazy %s argument; redact after formatting."""
112
+ record = logging.LogRecord(
113
+ name="httpx",
114
+ level=logging.INFO,
115
+ pathname=__file__,
116
+ lineno=1,
117
+ msg='HTTP Request: %s %s "%s"',
118
+ args=(
119
+ "GET",
120
+ f"https://graph.threads.net/v1.0/me?access_token={_TOKEN}",
121
+ "HTTP/1.1 200 OK",
122
+ ),
123
+ exc_info=None,
124
+ )
125
+ formatted = RedactingFormatter("%(message)s").format(record)
126
+ assert _TOKEN not in formatted
127
+ assert MASK in formatted
128
+
129
+
130
+ # ---------------------------------------------------------------------------
131
+ # Over-redaction guard (observability)
132
+ # ---------------------------------------------------------------------------
133
+
134
+
135
+ @pytest.mark.parametrize(
136
+ "line",
137
+ [
138
+ # These names are credentials only as query parameters. In an ordinary
139
+ # log line they are diagnostics, and hiding them would erase the
140
+ # identifiers needed to correlate an incident.
141
+ "threads api failed code=502 retry=2",
142
+ "prompt activate key=contents.brief.system service=contents",
143
+ "error_code=rate_limited status_code=429",
144
+ "session=warm pool=8",
145
+ "sig=v2 handler=threads_posts_sync",
146
+ ],
147
+ )
148
+ def test_diagnostic_fields_survive_redaction(line: str) -> None:
149
+ assert redact_text(line) == line
150
+
151
+
152
+ @pytest.mark.parametrize(
153
+ ("line", "leaked"),
154
+ [
155
+ # The same names are credentials in query-string position.
156
+ ("https://x.test/cb?code=AQDxSECRETcode", "AQDxSECRETcode"),
157
+ ("https://places.test/media?maxWidth=800&key=AIzaSyLIVEKEY", "AIzaSyLIVEKEY"),
158
+ ("https://blob.test/f.png?sv=2021&sig=abc%2Bdef", "abc%2Bdef"),
159
+ ],
160
+ )
161
+ def test_query_position_still_masks_ambiguous_names(line: str, leaked: str) -> None:
162
+ out = redact_text(line)
163
+ assert leaked not in out
164
+ assert MASK in out
165
+
166
+
167
+ def test_structlog_keeps_diagnostic_fields_but_masks_credentials() -> None:
168
+ out = redact_processor(
169
+ logging.getLogger("t"),
170
+ "info",
171
+ {
172
+ "event": "prompt.activate",
173
+ "key": "contents.brief.system", # Prompt-registry usage shape
174
+ "code": 502,
175
+ "access_token": _TOKEN,
176
+ "api_key": "sk-live-x",
177
+ },
178
+ )
179
+ assert out["key"] == "contents.brief.system"
180
+ assert out["code"] == 502
181
+ assert out["access_token"] == MASK
182
+ assert out["api_key"] == MASK
@@ -0,0 +1,67 @@
1
+ """Patient lookup values must not escape through URL access/error logging."""
2
+
3
+ import logging
4
+
5
+ import pytest
6
+
7
+ from log_redaction import (
8
+ MASK,
9
+ RedactingFormatter,
10
+ redact_processor,
11
+ redact_text,
12
+ )
13
+
14
+
15
+ @pytest.mark.parametrize(
16
+ "query",
17
+ (
18
+ "search=01000000000",
19
+ "SEARCH=%2B82%2010-0000-0000",
20
+ "search=%ED%99%98%EC%9E%90%20Test",
21
+ ),
22
+ )
23
+ def test_search_query_value_is_redacted_without_hiding_other_query_params(
24
+ query: str,
25
+ ) -> None:
26
+ url = f"/v1/medi24/tenants/test/conversations?{query}&limit=20"
27
+ key = query.split("=", 1)[0]
28
+ assert redact_text(url) == (
29
+ f"/v1/medi24/tenants/test/conversations?{key}={MASK}&limit=20"
30
+ )
31
+
32
+
33
+ def test_repeated_search_after_another_query_is_redacted() -> None:
34
+ assert redact_text("/inbox?status=open&search=01000000000&search=Test") == (
35
+ f"/inbox?status=open&search={MASK}&search={MASK}"
36
+ )
37
+
38
+
39
+ def test_access_formatter_redacts_search_after_interpolating_arguments() -> None:
40
+ record = logging.LogRecord(
41
+ "uvicorn.access",
42
+ logging.INFO,
43
+ "test",
44
+ 1,
45
+ "GET %s HTTP/1.1 200",
46
+ ("/inbox?limit=20&search=01000000000",),
47
+ None,
48
+ )
49
+ assert RedactingFormatter("%(message)s").format(record) == (
50
+ f"GET /inbox?limit=20&search={MASK} HTTP/1.1 200"
51
+ )
52
+
53
+
54
+ def test_structured_error_url_is_redacted_without_hiding_diagnostic_fields() -> None:
55
+ event = {
56
+ "event": "lookup failed",
57
+ "details": {"url": "/inbox?search=Test&status=open"},
58
+ "search": "diagnostic-key",
59
+ "code": 502,
60
+ }
61
+ assert redact_processor(logging.getLogger(__name__), "info", event) == {
62
+ **event,
63
+ "details": {"url": f"/inbox?search={MASK}&status=open"},
64
+ }
65
+ assert redact_text("search=diagnostic-key code=502") == (
66
+ "search=diagnostic-key code=502"
67
+ )
@@ -0,0 +1,46 @@
1
+ """Custom name lists replace the defaults."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+
7
+ from log_redaction import MASK, RedactingFormatter, Redactor
8
+
9
+
10
+ def test_custom_lists_replace_defaults() -> None:
11
+ redactor = Redactor(
12
+ secret_names=("session_id",),
13
+ query_secret_names=("phone",),
14
+ sensitive_keys=("ssn",),
15
+ )
16
+
17
+ assert redactor.redact_text("session_id=abc access_token=xyz") == (
18
+ f"session_id={MASK} access_token=xyz"
19
+ )
20
+ assert redactor.redact_text("/users?phone=010&code=1 phone=010") == (
21
+ f"/users?phone={MASK}&code=1 phone=010"
22
+ )
23
+ assert redactor(None, "info", {"ssn": "1", "session_id": "2", "token": "3"}) == {
24
+ "ssn": MASK,
25
+ "session_id": MASK,
26
+ "token": "3",
27
+ }
28
+
29
+
30
+ def test_empty_lists_disable_name_matching() -> None:
31
+ redactor = Redactor(secret_names=(), query_secret_names=(), sensitive_keys=())
32
+
33
+ assert redactor.redact_text("/cb?code=1&token=2 password=3") == (
34
+ "/cb?code=1&token=2 password=3"
35
+ )
36
+
37
+
38
+ def test_formatter_uses_given_redactor() -> None:
39
+ record = logging.LogRecord(
40
+ "t", logging.INFO, "t", 1, "/users?phone=010", None, None
41
+ )
42
+ formatter = RedactingFormatter(
43
+ "%(message)s", redactor=Redactor(query_secret_names=("phone",))
44
+ )
45
+
46
+ assert formatter.format(record) == f"/users?phone={MASK}"