Debian Codegraph @

src/anthropic/lib/credentials/_secrets.py

raw
1 from __future__ import annotations
2
3 import json
4 from typing import Any, Dict, Optional, cast
5
6 from pydantic import SecretStr
7
8 __all__ = [
9 "SecretStr",
10 "_NonObjectPayloadError",
11 "_wrap_secret_fields",
12 "_unwrap_secret",
13 "_json_dumps_secrets",
14 "_strip_traceback",
15 ]
16
17
18 class _NonObjectPayloadError(TypeError):
19 """Raised by `_wrap_secret_fields` for JSON payloads that are not
20 objects. Carries only the payload's type name — a non-object payload can
21 be an echo of the request (assertion included), so it must never bind in
22 a caller's frame or ride along in an exception.
23 """
24
25 def __init__(self, type_name: str) -> None:
26 super().__init__(f"expected a JSON object, got {type_name}")
27 self.type_name = type_name
28
29
30 # Top-level keys that are plumbing, not secrets, in the credentials file and
31 # in token-endpoint responses. Every OTHER string value is treated as secret
32 # by default, so new fields (id_token, client_secret, ...) are wrapped without
33 # anyone having to remember to list them.
34 _PLAIN_KEYS = frozenset(
35 (
36 # credentials file
37 "type",
38 "version",
39 "expires_at",
40 # RFC 6749 token / error response
41 "token_type",
42 "expires_in",
43 "scope",
44 "error",
45 "error_description",
46 "error_uri",
47 )
48 )
49
50
51 def _wrap_secret_fields(payload: Any) -> Dict[str, Any]:
52 """Wrap the secret fields of a parsed JSON object in `SecretStr`.
53
54 Called at every boundary where credential material enters SDK code.
55 Traceback frames retain their locals, so any dict a raise site (or a
56 frame an error merely propagates through) still holds must already be
57 redacted — `SecretStr` renders as `SecretStr('**********')` under
58 crash reporters that capture and render locals.
59
60 String values are secret unless their key is in `_PLAIN_KEYS`; wrapped
61 empty strings stay falsy (`SecretStr` defines `__len__` across the
62 supported pydantic range), so `if not creds.get("access_token")` checks
63 behave unchanged. Only top-level values are wrapped — the credential
64 formats are flat; revisit if a nested shape ever appears. Mutates
65 `payload` in place — a copy would leave the raw-valued original
66 reachable — and returns it.
67
68 Non-object payloads raise `_NonObjectPayloadError` from this frame,
69 with the payload unbound first, so the raw value never lands in any frame
70 of the traceback — callers translate to their own redacted error.
71 """
72 if not isinstance(payload, dict):
73 type_name = type(payload).__name__
74 del payload
75 raise _NonObjectPayloadError(type_name)
76 mapping = cast("Dict[str, Any]", payload)
77 for key in mapping:
78 if key not in _PLAIN_KEYS and isinstance(mapping.get(key), str):
79 mapping[key] = SecretStr(mapping[key])
80 return mapping
81
82
83 def _unwrap_secret(value: Any) -> Any:
84 """Inverse of `_wrap_secret_fields` for a single value; pass-through
85 for values that were never wrapped (absent or non-string fields)."""
86 return value.get_secret_value() if isinstance(value, SecretStr) else value
87
88
89 def _json_default(value: Any) -> Any:
90 if isinstance(value, SecretStr):
91 return value.get_secret_value()
92 raise TypeError(f"Object of type {type(value).__name__} is not JSON serializable")
93
94
95 def _json_dumps_secrets(payload: Any, *, indent: Optional[int] = None) -> bytes:
96 """`json.dumps` with `SecretStr` values unwrapped at dump time.
97
98 Returns bytes so call sites can pass the result inline (request content,
99 `os.write`) without binding the raw serialization to a local.
100 """
101 return json.dumps(payload, indent=indent, default=_json_default).encode("utf-8")
102
103
104 def _strip_traceback(err: BaseException) -> BaseException:
105 """Detach the frames chained onto `err` before raising from it.
106
107 Foreign frames (json decoder, httpx transport) hold raw payloads —
108 request bodies, response text, credentials-file contents — as locals.
109 Dropping the traceback removes them from every renderer and programmatic
110 chain-walker, while the cause's type and message (which never carry the
111 payload) stay visible in renderings.
112 """
113 err.__traceback__ = None
114 return err