devzero-sandbox 0.1.0__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.
File without changes
@@ -0,0 +1,78 @@
1
+ """Token redaction for logs, reprs and exception messages (ADR-005-W11).
2
+
3
+ Tokens live in memory only and are never written anywhere a human or a log
4
+ pipeline reads. The SDK holds them as :class:`devzero_sandbox.auth.BearerToken`
5
+ (whose ``repr``/``str`` hide the value), formats error messages through
6
+ :func:`redact`, and logs only through loggers from :func:`get_logger`, which
7
+ carry a :class:`RedactingFilter`. Applications that log other libraries at
8
+ DEBUG can add the same filter to their own handlers.
9
+
10
+ Both credentials the gateway accepts are JWTs (the ES256 sandbox token and the
11
+ projected ServiceAccount token), so a JWT-shaped string is redacted wherever it
12
+ appears; so is whatever follows ``Bearer`` and the browser-only
13
+ ``devzero.bearer.<token>`` WebSocket subprotocol (ADR-005, waves 15–16). The
14
+ control-plane credential, a DevZero personal access token (``dzu-``) or team
15
+ service-account token (``dzs-``), is redacted by its prefix (ADR-007-W13).
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import logging
21
+ import re
22
+
23
+ REDACTED = "[REDACTED]"
24
+
25
+ _PATTERNS = (
26
+ # A JWT: three base64url segments, the first a JSON object ("eyJ" = '{"').
27
+ re.compile(r"eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*"),
28
+ # The WebSocket subprotocol carrier, whatever the token looks like.
29
+ re.compile(r"(?<=devzero\.bearer\.)(?!\[REDACTED\])[^\s,;'\"\]\)]+"),
30
+ # A DevZero personal access or service-account token (dakr's dzu-/dzs- prefixes).
31
+ re.compile(r"(?<![A-Za-z0-9])dz[us]-[A-Za-z0-9_-]{8,}"),
32
+ # Anything else after "Bearer " (an opaque token).
33
+ re.compile(r"(?i)(?<=bearer )(?!\[REDACTED\])[^\s,;'\"\]\)]+"),
34
+ )
35
+
36
+
37
+ def redact(text: str) -> str:
38
+ """Return ``text`` with every bearer credential replaced by ``[REDACTED]``."""
39
+ for pattern in _PATTERNS:
40
+ text = pattern.sub(REDACTED, text)
41
+ return text
42
+
43
+
44
+ class RedactingFilter(logging.Filter):
45
+ """A logging filter that redacts bearer credentials from a record.
46
+
47
+ It renders the message with its arguments first, so a token passed as a
48
+ ``%s`` argument (or nested in a dict or tuple argument) is caught too, and
49
+ then drops the arguments. Attach it to a logger (the SDK's own) or to a
50
+ handler (to cover other libraries, such as ``httpx`` and ``httpcore``).
51
+ """
52
+
53
+ def filter(self, record: logging.LogRecord) -> bool:
54
+ try:
55
+ message = record.getMessage()
56
+ except (TypeError, ValueError, KeyError): # malformed: keep what we can
57
+ message = f"{record.msg!s} {record.args!r}"
58
+ record.msg = redact(message)
59
+ record.args = None
60
+ if record.exc_text:
61
+ record.exc_text = redact(record.exc_text)
62
+ return True
63
+
64
+
65
+ _FILTER = RedactingFilter()
66
+
67
+
68
+ def get_logger(name: str) -> logging.Logger:
69
+ """Return the named logger with the redacting filter attached once.
70
+
71
+ A filter on a logger applies only to records created on that logger, so
72
+ every SDK module takes its logger from here rather than from
73
+ ``logging.getLogger``.
74
+ """
75
+ logger = logging.getLogger(name)
76
+ if _FILTER not in logger.filters:
77
+ logger.addFilter(_FILTER)
78
+ return logger