hushfang 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.
hushfang/__init__.py ADDED
@@ -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
+ ]
hushfang/boundaries.py ADDED
@@ -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
hushfang/crypto.py ADDED
@@ -0,0 +1,249 @@
1
+ """Recognition of explicitly registered private material. No signing or key derivation."""
2
+
3
+ import base64
4
+ import binascii
5
+ import hashlib
6
+ import json
7
+ import re
8
+ import unicodedata
9
+ from collections.abc import Iterator
10
+ from dataclasses import dataclass
11
+ from urllib.parse import unquote_to_bytes
12
+
13
+ _ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
14
+ _WIF = {0x80, 0xEF, 0xB0, 0x9E, 0xCC, 0xF1}
15
+ _PRIVATE_VERSIONS = {bytes.fromhex(v) for v in ("0488ade4", "04358394")}
16
+ _ORDER = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
17
+ _HEX = re.compile(r"(?:0[xX])?((?:[0-9a-fA-F]{2})+)")
18
+ _MIN_CHUNK = 15
19
+ # Bound expensive base conversions to key-sized inputs. Exact masking still applies above this size.
20
+ _MAX_BASE_CONVERSION = 1785
21
+
22
+
23
+ def _base58(raw: bytes) -> str:
24
+ leading = len(raw) - len(raw.lstrip(b"\x00"))
25
+ number = int.from_bytes(raw)
26
+ digits = []
27
+ while number:
28
+ number, digit = divmod(number, 58)
29
+ digits.append(_ALPHABET[digit])
30
+ return "1" * leading + "".join(reversed(digits))
31
+
32
+
33
+ def _checksum(payload: bytes) -> bytes:
34
+ return hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4]
35
+
36
+
37
+ def _scalar(raw: bytes) -> bool:
38
+ return len(raw) == 32 and 0 < int.from_bytes(raw) < _ORDER
39
+
40
+
41
+ def _key_bytes(text: str) -> bytes | None:
42
+ if text.startswith("-----BEGIN "):
43
+ lines = text.strip().splitlines()
44
+ label = lines[0].removeprefix("-----BEGIN ").removesuffix("-----")
45
+ if (
46
+ label
47
+ in {
48
+ "PRIVATE KEY",
49
+ "ENCRYPTED PRIVATE KEY",
50
+ "RSA PRIVATE KEY",
51
+ "EC PRIVATE KEY",
52
+ "OPENSSH PRIVATE KEY",
53
+ }
54
+ and len(lines) >= 3
55
+ and lines[-1] == f"-----END {label}-----"
56
+ ):
57
+ try:
58
+ return base64.b64decode("".join(lines[1:-1]), validate=True)
59
+ except (ValueError, binascii.Error):
60
+ return None
61
+ if m := _HEX.fullmatch(text):
62
+ return bytes.fromhex(m[1])
63
+ if text.startswith("[") and len(text) <= 2048:
64
+ try:
65
+ seq = json.loads(text)
66
+ except (ValueError, RecursionError):
67
+ return None
68
+ if (
69
+ isinstance(seq, list)
70
+ and len(seq) in (32, 64)
71
+ and all(type(n) is int and 0 <= n <= 255 for n in seq)
72
+ ):
73
+ return bytes(seq)
74
+ return None
75
+ if not 32 <= len(text) <= 120:
76
+ return None
77
+ n = 0
78
+ for char in text:
79
+ digit = _ALPHABET.find(char)
80
+ if digit < 0:
81
+ return None
82
+ n = 58 * n + digit
83
+ raw = b"\x00" * (len(text) - len(text.lstrip("1"))) + n.to_bytes((n.bit_length() + 7) // 8)
84
+ if len(raw) in (32, 64):
85
+ return raw
86
+ payload = raw[:-4]
87
+ if raw[-4:] != _checksum(payload):
88
+ return None
89
+ if len(payload) in (33, 34) and payload[0] in _WIF:
90
+ private = payload[1:33]
91
+ if _scalar(private) and payload[33:] in (b"", b"\x01"):
92
+ return private
93
+ if (
94
+ len(payload) == 78
95
+ and payload[:4] in _PRIVATE_VERSIONS
96
+ and payload[45] == 0
97
+ and (payload[4] != 0 or payload[5:13] == bytes(8))
98
+ and _scalar(payload[46:])
99
+ ):
100
+ return payload[46:]
101
+ return None
102
+
103
+
104
+ def key_material(value: str | bytes) -> bytes | None:
105
+ """Unknown or malformed textual keys keep their literal mask."""
106
+ if isinstance(value, bytes):
107
+ return value
108
+ return _key_bytes(value.strip())
109
+
110
+
111
+ def key_encodings(raw: bytes) -> set[str]:
112
+ if not raw:
113
+ return set()
114
+ decimal_list = ",".join(str(n) for n in raw)
115
+ forms = {
116
+ raw.hex(" "),
117
+ raw.hex(":"),
118
+ raw.hex(" ").upper(),
119
+ raw.hex(":").upper(),
120
+ repr(raw)[2:-1],
121
+ decimal_list,
122
+ decimal_list.replace(",", ", "),
123
+ "[" + decimal_list + "]",
124
+ "[" + decimal_list.replace(",", ", ") + "]",
125
+ }
126
+ for prefix in ("0x", "0X"):
127
+ forms.update((prefix + raw.hex(), prefix + raw.hex().upper()))
128
+ if len(raw) <= _MAX_BASE_CONVERSION:
129
+ forms.add(_base58(raw))
130
+ try:
131
+ decimal = str(int.from_bytes(raw))
132
+ except ValueError:
133
+ decimal = "" # A process can lower the interpreter decimal-digit limit.
134
+ if len(decimal) >= 10:
135
+ forms.add(decimal)
136
+ if _scalar(raw):
137
+ for version in _WIF:
138
+ for flag in (b"", b"\x01"):
139
+ payload = bytes([version]) + raw + flag
140
+ forms.add(_base58(payload + _checksum(payload)))
141
+ return {form for form in forms if form}
142
+
143
+
144
+ def key_anchors(forms: set[str]) -> dict[str, list[tuple[str, int]]]:
145
+ """Index overlapping anchors. Any span of at least 15 characters contains an indexed 8-gram."""
146
+ anchors: dict[str, list[tuple[str, int]]] = {}
147
+ for form in forms:
148
+ for offset in range(0, len(form) - 7, 8):
149
+ anchor = form[offset : offset + 8]
150
+ if len(set(anchor)) >= 3:
151
+ anchors.setdefault(anchor, []).append((form, offset))
152
+ return anchors
153
+
154
+
155
+ def key_spans(text: str, anchors: dict[str, list[tuple[str, int]]]) -> Iterator[tuple[int, int]]:
156
+ # Find a maximal match once, even when a long representation contains many anchors.
157
+ covered: dict[tuple[str, int], int] = {}
158
+ for pos in range(len(text) - 7):
159
+ for form, offset in anchors.get(text[pos : pos + 8], ()):
160
+ diagonal = (form, pos - offset)
161
+ if pos < covered.get(diagonal, 0):
162
+ continue
163
+ start, end = pos, pos + 8
164
+ while (
165
+ start > max(0, pos - offset) and text[start - 1] == form[offset + start - pos - 1]
166
+ ):
167
+ start -= 1
168
+ limit = min(len(text), pos + len(form) - offset)
169
+ while end < limit and text[end] == form[offset + end - pos]:
170
+ end += 1
171
+ covered[diagonal] = end
172
+ if end - start >= _MIN_CHUNK:
173
+ yield start, end
174
+
175
+
176
+ _ESCAPED = re.compile(r"(?:%[0-9a-fA-F]{2})+|\\u([0-9a-fA-F]{4})|\\[nrt]")
177
+ _LABEL = re.compile(r"(?i)\bword\s*\d{1,2}\s*[:=]\s*")
178
+ Triple = tuple[str, str, str]
179
+
180
+
181
+ def _decoded_chars(text: str) -> Iterator[tuple[str, int, int]]:
182
+ last = 0
183
+ for match in _ESCAPED.finditer(text):
184
+ for i in range(last, match.start()):
185
+ yield text[i], i, i + 1
186
+ if match[0][0] == "%":
187
+ pos = match.start()
188
+ for char in unquote_to_bytes(match[0]).decode("utf-8", "surrogateescape"):
189
+ stop = pos + 3 * len(char.encode("utf-8", "surrogateescape"))
190
+ yield char, pos, stop
191
+ pos = stop
192
+ else:
193
+ yield chr(int(match[1], 16)) if match[1] else " ", match.start(), match.end()
194
+ last = match.end()
195
+ for i in range(last, len(text)):
196
+ yield text[i], i, i + 1
197
+
198
+
199
+ @dataclass(frozen=True, slots=True)
200
+ class Word:
201
+ folded: str
202
+ start: int
203
+ end: int
204
+
205
+
206
+ def _fold(word: str) -> str:
207
+ return "".join(
208
+ c for c in unicodedata.normalize("NFKD", word.casefold()) if not unicodedata.combining(c)
209
+ )
210
+
211
+
212
+ def _words(text: str, split_han: bool) -> Iterator[Word]:
213
+ # Preserve original offsets across JSON escapes, percent escapes and decomposed accents.
214
+ text = _LABEL.sub(lambda m: " " * len(m[0]), text)
215
+ word: list[str] = []
216
+ start = end = 0
217
+ for char, left, right in _decoded_chars(text):
218
+ han = split_han and "\u3400" <= char <= "\u9fff"
219
+ if word and (han or not (char.isalpha() or unicodedata.category(char).startswith("M"))):
220
+ yield Word(_fold("".join(word)), start, end)
221
+ word.clear()
222
+ if han:
223
+ yield Word(char, left, right)
224
+ elif char.isalpha() or (word and unicodedata.category(char).startswith("M")):
225
+ if not word:
226
+ start = left
227
+ word.append(char)
228
+ end = right
229
+ if word:
230
+ yield Word(_fold("".join(word)), start, end)
231
+
232
+
233
+ def phrase_triples(phrase: str) -> tuple[set[Triple], bool]:
234
+ words = [t.folded for t in _words(phrase, False)]
235
+ han = bool(words) and all(len(w) == 1 and "\u3400" <= w <= "\u9fff" for w in words)
236
+ return set(zip(words, words[1:], words[2:], strict=False)), han
237
+
238
+
239
+ def phrase_spans(text: str, triples: frozenset[Triple], han: bool) -> Iterator[tuple[int, int]]:
240
+ # Scan in both modes when mixed scripts are registered. Japanese words stay whole in normal mode.
241
+ for split_han in (False, True) if han else (False,):
242
+ previous: tuple[Word, ...] = ()
243
+ for word in _words(text, split_han):
244
+ if (
245
+ len(previous) == 2
246
+ and (previous[0].folded, previous[1].folded, word.folded) in triples
247
+ ):
248
+ yield previous[0].start, word.end
249
+ previous = (*previous[-1:], word)