hushfang 0.1.0__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.
- hushfang-0.1.0/PKG-INFO +90 -0
- hushfang-0.1.0/README.md +75 -0
- hushfang-0.1.0/pyproject.toml +60 -0
- hushfang-0.1.0/pyproject.toml.orig +39 -0
- hushfang-0.1.0/src/hushfang/__init__.py +31 -0
- hushfang-0.1.0/src/hushfang/boundaries.py +218 -0
- hushfang-0.1.0/src/hushfang/crypto.py +249 -0
- hushfang-0.1.0/src/hushfang/matching.py +306 -0
- hushfang-0.1.0/src/hushfang/py.typed +0 -0
- hushfang-0.1.0/src/hushfang/registry.py +174 -0
- hushfang-0.1.0/src/hushfang/structure.py +90 -0
- hushfang-0.1.0/src/hushfang/types.py +209 -0
hushfang-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: hushfang
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Redact registered Pydantic secret values in formatted Python logs
|
|
5
|
+
Requires-Dist: pydantic>=2.14,<3
|
|
6
|
+
Requires-Dist: pydantic==2.14.4 ; extra == 'evaluation'
|
|
7
|
+
Requires-Dist: logmask==0.1.5 ; python_full_version >= '3.12' and extra == 'evaluation'
|
|
8
|
+
Requires-Dist: loggingredactor==0.0.7 ; extra == 'evaluation'
|
|
9
|
+
Requires-Python: >=3.11
|
|
10
|
+
Project-URL: Repository, https://github.com/yupasik/hushfang
|
|
11
|
+
Project-URL: Issues, https://github.com/yupasik/hushfang/issues
|
|
12
|
+
Project-URL: Documentation, https://github.com/yupasik/hushfang#readme
|
|
13
|
+
Provides-Extra: evaluation
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# Hushfang
|
|
17
|
+
|
|
18
|
+
Hushfang masks Pydantic secrets in formatted Python logs, including values revealed to a client or SDK. A log handler applies the registry to the formatted message, including exception chains, stack text and interpolated arguments. The library depends only on Pydantic.
|
|
19
|
+
|
|
20
|
+
[Design principles for logging secrets](https://github.com/yupasik/hushfang/blob/main/docs/design-principles.md) · [Hushbench](https://github.com/yupasik/hushfang/tree/main/benchmark) · [Detailed test report](https://github.com/yupasik/hushfang/blob/main/benchmark/RESULTS.md)
|
|
21
|
+
|
|
22
|
+
## Run the example
|
|
23
|
+
|
|
24
|
+
From a checkout with uv and Python 3.11 or later:
|
|
25
|
+
|
|
26
|
+
```sh
|
|
27
|
+
uv sync --locked
|
|
28
|
+
uv run --no-sync python demo.py
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
import logging
|
|
33
|
+
|
|
34
|
+
from pydantic import BaseModel, SecretStr
|
|
35
|
+
from hushfang import RedactingFormatter, SecretRegistry
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Settings(BaseModel):
|
|
39
|
+
api_key: SecretStr
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
settings = Settings(api_key="example-token-42")
|
|
43
|
+
registry = SecretRegistry()
|
|
44
|
+
registry.register_model(settings)
|
|
45
|
+
|
|
46
|
+
handler = logging.StreamHandler()
|
|
47
|
+
handler.setFormatter(RedactingFormatter(registry, "%(message)s"))
|
|
48
|
+
logger = logging.getLogger("client")
|
|
49
|
+
logger.propagate = False
|
|
50
|
+
logger.addHandler(handler)
|
|
51
|
+
|
|
52
|
+
logger.warning("Retrying with credential %s", settings.api_key.get_secret_value())
|
|
53
|
+
# Retrying with credential ***
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Each registry belongs to its application or worker. Register secrets before clients can log them. Register replacements before rotating credentials. Old values remain available for delayed log messages until the registry is cleared or released. The registry holds sensitive values and reversible representations in memory.
|
|
57
|
+
|
|
58
|
+
## Coverage
|
|
59
|
+
|
|
60
|
+
[Secret types, validation, disclosure and exceptions](https://github.com/yupasik/hushfang/blob/main/docs/secret-handling.md) · [Cryptographic test vectors](https://github.com/yupasik/hushfang/blob/main/benchmark/SOURCES.md)
|
|
61
|
+
|
|
62
|
+
- Register individual `SecretStr` and `SecretBytes` instances, or walk stored fields on an already validated model. The walk includes excluded fields, extras, nested models and standard containers. It handles cycles and skips computed properties.
|
|
63
|
+
- Matching covers complete literals, Python and JSON escapes, standard and URL-safe padded Base64, hexadecimal, and common URL encodings. For a URL with credentials, the registry also covers its password and Basic credentials encoded as UTF-8 or Latin-1 when representable. A validated `Secret[HttpUrl]` can be registered directly.
|
|
64
|
+
- Overlapping matches are merged. Registering a short value can also mask ordinary text containing it. With the default policy, fragments of a truncated credential may survive. Select `SecretRegistry(token_mode="delimited")` for clients that log token fragments.
|
|
65
|
+
- Pass `mask_extra={"password"}` to the formatter to replace that top-level log-record field even if its value is unknown. The same rule applies to nested mapping keys in messages, arguments and extras.
|
|
66
|
+
- Install the formatter on each text handler that needs masking. Direct writes, separate telemetry exporters, validation failures before registration and logs emitted before registration are outside its coverage. A formatting failure emits a fixed diagnostic so the logging error path cannot echo the bad arguments.
|
|
67
|
+
|
|
68
|
+
## Test and compare
|
|
69
|
+
|
|
70
|
+
Hushbench is the benchmark workspace member. It compares Hushfang, Python's standard formatter, logmask and loggingredactor on the same synthetic records. Reports show exact output, exposed canaries, altered public controls, dropped records and formatting cost. Expand a case in the HTML report to see the original event alongside each adapter's output.
|
|
71
|
+
|
|
72
|
+
```sh
|
|
73
|
+
uv sync --locked --all-packages
|
|
74
|
+
uv run --no-sync hushbench --output hushbench-report
|
|
75
|
+
uv run --no-sync ruff check .
|
|
76
|
+
uv run --no-sync ruff format --check .
|
|
77
|
+
uv run --no-sync ty check
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
CI runs the library tests and benchmark on Python 3.11, 3.12, 3.13, 3.14 and 3.15. The combined artifact contains an offline HTML index with a report for each interpreter. [Results by scenario](https://github.com/yupasik/hushfang/blob/main/benchmark/RESULTS.md) · [Corpus and metrics](https://github.com/yupasik/hushfang/blob/main/benchmark/README.md) · [CI runs and downloads](https://github.com/yupasik/hushfang/actions/workflows/evaluation.yml)
|
|
81
|
+
|
|
82
|
+
The CI artifact includes a second report from **1,630 public cryptographic test events** on each Python version. [Sources and reproduction](https://github.com/yupasik/hushfang/blob/main/benchmark/SOURCES.md)
|
|
83
|
+
|
|
84
|
+
## Packaging
|
|
85
|
+
|
|
86
|
+
The library and benchmark share a uv lockfile. Installing Hushfang alone brings in Pydantic. The release rehearsal builds the library's wheel and source distribution and tests each in a clean environment. [Packaging and release workflow](https://github.com/yupasik/hushfang/blob/main/docs/releasing.md)
|
|
87
|
+
|
|
88
|
+
## Related Pydantic experiment
|
|
89
|
+
|
|
90
|
+
An unsuccessful model validation can include the original input before a secret wrapper exists. On Pydantic 2.14.4, `hide_input_in_errors=True` hides input when printing the exception. Structured outputs still include it unless the caller passes `include_input=False`. The accompanying fork changes that default for structured errors and preserves explicit overrides. [Experimental patch and regression tests](https://github.com/yupasik/pydantic/commit/f263021eb5b703709e839d243e47a72fa07c8a03) | [Pydantic issue 7461](https://github.com/pydantic/pydantic/issues/7461)
|
hushfang-0.1.0/README.md
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# Hushfang
|
|
2
|
+
|
|
3
|
+
Hushfang masks Pydantic secrets in formatted Python logs, including values revealed to a client or SDK. A log handler applies the registry to the formatted message, including exception chains, stack text and interpolated arguments. The library depends only on Pydantic.
|
|
4
|
+
|
|
5
|
+
[Design principles for logging secrets](https://github.com/yupasik/hushfang/blob/main/docs/design-principles.md) · [Hushbench](https://github.com/yupasik/hushfang/tree/main/benchmark) · [Detailed test report](https://github.com/yupasik/hushfang/blob/main/benchmark/RESULTS.md)
|
|
6
|
+
|
|
7
|
+
## Run the example
|
|
8
|
+
|
|
9
|
+
From a checkout with uv and Python 3.11 or later:
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
uv sync --locked
|
|
13
|
+
uv run --no-sync python demo.py
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
```python
|
|
17
|
+
import logging
|
|
18
|
+
|
|
19
|
+
from pydantic import BaseModel, SecretStr
|
|
20
|
+
from hushfang import RedactingFormatter, SecretRegistry
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Settings(BaseModel):
|
|
24
|
+
api_key: SecretStr
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
settings = Settings(api_key="example-token-42")
|
|
28
|
+
registry = SecretRegistry()
|
|
29
|
+
registry.register_model(settings)
|
|
30
|
+
|
|
31
|
+
handler = logging.StreamHandler()
|
|
32
|
+
handler.setFormatter(RedactingFormatter(registry, "%(message)s"))
|
|
33
|
+
logger = logging.getLogger("client")
|
|
34
|
+
logger.propagate = False
|
|
35
|
+
logger.addHandler(handler)
|
|
36
|
+
|
|
37
|
+
logger.warning("Retrying with credential %s", settings.api_key.get_secret_value())
|
|
38
|
+
# Retrying with credential ***
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Each registry belongs to its application or worker. Register secrets before clients can log them. Register replacements before rotating credentials. Old values remain available for delayed log messages until the registry is cleared or released. The registry holds sensitive values and reversible representations in memory.
|
|
42
|
+
|
|
43
|
+
## Coverage
|
|
44
|
+
|
|
45
|
+
[Secret types, validation, disclosure and exceptions](https://github.com/yupasik/hushfang/blob/main/docs/secret-handling.md) · [Cryptographic test vectors](https://github.com/yupasik/hushfang/blob/main/benchmark/SOURCES.md)
|
|
46
|
+
|
|
47
|
+
- Register individual `SecretStr` and `SecretBytes` instances, or walk stored fields on an already validated model. The walk includes excluded fields, extras, nested models and standard containers. It handles cycles and skips computed properties.
|
|
48
|
+
- Matching covers complete literals, Python and JSON escapes, standard and URL-safe padded Base64, hexadecimal, and common URL encodings. For a URL with credentials, the registry also covers its password and Basic credentials encoded as UTF-8 or Latin-1 when representable. A validated `Secret[HttpUrl]` can be registered directly.
|
|
49
|
+
- Overlapping matches are merged. Registering a short value can also mask ordinary text containing it. With the default policy, fragments of a truncated credential may survive. Select `SecretRegistry(token_mode="delimited")` for clients that log token fragments.
|
|
50
|
+
- Pass `mask_extra={"password"}` to the formatter to replace that top-level log-record field even if its value is unknown. The same rule applies to nested mapping keys in messages, arguments and extras.
|
|
51
|
+
- Install the formatter on each text handler that needs masking. Direct writes, separate telemetry exporters, validation failures before registration and logs emitted before registration are outside its coverage. A formatting failure emits a fixed diagnostic so the logging error path cannot echo the bad arguments.
|
|
52
|
+
|
|
53
|
+
## Test and compare
|
|
54
|
+
|
|
55
|
+
Hushbench is the benchmark workspace member. It compares Hushfang, Python's standard formatter, logmask and loggingredactor on the same synthetic records. Reports show exact output, exposed canaries, altered public controls, dropped records and formatting cost. Expand a case in the HTML report to see the original event alongside each adapter's output.
|
|
56
|
+
|
|
57
|
+
```sh
|
|
58
|
+
uv sync --locked --all-packages
|
|
59
|
+
uv run --no-sync hushbench --output hushbench-report
|
|
60
|
+
uv run --no-sync ruff check .
|
|
61
|
+
uv run --no-sync ruff format --check .
|
|
62
|
+
uv run --no-sync ty check
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
CI runs the library tests and benchmark on Python 3.11, 3.12, 3.13, 3.14 and 3.15. The combined artifact contains an offline HTML index with a report for each interpreter. [Results by scenario](https://github.com/yupasik/hushfang/blob/main/benchmark/RESULTS.md) · [Corpus and metrics](https://github.com/yupasik/hushfang/blob/main/benchmark/README.md) · [CI runs and downloads](https://github.com/yupasik/hushfang/actions/workflows/evaluation.yml)
|
|
66
|
+
|
|
67
|
+
The CI artifact includes a second report from **1,630 public cryptographic test events** on each Python version. [Sources and reproduction](https://github.com/yupasik/hushfang/blob/main/benchmark/SOURCES.md)
|
|
68
|
+
|
|
69
|
+
## Packaging
|
|
70
|
+
|
|
71
|
+
The library and benchmark share a uv lockfile. Installing Hushfang alone brings in Pydantic. The release rehearsal builds the library's wheel and source distribution and tests each in a clean environment. [Packaging and release workflow](https://github.com/yupasik/hushfang/blob/main/docs/releasing.md)
|
|
72
|
+
|
|
73
|
+
## Related Pydantic experiment
|
|
74
|
+
|
|
75
|
+
An unsuccessful model validation can include the original input before a secret wrapper exists. On Pydantic 2.14.4, `hide_input_in_errors=True` hides input when printing the exception. Structured outputs still include it unless the caller passes `include_input=False`. The accompanying fork changes that default for structured errors and preserves explicit overrides. [Experimental patch and regression tests](https://github.com/yupasik/pydantic/commit/f263021eb5b703709e839d243e47a72fa07c8a03) | [Pydantic issue 7461](https://github.com/pydantic/pydantic/issues/7461)
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["uv_build>=0.13.12,<0.14"]
|
|
3
|
+
build-backend = "uv_build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "hushfang"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Redact registered Pydantic secret values in formatted Python logs"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
dependencies = ["pydantic>=2.14,<3"]
|
|
12
|
+
|
|
13
|
+
[project.optional-dependencies]
|
|
14
|
+
evaluation = [
|
|
15
|
+
"pydantic==2.14.4",
|
|
16
|
+
"logmask==0.1.5; python_version >= '3.12'",
|
|
17
|
+
"loggingredactor==0.0.7",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
[project.urls]
|
|
21
|
+
Repository = "https://github.com/yupasik/hushfang"
|
|
22
|
+
Issues = "https://github.com/yupasik/hushfang/issues"
|
|
23
|
+
Documentation = "https://github.com/yupasik/hushfang#readme"
|
|
24
|
+
|
|
25
|
+
[dependency-groups]
|
|
26
|
+
dev = [
|
|
27
|
+
"ruff==0.17.6",
|
|
28
|
+
"ty==1.1.0",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
[tool.ruff]
|
|
32
|
+
target-version = "py311"
|
|
33
|
+
line-length = 100
|
|
34
|
+
|
|
35
|
+
[tool.ruff.lint]
|
|
36
|
+
select = [
|
|
37
|
+
"E4",
|
|
38
|
+
"E7",
|
|
39
|
+
"E9",
|
|
40
|
+
"F",
|
|
41
|
+
"I",
|
|
42
|
+
"B",
|
|
43
|
+
"UP",
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
[tool.ty.environment]
|
|
47
|
+
python-version = "3.11"
|
|
48
|
+
|
|
49
|
+
[tool.ty.src]
|
|
50
|
+
include = [
|
|
51
|
+
"src",
|
|
52
|
+
"benchmark/hushbench",
|
|
53
|
+
"demo.py",
|
|
54
|
+
"tests",
|
|
55
|
+
"benchmark/tests",
|
|
56
|
+
"evaluation",
|
|
57
|
+
]
|
|
58
|
+
|
|
59
|
+
[tool.uv.workspace]
|
|
60
|
+
members = ["benchmark"]
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["uv_build>=0.13.12,<0.14"]
|
|
3
|
+
build-backend = "uv_build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "hushfang"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Redact registered Pydantic secret values in formatted Python logs"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
dependencies = ["pydantic>=2.14,<3"]
|
|
12
|
+
|
|
13
|
+
[project.optional-dependencies]
|
|
14
|
+
evaluation = ["pydantic==2.14.4", "logmask==0.1.5; python_version >= '3.12'", "loggingredactor==0.0.7"]
|
|
15
|
+
|
|
16
|
+
[project.urls]
|
|
17
|
+
Repository = "https://github.com/yupasik/hushfang"
|
|
18
|
+
Issues = "https://github.com/yupasik/hushfang/issues"
|
|
19
|
+
Documentation = "https://github.com/yupasik/hushfang#readme"
|
|
20
|
+
|
|
21
|
+
[dependency-groups]
|
|
22
|
+
dev = ["ruff==0.17.6", "ty==1.1.0"]
|
|
23
|
+
|
|
24
|
+
[tool.ruff]
|
|
25
|
+
target-version = "py311"
|
|
26
|
+
line-length = 100
|
|
27
|
+
|
|
28
|
+
[tool.ruff.lint]
|
|
29
|
+
select = ["E4", "E7", "E9", "F", "I", "B", "UP"]
|
|
30
|
+
|
|
31
|
+
[tool.ty.environment]
|
|
32
|
+
python-version = "3.11"
|
|
33
|
+
|
|
34
|
+
[tool.ty.src]
|
|
35
|
+
include = ["src", "benchmark/hushbench", "demo.py", "tests", "benchmark/tests", "evaluation"]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
[tool.uv.workspace]
|
|
39
|
+
members = ["benchmark"]
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Value-based redaction for text log handlers."""
|
|
2
|
+
|
|
3
|
+
from .boundaries import (
|
|
4
|
+
RedactedError,
|
|
5
|
+
RedactedValidationError,
|
|
6
|
+
SecretModel,
|
|
7
|
+
revealing,
|
|
8
|
+
sanitize_exception,
|
|
9
|
+
validate_model,
|
|
10
|
+
)
|
|
11
|
+
from .registry import RedactingFormatter, SecretRegistry
|
|
12
|
+
from .structure import reveal_structure
|
|
13
|
+
from .types import SecretBinary, SecretKey, SecretMnemonic, SecretSeed, SecretText, SecretURL
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"RedactedError",
|
|
17
|
+
"RedactedValidationError",
|
|
18
|
+
"SecretModel",
|
|
19
|
+
"revealing",
|
|
20
|
+
"reveal_structure",
|
|
21
|
+
"sanitize_exception",
|
|
22
|
+
"validate_model",
|
|
23
|
+
"SecretText",
|
|
24
|
+
"SecretSeed",
|
|
25
|
+
"SecretBinary",
|
|
26
|
+
"SecretURL",
|
|
27
|
+
"RedactingFormatter",
|
|
28
|
+
"SecretRegistry",
|
|
29
|
+
"SecretKey",
|
|
30
|
+
"SecretMnemonic",
|
|
31
|
+
]
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
"""Application boundaries for Pydantic validation and deliberate access to raw values."""
|
|
2
|
+
|
|
3
|
+
import traceback
|
|
4
|
+
from asyncio import CancelledError
|
|
5
|
+
from collections.abc import Generator
|
|
6
|
+
from contextlib import contextmanager
|
|
7
|
+
from types import GetSetDescriptorType, MemberDescriptorType
|
|
8
|
+
from typing import Any, TypeVar, get_args
|
|
9
|
+
|
|
10
|
+
from pydantic import (
|
|
11
|
+
BaseModel,
|
|
12
|
+
ConfigDict,
|
|
13
|
+
GetJsonSchemaHandler,
|
|
14
|
+
ValidationError,
|
|
15
|
+
)
|
|
16
|
+
from pydantic.json_schema import JsonSchemaValue
|
|
17
|
+
from pydantic_core import CoreSchema, ErrorType
|
|
18
|
+
|
|
19
|
+
from .matching import SupportedSecret
|
|
20
|
+
from .registry import SecretRegistry
|
|
21
|
+
from .structure import transform
|
|
22
|
+
from .types import SecretBinary, SecretText
|
|
23
|
+
|
|
24
|
+
_Model = TypeVar("_Model", bound=BaseModel)
|
|
25
|
+
_ERROR_TYPES = frozenset(get_args(ErrorType))
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class SecretModel(BaseModel):
|
|
29
|
+
"""Validate defaults using their declared types before registering credentials."""
|
|
30
|
+
|
|
31
|
+
model_config = ConfigDict(validate_default=True, hide_input_in_errors=True)
|
|
32
|
+
|
|
33
|
+
@classmethod
|
|
34
|
+
def __get_pydantic_json_schema__(
|
|
35
|
+
cls, schema: CoreSchema, handler: GetJsonSchemaHandler
|
|
36
|
+
) -> JsonSchemaValue:
|
|
37
|
+
root = handler.resolve_ref_schema(handler(schema))
|
|
38
|
+
|
|
39
|
+
def sensitive(node: Any, ancestors: set[int]) -> bool:
|
|
40
|
+
if isinstance(node, list):
|
|
41
|
+
return any([sensitive(v, ancestors) for v in node])
|
|
42
|
+
if not isinstance(node, dict):
|
|
43
|
+
return False
|
|
44
|
+
if "$ref" in node:
|
|
45
|
+
try:
|
|
46
|
+
node = handler.resolve_ref_schema(node)
|
|
47
|
+
except LookupError:
|
|
48
|
+
# A recursive reference may still be under construction.
|
|
49
|
+
return True
|
|
50
|
+
if id(node) in ancestors:
|
|
51
|
+
return False
|
|
52
|
+
children = ancestors | {id(node)}
|
|
53
|
+
found = node.get("writeOnly") is True or node.get("format") == "password"
|
|
54
|
+
for name, value in tuple(node.items()):
|
|
55
|
+
if name == "properties" and isinstance(value, dict):
|
|
56
|
+
for prop in value.values():
|
|
57
|
+
found |= sensitive(prop, children)
|
|
58
|
+
elif name not in {"default", "examples"}:
|
|
59
|
+
found |= sensitive(value, children)
|
|
60
|
+
if found:
|
|
61
|
+
node.pop("default", None)
|
|
62
|
+
node.pop("examples", None)
|
|
63
|
+
return found
|
|
64
|
+
|
|
65
|
+
sensitive(root, set())
|
|
66
|
+
return root
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class RedactedError(Exception):
|
|
70
|
+
"""A diagnostic whose original exception could not be safely forwarded."""
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class RedactedValidationError(ValueError):
|
|
74
|
+
"""A validation summary containing only trusted schema field names and error codes."""
|
|
75
|
+
|
|
76
|
+
def __init__(self, problems: tuple[tuple[str, str], ...]) -> None:
|
|
77
|
+
self.problems = problems
|
|
78
|
+
super().__init__(", ".join(f"{name} ({code})" for name, code in problems))
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def validate_model(model: type[_Model], data: Any, registry: SecretRegistry) -> _Model:
|
|
82
|
+
"""Register only a successfully validated model. Invalid input never enters the summary."""
|
|
83
|
+
try:
|
|
84
|
+
result = model.model_validate(data)
|
|
85
|
+
except ValidationError as exc:
|
|
86
|
+
issues = []
|
|
87
|
+
for detail in exc.errors(include_input=False, include_context=False, include_url=False):
|
|
88
|
+
path = detail["loc"]
|
|
89
|
+
first = path[0] if path else None
|
|
90
|
+
name = first if isinstance(first, str) and first in model.model_fields else "model"
|
|
91
|
+
code = detail["type"]
|
|
92
|
+
issues.append((name, code if code in _ERROR_TYPES else "validation_error"))
|
|
93
|
+
failure = RedactedValidationError(tuple(issues))
|
|
94
|
+
except Exception:
|
|
95
|
+
failure = RedactedValidationError((("model", "validation_error"),))
|
|
96
|
+
else:
|
|
97
|
+
registry.register_model(result)
|
|
98
|
+
return result
|
|
99
|
+
raise failure
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _clean(value: Any, registry: SecretRegistry, pending: list[BaseException]) -> Any:
|
|
103
|
+
def redact(item: Any) -> Any:
|
|
104
|
+
if isinstance(item, str):
|
|
105
|
+
return registry.redact(item)
|
|
106
|
+
if isinstance(item, bytes):
|
|
107
|
+
return registry.redact_bytes(item)
|
|
108
|
+
if isinstance(item, BaseException):
|
|
109
|
+
pending.append(item)
|
|
110
|
+
return item
|
|
111
|
+
if item is None or isinstance(item, (int, float, bool)):
|
|
112
|
+
return item
|
|
113
|
+
return "[opaque value]"
|
|
114
|
+
|
|
115
|
+
return transform(value, redact)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _fallback(error: BaseException) -> BaseException:
|
|
119
|
+
if isinstance(error, BaseExceptionGroup):
|
|
120
|
+
# Preserve the distinction between control flow and an ordinary ExceptionGroup.
|
|
121
|
+
children = [_fallback(child) for child in error.exceptions]
|
|
122
|
+
return BaseExceptionGroup("redacted group", children)
|
|
123
|
+
if isinstance(error, SystemExit):
|
|
124
|
+
return SystemExit(error.code if type(error.code) is int else "[redacted]")
|
|
125
|
+
if not isinstance(error, Exception):
|
|
126
|
+
for kind in (CancelledError, GeneratorExit, KeyboardInterrupt):
|
|
127
|
+
if isinstance(error, kind):
|
|
128
|
+
return kind()
|
|
129
|
+
return BaseException("[redacted]")
|
|
130
|
+
return RedactedError("Exception detail omitted")
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def sanitize_exception(error: BaseException, registry: SecretRegistry) -> BaseException:
|
|
134
|
+
"""Clean args, attributes, notes, chains and groups. Return the exception safe to forward."""
|
|
135
|
+
pending = [error]
|
|
136
|
+
visited = set()
|
|
137
|
+
cleaned = []
|
|
138
|
+
try:
|
|
139
|
+
while pending:
|
|
140
|
+
current = pending.pop()
|
|
141
|
+
if id(current) in visited:
|
|
142
|
+
continue
|
|
143
|
+
visited.add(id(current))
|
|
144
|
+
cleaned.append(current)
|
|
145
|
+
if isinstance(current, ValidationError):
|
|
146
|
+
# Native structured errors can retain input even when their text is already safe.
|
|
147
|
+
return _fallback(error)
|
|
148
|
+
for cls in type(current).__mro__:
|
|
149
|
+
if cls in (BaseException, BaseExceptionGroup):
|
|
150
|
+
continue
|
|
151
|
+
for name, descriptor in vars(cls).items():
|
|
152
|
+
if not isinstance(descriptor, (MemberDescriptorType, GetSetDescriptorType)):
|
|
153
|
+
continue
|
|
154
|
+
if name.startswith("__") or not hasattr(current, name):
|
|
155
|
+
continue
|
|
156
|
+
value = getattr(current, name)
|
|
157
|
+
safe = _clean(value, registry, pending)
|
|
158
|
+
if cls.__module__ == "builtins":
|
|
159
|
+
# Built-in exception fields may retain data outside args and str(error).
|
|
160
|
+
# Avoid altering diagnostic invariants such as Unicode codec offsets.
|
|
161
|
+
if type(value) is not type(safe) or value != safe:
|
|
162
|
+
if isinstance(current, SystemExit) and name == "code":
|
|
163
|
+
current.code = safe
|
|
164
|
+
else:
|
|
165
|
+
return _fallback(error)
|
|
166
|
+
else:
|
|
167
|
+
setattr(current, name, safe)
|
|
168
|
+
pending.extend(e for e in (current.__cause__, current.__context__) if e is not None)
|
|
169
|
+
if isinstance(current, BaseExceptionGroup):
|
|
170
|
+
pending.extend(current.exceptions)
|
|
171
|
+
pending.extend(x for x in current.args if isinstance(x, BaseException))
|
|
172
|
+
if not isinstance(current, BaseExceptionGroup):
|
|
173
|
+
current.args = _clean(current.args, registry, pending)
|
|
174
|
+
for name, value in tuple(vars(current).items()):
|
|
175
|
+
clean_name = registry.redact(name)
|
|
176
|
+
if clean_name != name:
|
|
177
|
+
del vars(current)[name]
|
|
178
|
+
vars(current)[clean_name] = _clean(value, registry, pending)
|
|
179
|
+
if isinstance(current, SystemExit):
|
|
180
|
+
current.code = _clean(current.code, registry, pending)
|
|
181
|
+
for current in cleaned:
|
|
182
|
+
displayed = "\n".join(
|
|
183
|
+
(str(current), repr(current), *traceback.format_exception_only(current))
|
|
184
|
+
)
|
|
185
|
+
if registry.redact(displayed) != displayed:
|
|
186
|
+
return _fallback(error)
|
|
187
|
+
return error
|
|
188
|
+
except Exception:
|
|
189
|
+
return _fallback(error)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
@contextmanager
|
|
193
|
+
def revealing(
|
|
194
|
+
*values: SupportedSecret | str | bytes, registry: SecretRegistry | None = None
|
|
195
|
+
) -> Generator[tuple[Any, ...], None, None]:
|
|
196
|
+
"""Reveal each credential to one operation and sanitize exceptions leaving the block."""
|
|
197
|
+
active = registry if registry is not None else SecretRegistry()
|
|
198
|
+
wrapped = [
|
|
199
|
+
SecretText(v) if isinstance(v, str) else SecretBinary(v) if isinstance(v, bytes) else v
|
|
200
|
+
for v in values
|
|
201
|
+
]
|
|
202
|
+
active.register(*wrapped)
|
|
203
|
+
try:
|
|
204
|
+
yield tuple(v.get_secret_value() for v in wrapped)
|
|
205
|
+
except BaseException as original:
|
|
206
|
+
cleaned = sanitize_exception(original, active)
|
|
207
|
+
if cleaned is original:
|
|
208
|
+
raise
|
|
209
|
+
else:
|
|
210
|
+
return
|
|
211
|
+
# The with machinery may attach the active exception when a replacement is raised.
|
|
212
|
+
try:
|
|
213
|
+
raise cleaned
|
|
214
|
+
except BaseException as replacement:
|
|
215
|
+
replacement.__context__ = None
|
|
216
|
+
replacement.__cause__ = None
|
|
217
|
+
replacement.__suppress_context__ = True
|
|
218
|
+
raise
|