Repository navigation
fix(bub): keep recognized credentials out of automatic recall and capture #2820
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,162 @@ | ||
| # 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 | ||
|
|
||
| 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. | ||
| 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)) | ||
| # 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 | ||
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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"""(?<![\w-])["']?(?:HTTP(?:_[A-Za-z0-9]+)*_|(?:[A-Za-z0-9]+-)*)(?:authorization|cookie)\b["'`*]*""" | ||
| rf"[ \t]*[:=]\**{_NOT_A_HEADER_SETTING}[ \t]*[^\r\n]*(?:\r?\n[ \t]+[^\r\n]*)*", | ||
| # A key name may carry any prefix, as in OPENAI_API_KEY, X-Api-Key, --password, or dbPassword, but must end | ||
| # with the marker, so max_tokens and password_min_length stay ordinary. Markdown emphasis or code around | ||
| # the name, as in **Password:** or `DB_PASSWORD`:, is part of it. Tokenizer special tokens such as pad_token | ||
| # are configuration. A scheme word belongs to the value that follows it. | ||
| r"""(?<![\w-])["']?(?!(?:bos|eos|pad|unk|sep|cls|mask)_token\b)[\w-]*?(?:api[_ -]?key""" | ||
| r"""|access[_ -]?(?:key(?:[_-]id)?|token)|client[_ -]?secret|secret(?:[_ -]?key)?|private[_ -]?key|password""" | ||
| rf"""|passwd|passphrase|token|authorization|cookie)\b["'`*]*[\s{_SPACES}]*[:=]\**{_NOT_A_SETTING}{_GAP}""" | ||
| rf"""(?:(?:bearer|basic)[{_SPACES}]+)?(?:"[^"\r\n]*"|'[^'\r\n]*'|`[^`\r\n]*`|[^\s,;}}\]{_SPACES}]+)""", | ||
| rf"(?<![\w-])bearer[\s{_SPACES}]+[A-Za-z0-9._~+/=-]{{8,}}(?![\w-])", | ||
| r"(?<![\w-])(?:sk-[A-Za-z0-9][A-Za-z0-9_-]{7,}|[sr]k_(?:live|test)_[A-Za-z0-9]{16,}|github_pat_[A-Za-z0-9_]{8,}" | ||
| r"|gh[pousr]_[A-Za-z0-9_]{8,}|xox[baprs]-[A-Za-z0-9-]{8,})(?![\w-])", | ||
| ) | ||
| ) | ||
|
|
||
|
|
||
| def scrub_secrets(text: str, authorization: str | None = None) -> 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.