From 9c5511936adddbed36733394ac7e5221318b371e Mon Sep 17 00:00:00 2001 From: Fengzdadi <453788063@qq.com> Date: Mon, 23 Nov 2026 16:24:28 -0500 Subject: [PATCH 1/2] fix(bub): keep recognized credentials out of automatic recall and capture Bub was the last in-process adapter with automatic recall and capture that did not apply the shared prompt-privacy rule. The plugin now ships a generated copy of src/powercontext_integration_lifecycle/prompt_privacy.py and, like Pydantic AI after #2703: - scrubs recognized credentials from the recall query before bounding it, so recall still runs with [REDACTED] in place of each value; - skips the user_prompt event when the initial task contains a recognized credential, and records the skip in the capture log with the reason sensitive_content and without the text; - leaves llm_result and tool_result events to their existing key-based and known-credential redaction. The configured API token counts as a known credential. A new harness test drives a Bub turn for every case in automatic_prompt_privacy.json. --- docs/en/docs/integrations/evaluation.md | 7 + docs/zh/docs/integrations/evaluation.md | 7 + e2e/bub/tests/test_bub_prompt_privacy.py | 157 ++++++++++++++++++ integrations/bub/README.md | 9 + .../src/powercontext_bub/_prompt_privacy.py | 73 ++++++++ .../bub/src/powercontext_bub/plugin.py | 24 ++- integrations/capabilities.toml | 2 +- pyproject.toml | 1 + scripts/generate_integration_lifecycle.py | 6 +- 9 files changed, 276 insertions(+), 10 deletions(-) create mode 100644 e2e/bub/tests/test_bub_prompt_privacy.py create mode 100644 integrations/bub/src/powercontext_bub/_prompt_privacy.py diff --git a/docs/en/docs/integrations/evaluation.md b/docs/en/docs/integrations/evaluation.md index 739d82f3e0..40346010e1 100644 --- a/docs/en/docs/integrations/evaluation.md +++ b/docs/en/docs/integrations/evaluation.md @@ -13,6 +13,13 @@ The Bub plugin connects to the Server through the Python Client and provides Mem preparation, including context before model calls. Event capture is disabled by default. When enabled, completed events become Sources and can be flushed periodically. No Handoff capability is declared. +Automatic recall and capture follow the [automatic prompt privacy](index.md#automatic-prompt-privacy) rule. The +recall query is the user's text with recognized credentials replaced by `[REDACTED]`; the replacement happens before +the query is trimmed and, when longer than 8,192 characters or 8,192 UTF-8 bytes, cut to its most recent text. With +event capture on, an initial task that contains a recognized credential is not captured as a `user_prompt` event; the +optional capture log records the skip with the reason `sensitive_content` and without the text. LLM and tool events +keep their key-based and known-credential redaction. + Loopback HTTP is allowed by default. Non-loopback HTTP requires `POWERCONTEXT_BUB_ALLOW_INSECURE_HTTP=true` or `PowerContextSettings(allow_insecure_http=True)`, covering both plugin hooks and tools. HTTPS certificate validation stays enabled. See [Connect to a remote Server](../operate/connect-remote-server.md) for shared client settings; diff --git a/docs/zh/docs/integrations/evaluation.md b/docs/zh/docs/integrations/evaluation.md index 54be13b543..ae565fc8e3 100644 --- a/docs/zh/docs/integrations/evaluation.md +++ b/docs/zh/docs/integrations/evaluation.md @@ -13,6 +13,13 @@ Bub 插件通过 Python Client 连接 Server,提供 Memory 搜索、写入和 模型调用前可准备上下文。事件采集默认关闭,启用后可将已完成的事件作为 Sources,并定期 flush。 它没有 Handoff 能力声明。 +自动召回和采集遵循[自动 prompt 隐私策略](index.md#自动-prompt-隐私策略)。 +召回查询是用户文本:先将识别出的凭据替换为 `[REDACTED]`, +再去除首尾空白;超过 8192 个字符或 8192 个 UTF-8 字节时,截取最近的文本。 +启用事件采集时,含有识别出的凭据的初始任务不会作为 `user_prompt` 事件采集; +可选的采集日志记录这次跳过,原因为 `sensitive_content`,不含文本。 +LLM 和工具事件仍按敏感键和已知凭据清洗。 + 环回 HTTP 默认可用;非环回 HTTP 需要设置 `POWERCONTEXT_BUB_ALLOW_INSECURE_HTTP=true`,或传入 `PowerContextSettings(allow_insecure_http=True)`,对插件 Hook 和工具调用都生效。HTTPS 证书校验仍然启用。 共享客户端配置见[连接远程 Server](../operate/connect-remote-server.md);Bub 没有 PowerContext setup 安装命令。 diff --git a/e2e/bub/tests/test_bub_prompt_privacy.py b/e2e/bub/tests/test_bub_prompt_privacy.py new file mode 100644 index 0000000000..a05a26b20b --- /dev/null +++ b/e2e/bub/tests/test_bub_prompt_privacy.py @@ -0,0 +1,157 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Bub's automatic recall and capture keep recognized credentials out, like the other automatic adapters.""" + +from __future__ import annotations + +import asyncio +import json +from pathlib import Path +from types import SimpleNamespace +from typing import Any, ClassVar + +import httpx2 +import pytest +from bub.channels.message import ChannelMessage +from bub.framework import BubFramework +from powercontext_bub import plugin as plugin_module +from powercontext_bub.plugin import PowerContextPlugin, PowerContextSettings +from pydantic import SecretStr + +_ROOT = Path(__file__).resolve().parents[3] +CASES = json.loads((_ROOT / "tests/fixtures/automatic_prompt_privacy.json").read_text(encoding="utf-8"))["cases"] +# Every synthetic credential value in the fixture contains one of these markers. +VALUE_MARKERS = ("synthetic-value-2084", "synthetic_value_2084", "SyntheticValue2084") +ANSWER = "Noted." + + +class RecordingClient: + prepared: ClassVar[list[Any]] = [] + captured: ClassVar[list[Any]] = [] + + def __init__(self, base_url: str, **options: object) -> None: + del base_url, options + + async def __aenter__(self) -> RecordingClient: + return self + + async def __aexit__(self, *exc_info: object) -> None: + del exc_info + + async def resolve_scope_binding(self, request: Any) -> SimpleNamespace: + del request + return SimpleNamespace(scope_id="scp_00000000000000000000000000") + + async def prepare_context(self, request: Any) -> SimpleNamespace: + self.prepared.append(request) + return SimpleNamespace(content="remembered context", content_bytes=18, status=SimpleNamespace(value="ready")) + + async def capture_content_source(self, request: Any) -> SimpleNamespace: + self.captured.append(request) + return SimpleNamespace(position=len(self.captured)) + + async def flush_memory(self, request: Any) -> SimpleNamespace: + del request + position = len(self.captured) + return SimpleNamespace( + status=SimpleNamespace(value="completed"), + previous_cursor=0, + current_cursor=position, + high_watermark=position, + processed_source_count=position, + remaining_work=False, + ) + + +def _token(case: dict[str, Any]) -> SecretStr | None: + authorization = case.get("authorization") + return None if authorization is None else SecretStr(str(authorization).removeprefix("Bearer ")) + + +def _run_turn(monkeypatch, tmp_path: Path, prompt: str, *, token: SecretStr | None) -> list[dict[str, Any]]: + """Run one message through Bub's own turn with a stub model and return the capture log's records.""" + RecordingClient.prepared.clear() + RecordingClient.captured.clear() + capture_log = tmp_path / "capture.jsonl" + settings = PowerContextSettings( + base_url="http://127.0.0.1:8000", + api_token=token, + capture_events=True, + capture_checkpoint_every=100, + capture_log=capture_log, + ) + monkeypatch.setattr(plugin_module, "ensure_config", lambda _: settings) + monkeypatch.setattr(plugin_module, "PowerContextClient", RecordingClient) + + def model_reply(request: httpx2.Request) -> httpx2.Response: + del request + events = [{"choices": [{"delta": {"content": ANSWER}, "finish_reason": "stop"}]}, "[DONE]"] + body = "".join(f"data: {event if isinstance(event, str) else json.dumps(event)}\n\n" for event in events) + return httpx2.Response(200, headers={"content-type": "text/event-stream"}, text=body) + + client = httpx2.AsyncClient + monkeypatch.setattr( + httpx2, "AsyncClient", lambda **options: client(**{"transport": httpx2.MockTransport(model_reply), **options}) + ) + for name, value in { + "BUB_HOME": str(tmp_path / "home"), + "BUB_MODEL": "openai:test-model", + "BUB_API_KEY": "stub-model-credential", + "BUB_CLIENT_ARGS": '{"api_format": "chat"}', + # Keep the known-credential redaction of captured events to this test's own environment. + "CODEX_HOME": str(tmp_path / "codex"), + }.items(): + monkeypatch.setenv(name, value) + monkeypatch.chdir(tmp_path) + framework = BubFramework(config_file=tmp_path / "bub.yml") + framework.load_builtin_hooks() + framework.plugin_manager.register(PowerContextPlugin(framework), name="powercontext") + message = ChannelMessage( + session_id="cli:local", channel="cli", chat_id="local", content=prompt, context={"sender_id": "human"} + ) + + async def turn() -> None: + async with framework.running(): + await framework.process_inbound(message) + + asyncio.run(turn()) + return [json.loads(line) for line in capture_log.read_text(encoding="utf-8").splitlines()] + + +@pytest.mark.parametrize("case", CASES, ids=[case["id"] for case in CASES]) +def test_turn_keeps_recognized_credentials_out_of_recall_and_capture( + monkeypatch, tmp_path: Path, case: dict[str, Any] +) -> None: + prompt = str(case["prompt"]) + + records = _run_turn(monkeypatch, tmp_path, prompt, token=_token(case)) + + # Recall runs either way. + assert len(RecordingClient.prepared) == 1 + events = [captured.metadata["event"] for captured in RecordingClient.captured] + sent = json.dumps([RecordingClient.prepared[0].query, *(captured.content for captured in RecordingClient.captured)]) + log = json.dumps(records) + if case["sensitive"]: + for marker in VALUE_MARKERS: + assert marker not in sent + assert marker not in log + # The initial task is not stored as a redacted copy; the model's reply is still captured. + assert events == ["llm_result"] + skip = {"event": "user_prompt", "status": "skipped", "reason": "sensitive_content"} + assert skip.items() <= records[0].items() + else: + assert RecordingClient.prepared[0].query == prompt.strip() + assert events == ["user_prompt", "llm_result"] + assert json.dumps(prompt)[1:-1] in RecordingClient.captured[0].content diff --git a/integrations/bub/README.md b/integrations/bub/README.md index a307bc939c..5c8462c946 100644 --- a/integrations/bub/README.md +++ b/integrations/bub/README.md @@ -55,6 +55,15 @@ to resolve the configured explicit Scope first, then an opaque stable binding ke and finally the Server default. Only the real Scope returned by the Server is cached and used for recall, capture, and tools. +The recall query is the user's text, trimmed, with recognized credentials, such as `api_key=…` assignments, Bearer +values, and common provider tokens, replaced by `[REDACTED]`. When a prompt longer than 8,192 characters or 8,192 +UTF-8 bytes is cut to its most recent text, the replacement happens first, so the cut cannot leave a bare credential. +With capture enabled, an initial task that contains a recognized credential is not captured; the capture log records +a `user_prompt` event with status `skipped` and reason `sensitive_content`, without the text. Bub applies the same +recognition as the other automatic PowerContext integrations, described in the +[automatic prompt privacy](../../docs/en/docs/integrations/index.md#automatic-prompt-privacy) guide. Recognition is +best effort. + Captured tool arguments redact values under credential-like keys. Known credential environment values are also removed from serialized event content. Keep the PowerContext scope and optional capture log protected because normal tool output can still contain sensitive project data. diff --git a/integrations/bub/src/powercontext_bub/_prompt_privacy.py b/integrations/bub/src/powercontext_bub/_prompt_privacy.py new file mode 100644 index 0000000000..eb495802ce --- /dev/null +++ b/integrations/bub/src/powercontext_bub/_prompt_privacy.py @@ -0,0 +1,73 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated from src/powercontext_integration_lifecycle/prompt_privacy.py; do not edit. +# Edit the source and run `make integration-lifecycle` instead. + +"""Best-effort credential recognition for automatic host inputs.""" + +from __future__ import annotations + +import re + +# Horizontal space, spelled out so that Python's ASCII \s and JavaScript's Unicode \s agree: NBSP and the full-width +# space that Chinese input methods produce separate a value just as a space does. +_SPACES = r" \t\f\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff" +# A value starts on the separator's line or on an indented continuation line, as in YAML, so an empty .env value +# cannot reach into the next line. +_GAP = rf"[{_SPACES}]*(?:\r?\n[{_SPACES}]+)?" +# A boolean or null literal or an unexpanded ${NAME} or ${{ expression }} placeholder is a setting, not a credential. +# A placeholder with a literal default, such as ${NAME:-value}, is not excluded. +_PLACEHOLDER = r"(?:\$\{\{[^{}\r\n]*\}\}|\$\{[A-Za-z_][A-Za-z0-9_]*\})" +_SETTING = rf"""(?:true|false|yes|no|on|off|null|none|{_PLACEHOLDER}|"{_PLACEHOLDER}"|'{_PLACEHOLDER}')""" +_NOT_A_SETTING = rf"""(?!{_GAP}{_SETTING}(?:[\s,;)\]}}`'"{_SPACES}]|\.(?![^\s{_SPACES}])|$))""" +# A header value is a setting only when nothing more of the header follows it: the line ends, optionally after closing +# punctuation, and the next line is not an indented continuation. Anything else, as in Cookie: on; sid=…, +# Cookie: ${THEME} sid=…, or a setting followed by an indented line, keeps the whole header. +_NOT_A_HEADER_SETTING = rf"""(?![ \t]*{_SETTING}[`")'\]}}]*[,.;]?[{_SPACES}]*(?:$|\r?\n(?![ \t])))""" +# Applied in order, like the TypeScript source, so an earlier rule consumes the whole of what a later one would cut. +_PATTERNS = tuple( + re.compile(pattern, re.IGNORECASE | re.ASCII) + for pattern in ( + r"-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY-----|$)", + # Headers can contain schemes, multiple cookies, and folded continuation lines. A hyphenated prefix such as + # Proxy-, Set-, or X-Forwarded-, or the CGI form HTTP_, names another header of the same kind. + r"""(? str: + """Replace recognized values in a read-only query; never use this to rewrite a captured event.""" + + if authorization: + _, _, credential = authorization.partition(" ") + if credential: + text = text.replace(credential, "[REDACTED]") + # The private-key rule runs first, so a header or assignment cannot consume just a PEM block's BEGIN marker. + for pattern in _PATTERNS: + text = pattern.sub("[REDACTED]", text) + return text diff --git a/integrations/bub/src/powercontext_bub/plugin.py b/integrations/bub/src/powercontext_bub/plugin.py index 0aebc6ade1..4dc02bffd3 100644 --- a/integrations/bub/src/powercontext_bub/plugin.py +++ b/integrations/bub/src/powercontext_bub/plugin.py @@ -49,6 +49,7 @@ # Older core releases support legacy recall but cannot accept assembly settings. from types import NoneType as ContextAssembly +from ._prompt_privacy import scrub_secrets from .scope import resolve_scope_id, workspace_binding_key STATE_KEY = "_powercontext" @@ -232,12 +233,16 @@ async def before_llm_call(self, request: LLMCallRequest, state: TurnState) -> LL capture_state = state[STATE_KEY] if self.settings.capture_events and not capture_state["prompt_captured"]: capture_state["prompt_captured"] = True - await self._capture_event( - event="user_prompt", - run_id=request.run_id, - payload={"text": prompt}, - state=state, - ) + if scrub_secrets(prompt, self._authorization()) != prompt: + # A recognized credential skips the event rather than storing a redacted copy of the prompt. + self._write_capture_record(event="user_prompt", status="skipped", reason="sensitive_content") + else: + await self._capture_event( + event="user_prompt", + run_id=request.run_id, + payload={"text": prompt}, + state=state, + ) if any(_contains_context_marker(message) for message in request.messages): return None @@ -295,6 +300,10 @@ async def save_state(self, session_id: str, state: TurnState, message: Any, mode async with self._capture_lock: await self._flush_captured_sources(state, final=True) + def _authorization(self) -> str | None: + token = self.settings.api_token + return None if token is None else f"Bearer {token.get_secret_value()}" + def _client(self) -> AbstractAsyncContextManager[PowerContextClient]: return open_client( self.base_url, @@ -338,7 +347,8 @@ async def _scope_id(self, state: TurnState) -> str | None: async def _prepare_context(self, query: str, scope_id: str, state: TurnState) -> str | None: try: - bounded_query = _bounded_recall_query(query) + # Scrubbing first means a cut cannot leave a bare credential behind. + bounded_query = _bounded_recall_query(scrub_secrets(query, self._authorization())) except UnicodeEncodeError as exc: # Unpaired surrogates, such as a file name decoded with ``surrogateescape``, have no UTF-8 form to send. self._write_capture_record( diff --git a/integrations/capabilities.toml b/integrations/capabilities.toml index cbde6baba4..76163959c2 100644 --- a/integrations/capabilities.toml +++ b/integrations/capabilities.toml @@ -1140,7 +1140,7 @@ toolsets = ["bub-tools", "bub-lifecycle"] [integrations.evidence] implementation = ["integrations/bub/src/powercontext_bub/tools.py", "integrations/bub/src/powercontext_bub/plugin.py"] documentation = ["integrations/bub/README.md"] -tests = ["e2e/bub/tests/test_workload_catalog.py", "tests/e2e/test_bub_service_chain.py"] +tests = ["e2e/bub/tests/test_workload_catalog.py", "e2e/bub/tests/test_bub_prompt_privacy.py", "tests/e2e/test_bub_service_chain.py"] [[integrations]] id = "dify" diff --git a/pyproject.toml b/pyproject.toml index 6f66c4e003..a004c9aeb7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -319,6 +319,7 @@ fix = true # fix that it applies to a copy makes the copy drift. "src/powercontext_integration_lifecycle/**/*.py" = "py39" "integrations/codex/plugins/powercontext/powercontext_lifecycle/**/*.py" = "py39" +"integrations/bub/src/powercontext_bub/_prompt_privacy.py" = "py39" "integrations/hermes/plugins/powercontext/{powercontext_client_config,prepared_context,prompt_privacy}.py" = "py39" "integrations/workbuddy/plugins/powercontext/hooks/{powercontext_client_config,prepared_context,prompt_privacy}.py" = "py39" "integrations/langchain/src/powercontext_langchain/{_prepared_context,_prompt_privacy}.py" = "py39" diff --git a/scripts/generate_integration_lifecycle.py b/scripts/generate_integration_lifecycle.py index cc6d60d76e..cb31f50764 100644 --- a/scripts/generate_integration_lifecycle.py +++ b/scripts/generate_integration_lifecycle.py @@ -37,8 +37,9 @@ _OPENCLAW = "integrations/openclaw/plugins/memory-powercontext" _OPENCODE = "integrations/opencode/plugins/powercontext" _PI = "integrations/pi/plugins/powercontext" -# The SDK adapters install with the PowerContext package, but they also support released cores that predate +# The SDK adapters and Bub install with the PowerContext package, but they also support released cores that predate # powercontext_integration_lifecycle, so each keeps a private copy beside its own modules. +_BUB = "integrations/bub/src/powercontext_bub" _LANGCHAIN = "integrations/langchain/src/powercontext_langchain" _LANGGRAPH = "integrations/langgraph/src/powercontext_langgraph" _PYDANTIC_AI = "integrations/pydantic-ai/src/powercontext_pydantic_ai" @@ -46,7 +47,7 @@ # The copies use another name than the source, so a process that has already imported the source, such as the test # suite, still loads the plugin's own copy. PACKAGE_COPIES = (f"{_CLAUDE_CODE}/powercontext_lifecycle", f"{_CODEX}/powercontext_lifecycle") -# WorkBuddy, Hermes, and the SDK adapters ship single modules where their hooks, installers, and imports already +# WorkBuddy, Hermes, Bub, and the SDK adapters ship single modules where their hooks, installers, and imports already # expect them. COPIES = { "client_config.py": ( @@ -61,6 +62,7 @@ f"{_PYDANTIC_AI}/_prepared_context.py", ), "prompt_privacy.py": ( + f"{_BUB}/_prompt_privacy.py", f"{_HERMES}/prompt_privacy.py", f"{_WORKBUDDY}/hooks/prompt_privacy.py", f"{_LANGCHAIN}/_prompt_privacy.py", From f08ad372714be1419f5452999c3baa5a6bf6a834 Mon Sep 17 00:00:00 2001 From: Fengzdadi <453788063@qq.com> Date: Wed, 25 Nov 2026 03:18:03 -0500 Subject: [PATCH 2/2] test(bub): expect the skipped user_prompt in host acceptance The Bub service-chain case still expected a redacted user_prompt Source for a prompt that carries Bub's own provider key. That prompt now holds a recognized credential, so the plugin skips the event. The case now asserts that no user_prompt Source is sent and that the capture log records the skip without the prompt text. It keeps the checks that the model receives the prompt as written, that no captured Source, stored Source, generation request or log line carries the credential, and that the turn flushes. The replay harness reads the same capture log into CaptureRecord, which forbids unknown fields and rejected the skip record's reason. It now accepts the field, and the plugin privacy test validates every record against it. --- e2e/bub/src/powercontext_e2e/models.py | 1 + e2e/bub/tests/test_bub_prompt_privacy.py | 5 +++++ tests/e2e/test_bub_service_chain.py | 23 ++++++++++++++++------- 3 files changed, 22 insertions(+), 7 deletions(-) diff --git a/e2e/bub/src/powercontext_e2e/models.py b/e2e/bub/src/powercontext_e2e/models.py index 07997f003d..8e722ba5cc 100644 --- a/e2e/bub/src/powercontext_e2e/models.py +++ b/e2e/bub/src/powercontext_e2e/models.py @@ -90,6 +90,7 @@ class CaptureRecord(EvidenceModel): source_id: str | None = None source_position: int | None = None error: str | None = None + reason: str | None = None final: bool | None = None target_position: int | None = None previous_cursor: int | None = None diff --git a/e2e/bub/tests/test_bub_prompt_privacy.py b/e2e/bub/tests/test_bub_prompt_privacy.py index a05a26b20b..68bb9a4cd1 100644 --- a/e2e/bub/tests/test_bub_prompt_privacy.py +++ b/e2e/bub/tests/test_bub_prompt_privacy.py @@ -30,6 +30,8 @@ from powercontext_bub.plugin import PowerContextPlugin, PowerContextSettings from pydantic import SecretStr +from powercontext_e2e.models import CaptureRecord + _ROOT = Path(__file__).resolve().parents[3] CASES = json.loads((_ROOT / "tests/fixtures/automatic_prompt_privacy.json").read_text(encoding="utf-8"))["cases"] # Every synthetic credential value in the fixture contains one of these markers. @@ -137,6 +139,9 @@ def test_turn_keeps_recognized_credentials_out_of_recall_and_capture( prompt = str(case["prompt"]) records = _run_turn(monkeypatch, tmp_path, prompt, token=_token(case)) + # The harness reads the same capture log as run evidence. + for record in records: + CaptureRecord.model_validate(record) # Recall runs either way. assert len(RecordingClient.prepared) == 1 diff --git a/tests/e2e/test_bub_service_chain.py b/tests/e2e/test_bub_service_chain.py index f9ea8dcb87..09aac08122 100644 --- a/tests/e2e/test_bub_service_chain.py +++ b/tests/e2e/test_bub_service_chain.py @@ -210,27 +210,36 @@ def test_bub_prompt_is_recalled_in_a_later_bub_session(bub_stack: BubStack) -> N def test_bub_capture_removes_known_credential_values(bub_stack: BubStack) -> None: credential = "sk-bube2ecredential0123456789" workspace = bub_stack.workspace("workspace") + capture_log = bub_stack.root / "capture.jsonl" model_start = len(bub_stack.model.requests) # Bub's own provider key is a credential environment value of the Bub process. start = bub_stack.run( workspace, f"Rotate the model provider key {credential} before the orchid release.", POWERCONTEXT_BUB_CAPTURE_EVENTS="true", + POWERCONTEXT_BUB_CAPTURE_LOG=str(capture_log), BUB_API_KEY=credential, ) # Bub's own model received the prompt as written. assert credential in json.dumps(bub_stack.model.requests[model_start]["messages"]) captures = [record["request"] for record in bub_stack.calls("/v1/sources/content", start)] - prompts = [capture["content"] for capture in captures if capture["metadata"]["event"] == "user_prompt"] - assert len(prompts) == 1 - assert ( - "Rotate the model provider key [REDACTED] before the orchid release." - in json.loads(prompts[0])["payload"]["text"] - ) + events = [capture["metadata"]["event"] for capture in captures] + # A prompt with a recognized credential is skipped rather than stored as a redacted copy; the turn's other + # events are still captured. + assert events + assert "user_prompt" not in events + log = capture_log.read_text(encoding="utf-8") + records = [json.loads(line) for line in log.splitlines()] + skips = [record for record in records if record["event"] == "user_prompt"] + assert len(skips) == 1 + assert skips[0]["status"] == "skipped" + assert skips[0]["reason"] == "sensitive_content" + assert "orchid release" not in log + assert [record["event"] for record in records if record["status"] == "captured"] == events assert bub_stack.calls("/v1/memory/flush", start), "bub_turn_flush_missing" # Neither the captured Sources nor the Server's generation model receive the credential. stored = bub_stack.sources(bub_stack.scope_of(start)) - assert credential not in json.dumps([captures, stored, bub_stack.model.generation_requests]) + assert credential not in json.dumps([captures, stored, bub_stack.model.generation_requests, log]) def test_bub_workspace_binding_holds_across_a_resumed_session(bub_stack: BubStack) -> None: