agent-guard-kit-sdk 0.1.0a3__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.
@@ -0,0 +1,220 @@
1
+ Metadata-Version: 2.5
2
+ Name: agent-guard-kit-sdk
3
+ Version: 0.1.0a3
4
+ Summary: Tenant-isolated credential brokering, deny-by-default capabilities, and typed audit sanitization for AI agents.
5
+ Project-URL: Homepage, https://github.com/techmsd/agent-guard-kit
6
+ Project-URL: Documentation, https://github.com/techmsd/agent-guard-kit/tree/main/docs
7
+ Project-URL: Repository, https://github.com/techmsd/agent-guard-kit.git
8
+ Project-URL: Issues, https://github.com/techmsd/agent-guard-kit/issues
9
+ Project-URL: Changelog, https://github.com/techmsd/agent-guard-kit/blob/main/CHANGELOG.md
10
+ Author: AgentGuardKit Maintainers
11
+ License-Expression: Apache-2.0
12
+ License-File: LICENSE
13
+ Keywords: ai-agents,credentials,governance,llm-security,mcp,security,vault
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Intended Audience :: Information Technology
17
+ Classifier: License :: OSI Approved :: Apache Software License
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Topic :: Security
24
+ Classifier: Topic :: Security :: Cryptography
25
+ Classifier: Typing :: Typed
26
+ Requires-Python: >=3.10
27
+ Provides-Extra: dev
28
+ Requires-Dist: build>=1.1.0; extra == 'dev'
29
+ Requires-Dist: mypy>=1.9.0; extra == 'dev'
30
+ Requires-Dist: pytest-cov>=4.1.0; extra == 'dev'
31
+ Requires-Dist: pytest>=8.0.0; extra == 'dev'
32
+ Requires-Dist: ruff>=0.4.0; extra == 'dev'
33
+ Description-Content-Type: text/markdown
34
+
35
+ # AgentGuardKit
36
+
37
+ > **Tenant-isolated credential brokering, deny-by-default capabilities, and typed audit sanitization for AI agents.**
38
+
39
+ > [!WARNING]
40
+ > ### EXPERIMENTAL PRE-RELEASE ALPHA (`v0.1.0a3`)
41
+ > **AgentGuardKit is currently an experimental proof-of-concept release.**
42
+ >
43
+ > - **NOT Independently Security Audited**: This codebase has undergone internal automated testing and architectural review, but has **NOT** yet been audited by an independent third-party application security firm.
44
+ > - **NOT Recommended for Production**: **Do NOT use this package to manage live production credentials, financial keys, or sensitive customer data.**
45
+ > - **Unstable API**: Interfaces, authorization contexts, and storage adapters are subject to breaking changes prior to the stable `v1.0.0` release.
46
+ > - **In-Process Boundary**: AgentGuardKit evaluates policy in host memory; it is not an operating system container, sandbox, or network firewall.
47
+
48
+ [![CI](https://github.com/techmsd/agent-guard-kit/actions/workflows/ci.yml/badge.svg)](https://github.com/techmsd/agent-guard-kit/actions/workflows/ci.yml)
49
+ [![Python Versions](https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13-blue)](https://github.com/techmsd/agent-guard-kit)
50
+ [![License](https://img.shields.io/badge/license-Apache--2.0-green)](LICENSE)
51
+ [![Zero Dependencies](https://img.shields.io/badge/dependencies-zero%20runtime-brightgreen)](#framework-independence)
52
+
53
+ ---
54
+
55
+ ## The Problem: Why LLM Agents Break Traditional Secrets Management
56
+
57
+ Most secrets managers (HashiCorp Vault, AWS Secrets Manager, Doppler) store credentials securely at rest and return them upon authentication. However, when an autonomous AI agent interacts with third-party tools, **yielding raw plaintext credentials directly to the agent runtime creates severe vulnerabilities**:
58
+
59
+ 1. **Prompt Injection & Exfiltration**: LLMs process instructions and untrusted data (user emails, scraped web content, tool responses) in the same context window. If a long-lived API key or OAuth token enters the model's prompt or context, indirect prompt injection can induce the agent to emit or transmit that secret. *System prompts are not security boundaries.*
60
+ 2. **Over-Privileged Non-Human Identities**: Agents executing autonomous sub-tasks often receive broad service account permissions rather than tightly scoped, tenant-isolated credentials.
61
+ 3. **Audit Blindness**: Tracing tools and LLM observability platforms often capture unredacted tool inputs and error dumps, inadvertently recording sensitive authentication material in telemetry tables.
62
+
63
+ ---
64
+
65
+ ## What AgentGuardKit Provides
66
+
67
+ AgentGuardKit is a lightweight, embeddable Python security library that introduces a brokered credential isolation layer between autonomous agents and secret stores:
68
+
69
+ - **Plaintext Credential Withholding**: AI agents receive only opaque references and capability proposals—never raw tokens.
70
+ - **Tenant-Scoped Authorization & Path Isolation**: Requires an explicit, host-authenticated `AuthorizationContext` binding callers to permitted tenant and connector scopes.
71
+ - **Deny-by-Default Capability Engine**: Non-overridable security invariants unconditionally prohibit agents from reading decrypted credentials, requiring human-in-the-loop sign-off for lifecycle operations.
72
+ - **Optimistic Concurrency & Compensating Rollback**: Enforces CAS=0 on registration to prevent overwriting existing keys, CAS on rotation to prevent lost updates, and version-scoped compensating deletion with structured recovery records if metadata persistence fails.
73
+ - **Strict Typed Audit Sanitization**: Scrubs telemetry and logs using typed scalar allowlists (IPs, HTTP verbs, status codes) and regex pattern scrubbers (AWS keys, GitHub tokens, Bearer headers, JWTs).
74
+ - **Framework-Independent & Zero Runtime Dependencies**: Pure Python standard library implementation (`urllib.request`, `ssl`, `json`, `dataclasses`). No mandatory Django, FastAPI, or third-party HTTP client dependencies.
75
+
76
+ ---
77
+
78
+ ## Security Boundary & Host Application Responsibilities
79
+
80
+ > [!WARNING]
81
+ > **In-Process Scope**: AgentGuardKit evaluates capability policies and manages credential paths within the host application process. It is **not** an operating system sandbox, container isolation layer, or hypervisor boundary.
82
+ >
83
+ > **Host Responsibilities**:
84
+ > 1. **Authentication**: The host application must authenticate users/agents and generate a verified `AuthorizationContext`. Untrusted inputs from LLM chat loops or prompts must never be trusted to set identity or scopes.
85
+ > 2. **Execution Sandboxing**: To protect against prompt injection and tool misuse, the host must execute untrusted agent processes in isolated environments (e.g. sandboxed containers or microVMs) with strict network egress filtering.
86
+ > 3. **Proxy Execution**: Downstream tools requiring third-party credentials should execute through trusted server-side brokers rather than passing credentials into agent contexts.
87
+
88
+ ---
89
+
90
+ ## Installation
91
+
92
+ ```bash
93
+ # Direct installation from PyPI
94
+ pip install agent-guard-kit-sdk
95
+
96
+ # Or installation from source
97
+ git clone https://github.com/techmsd/agent-guard-kit.git
98
+ cd agent-guard-kit
99
+ pip install -e .
100
+ ```
101
+
102
+ *(Note: The official distribution package name on PyPI is `agent-guard-kit-sdk`. The Python import namespace remains `agentguardkit`.)*
103
+
104
+ ---
105
+
106
+ ## Quick Start
107
+
108
+ ### 1. In-Memory Mock (for Local Development & Tests)
109
+
110
+ ```python
111
+ from agentguardkit import (
112
+ CredentialBroker,
113
+ SecretPayload,
114
+ AgentRole,
115
+ AuthorizationContext,
116
+ MockVaultStorage,
117
+ )
118
+
119
+ # Initialize standalone broker with mock storage
120
+ storage = MockVaultStorage()
121
+ broker = CredentialBroker(storage=storage)
122
+
123
+ # Operator authorization context supplied by trusted host application
124
+ admin_ctx = AuthorizationContext(
125
+ actor_id="admin_user",
126
+ role=AgentRole.HUMAN_ADMIN,
127
+ permitted_tenants=frozenset({"tenant_acme"}),
128
+ permitted_connectors=frozenset({"stripe_payments"}),
129
+ is_authenticated=True,
130
+ )
131
+
132
+ # Register a credential
133
+ payload = SecretPayload(
134
+ secret_type="api_key",
135
+ secret_value="synthetic_token_12345",
136
+ description="Primary payment gateway connector",
137
+ )
138
+
139
+ result = broker.register_secret(
140
+ tenant_id="tenant_acme",
141
+ connector_id="stripe_payments",
142
+ payload=payload,
143
+ auth_context=admin_ctx,
144
+ )
145
+ print("Registered:", result)
146
+
147
+ # AI agents attempting to decrypt credentials are denied fail-closed
148
+ from agentguardkit.exceptions import UnauthorizedActionError
149
+
150
+ agent_ctx = AuthorizationContext(
151
+ actor_id="specialist_agent",
152
+ role=AgentRole.SPECIALIST,
153
+ permitted_tenants=frozenset({"tenant_acme"}),
154
+ is_authenticated=True,
155
+ )
156
+
157
+ try:
158
+ broker.policy_engine.enforce(
159
+ auth_context=agent_ctx,
160
+ action="vault:decrypt_value",
161
+ tenant_id="tenant_acme",
162
+ connector_id="stripe_payments",
163
+ )
164
+ except UnauthorizedActionError as e:
165
+ print("Blocked agent action:", e)
166
+ ```
167
+
168
+ ### 2. HashiCorp Vault KV v2 Production Storage
169
+
170
+ ```python
171
+ from agentguardkit.storage.kv2 import HashiCorpVaultKV2Storage
172
+
173
+ # Enforces remote HTTPS and TLS certificate verification fail-closed
174
+ storage = HashiCorpVaultKV2Storage(
175
+ base_url="https://vault.internal.corp:8200",
176
+ mount_point="secret",
177
+ token="s.synthetic_vault_token",
178
+ verify_ssl=True,
179
+ timeout=5.0,
180
+ )
181
+ ```
182
+
183
+ ### 3. Strict Audit Sanitization
184
+
185
+ ```python
186
+ from agentguardkit import AuditSanitizer
187
+
188
+ sanitizer = AuditSanitizer()
189
+
190
+ raw_telemetry = {
191
+ "ip": "10.0.0.1",
192
+ "method": "POST",
193
+ "status_code": 200,
194
+ "user_agent": "Mozilla/5.0 Bearer ya29.secretBearerToken123",
195
+ "password": "RawPasswordMustBeScrubbed",
196
+ "admin_note": "Rotated synthetic token for prod",
197
+ }
198
+
199
+ clean = sanitizer.sanitize(raw_telemetry)
200
+ print(clean)
201
+ # Output: {'ip': '10.0.0.1', 'method': 'POST', 'status_code': 200}
202
+ ```
203
+
204
+ ---
205
+
206
+ ## Implemented vs. Future Roadmap
207
+
208
+ | Capability | Status in v0.1.0a3 | Notes |
209
+ | :--- | :--- | :--- |
210
+ | **Tenant Path Derivation** | **Implemented & Tested** | Canonical hierarchical validation (`^[a-zA-Z0-9_-]+$`) |
211
+ | **Tenant Authorization Context** | **Implemented & Tested** | Explicit `AuthorizationContext` scope binding fail-closed |
212
+ | **Pluggable Storage Protocol** | **Implemented & Tested** | `SecretStorageBackend` protocol |
213
+ | **HashiCorp Vault KV v2** | **Implemented & Tested** | Pure Python TLS REST adapter with schema validation |
214
+ | **Mock Vault Storage** | **Implemented & Tested** | Thread-safe in-memory engine with fault injection |
215
+ | **CAS Concurrency** | **Implemented & Tested** | CAS=0 registration and CAS version rotation |
216
+ | **Compensating Rollback** | **Implemented & Tested** | Version rollback with structured recovery records |
217
+ | **Deny-by-Default Policy** | **Implemented & Tested** | In-process capability engine with non-overridable invariants |
218
+ | **Typed Audit Sanitizer** | **Implemented & Tested** | Typed allowlists and regex pattern scrubbing |
219
+ | **Django / FastAPI Adapters** | *Future Roadmap* | Optional framework integrations |
220
+ | **Remote MCP Gateway** | *Future Roadmap* | Brokered tool proxy executing outside LLM context |
@@ -0,0 +1,22 @@
1
+ agentguardkit/__init__.py,sha256=UE23q3GQgwqSxcTym4BqZLilfmz8CC4V4l9xCQT-9nA,2470
2
+ agentguardkit/broker.py,sha256=eayJYcAgNNwU65uk5i-pVqRqsbDwh_mIlDTUKf1Jajo,31433
3
+ agentguardkit/exceptions.py,sha256=3_t51P6OAGcVPaVFYHYfRmcLGCOJgGqjzt8P-rGXbUg,6837
4
+ agentguardkit/interfaces.py,sha256=RByKcTe_b3dgmoKi08JeoDc78L0oj58rSvCk-Bm2J4o,6087
5
+ agentguardkit/path.py,sha256=_29VnHCIkhdokB_HFD76Y7kNtOwuRgTTEVdfoysd5tw,2225
6
+ agentguardkit/policy.py,sha256=itGZIfWGP5ViV5vnkwG4Hu6AfqYTVLde-6di46U5O8Q,14836
7
+ agentguardkit/py.typed,sha256=PJ_YZbt5nkjKh0iaaFQuYexgNZP1cmmmVvpd5mS6vb0,77
8
+ agentguardkit/audit/__init__.py,sha256=x_jBSSFHQ6jLBi1L16emzxq5jbN-TGqLg3Tw2O6KFGE,337
9
+ agentguardkit/audit/sanitizer.py,sha256=pYmX1xGJ_EUF7mkdgq2_CqtSYu9YEg3dg0603mLgJyU,8378
10
+ agentguardkit/metadata/__init__.py,sha256=MGC-NTnxQHoQxVbiWk_YbAQbmQhQJ2FPC_tvocQJZ34,305
11
+ agentguardkit/metadata/base.py,sha256=ppa76snwNLu1_0y0AOhqLVbZio_qldTN-CRsjkhjgak,2502
12
+ agentguardkit/metadata/memory.py,sha256=nI4nKADdUDPKivC0SDmxhtp9vASH9lJRzNCA7HN6tAE,3341
13
+ agentguardkit/storage/__init__.py,sha256=pWbJxww8CFW497x_37wSpB4tSrpHJVGFxRpEQdaVQn0,274
14
+ agentguardkit/storage/base.py,sha256=JSrQLwDVVP9blEroCSC6kkjcdikbBqompTG6lXcmdAo,1608
15
+ agentguardkit/storage/kv2.py,sha256=UjhUhkzcLOu8467hxCEPVq0DHJw3fe-G97hDuZ4lAr4,17648
16
+ agentguardkit/storage/memory.py,sha256=UVnm8Kp8hLUf0lWW7PhNszSqsDA6crafjvSUK8o6d6o,7195
17
+ agentguardkit/testing/__init__.py,sha256=SESTqAM67FdsXRuwjQWY6eHy0TT4_B4xWFdfypVjwE8,99
18
+ agentguardkit/testing/mock_vault.py,sha256=73UBtvaLThGLIwILtn-GfLOBhiNywyP2k8R3b7uM_ho,151
19
+ agent_guard_kit_sdk-0.1.0a3.dist-info/METADATA,sha256=jFKA-KDe4_Q2Ct8hjVOq2mLStbVS2EGYwCDGZ_8H_To,10669
20
+ agent_guard_kit_sdk-0.1.0a3.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
21
+ agent_guard_kit_sdk-0.1.0a3.dist-info/licenses/LICENSE,sha256=lEtlFwMr_puGx3dJG1xIL2ALg6vaIU6V03NfO3gH7Nk,567
22
+ agent_guard_kit_sdk-0.1.0a3.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,13 @@
1
+ Copyright 2026 AgentGuardKit Contributors
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
@@ -0,0 +1,92 @@
1
+ """AgentGuardKit: Tenant-isolated credential brokering, capability policies, and audit sanitization for AI agents."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __version__ = "0.1.0a3"
6
+
7
+ from .audit.sanitizer import AuditSanitizer, scrub_string
8
+ from .broker import CredentialBroker
9
+ from .exceptions import (
10
+ AgentGuardError,
11
+ CasMismatchError,
12
+ InsecureTransportError,
13
+ InvalidPathError,
14
+ InvalidPayloadError,
15
+ RevocationError,
16
+ RollbackError,
17
+ SecurityError,
18
+ StorageAuthenticationError,
19
+ StorageConnectionError,
20
+ StorageError,
21
+ StorageNotFoundError,
22
+ StoragePermissionDeniedError,
23
+ StorageSealedError,
24
+ TenantMismatchError,
25
+ UnauthorizedActionError,
26
+ UnsafeRedirectError,
27
+ ValidationError,
28
+ )
29
+ from .interfaces import (
30
+ BrokerReadiness,
31
+ SecretMetadataResult,
32
+ SecretPayload,
33
+ SecretWriteResult,
34
+ StorageHealthStatus,
35
+ )
36
+ from .metadata.base import (
37
+ AuditEventRecord,
38
+ ConnectionMetadata,
39
+ CredentialMetadataStore,
40
+ RollbackRecoveryRecord,
41
+ )
42
+ from .metadata.memory import InMemoryMetadataStore
43
+ from .path import derive_tenant_secret_path, validate_identifier
44
+ from .policy import AgentRole, AuthorizationContext, CredentialAction, PolicyDecision, PolicyEngine
45
+ from .storage.base import SecretStorageBackend
46
+ from .storage.kv2 import HashiCorpVaultKV2Storage
47
+ from .storage.memory import MockVaultStorage
48
+
49
+ __all__ = [
50
+ "AgentGuardError",
51
+ "AgentRole",
52
+ "AuditEventRecord",
53
+ "AuditSanitizer",
54
+ "AuthorizationContext",
55
+ "BrokerReadiness",
56
+ "CasMismatchError",
57
+ "ConnectionMetadata",
58
+ "CredentialAction",
59
+ "CredentialBroker",
60
+ "CredentialMetadataStore",
61
+ "HashiCorpVaultKV2Storage",
62
+ "InMemoryMetadataStore",
63
+ "InsecureTransportError",
64
+ "InvalidPathError",
65
+ "InvalidPayloadError",
66
+ "MockVaultStorage",
67
+ "PolicyDecision",
68
+ "PolicyEngine",
69
+ "RevocationError",
70
+ "RollbackError",
71
+ "RollbackRecoveryRecord",
72
+ "SecretMetadataResult",
73
+ "SecretPayload",
74
+ "SecretStorageBackend",
75
+ "SecretWriteResult",
76
+ "SecurityError",
77
+ "StorageAuthenticationError",
78
+ "StorageConnectionError",
79
+ "StorageError",
80
+ "StorageHealthStatus",
81
+ "StorageNotFoundError",
82
+ "StoragePermissionDeniedError",
83
+ "StorageSealedError",
84
+ "TenantMismatchError",
85
+ "UnauthorizedActionError",
86
+ "UnsafeRedirectError",
87
+ "ValidationError",
88
+ "__version__",
89
+ "derive_tenant_secret_path",
90
+ "scrub_string",
91
+ "validate_identifier",
92
+ ]
@@ -0,0 +1,17 @@
1
+ """Audit sanitization and scrubbing tools."""
2
+
3
+ from .sanitizer import (
4
+ ALLOWED_HTTP_METHODS,
5
+ DEFAULT_FIELD_VALIDATORS,
6
+ SENSITIVE_KEY_TERMS,
7
+ AuditSanitizer,
8
+ scrub_string,
9
+ )
10
+
11
+ __all__ = [
12
+ "ALLOWED_HTTP_METHODS",
13
+ "DEFAULT_FIELD_VALIDATORS",
14
+ "SENSITIVE_KEY_TERMS",
15
+ "AuditSanitizer",
16
+ "scrub_string",
17
+ ]
@@ -0,0 +1,243 @@
1
+ """Strict typed allowlist metadata sanitizer and secret scrubber.
2
+
3
+ Security Model:
4
+ ---------------
5
+ Audit metadata and tool execution logs are UNTRUSTED data originating from LLM agents,
6
+ external tool responses, and background tasks. They may contain arbitrary key/value pairs,
7
+ accidental tokens, prompt-injected strings, or malformed dumps.
8
+
9
+ We apply a strict TYPED allowlist for metadata:
10
+ - Only explicitly registered fields with declared scalar types survive.
11
+ - Custom validators MUST NOT bypass sensitive-key restrictions or introduce nested structures.
12
+ - Non-scalar objects (dicts, lists, custom classes) are NEVER coerced to strings and are dropped.
13
+ - Semantic validators are enforced:
14
+ - 'ip': parsed strictly with ipaddress.ip_address
15
+ - 'method': validated against safe HTTP verbs
16
+ - 'target_resource', 'target_model', 'resource_type': validated as clean alphanumeric identifiers
17
+ - 'status_code': bounded integer [100, 599]
18
+ - 'duration_ms': non-negative numeric value
19
+ - 'version': positive integer
20
+ - 'created_time', 'rotated_time', 'revoked_at': bounded timestamp strings
21
+ - 'error': bounded clean identifier string
22
+ - All surviving strings are scrubbed for known token signatures (AWS keys, GitHub tokens, JWTs, Bearer headers)
23
+ before length clamping, with input bounded to prevent ReDoS.
24
+ - Total serialized metadata payload is capped at MAX_METADATA_BYTES (4096 bytes).
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import ipaddress
30
+ import json
31
+ import math
32
+ import re
33
+ from collections.abc import Callable
34
+ from typing import Any
35
+
36
+ SENSITIVE_KEY_TERMS = frozenset(
37
+ {
38
+ "secret",
39
+ "key",
40
+ "token",
41
+ "password",
42
+ "cookie",
43
+ "auth",
44
+ "bearer",
45
+ "credential",
46
+ "hash",
47
+ "private",
48
+ "vault",
49
+ "jwt",
50
+ "sign",
51
+ "hmac",
52
+ "api",
53
+ }
54
+ )
55
+
56
+ ALLOWED_HTTP_METHODS = frozenset({"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"})
57
+
58
+ SECRET_VALUE_REGEXES = [
59
+ # Specific high-entropy token signatures
60
+ (re.compile(r"gh[pousr]_[A-Za-z0-9_]{20,255}"), "[REDACTED_TOKEN]"),
61
+ (re.compile(r"AKIA[0-9A-Z]{16}"), "[REDACTED_AWS_KEY]"),
62
+ (re.compile(r"(?i)bearer\s+[a-zA-Z0-9_\-\.]+"), "Bearer [REDACTED]"),
63
+ (
64
+ re.compile(r"eyJ[a-zA-Z0-9_-]{10,}\.[a-zA-Z0-9_-]{10,}\.[a-zA-Z0-9_-]{10,}"),
65
+ "[REDACTED_JWT]",
66
+ ),
67
+ # General key=value / key: value patterns
68
+ (
69
+ re.compile(
70
+ r"(?i)(password|secret|token|api[_-]?key|jwt|access[_-]?token|bearer[_-]?token)\s*(?:is|to|[:=])\s*(?!\[REDACTED)\S+"
71
+ ),
72
+ r"\1=[REDACTED]",
73
+ ),
74
+ ]
75
+
76
+ MAX_INPUT_STRING_LEN = 1000
77
+ MAX_STRING_LEN = 120
78
+ MAX_METADATA_BYTES = 4096
79
+
80
+
81
+ def scrub_string(s: str) -> str:
82
+ """Scrub known secret patterns from string and clamp output length."""
83
+ if not isinstance(s, str):
84
+ return ""
85
+ # Bound input length to protect against regex denial of service
86
+ bounded_input = s[:MAX_INPUT_STRING_LEN]
87
+ scrubbed = bounded_input
88
+ for pattern, replacement in SECRET_VALUE_REGEXES:
89
+ scrubbed = pattern.sub(replacement, scrubbed)
90
+ return scrubbed[:MAX_STRING_LEN]
91
+
92
+
93
+ def _validate_ip(value: Any) -> tuple[bool, str | None]:
94
+ if not isinstance(value, str) or isinstance(value, bool):
95
+ return False, None
96
+ clean = value.strip()
97
+ try:
98
+ ipaddress.ip_address(clean)
99
+ return True, clean
100
+ except ValueError:
101
+ return False, None
102
+
103
+
104
+ def _validate_method(value: Any) -> tuple[bool, str | None]:
105
+ if not isinstance(value, str) or isinstance(value, bool):
106
+ return False, None
107
+ clean = value.strip().upper()
108
+ if clean in ALLOWED_HTTP_METHODS:
109
+ return True, clean
110
+ return False, None
111
+
112
+
113
+ def _validate_target_resource(value: Any) -> tuple[bool, str | None]:
114
+ if not isinstance(value, str) or isinstance(value, bool):
115
+ return False, None
116
+ clean = value.strip()
117
+ if re.match(r"^[A-Za-z][a-zA-Z0-9_\-]{0,63}$", clean):
118
+ if not any(term in clean.lower() for term in SENSITIVE_KEY_TERMS):
119
+ return True, clean
120
+ return False, None
121
+
122
+
123
+ def _validate_status_code(value: Any) -> tuple[bool, int | None]:
124
+ if isinstance(value, bool) or not isinstance(value, int):
125
+ return False, None
126
+ if 100 <= value <= 599:
127
+ return True, value
128
+ return False, None
129
+
130
+
131
+ def _validate_duration_ms(value: Any) -> tuple[bool, float | None]:
132
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
133
+ return False, None
134
+ if not math.isfinite(value):
135
+ return False, None
136
+ if 0 <= value <= 3_600_000:
137
+ return True, round(float(value), 2)
138
+ return False, None
139
+
140
+
141
+ def _validate_version(value: Any) -> tuple[bool, int | None]:
142
+ if isinstance(value, bool) or not isinstance(value, int):
143
+ return False, None
144
+ if 1 <= value <= 1_000_000:
145
+ return True, value
146
+ return False, None
147
+
148
+
149
+ def _validate_timestamp_str(value: Any) -> tuple[bool, str | None]:
150
+ if not isinstance(value, str) or isinstance(value, bool):
151
+ return False, None
152
+ clean = value.strip()
153
+ if len(clean) <= 50 and re.match(r"^[0-9TZ:\-\.\+]+$", clean):
154
+ return True, clean
155
+ return False, None
156
+
157
+
158
+ def _validate_clean_str(value: Any) -> tuple[bool, str | None]:
159
+ if not isinstance(value, str) or isinstance(value, bool):
160
+ return False, None
161
+ clean = value.strip()
162
+ if len(clean) <= 100 and re.match(r"^[a-zA-Z0-9_\-]+$", clean):
163
+ return True, clean
164
+ return False, None
165
+
166
+
167
+ DEFAULT_FIELD_VALIDATORS: dict[str, Callable[[Any], tuple[bool, Any]]] = {
168
+ "ip": _validate_ip,
169
+ "method": _validate_method,
170
+ "target_resource": _validate_target_resource,
171
+ "target_model": _validate_target_resource,
172
+ "resource_type": _validate_clean_str,
173
+ "status_code": _validate_status_code,
174
+ "duration_ms": _validate_duration_ms,
175
+ "version": _validate_version,
176
+ "created_time": _validate_timestamp_str,
177
+ "rotated_time": _validate_timestamp_str,
178
+ "revoked_at": _validate_timestamp_str,
179
+ "error": _validate_clean_str,
180
+ }
181
+
182
+
183
+ class AuditSanitizer:
184
+ """Strict typed-allowlist sanitizer for audit and telemetry metadata."""
185
+
186
+ def __init__(
187
+ self,
188
+ custom_validators: dict[str, Callable[[Any], tuple[bool, Any]]] | None = None,
189
+ max_bytes: int = MAX_METADATA_BYTES,
190
+ ):
191
+ self.validators = dict(DEFAULT_FIELD_VALIDATORS)
192
+ if custom_validators:
193
+ self.validators.update(custom_validators)
194
+ self.max_bytes = max_bytes
195
+
196
+ def sanitize(self, raw_metadata: Any) -> dict[str, Any]:
197
+ """Sanitize an untrusted dictionary of audit metadata."""
198
+ if not isinstance(raw_metadata, dict):
199
+ return {}
200
+
201
+ out: dict[str, Any] = {}
202
+ for k, v in raw_metadata.items():
203
+ if not isinstance(k, str):
204
+ continue
205
+ k_clean = k.lower().strip()
206
+
207
+ # NON-OVERRIDABLE INVARIANT: Drop any key containing sensitive terms unconditionally
208
+ if any(term in k_clean for term in SENSITIVE_KEY_TERMS):
209
+ continue
210
+
211
+ validator = self.validators.get(k_clean)
212
+ if validator is not None:
213
+ try:
214
+ result = validator(v)
215
+ if not isinstance(result, tuple) or len(result) != 2:
216
+ continue
217
+ accepted, cleaned = result
218
+ except Exception:
219
+ # Fail-closed if a validator raises an unexpected error
220
+ continue
221
+
222
+ if accepted:
223
+ # Invariant: Only valid bounded scalar types survive sanitization
224
+ if isinstance(cleaned, bool):
225
+ out[k_clean] = cleaned
226
+ elif isinstance(cleaned, (int, float)):
227
+ if math.isfinite(cleaned):
228
+ out[k_clean] = cleaned
229
+ elif isinstance(cleaned, str):
230
+ out[k_clean] = scrub_string(cleaned)
231
+ else:
232
+ # Non-scalar values (dicts, lists, objects) are dropped fail-closed
233
+ continue
234
+
235
+ try:
236
+ serialized = json.dumps(out)
237
+ except (TypeError, ValueError):
238
+ return {}
239
+
240
+ if len(serialized.encode("utf-8")) > self.max_bytes:
241
+ return {"_error": "metadata_too_large"}
242
+
243
+ return out