|
| 1 | +# |
| 2 | +# Copyright 2025 ABSA Group Limited |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +# |
| 16 | + |
| 17 | +"""Safe serialization utilities for logging. |
| 18 | +
|
| 19 | +Provides PII-safe, size-bounded JSON serialization for TRACE logging. |
| 20 | +""" |
| 21 | + |
| 22 | +import json |
| 23 | +import os |
| 24 | +from typing import Any, List, Set |
| 25 | + |
| 26 | + |
| 27 | +def _redact_sensitive_keys(obj: Any, redact_keys: Set[str]) -> Any: |
| 28 | + """Recursively redact sensitive keys from nested structures. |
| 29 | +
|
| 30 | + Args: |
| 31 | + obj: Object to redact (dict, list, or scalar). |
| 32 | + redact_keys: Set of key names to redact (case-insensitive). |
| 33 | +
|
| 34 | + Returns: |
| 35 | + Copy of obj with sensitive values replaced by "***REDACTED***". |
| 36 | + """ |
| 37 | + if isinstance(obj, dict): |
| 38 | + return { |
| 39 | + k: "***REDACTED***" if k.lower() in redact_keys else _redact_sensitive_keys(v, redact_keys) |
| 40 | + for k, v in obj.items() |
| 41 | + } |
| 42 | + if isinstance(obj, list): |
| 43 | + return [_redact_sensitive_keys(item, redact_keys) for item in obj] |
| 44 | + return obj |
| 45 | + |
| 46 | + |
| 47 | +def safe_serialize_for_log(message: Any, redact_keys: List[str] | None = None, max_bytes: int | None = None) -> str: |
| 48 | + """Safely serialize a message for logging with redaction and size capping. |
| 49 | +
|
| 50 | + Args: |
| 51 | + message: Object to serialize (typically a dict). |
| 52 | + redact_keys: List of key names to redact (case-insensitive). If None, uses env TRACE_REDACT_KEYS. |
| 53 | + max_bytes: Maximum serialized output size in bytes. If None, uses env TRACE_MAX_BYTES (default 10000). |
| 54 | +
|
| 55 | + Returns: |
| 56 | + JSON string (redacted and truncated if needed), or empty string on serialization error. |
| 57 | + """ |
| 58 | + # Apply configuration defaults |
| 59 | + if redact_keys is None: |
| 60 | + redact_keys_str = os.environ.get("TRACE_REDACT_KEYS", "password,secret,token,key,apikey,api_key") |
| 61 | + redact_keys = [k.strip() for k in redact_keys_str.split(",") if k.strip()] |
| 62 | + if max_bytes is None: |
| 63 | + max_bytes = int(os.environ.get("TRACE_MAX_BYTES", "10000")) |
| 64 | + |
| 65 | + # Normalize to case-insensitive set |
| 66 | + redact_set = {k.lower() for k in redact_keys} |
| 67 | + |
| 68 | + try: |
| 69 | + # Redact sensitive keys |
| 70 | + redacted = _redact_sensitive_keys(message, redact_set) |
| 71 | + # Serialize with minimal whitespace |
| 72 | + serialized = json.dumps(redacted, separators=(",", ":")) |
| 73 | + # Truncate if needed |
| 74 | + if len(serialized.encode("utf-8")) > max_bytes: |
| 75 | + # Binary truncate to max_bytes and append marker |
| 76 | + truncated_bytes = serialized.encode("utf-8")[:max_bytes] |
| 77 | + # Ensure we don't break mid-multibyte character |
| 78 | + try: |
| 79 | + return truncated_bytes.decode("utf-8", errors="ignore") + "..." |
| 80 | + except UnicodeDecodeError: # pragma: no cover - defensive |
| 81 | + return "" |
| 82 | + return serialized |
| 83 | + except (TypeError, ValueError, OverflowError): # pragma: no cover - catch serialization errors |
| 84 | + return "" |
| 85 | + |
| 86 | + |
| 87 | +__all__ = ["safe_serialize_for_log"] |
0 commit comments