log-redaction 0.1.1__py3-none-any.whl

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,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"]
log_redaction/py.typed ADDED
File without changes
@@ -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,7 @@
1
+ log_redaction/__init__.py,sha256=AVwUbVCowghY0fIbMeV2PmU01uQ7b0lRlmhX08nhjIM,8507
2
+ log_redaction/litestar.py,sha256=rYM7_Tekcw83g6SUskza2WVXNohy2b-bHgl-OpvOIZ8,1794
3
+ log_redaction/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ log_redaction-0.1.1.dist-info/METADATA,sha256=1bDR_Zlp8rubPrRDxySK5E1xN_QbiTDywlRDS7DwwnY,6696
5
+ log_redaction-0.1.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
6
+ log_redaction-0.1.1.dist-info/licenses/LICENSE,sha256=5_K-7am5a5Cj3sQmqoquVPDBKcFq2QW3zJoTgm4R8uU,1070
7
+ log_redaction-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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.