From 0e241e4e97be7caff1a22eb9f341d1ddd7eb5453 Mon Sep 17 00:00:00 2001 From: Naseem Alnaji Date: Thu, 26 Nov 2026 19:24:01 +0000 Subject: [PATCH 1/2] feat: mask sensitive keys in events Add sensitive_keys.py, a port of the shared reference, and call it once in the event queue after redaction and sanitization and before truncation. It masks the values of secret keys in parameters, response and error, so request headers such as authorization and cookie leave the server as [redacted]. A field that cannot be masked is dropped and the event is sent without it. --- CHANGELOG.md | 12 + README.md | 2 + src/agentcat/modules/event_queue.py | 27 + src/agentcat/modules/request_extra.py | 3 + src/agentcat/modules/sensitive_keys.py | 131 ++ tests/e2e/official/test_redaction_http.py | 3 +- tests/sensitive_keys_vectors.json | 1624 +++++++++++++++++++++ tests/test_event_queue.py | 10 +- tests/test_request_extra.py | 3 +- tests/test_sensitive_keys.py | 118 ++ 10 files changed, 1926 insertions(+), 7 deletions(-) create mode 100644 src/agentcat/modules/sensitive_keys.py create mode 100644 tests/sensitive_keys_vectors.json create mode 100644 tests/test_sensitive_keys.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c7082c..f1b48bf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,18 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and ## [Unreleased] +### Security + +- The SDK now masks sensitive values in every event before the event leaves your server. It tests + each key in `parameters`, `response` and `error`, at any depth. When the key names a secret, the + SDK keeps the key and replaces the value with `[redacted]`. A key names a secret when it is a + known credential header (`authorization`, `cookie`, `x-api-key` and others) or has a word such + as `token`, `secret`, `password`, `signature` or `api-key`, in any spelling (`X-Api-Key`, + `HTTP_X_API_KEY`, `xApiKey`). Before, the SDK sent the HTTP headers of each MCP request as + received, in `parameters.extra.requestInfo.headers`. Tool arguments and results under such key + names lose their values too, for example `pageToken` and `auth_type`. `null`, `true` and + `false` stay. No option turns the mask off (#62). + ## [2.2.0] - 2026-11-17 ### Added diff --git a/README.md b/README.md index d0b233e..5467bd9 100644 --- a/README.md +++ b/README.md @@ -133,6 +133,8 @@ agentcat.track(server, "proj_0000000", AgentCatOptions(identify=identify)) AgentCat redacts all data sent to its servers and encrypts at rest, but for additional security, it offers a hook to do your own redaction on all text data returned back to our servers. +Before an event leaves your server, the SDK replaces the value of each key that names a secret (such as the `authorization`, `cookie` and `x-api-key` request headers, or any key with `token`, `secret` or `password` in its name) with `[redacted]`. Your hooks run first and still see the raw values. + ```python from agentcat import AgentCatOptions diff --git a/src/agentcat/modules/event_queue.py b/src/agentcat/modules/event_queue.py index 63e8dcd..c83a6b9 100644 --- a/src/agentcat/modules/event_queue.py +++ b/src/agentcat/modules/event_queue.py @@ -17,6 +17,8 @@ from datetime import datetime, timezone from typing import Any, Optional, TYPE_CHECKING +import pydantic_core + if TYPE_CHECKING: from .telemetry import TelemetryManager @@ -36,6 +38,7 @@ from .logging import write_to_log from .redaction import apply_event_redaction, redact_event from .sanitization import sanitize_event +from .sensitive_keys import mask_sensitive_keys from .truncation import truncate_event # Stamped on every event. Same value 1.x reported, resolved once at import @@ -68,6 +71,29 @@ def __init__(self, run: Callable[[], None]) -> None: self.run = run +def _mask_event(event: UnredactedEvent) -> None: + """Mask the values of sensitive keys in the payload fields of `event`. + + Each field is first turned into plain data, as truncation does, so the + mask sees what is sent. The mask builds new values and never changes the + objects it reads. A field that fails is dropped, so the event goes out + without it. + """ + for field in ("parameters", "response", "error"): + value = getattr(event, field) + if value is None: + continue + try: + plain = pydantic_core.to_jsonable_python(value, fallback=str) + setattr(event, field, mask_sensitive_keys(plain)) + except Exception as error: + setattr(event, field, None) + write_to_log( + f"WARNING: Masking failed for {field} of event " + f"{event.id or 'unknown'}, sending it without {field}: {error}" + ) + + def _ensure_event_id(event: UnredactedEvent) -> None: """Assign a ksuid if the event doesn't already have one.""" if not event.id: @@ -280,6 +306,7 @@ def _process_event(self, event: UnredactedEvent) -> None: write_to_log( f"WARNING: Sanitization failed for event {event.id or 'unknown'}, sending unsanitized: {error}" ) + _mask_event(event) try: event = truncate_event(event) except Exception as error: diff --git a/src/agentcat/modules/request_extra.py b/src/agentcat/modules/request_extra.py index 71a2ee8..1492d56 100644 --- a/src/agentcat/modules/request_extra.py +++ b/src/agentcat/modules/request_extra.py @@ -7,6 +7,9 @@ HTTP / SSE / Streamable HTTP transports populate `requestInfo.headers` from the Starlette `Request`. stdio transports omit `requestInfo` entirely (parity with the TS SDK, which only sets `requestInfo` on HTTP-based transports). + +The headers are captured as received; the event queue masks the values of +secret headers such as `authorization` and `cookie` before the event is sent. """ from __future__ import annotations diff --git a/src/agentcat/modules/sensitive_keys.py b/src/agentcat/modules/sensitive_keys.py new file mode 100644 index 0000000..06218a0 --- /dev/null +++ b/src/agentcat/modules/sensitive_keys.py @@ -0,0 +1,131 @@ +"""Masks the values of keys that name a secret, such as `authorization` or `x-api-key`. + +A port of the shared AgentCat reference implementation. Every SDK passes the same cases +in `tests/sensitive_keys_vectors.json`. +""" + +from typing import Any + +MASK = "[redacted]" + +# A key matches a name when its canonical form equals the name or ends with "-" + name. +EXACT = [ + "accesskey", "cb-access-sign", "cf-access-client-id", "dpop", "fastly-key", + "jenkins-crumb", "paypal-transmission-sig", "plaid-verification", + "sec-websocket-protocol", "x-airtable-content-mac", "x-amzn-ava-user-context", + "x-amzn-oidc-data", "x-firebase-appcheck", "x-forge-oauth-system", + "x-forge-oauth-user", "x-honeycomb-team", "x-insert-key", "x-jfrog-art-api", + "x-nf-sign", "x-registry-config", "x-requestdigest", "x-sfdc-session", + "x-trello-webhook", "x-vault-mfa", "x-vercel-protection-bypass", "x-wp-nonce", +] # fmt: skip +# A key matches when its canonical form contains the word. +CONTAINS = [ + "authorization", "secret", "password", "passwd", "passphrase", "cookie", + "signature", "credential", "jwt", "assertion", "bearer", "csrf", "xsrf", "hmac", + "saml", + "api-key", "apikey", "access-key", "private-key", "privatekey", "subscription-key", + "encryption-key", "signing-key", "shared-key", "sharedkey", "master-key", + "account-key", "app-key", "appkey", "application-key", "functions-key", "sas-key", + "license-key", "consumer-key", "client-key", "customer-key", +] # fmt: skip +# A key matches when one hyphen-separated part of its canonical form equals the word. +SEGMENT = ["auth", "token", "otp"] +# A key matches when its canonical form ends with the word. +SUFFIX = ["token"] + +# The pair rule: a map that names a key in one entry and holds its value in another. +PAIR_NAME_KEYS = ["name", "key", "header"] +PAIR_VALUE_KEYS = ["value", "values"] +# The children of a map stored under this exact key are JSON Schema property names. +SCHEMA_PROPERTIES_KEY = "properties" + + +def camel_split(text: str) -> str: + out = [] + for i, ch in enumerate(text): + if i > 0 and "A" <= ch <= "Z": + prev = text[i - 1] + nxt = text[i + 1] if i + 1 < len(text) else "" + if ("a" <= prev <= "z") or ("0" <= prev <= "9"): + out.append("-") + elif ("A" <= prev <= "Z") and ("a" <= nxt <= "z"): + out.append("-") + out.append(ch) + return "".join(out) + + +def canonical_parts(text: str) -> list[str]: + out = [] + for ch in text: + if "A" <= ch <= "Z": + out.append(chr(ord(ch) + 32)) + elif ("a" <= ch <= "z") or ("0" <= ch <= "9"): + out.append(ch) + else: + out.append("-") + parts = [p for p in "".join(out).split("-") if p] + while parts and all("0" <= c <= "9" for c in parts[-1]): + parts.pop() + return parts + + +def parts_match(parts: list[str]) -> bool: + if not parts: + return False + joined = "-".join(parts) + for name in EXACT: + if joined == name or joined.endswith("-" + name): + return True + for word in CONTAINS: + if word in joined: + return True + for part in parts: + if part in SEGMENT: + return True + for word in SUFFIX: + if joined.endswith(word): + return True + return False + + +def is_sensitive_key(key: str) -> bool: + return parts_match(canonical_parts(key)) or parts_match( + canonical_parts(camel_split(key)) + ) + + +def canonical(key: str) -> str: + return "-".join(canonical_parts(key)) + + +def mask_value(value: Any, under_properties: bool) -> Any: + if value is None or isinstance(value, bool): + return value + if isinstance(value, dict) and under_properties: + return mask_sensitive_keys(value, False) + return MASK + + +def mask_sensitive_keys(value: Any, under_properties: bool = False) -> Any: + """A masked copy of `value`. `under_properties` is true when `value` is the map + stored under the key "properties".""" + if isinstance(value, list): + return [mask_sensitive_keys(item, False) for item in value] + if not isinstance(value, dict): + return value + out = {} + for key, child in value.items(): + if isinstance(key, str) and is_sensitive_key(key): + out[key] = mask_value(child, under_properties) + else: + out[key] = mask_sensitive_keys(child, key == SCHEMA_PROPERTIES_KEY) + names_a_sensitive_key = False + for key, child in value.items(): + if isinstance(key, str) and canonical(key) in PAIR_NAME_KEYS: + if isinstance(child, str) and is_sensitive_key(child): + names_a_sensitive_key = True + if names_a_sensitive_key: + for key, child in value.items(): + if isinstance(key, str) and canonical(key) in PAIR_VALUE_KEYS: + out[key] = mask_value(child, False) + return out diff --git a/tests/e2e/official/test_redaction_http.py b/tests/e2e/official/test_redaction_http.py index a538d5d..293802f 100644 --- a/tests/e2e/official/test_redaction_http.py +++ b/tests/e2e/official/test_redaction_http.py @@ -94,7 +94,8 @@ def redact(s: str) -> str: auth = headers.get("authorization") assert auth is not None assert "super-secret-token-xyz" not in auth - assert auth == "Bearer [REDACTED]" + # The hook runs first; the event queue then masks the whole value. + assert auth == "[redacted]" finally: _set_redact(server, None) diff --git a/tests/sensitive_keys_vectors.json b/tests/sensitive_keys_vectors.json new file mode 100644 index 0000000..05fd70f --- /dev/null +++ b/tests/sensitive_keys_vectors.json @@ -0,0 +1,1624 @@ +{ + "mask": "[redacted]", + "keys": [ + { + "key": "Authorization", + "sensitive": true + }, + { + "key": "authorization", + "sensitive": true + }, + { + "key": "AUTHORIZATION", + "sensitive": true + }, + { + "key": " Authorization ", + "sensitive": true + }, + { + "key": "HTTP_AUTHORIZATION", + "sensitive": true + }, + { + "key": "REDIRECT_HTTP_AUTHORIZATION", + "sensitive": true + }, + { + "key": "http.request.header.authorization", + "sensitive": true + }, + { + "key": "headers[authorization][0]", + "sensitive": true + }, + { + "key": "request.headers.authorization", + "sensitive": true + }, + { + "key": "Proxy-Authorization", + "sensitive": true + }, + { + "key": "proxy_authorization", + "sensitive": true + }, + { + "key": "X-Forwarded-Authorization", + "sensitive": true + }, + { + "key": "authorization_servers", + "sensitive": true + }, + { + "key": "Cookie", + "sensitive": true + }, + { + "key": "cookie", + "sensitive": true + }, + { + "key": "Set-Cookie", + "sensitive": true + }, + { + "key": "set-cookie2", + "sensitive": true + }, + { + "key": "cookies", + "sensitive": true + }, + { + "key": "HTTP_COOKIE", + "sensitive": true + }, + { + "key": "X-Api-Key", + "sensitive": true + }, + { + "key": "x-api-key", + "sensitive": true + }, + { + "key": "x_api_key", + "sensitive": true + }, + { + "key": "X-API-KEY", + "sensitive": true + }, + { + "key": "xApiKey", + "sensitive": true + }, + { + "key": "XApiKey", + "sensitive": true + }, + { + "key": "apiKey", + "sensitive": true + }, + { + "key": "api_key", + "sensitive": true + }, + { + "key": "APIKey", + "sensitive": true + }, + { + "key": "apikey", + "sensitive": true + }, + { + "key": "api-key", + "sensitive": true + }, + { + "key": "api_key_id", + "sensitive": true + }, + { + "key": "HTTP_X_API_KEY", + "sensitive": true + }, + { + "key": "OPENAI_API_KEY", + "sensitive": true + }, + { + "key": "x-goog-api-key", + "sensitive": true + }, + { + "key": "xi-api-key", + "sensitive": true + }, + { + "key": "ocp-apim-subscription-key", + "sensitive": true + }, + { + "key": "x-functions-key", + "sensitive": true + }, + { + "key": "dd-api-key", + "sensitive": true + }, + { + "key": "dd-application-key", + "sensitive": true + }, + { + "key": "x-app-key", + "sensitive": true + }, + { + "key": "private_key", + "sensitive": true + }, + { + "key": "privateKey", + "sensitive": true + }, + { + "key": "access_key_id", + "sensitive": true + }, + { + "key": "AWS_SECRET_ACCESS_KEY", + "sensitive": true + }, + { + "key": "aeg-sas-key", + "sensitive": true + }, + { + "key": "cb-access-key", + "sensitive": true + }, + { + "key": "X-Amz-Server-Side-Encryption-Customer-Key", + "sensitive": true + }, + { + "key": "x-goog-encryption-key", + "sensitive": true + }, + { + "key": "license_key", + "sensitive": true + }, + { + "key": "token", + "sensitive": true + }, + { + "key": "Token", + "sensitive": true + }, + { + "key": "TOKEN", + "sensitive": true + }, + { + "key": "access_token", + "sensitive": true + }, + { + "key": "accessToken", + "sensitive": true + }, + { + "key": "AccessToken", + "sensitive": true + }, + { + "key": "accesstoken", + "sensitive": true + }, + { + "key": "refresh_token", + "sensitive": true + }, + { + "key": "id_token", + "sensitive": true + }, + { + "key": "x-auth-token", + "sensitive": true + }, + { + "key": "authToken", + "sensitive": true + }, + { + "key": "X-Amz-Security-Token", + "sensitive": true + }, + { + "key": "x-vault-token", + "sensitive": true + }, + { + "key": "private-token", + "sensitive": true + }, + { + "key": "x-ms-token-aad-access-token", + "sensitive": true + }, + { + "key": "x-amzn-oidc-accesstoken", + "sensitive": true + }, + { + "key": "pageToken", + "sensitive": true + }, + { + "key": "nextPageToken", + "sensitive": true + }, + { + "key": "page_token", + "sensitive": true + }, + { + "key": "progressToken", + "sensitive": true + }, + { + "key": "token_count", + "sensitive": true + }, + { + "key": "token_type", + "sensitive": true + }, + { + "key": "token_endpoint", + "sensitive": true + }, + { + "key": "tokenInfo", + "sensitive": true + }, + { + "key": "token_2", + "sensitive": true + }, + { + "key": "x-csrf-token", + "sensitive": true + }, + { + "key": "X-CSRFToken", + "sensitive": true + }, + { + "key": "x-xsrf-token", + "sensitive": true + }, + { + "key": "csrfmiddlewaretoken", + "sensitive": true + }, + { + "key": "csrf", + "sensitive": true + }, + { + "key": "auth", + "sensitive": true + }, + { + "key": "Auth", + "sensitive": true + }, + { + "key": "auth_type", + "sensitive": true + }, + { + "key": "authType", + "sensitive": true + }, + { + "key": "authInfo", + "sensitive": true + }, + { + "key": "x-sentry-auth", + "sensitive": true + }, + { + "key": "PHP_AUTH_PW", + "sensitive": true + }, + { + "key": "php-auth-user", + "sensitive": true + }, + { + "key": "x-auth-request-email", + "sensitive": true + }, + { + "key": "x-registry-auth", + "sensitive": true + }, + { + "key": "password", + "sensitive": true + }, + { + "key": "Password", + "sensitive": true + }, + { + "key": "db_password", + "sensitive": true + }, + { + "key": "passwd", + "sensitive": true + }, + { + "key": "passphrase", + "sensitive": true + }, + { + "key": "cb-access-passphrase", + "sensitive": true + }, + { + "key": "secret", + "sensitive": true + }, + { + "key": "client_secret", + "sensitive": true + }, + { + "key": "clientSecret", + "sensitive": true + }, + { + "key": "secret_name", + "sensitive": true + }, + { + "key": "cf-access-client-secret", + "sensitive": true + }, + { + "key": "signature", + "sensitive": true + }, + { + "key": "Signature", + "sensitive": true + }, + { + "key": "stripe-signature", + "sensitive": true + }, + { + "key": "X-Hub-Signature", + "sensitive": true + }, + { + "key": "x-hub-signature-256", + "sensitive": true + }, + { + "key": "x-slack-signature", + "sensitive": true + }, + { + "key": "function_signature", + "sensitive": true + }, + { + "key": "signature-input", + "sensitive": true + }, + { + "key": "x-shopify-hmac-sha256", + "sensitive": true + }, + { + "key": "credentials", + "sensitive": true + }, + { + "key": "aws_credentials", + "sensitive": true + }, + { + "key": "jwt", + "sensitive": true + }, + { + "key": "x-goog-iap-jwt-assertion", + "sensitive": true + }, + { + "key": "client_assertion", + "sensitive": true + }, + { + "key": "bearer", + "sensitive": true + }, + { + "key": "SAMLResponse", + "sensitive": true + }, + { + "key": "otp", + "sensitive": true + }, + { + "key": "otp_code", + "sensitive": true + }, + { + "key": "dpop", + "sensitive": true + }, + { + "key": "DPoP", + "sensitive": true + }, + { + "key": "x-honeycomb-team", + "sensitive": true + }, + { + "key": "X-Honeycomb-Team", + "sensitive": true + }, + { + "key": "request.headers.x-honeycomb-team", + "sensitive": true + }, + { + "key": "x-vercel-protection-bypass", + "sensitive": true + }, + { + "key": "x-jfrog-art-api", + "sensitive": true + }, + { + "key": "fastly-key", + "sensitive": true + }, + { + "key": "x-nf-sign", + "sensitive": true + }, + { + "key": "cb-access-sign", + "sensitive": true + }, + { + "key": "x-registry-config", + "sensitive": true + }, + { + "key": "sec-websocket-protocol", + "sensitive": true + }, + { + "key": "cf-access-client-id", + "sensitive": true + }, + { + "key": "x-amzn-oidc-data", + "sensitive": true + }, + { + "key": "x-sfdc-session", + "sensitive": true + }, + { + "key": "x-wp-nonce", + "sensitive": true + }, + { + "key": "jenkins-crumb", + "sensitive": true + }, + { + "key": "accesskey", + "sensitive": true + }, + { + "key": "AccessKey", + "sensitive": true + }, + { + "key": "x-insert-key", + "sensitive": true + }, + { + "key": "paypal-transmission-sig", + "sensitive": true + }, + { + "key": "plaid-verification", + "sensitive": true + }, + { + "key": "x-trello-webhook", + "sensitive": true + }, + { + "key": "x-airtable-content-mac", + "sensitive": true + }, + { + "key": "x-vault-mfa", + "sensitive": true + }, + { + "key": "x-forge-oauth-system", + "sensitive": true + }, + { + "key": "x-requestdigest", + "sensitive": true + }, + { + "key": "x-firebase-appcheck", + "sensitive": true + }, + { + "key": "x-amzn-ava-user-context", + "sensitive": true + }, + { + "key": "user-agent", + "sensitive": false + }, + { + "key": "User-Agent", + "sensitive": false + }, + { + "key": "x-anthropic-client", + "sensitive": false + }, + { + "key": "mcp-session-id", + "sensitive": false + }, + { + "key": "Mcp-Session-Id", + "sensitive": false + }, + { + "key": "mcp-protocol-version", + "sensitive": false + }, + { + "key": "last-event-id", + "sensitive": false + }, + { + "key": "content-type", + "sensitive": false + }, + { + "key": "content-length", + "sensitive": false + }, + { + "key": "accept", + "sensitive": false + }, + { + "key": "host", + "sensitive": false + }, + { + "key": "origin", + "sensitive": false + }, + { + "key": "referer", + "sensitive": false + }, + { + "key": "traceparent", + "sensitive": false + }, + { + "key": "tracestate", + "sensitive": false + }, + { + "key": "etag", + "sensitive": false + }, + { + "key": "if-none-match", + "sensitive": false + }, + { + "key": "cache-control", + "sensitive": false + }, + { + "key": "x-request-id", + "sensitive": false + }, + { + "key": "www-authenticate", + "sensitive": false + }, + { + "key": "proxy-authenticate", + "sensitive": false + }, + { + "key": "authentication-info", + "sensitive": false + }, + { + "key": "x-author", + "sensitive": false + }, + { + "key": "author", + "sensitive": false + }, + { + "key": "authority", + "sensitive": false + }, + { + "key": ":authority", + "sensitive": false + }, + { + "key": "authenticated", + "sensitive": false + }, + { + "key": "oauth", + "sensitive": false + }, + { + "key": "x-oauth-scopes", + "sensitive": false + }, + { + "key": "otpauth", + "sensitive": false + }, + { + "key": "max_tokens", + "sensitive": false + }, + { + "key": "maxTokens", + "sensitive": false + }, + { + "key": "inputTokens", + "sensitive": false + }, + { + "key": "output_tokens", + "sensitive": false + }, + { + "key": "tokens", + "sensitive": false + }, + { + "key": "tokenizer", + "sensitive": false + }, + { + "key": "token2", + "sensitive": false + }, + { + "key": "x-ratelimit-remaining-tokens", + "sensitive": false + }, + { + "key": "key", + "sensitive": false + }, + { + "key": "Key", + "sensitive": false + }, + { + "key": "issue_key", + "sensitive": false + }, + { + "key": "issueKey", + "sensitive": false + }, + { + "key": "sort_key", + "sensitive": false + }, + { + "key": "object_key", + "sensitive": false + }, + { + "key": "partition_key", + "sensitive": false + }, + { + "key": "idempotency-key", + "sensitive": false + }, + { + "key": "sec-websocket-key", + "sensitive": false + }, + { + "key": "x-cache-key", + "sensitive": false + }, + { + "key": "public-key-pins", + "sensitive": false + }, + { + "key": "keyboard", + "sensitive": false + }, + { + "key": "monkey", + "sensitive": false + }, + { + "key": "session_id", + "sensitive": false + }, + { + "key": "sessionId", + "sensitive": false + }, + { + "key": "x-session-id", + "sensitive": false + }, + { + "key": "x-forwarded-for", + "sensitive": false + }, + { + "key": "x-real-ip", + "sensitive": false + }, + { + "key": "cf-connecting-ip", + "sensitive": false + }, + { + "key": "x-forwarded-email", + "sensitive": false + }, + { + "key": "x-forwarded-user", + "sensitive": false + }, + { + "key": "x-amzn-oidc-identity", + "sensitive": false + }, + { + "key": "x-ms-client-principal", + "sensitive": false + }, + { + "key": "remote-user", + "sensitive": false + }, + { + "key": "name", + "sensitive": false + }, + { + "key": "value", + "sensitive": false + }, + { + "key": "values", + "sensitive": false + }, + { + "key": "header", + "sensitive": false + }, + { + "key": "headers", + "sensitive": false + }, + { + "key": "properties", + "sensitive": false + }, + { + "key": "arguments", + "sensitive": false + }, + { + "key": "context", + "sensitive": false + }, + { + "key": "description", + "sensitive": false + }, + { + "key": "cursor", + "sensitive": false + }, + { + "key": "nextCursor", + "sensitive": false + }, + { + "key": "sign", + "sensitive": false + }, + { + "key": "design", + "sensitive": false + }, + { + "key": "assignee", + "sensitive": false + }, + { + "key": "requestId", + "sensitive": false + }, + { + "key": "clientId", + "sensitive": false + }, + { + "key": "scopes", + "sensitive": false + }, + { + "key": "url", + "sensitive": false + }, + { + "key": "", + "sensitive": false + }, + { + "key": " ", + "sensitive": false + }, + { + "key": "-", + "sensitive": false + }, + { + "key": "123", + "sensitive": false + }, + { + "key": "Autorizaci\u00f3n", + "sensitive": false + }, + { + "key": "\u043f\u0430\u0440\u043e\u043b\u044c", + "sensitive": false + } + ], + "trees": [ + { + "name": "headers under requestInfo, the TypeScript v1, Python, PHP, Ruby, Rust and C# shape", + "input": { + "request": { + "method": "tools/call", + "params": { + "name": "search", + "arguments": { + "query": "cats", + "session_id": "ses_1" + } + } + }, + "extra": { + "sessionId": "abc", + "requestId": 7, + "requestInfo": { + "url": "https://example.com/mcp", + "headers": { + "authorization": "Bearer abc.def", + "cookie": "sid=1; theme=dark", + "x-api-key": "k-123", + "user-agent": "claude-code/2.1.0", + "x-anthropic-client": "claude-code", + "mcp-session-id": "0b1c", + "mcp-protocol-version": "2025-06-18", + "content-type": "application/json", + "x-forwarded-for": "203.0.113.9" + } + }, + "authInfo": { + "token": "abc.def", + "clientId": "client-1", + "scopes": [ + "read" + ] + } + } + }, + "expected": { + "request": { + "method": "tools/call", + "params": { + "name": "search", + "arguments": { + "query": "cats", + "session_id": "ses_1" + } + } + }, + "extra": { + "sessionId": "abc", + "requestId": 7, + "requestInfo": { + "url": "https://example.com/mcp", + "headers": { + "authorization": "[redacted]", + "cookie": "[redacted]", + "x-api-key": "[redacted]", + "user-agent": "claude-code/2.1.0", + "x-anthropic-client": "claude-code", + "mcp-session-id": "0b1c", + "mcp-protocol-version": "2025-06-18", + "content-type": "application/json", + "x-forwarded-for": "203.0.113.9" + } + }, + "authInfo": "[redacted]" + } + } + }, + { + "name": "headers under http.req, the TypeScript v2 shape", + "input": { + "extra": { + "http": { + "req": { + "method": "POST", + "url": "https://example.com/mcp", + "headers": { + "authorization": "Bearer abc", + "x-acme-token": "t", + "accept": "application/json" + } + }, + "authInfo": { + "token": "abc" + } + } + } + }, + "expected": { + "extra": { + "http": { + "req": { + "method": "POST", + "url": "https://example.com/mcp", + "headers": { + "authorization": "[redacted]", + "x-acme-token": "[redacted]", + "accept": "application/json" + } + }, + "authInfo": "[redacted]" + } + } + } + }, + { + "name": "headers under header with list values, the Go shape", + "input": { + "extra": { + "header": { + "Authorization": [ + "Bearer abc" + ], + "Cookie": [ + "a=1", + "b=2" + ], + "User-Agent": [ + "mcp-go/1.0" + ], + "X-Api-Key": [ + "k" + ], + "Accept": [ + "application/json" + ] + }, + "tokenInfo": { + "Scopes": [ + "read" + ], + "UserID": "u1" + } + } + }, + "expected": { + "extra": { + "header": { + "Authorization": "[redacted]", + "Cookie": "[redacted]", + "User-Agent": [ + "mcp-go/1.0" + ], + "X-Api-Key": "[redacted]", + "Accept": [ + "application/json" + ] + }, + "tokenInfo": "[redacted]" + } + } + }, + { + "name": "key styles: CGI names, dotted paths, index suffixes, camelCase", + "input": { + "HTTP_AUTHORIZATION": "Basic abc", + "REDIRECT_HTTP_AUTHORIZATION": "Basic abc", + "http.request.header.authorization": "Bearer abc", + "headers[cookie][0]": "a=1", + "xApiKey": "k", + "XApiKey": "k", + "accessToken": "t", + "HTTP_USER_AGENT": "curl/8", + "http.request.header.user_agent": "curl/8" + }, + "expected": { + "HTTP_AUTHORIZATION": "[redacted]", + "REDIRECT_HTTP_AUTHORIZATION": "[redacted]", + "http.request.header.authorization": "[redacted]", + "headers[cookie][0]": "[redacted]", + "xApiKey": "[redacted]", + "XApiKey": "[redacted]", + "accessToken": "[redacted]", + "HTTP_USER_AGENT": "curl/8", + "http.request.header.user_agent": "curl/8" + } + }, + { + "name": "tool arguments and results lose values under sensitive names", + "input": { + "request": { + "params": { + "name": "list_files", + "_meta": { + "progressToken": "p1" + }, + "arguments": { + "pageToken": "CAE=", + "max_tokens": 100, + "query": "report", + "auth_type": "oauth", + "secret_name": "prod/db", + "issue_key": "PROJ-42", + "key": "Enter", + "password": "hunter2" + } + } + } + }, + "expected": { + "request": { + "params": { + "name": "list_files", + "_meta": { + "progressToken": "[redacted]" + }, + "arguments": { + "pageToken": "[redacted]", + "max_tokens": 100, + "query": "report", + "auth_type": "[redacted]", + "secret_name": "[redacted]", + "issue_key": "PROJ-42", + "key": "Enter", + "password": "[redacted]" + } + } + } + } + }, + { + "name": "null and boolean values stay, every other value becomes the mask", + "input": { + "token": null, + "auth": true, + "password": false, + "secret": 0, + "apiKey": "", + "cookie": [ + "a", + "b" + ], + "credentials": { + "user": "bob", + "pass": "x" + }, + "signature": [], + "jwt": 12345 + }, + "expected": { + "token": null, + "auth": true, + "password": false, + "secret": "[redacted]", + "apiKey": "[redacted]", + "cookie": "[redacted]", + "credentials": "[redacted]", + "signature": "[redacted]", + "jwt": "[redacted]" + } + }, + { + "name": "a JSON Schema properties map keeps its property schemas", + "input": { + "tools": [ + { + "name": "login", + "inputSchema": { + "type": "object", + "required": [ + "api_key" + ], + "properties": { + "api_key": { + "type": "string", + "description": "The API key" + }, + "token": { + "type": "string" + }, + "user": { + "type": "string" + }, + "options": { + "type": "object", + "properties": { + "password": { + "type": "string" + }, + "retries": { + "type": "integer" + } + } + } + } + } + } + ] + }, + "expected": { + "tools": [ + { + "name": "login", + "inputSchema": { + "type": "object", + "required": [ + "api_key" + ], + "properties": { + "api_key": { + "type": "string", + "description": "The API key" + }, + "token": { + "type": "string" + }, + "user": { + "type": "string" + }, + "options": { + "type": "object", + "properties": { + "password": { + "type": "string" + }, + "retries": { + "type": "integer" + } + } + } + } + } + } + ] + } + }, + { + "name": "a scalar under properties is still a value", + "input": { + "event": "pageview", + "properties": { + "token": "phc_abc", + "auth": true, + "path": "/home", + "cookie": null + } + }, + "expected": { + "event": "pageview", + "properties": { + "token": "[redacted]", + "auth": true, + "path": "/home", + "cookie": null + } + } + }, + { + "name": "a map under a sensitive key outside properties becomes the mask", + "input": { + "authorization": { + "scheme": "Bearer", + "parameter": "abc" + }, + "cookies": { + "sid": "1" + }, + "settings": { + "auth": { + "user": "bob" + }, + "theme": "dark" + } + }, + "expected": { + "authorization": "[redacted]", + "cookies": "[redacted]", + "settings": { + "auth": "[redacted]", + "theme": "dark" + } + } + }, + { + "name": "the pair rule masks the value entry of a named sensitive key", + "input": { + "headers": [ + { + "name": "Authorization", + "value": "Bearer abc" + }, + { + "name": "Accept", + "value": "application/json" + }, + { + "Name": "X-Api-Key", + "Value": "k" + }, + { + "header": "cookie", + "values": [ + "a=1", + "b=2" + ] + } + ], + "env": [ + { + "key": "OPENAI_API_KEY", + "value": "sk-1" + }, + { + "key": "PORT", + "value": "8080" + } + ], + "edge": [ + { + "name": "token", + "value": null + }, + { + "name": "password", + "value": { + "a": 1 + } + }, + { + "name": "secret", + "value": true + }, + { + "name": 5, + "value": "x" + }, + { + "name": "auth" + }, + { + "value": "alone" + }, + { + "name": "theme", + "key": "api_key", + "value": "v" + } + ] + }, + "expected": { + "headers": [ + { + "name": "Authorization", + "value": "[redacted]" + }, + { + "name": "Accept", + "value": "application/json" + }, + { + "Name": "X-Api-Key", + "Value": "[redacted]" + }, + { + "header": "cookie", + "values": "[redacted]" + } + ], + "env": [ + { + "key": "OPENAI_API_KEY", + "value": "[redacted]" + }, + { + "key": "PORT", + "value": "8080" + } + ], + "edge": [ + { + "name": "token", + "value": null + }, + { + "name": "password", + "value": "[redacted]" + }, + { + "name": "secret", + "value": true + }, + { + "name": 5, + "value": "x" + }, + { + "name": "auth" + }, + { + "value": "alone" + }, + { + "name": "theme", + "key": "api_key", + "value": "[redacted]" + } + ] + } + }, + { + "name": "lists, nesting and scalars keep their shape", + "input": { + "a": [ + 1, + "two", + null, + true, + [ + 3, + { + "token": "t", + "n": 4 + } + ], + { + "b": { + "c": { + "d": { + "e": { + "secret": "s", + "f": [ + { + "password": "p" + } + ] + } + } + } + } + } + ], + "empty_map": {}, + "empty_list": [], + "text": "Authorization: Bearer abc", + "number": 42 + }, + "expected": { + "a": [ + 1, + "two", + null, + true, + [ + 3, + { + "token": "[redacted]", + "n": 4 + } + ], + { + "b": { + "c": { + "d": { + "e": { + "secret": "[redacted]", + "f": [ + { + "password": "[redacted]" + } + ] + } + } + } + } + } + ], + "empty_map": {}, + "empty_list": [], + "text": "Authorization: Bearer abc", + "number": 42 + } + }, + { + "name": "a tool response", + "input": { + "content": [ + { + "type": "text", + "text": "token=abc is inside text and stays" + } + ], + "structuredContent": { + "access_token": "at", + "token_type": "Bearer", + "expires_in": 3600, + "items": [ + { + "id": 1, + "api_key": "k" + } + ] + }, + "isError": false + }, + "expected": { + "content": [ + { + "type": "text", + "text": "token=abc is inside text and stays" + } + ], + "structuredContent": { + "access_token": "[redacted]", + "token_type": "[redacted]", + "expires_in": 3600, + "items": [ + { + "id": 1, + "api_key": "[redacted]" + } + ] + }, + "isError": false + } + }, + { + "name": "an error with the headers of a failed HTTP call", + "input": { + "message": "Request failed with status code 401", + "type": "AxiosError", + "config": { + "url": "https://api.example.com", + "headers": { + "Authorization": "Bearer abc", + "Accept": "application/json" + } + } + }, + "expected": { + "message": "Request failed with status code 401", + "type": "AxiosError", + "config": { + "url": "https://api.example.com", + "headers": { + "Authorization": "[redacted]", + "Accept": "application/json" + } + } + } + }, + { + "name": "keys with other alphabets are not matched", + "input": { + "Autorizaci\u00f3n": "x", + "\u043f\u0430\u0440\u043e\u043b\u044c": "x", + "x-\u043a\u043b\u044e\u0447": 1, + "\u043f\u0430\u0440\u043e\u043b\u044c-token": "t" + }, + "expected": { + "Autorizaci\u00f3n": "x", + "\u043f\u0430\u0440\u043e\u043b\u044c": "x", + "x-\u043a\u043b\u044e\u0447": 1, + "\u043f\u0430\u0440\u043e\u043b\u044c-token": "[redacted]" + } + }, + { + "name": "a list at the root", + "input": [ + { + "token": "t" + }, + "plain", + 3 + ], + "expected": [ + { + "token": "[redacted]" + }, + "plain", + 3 + ] + }, + { + "name": "a string at the root", + "input": "token", + "expected": "token" + }, + { + "name": "null at the root", + "input": null, + "expected": null + } + ] +} diff --git a/tests/test_event_queue.py b/tests/test_event_queue.py index 67ec7e9..11b40f6 100644 --- a/tests/test_event_queue.py +++ b/tests/test_event_queue.py @@ -186,7 +186,7 @@ def test_process_event_with_redaction(self, mock_redact): project_id="project-123", session_id="session-123", timestamp=datetime.now(timezone.utc), - parameters={"secret": "[REDACTED]"}, + parameters={"query": "[REDACTED]"}, user_intent="redacted intent", redaction_fn=None, # This should be cleared after redaction ) @@ -200,7 +200,7 @@ def test_process_event_with_redaction(self, mock_redact): project_id="project-123", session_id="session-123", timestamp=datetime.now(timezone.utc), - parameters={"secret": "password123"}, + parameters={"query": "password123"}, user_intent="original intent", redaction_fn=mock_redaction_fn, ) @@ -211,7 +211,7 @@ def test_process_event_with_redaction(self, mock_redact): mock_redact.assert_called_once_with(event, mock_redaction_fn) # The send_event should be called with the redacted event called_event = mock_send.call_args[0][0] - assert called_event.parameters == {"secret": "[REDACTED]"} + assert called_event.parameters == {"query": "[REDACTED]"} assert called_event.user_intent == "redacted intent" assert called_event.redaction_fn is None mock_send.assert_called_once() @@ -232,7 +232,7 @@ def test_process_event_redacts_for_real(self): project_id="project-123", session_id="session-123", timestamp=datetime.now(timezone.utc), - parameters={"arguments": {"token": "hunter2"}}, + parameters={"arguments": {"query": "hunter2"}}, user_intent="spend hunter2", redaction_fn=lambda s: s.replace("hunter2", "[REDACTED]"), ) @@ -241,7 +241,7 @@ def test_process_event_redacts_for_real(self): eq._process_event(event) sent = mock_send.call_args[0][0] - assert sent.parameters == {"arguments": {"token": "[REDACTED]"}} + assert sent.parameters == {"arguments": {"query": "[REDACTED]"}} assert sent.user_intent == "spend [REDACTED]" assert sent.redaction_fn is None # Protected: the handle still identifies the task on the dashboard. diff --git a/tests/test_request_extra.py b/tests/test_request_extra.py index 283b72a..83151c9 100644 --- a/tests/test_request_extra.py +++ b/tests/test_request_extra.py @@ -352,7 +352,8 @@ def capture_event(publish_event_request, **kwargs): assert headers.get("mcp-session-id") == "sess-abc" assert extra.get("requestId") == "req-tools-call" assert extra.get("sessionId") == "sess-abc" - assert extra.get("meta") == {"progressToken": "tok-7"} + # The event queue masks values under secret key names such as `progressToken`. + assert extra.get("meta") == {"progressToken": "[redacted]"} @pytest.mark.asyncio async def test_transport_session_id_never_becomes_the_task_handle( diff --git a/tests/test_sensitive_keys.py b/tests/test_sensitive_keys.py new file mode 100644 index 0000000..68f3d26 --- /dev/null +++ b/tests/test_sensitive_keys.py @@ -0,0 +1,118 @@ +"""Tests for the sensitive key mask. + +`sensitive_keys_vectors.json` is shared by every AgentCat SDK; do not edit it here. +""" + +import copy +import json +from datetime import datetime, timezone +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +import pytest +from pydantic import BaseModel +from starlette.requests import Request + +from agentcat.modules import event_queue as event_queue_module +from agentcat.modules.event_queue import EventQueue +from agentcat.modules.request_extra import params_with_extra +from agentcat.modules.sensitive_keys import is_sensitive_key, mask_sensitive_keys +from agentcat.types import UnredactedEvent + +VECTORS = json.loads( + (Path(__file__).parent / "sensitive_keys_vectors.json").read_text() +) + + +@pytest.mark.parametrize("case", VECTORS["keys"], ids=lambda case: case["key"]) +def test_key_vectors(case): + assert is_sensitive_key(case["key"]) is case["sensitive"] + + +@pytest.mark.parametrize("case", VECTORS["trees"], ids=lambda case: case["name"]) +def test_tree_vectors(case): + before = copy.deepcopy(case["input"]) + assert mask_sensitive_keys(case["input"]) == case["expected"] + assert case["input"] == before + + +class Account(BaseModel): + user: str + api_key: str + + +def _sent_event(event): + sender = MagicMock() + telemetry = MagicMock() + with patch.object(event_queue_module, "_telemetry_manager", telemetry): + EventQueue(api_client=sender)._process_event(event) + exported = telemetry.export.call_args[0][0] + sent = sender.publish_event.call_args.kwargs["publish_event_request"] + assert exported is sent + return sent + + +def test_pipeline_masks_request_headers_and_typed_values(): + request = Request( + { + "type": "http", + "headers": [ + (b"authorization", b"Bearer abc.def"), + (b"cookie", b"sid=1"), + (b"x-api-key", b"k-123"), + (b"user-agent", b"claude-code/2.1.0"), + (b"x-anthropic-client", b"claude-code"), + (b"mcp-session-id", b"0b1c"), + ], + } + ) + event = UnredactedEvent( + event_type="mcp:tools/call", + project_id="project-123", + timestamp=datetime.now(timezone.utc), + parameters=params_with_extra( + {"name": "login", "arguments": {"query": "cats"}}, + SimpleNamespace(request=request, request_id=7, meta=None, session=None), + ), + response={"structuredContent": Account(user="ann", api_key="k-456")}, + ) + + sent = _sent_event(event) + + headers = sent.parameters["extra"]["requestInfo"]["headers"] + assert headers == { + "authorization": "[redacted]", + "cookie": "[redacted]", + "x-api-key": "[redacted]", + "user-agent": "claude-code/2.1.0", + "x-anthropic-client": "claude-code", + "mcp-session-id": "0b1c", + } + assert sent.parameters["arguments"] == {"query": "cats"} + assert sent.response == { + "structuredContent": {"user": "ann", "api_key": "[redacted]"} + } + # The objects the customer's handler holds keep their values. + assert request.headers["authorization"] == "Bearer abc.def" + assert request.headers["x-api-key"] == "k-123" + assert event.parameters["extra"]["requestInfo"]["headers"]["cookie"] == "sid=1" + assert event.response["structuredContent"].api_key == "k-456" + + +def test_pipeline_drops_a_field_that_cannot_be_masked(): + looped: dict = {"authorization": "Bearer abc"} + looped["self"] = looped + event = UnredactedEvent( + event_type="mcp:tools/call", + project_id="project-123", + parameters={"loop": looped}, + response={"token": "t-1", "text": "ok"}, + ) + + with patch.object(event_queue_module, "write_to_log") as log: + sent = _sent_event(event) + + assert sent.parameters is None + assert sent.response == {"token": "[redacted]", "text": "ok"} + assert any("Masking failed for parameters" in c.args[0] for c in log.call_args_list) From a467fb283293d46ecda269aee1b15b24aeb7251a Mon Sep 17 00:00:00 2001 From: Naseem Alnaji Date: Thu, 26 Nov 2026 19:33:53 +0000 Subject: [PATCH 2/2] test: make the server info page test pass on Python 3.10 and 3.11 The test asserted the exact order of loop turns, which holds only on Python 3.12 and later. Before 3.12, asyncio.wait_for runs the awaited coroutine in a task of its own, and that costs one more turn of the loop per page. The test now asserts the property itself: other work runs right before each page. CI runs Python 3.12 only, so it never showed the failure. --- tests/test_server_info.py | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/tests/test_server_info.py b/tests/test_server_info.py index 110c771..2e97bb7 100644 --- a/tests/test_server_info.py +++ b/tests/test_server_info.py @@ -1241,9 +1241,10 @@ async def enter(key: str = key, enter: Any = gate.enter) -> None: async def test_v10_the_build_gives_the_loop_a_turn_before_each_page() -> None: turns: list[str] = [] + pages_done = False async def other_work() -> None: - for _ in range(3): + while not pages_done: turns.append("other") await asyncio.sleep(0) @@ -1255,9 +1256,18 @@ async def fetch(cursor: Any) -> Any: task = asyncio.ensure_future(other_work()) await server_info._collect(fetch) + pages_done = True await task - assert turns == ["other", "page", "other", "page", "other", "page"] + # The other work runs right before each page. The count of its turns between + # two pages is not fixed: before Python 3.12, `asyncio.wait_for` runs the fetch + # in a task of its own, and that costs one more turn of the loop. + assert turns.count("page") == 3 + assert all( + index > 0 and turns[index - 1] == "other" + for index, turn in enumerate(turns) + if turn == "page" + ) def test_v10_a_start_that_never_fires_holds_nothing() -> None: