## Summary Follow-ups to the review threads left on four merged pull requests: #909, #912, #915 and #923. Each is a defect the review named, reproduced before any change, and repaired with a test that fails against the old code. This also addresses the Ollama spelling issue raised in this PR's review. **A cache-only window lookup no longer skips a model LiteLLM answers from its table** (from #909). The gate that keeps metadata lookups off a model's own server skipped `get_model_info` for any id carrying an Ollama segment, including ids LiteLLM answers offline: `ollama/Llama3`, `litellm_proxy/ollama/llama3` and `github/ollama/llama3` were sized on the 200000-token fallback where main read 8192. The gate now puts LiteLLM's own precondition to LiteLLM, keyed on the caller's id, and answers cautiously only for an id with an Ollama segment when the installed release does not ship that check. **A window the model's own server reported is reused inside the turn** (the second item of #909). A caller allowed to fetch resolved a local model's window by asking its server and threw the answer away; the next caller, which may not fetch, answered the fallback for the same model on every iteration, for the life of the process. The answer is now kept under the id the request goes out under, so `ollama/`, `ollama_chat/` and the stored `ollama-chat/` spelling share one entry. The table is consulted before the memo, so a row LiteLLM ships still outranks a previous ask; only a real figure is stored, so a server that was down is asked again. **A measurement taken while the boot verify ran is no longer overwritten** (from #915). The boot read a row before its handshake and wrote its verdict from that read, so a Test recorded during the handshake was replaced by a late timeout, refusal or pass. It reads the row again immediately before the write and leaves a newer measurement in place. The comparison is on `measured_at_ms`, so a modes relearn does not stop the write. Four docstrings that described the replaced rule are corrected. **The Windows environment capture's memo is pinned, and its docstring names the second failure mode** (from #912). **A key is written under the spelling the loaders read** (from #923). Below the top level pydantic reads the camelCase alias whenever it is present, null or not, so preferring a non-null spelling sent a write to a key the schema ignores, and `load_config` and the live readers then disagreed. Only the top level drops a null block; below it the first spelling present is the one read, and every caller now states which case it is in. **A write aimed at a wildcard map entry reaches that entry** (the follow-up #923's review asked for). Below the top level the spelling helper fell back to another spelling of a key, which is right for a schema field and wrong for a map entry: with only `tools.mcpServers.fooBar` present, a write to `tools.mcpServers.foo_bar.enabled` selected `fooBar`, disabling a server the caller never named. The catalog knows which segments a path binds, so a bound segment is now matched as written. `providers` keeps the tolerant rule, because its runtime reader folds those spellings through `names_same_provider`. **Configured Ollama models reach the metadata driver under its accepted spelling.** The wizard and model picker store Ollama ids as `ollama-chat/<model>`, while LiteLLM expects `ollama_chat/`. The window and output-ceiling lookups now translate that endpoint prefix using the provider registry before consulting the candidate list. The memo and no-fetch prefilters use the same registry normalization. The `ollama/` completion prefix is preserved because LiteLLM keys its offline table rows under it; non-Ollama prefixes are unchanged. ## Type - [x] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [ ] Refactor - [ ] Other ## Verification - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed Latest review fix (Linux, Python 3.12.13, LiteLLM 1.85.0; proxy variables unset; consumer tests rechecked after rebase onto current main): - New and strengthened regression cases ran before the fix: 6 failed / 108 passed, covering the memo spelling, both no-fetch metadata lookups, the conservative guard fallback, and an id produced by `stored_model_id` that could not reach the daemon. - `uv run --no-sync pytest tests/test_provider_rates.py -q -n 0 --tb=short`: 114 passed after the fix. - `uv run --no-sync pytest -q --tb=short <consumer-test-files> --cov=raven.providers.rates --cov-branch --cov-report=json:<coverage-json>`: 1312 passed, 1 skipped. The selection contains 16 test modules importing `raven.providers.rates`, plus `test_provider_registry_lookup.py` and `test_provider_wire_model.py`. The skip is the permission test that cannot deny a root process with `chmod 000`; existing Pydantic warnings remain. - Applying the repository's `parse_changed_lines` and `calculate_diff_coverage` to the fix commit after rebase yields 100% (13/13 executable changed lines). This is coverage of this fix, not a new full-PR coverage or full-suite ratchet result. - Six independent in-memory mutants were caught: raw memo prefilter, raw endpoint guard, raw shared predicate, omitted window spelling conversion, omitted ceiling spelling conversion, and replacing only the endpoint conversion with `wire_model` (which loses the `ollama/` table rows). The worktree was not rewritten by the mutation checks. - `UV_NO_SYNC=1 make lint-python lint-imports lint-deps lint-types`: passed after rebase; 2268 Python files formatted, 10 import contracts kept, no dependency issues. Both commit-message validators and the source-language and large-file gates also passed. `uv run --no-sync ty check raven/providers/rates.py tests/test_provider_rates.py` also passed. - Against a loopback stand-in daemon, the actual stored `ollama-chat/qwen2.5` id makes no request in cache-only mode before a fetch. One allowed `/api/show` request learns 8192, after which the cache-only lookup and `ModelBinding.context_window` both return 8192 without another request, and the output limit is 4096. - The daemon-path parameter cases clear LiteLLM's own id-keyed cache so alias cases cannot inherit a previous case's successful response. Earlier author verification, before this review fix: Commands recorded at the original PR revision and main baseline, with proxy variables unset: ``` uv run --frozen --python 3.12 --all-extras pytest -n 4 -q ``` 3 failed, 29796 passed, 158 skipped, 2 xfailed. A same-day run of the original main control gives the same 3 failed with 29771 passed, so the failure set is identical and the 25 extra passes are the tests added here. The three are environment-local: `test_resolve_node_dir_answers_each_case_it_exists_for` (npm on PATH), `test_a_legacy_workbook_is_converted_and_read` (LibreOffice), and `test_what_cannot_be_read_names_nothing` (load-dependent). Focused runs on the changed files: - `tests/test_provider_rates.py` 110 passed - `tests/test_config_self_surface.py` `tests/test_rpc_settings.py` `tests/test_config_update.py` `tests/test_raven_config_tool.py` `tests/test_rpc_console.py` 805 passed - `tests/test_subagent_host_env.py` 30 passed Gates: `ruff check`, `ruff format --check`, `ty check`, `lint-imports`, `deptry`, `scripts/check_commit_messages.py origin/main..HEAD`, `scripts/check_source_language.py origin/main..HEAD` and `scripts/check_large_files.py origin/main..HEAD` all pass. `pre-commit run --all-files` fails two hooks on three files this branch does not touch; the same three fail the same way at the base, so they are pre-existing. Every new test was checked by reverting the fix: six single-construct mutants over the two repaired rules, each restored and compared after running. Two survived the first pass and both were findings rather than tests to tighten. The guard that refused a zeroed window was unreachable (the one caller already has a window), so the parameter is required instead of optional. And the memo originally ranked above LiteLLM's own table, so a previous ask could have overridden a row a caller could have read offline; the table now comes first. Reproduced end to end against a stand-in server on a loopback port: one `/api/show` request answers 8192, `ollama/qwen2.5` read with `allow_fetch=False` answers 8192 with no second request, and `ModelBinding.context_window` on that model answers 8192 where it read the fallback before. ## Risk - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes No stored config changes shape or meaning. The alias-spelling fix changes where a write lands when a file carries both spellings of one key, which is the file that did not load correctly before. The wildcard fix changes where a write lands when two map entries differ only by spelling; both are left as written, where the old code silently edited the neighbour. The window memo is process-wide and holds context-window and optional output-limit counts per model, cleared by the same `reset_openrouter_cache` the catalogue uses. Stored `ollama-chat/` ids can now make a metadata request to the configured daemon when fetch is allowed; cache-only callers continue to reuse local data. Other hyphenated provider prefixes are outside this fix. Roll back by reverting the merged change; the memo is not persisted. ## Related Issues #909, #912, #915, #923
674 lines
31 KiB
Python
674 lines
31 KiB
Python
"""The self-configuration catalog against the schema, the live readers and the writers."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import importlib
|
|
import inspect
|
|
import json
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
from raven.config import self_surface as surface
|
|
from raven.config.self_surface import Effect
|
|
|
|
# Where each next-turn claim is honoured: the module and the name that re-reads
|
|
# the setting while the process serves. A new NEXT_TURN entry must add its
|
|
# evidence here, or say in the catalog that it is not next-turn.
|
|
_NEXT_TURN_READERS: dict[str, tuple[str, str]] = {
|
|
"agents.defaults.reasoningEffort": ("raven.config.live", "reasoning_effort"),
|
|
"agents.defaults.maxToolIterations": ("raven.config.live", "max_tool_iterations"),
|
|
"agents.defaults.contextWindowTokens": ("raven.config.live", "context_window_tokens"),
|
|
"agents.defaults.enablePersonalization": ("raven.config.live", "personalization_enabled"),
|
|
"routing.profile": ("raven.config.live", "routing_profile"),
|
|
"providers.*.apiKey": ("raven.providers.resolving_provider", "ResolvingProvider"),
|
|
"providers.*.apiBase": ("raven.providers.resolving_provider", "ResolvingProvider"),
|
|
"providers.*.models": ("raven.rpc.methods.model", "model_options"),
|
|
"tools.disabledTools": ("raven.config.live", "disabled_tool_names"),
|
|
"tools.exec.timeout": ("raven.config.live", "exec_timeout"),
|
|
"tools.exec.extraDenyPatterns": ("raven.config.live", "exec_extra_deny_patterns"),
|
|
"tools.web.search.provider": ("raven.config.live", "web_providers"),
|
|
"tools.web.fetch.provider": ("raven.config.live", "web_providers"),
|
|
"tools.mcpServers.*.enabled": ("raven.config.live", "mcp_server_configs"),
|
|
"memory.memoryTopK": ("raven.config.live", "memory_top_k"),
|
|
"skillForge.blocklist": ("raven.config.live", "skill_blocklist"),
|
|
"skillForge": ("raven.config.live", "skill_gate_pin"),
|
|
"context": ("raven.config.live", "curator_pin"),
|
|
"playbooks.disabled": ("raven.config.live", "disabled_playbook_names"),
|
|
"tracing.enabled": ("raven.tracing.config", "def enabled"),
|
|
"tracing.previewLen": ("raven.tracing.config", "preview_len"),
|
|
"sessionTitle.enabled": ("raven.rpc.methods.turn", "load_raven_config"),
|
|
"sessions.autoArchiveAfterDays": ("raven.rpc.methods.session", "load_raven_config"),
|
|
"permissions.mode": ("raven.config.live", "permissions_config"),
|
|
"permissions.judgeModel": ("raven.config.live", "permissions_config"),
|
|
"language": ("raven.i18n", "set_language"),
|
|
"session.model": ("raven.agent.loop.wiring", "set_session_binding"),
|
|
"cron.defaultTimezone": ("raven.config.live", "cron_default_timezone"),
|
|
}
|
|
|
|
|
|
def _next_turn_paths() -> set[str]:
|
|
out = set()
|
|
for s in surface.all_settings():
|
|
if s.effect is not Effect.NEXT_TURN:
|
|
continue
|
|
if s.path.startswith(("tools.web.providers.", "tools.media.")):
|
|
continue
|
|
out.add(s.path)
|
|
return out
|
|
|
|
|
|
def test_every_next_turn_claim_names_a_live_reader():
|
|
assert _next_turn_paths() == set(_NEXT_TURN_READERS)
|
|
for path, (module, name) in _NEXT_TURN_READERS.items():
|
|
source = inspect.getsource(importlib.import_module(module))
|
|
assert name in source, f"{path}: {module} no longer carries {name}"
|
|
|
|
|
|
def test_the_media_and_vendor_key_claims_ride_the_live_readers():
|
|
live = importlib.import_module("raven.config.live")
|
|
assert hasattr(live, "media_tool_config")
|
|
assert hasattr(live, "web_provider_keys")
|
|
|
|
|
|
def test_every_concrete_path_is_a_schema_field():
|
|
missing = []
|
|
for s in surface.all_settings():
|
|
if "*" in s.path or s.kind == "pin" or s.session or s.stored_at:
|
|
continue
|
|
if surface.default_of(s.path) is None and not s.nullable and s.path != "agents.defaults.reasoningEffort":
|
|
missing.append(s.path)
|
|
assert missing == []
|
|
|
|
|
|
def test_paths_are_unique():
|
|
paths = [s.path for s in surface.all_settings()]
|
|
assert len(paths) == len(set(paths))
|
|
|
|
|
|
def test_settings_writer_paths_are_ones_settings_set_accepts():
|
|
from raven.rpc.methods import console
|
|
|
|
source = inspect.getsource(console.settings_set)
|
|
for s in surface.all_settings():
|
|
if s.writer != "settings":
|
|
continue
|
|
assert s.path in console._SETTINGS_SIMPLE_KEYS or f'"{s.path}"' in source, s.path
|
|
|
|
|
|
def test_no_catalog_entry_composes_a_command():
|
|
for s in surface.all_settings():
|
|
assert not s.path.endswith((".command", ".env", ".args")), s.path
|
|
|
|
|
|
def test_find_prefers_an_exact_entry_and_binds_wildcards():
|
|
setting, bound = surface.find("tools.web.providers.jina.apiKey")
|
|
assert setting.path == "tools.web.providers.jina.apiKey" and bound == []
|
|
setting, bound = surface.find("providers.openrouter.apiBase")
|
|
assert setting.path == "providers.*.apiBase" and bound == ["openrouter"]
|
|
assert surface.find("providers.openrouter") is None
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("path", "value", "ok"),
|
|
[
|
|
("tools.exec.timeout", 30, True),
|
|
("tools.exec.timeout", 2, False),
|
|
("tools.exec.timeout", "30", False),
|
|
("tools.exec.timeout", 30.5, False),
|
|
("tools.exec.timeout", True, False),
|
|
("routing.profile", "eco", True),
|
|
("routing.profile", "cheap", False),
|
|
("tools.disabledTools", ["exec"], True),
|
|
("tools.disabledTools", "exec", False),
|
|
("agents.defaults.contextWindowTokens", None, True),
|
|
("tools.exec.timeout", None, False),
|
|
("agents.defaults.model", {"provider": "openrouter", "model": "x/y"}, True),
|
|
("agents.defaults.model", {"provider": "openrouter"}, False),
|
|
],
|
|
)
|
|
def test_check_value(path, value, ok):
|
|
setting, _ = surface.find(path)
|
|
if ok:
|
|
surface.check_value(setting, value)
|
|
else:
|
|
with pytest.raises(ValueError):
|
|
surface.check_value(setting, value)
|
|
|
|
|
|
def test_change_line_states_the_effect_and_the_risk():
|
|
line = surface.change_line({"action": "set", "path": "permissions.mode", "value": "full"})
|
|
assert "permissions.mode" in line and "full" in line
|
|
assert "next turn" in line
|
|
assert "without asking" in line
|
|
assert "Reload" in surface.change_line({"action": "restart", "value": "reload"})
|
|
assert "whole Raven process" in surface.change_line({"action": "restart", "value": '"restart"'})
|
|
|
|
|
|
def _home(tmp_path: Path, monkeypatch, data: dict) -> Path:
|
|
home = tmp_path / "home"
|
|
home.mkdir()
|
|
(home / "config.json").write_text(json.dumps(data))
|
|
monkeypatch.setenv("RAVEN_HOME", str(home))
|
|
return home / "config.json"
|
|
|
|
|
|
def test_write_keeps_the_spelling_already_in_the_file(tmp_path, monkeypatch):
|
|
path = _home(tmp_path, monkeypatch, {"tools": {"exec": {"timeout": 60}}, "agents": {"defaults": {}}})
|
|
previous = surface.write_value("tools.exec.timeout", 90)
|
|
surface.write_value("agents.defaults.maxToolIterations", 12)
|
|
data = json.loads(path.read_text())
|
|
assert previous == 60
|
|
assert data["tools"]["exec"] == {"timeout": 90}
|
|
assert data["agents"]["defaults"] == {"maxToolIterations": 12}
|
|
|
|
|
|
def test_write_follows_a_snake_case_file(tmp_path, monkeypatch):
|
|
path = _home(tmp_path, monkeypatch, {"agents": {"defaults": {"max_tool_iterations": 5}}})
|
|
surface.write_value("agents.defaults.maxToolIterations", 7)
|
|
assert json.loads(path.read_text())["agents"]["defaults"] == {"max_tool_iterations": 7}
|
|
|
|
|
|
@pytest.mark.parametrize("snake_active", [False, True])
|
|
@pytest.mark.parametrize("remove", [False, True])
|
|
def test_raw_access_follows_the_non_null_alias(tmp_path, monkeypatch, snake_active, remove):
|
|
from raven.config.raven import load_raven_config
|
|
|
|
active, empty = ("skill_forge", "skillForge") if snake_active else ("skillForge", "skill_forge")
|
|
path = _home(tmp_path, monkeypatch, {empty: None, active: {"autoInstall": "off", "blocklist": ["a"]}})
|
|
assert load_raven_config(config_path=path).skill_forge.blocklist == ["a"]
|
|
assert surface.lookup(surface.read_raw(path), "skillForge.blocklist") == (True, ["a"])
|
|
|
|
if remove:
|
|
assert surface.remove_value("skillForge.blocklist", config_path=path) == ["a"]
|
|
expected = {"autoInstall": "off"}
|
|
else:
|
|
assert surface.write_value("skillForge.blocklist", ["zed"], config_path=path) == ["a"]
|
|
expected = {"autoInstall": "off", "blocklist": ["zed"]}
|
|
|
|
assert json.loads(path.read_text(encoding="utf-8")) == {empty: None, active: expected}
|
|
assert load_raven_config(config_path=path).skill_forge.blocklist == ([] if remove else ["zed"])
|
|
|
|
|
|
@pytest.mark.parametrize("invalid", [[], 0, False, "invalid"])
|
|
@pytest.mark.parametrize("remove", [False, True])
|
|
def test_raw_write_refuses_an_invalid_alias_beside_null(tmp_path, monkeypatch, invalid, remove):
|
|
path = _home(tmp_path, monkeypatch, {"skillForge": None, "skill_forge": invalid})
|
|
before = path.read_bytes()
|
|
|
|
with pytest.raises(ValueError, match="not an object"):
|
|
if remove:
|
|
surface.remove_value("skillForge.blocklist", config_path=path)
|
|
else:
|
|
surface.write_value("skillForge.blocklist", ["zed"], config_path=path)
|
|
|
|
assert path.read_bytes() == before
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"camel,snake,previous,value",
|
|
[
|
|
("contextWindowTokens", "context_window_tokens", 200000, 100000),
|
|
("reasoningEffort", "reasoning_effort", "low", "high"),
|
|
],
|
|
)
|
|
def test_raw_leaf_access_lands_on_the_alias_pydantic_reads(tmp_path, monkeypatch, camel, snake, previous, value):
|
|
"""Below the top level pydantic reads a null alias over a populated snake_case key.
|
|
|
|
So ``lookup`` reports that null, as the schema does, and a write replaces
|
|
it: afterwards ``load_config`` reads the new value and the snake_case key
|
|
is left as it was.
|
|
"""
|
|
from raven.config.loader import load_config
|
|
|
|
path = _home(tmp_path, monkeypatch, {"agents": {"defaults": {camel: None, snake: previous}}})
|
|
leaf = f"agents.defaults.{camel}"
|
|
assert getattr(load_config(path).agents.defaults, snake) is None
|
|
assert surface.lookup(surface.read_raw(path), leaf) == (True, None)
|
|
|
|
assert surface.write_value(leaf, value, config_path=path) is None
|
|
|
|
assert json.loads(path.read_text(encoding="utf-8")) == {"agents": {"defaults": {camel: value, snake: previous}}}
|
|
assert getattr(load_config(path).agents.defaults, snake) == value
|
|
|
|
|
|
def test_a_nested_block_write_lands_on_the_alias_pydantic_reads(tmp_path, monkeypatch):
|
|
"""Only the top level drops a null block; below it pydantic reads the null alias.
|
|
|
|
So this file does not load, and a write into the populated snake_case block
|
|
would leave it unloadable. The write goes to the alias instead, which is
|
|
the block the schema then reads.
|
|
"""
|
|
from raven.config.loader import load_config
|
|
|
|
path = _home(tmp_path, monkeypatch, {"tools": {"askUser": None, "ask_user": {"timeout": 30}}})
|
|
with pytest.raises(ValueError, match="fails schema validation"):
|
|
load_config(path)
|
|
|
|
assert surface.write_value("tools.askUser.timeout", 45, config_path=path) is None
|
|
|
|
assert json.loads(path.read_text(encoding="utf-8")) == {
|
|
"tools": {"askUser": {"timeout": 45}, "ask_user": {"timeout": 30}}
|
|
}
|
|
assert load_config(path).tools.ask_user.timeout == 45
|
|
|
|
|
|
def test_a_write_the_schema_rejects_is_refused_and_nothing_changes(tmp_path, monkeypatch):
|
|
path = _home(tmp_path, monkeypatch, {"tools": {"exec": {"timeout": 60}}})
|
|
before = path.read_text()
|
|
with pytest.raises(ValueError, match="would not load"):
|
|
surface.write_value("tools.exec.timeout", "soon")
|
|
assert path.read_text() == before
|
|
|
|
|
|
def test_a_file_that_was_already_broken_does_not_block_a_write(tmp_path, monkeypatch):
|
|
path = _home(tmp_path, monkeypatch, {"bogusTopLevel": 1})
|
|
surface.write_value("tools.exec.timeout", 45)
|
|
assert json.loads(path.read_text())["tools"]["exec"]["timeout"] == 45
|
|
|
|
|
|
def test_remove_restores_the_default(tmp_path, monkeypatch):
|
|
path = _home(tmp_path, monkeypatch, {"tools": {"exec": {"timeout": 90}}})
|
|
assert surface.remove_value("tools.exec.timeout") == 90
|
|
assert json.loads(path.read_text())["tools"]["exec"] == {}
|
|
assert surface.remove_value("tools.exec.timeout") is None
|
|
|
|
|
|
def test_extension_blocks_validate_too(tmp_path, monkeypatch):
|
|
path = _home(tmp_path, monkeypatch, {})
|
|
surface.write_value("tracing.enabled", False)
|
|
assert json.loads(path.read_text()) == {"tracing": {"enabled": False}}
|
|
with pytest.raises(ValueError, match="would not load"):
|
|
surface.write_value("sentinel.nudgePolicy.maxNudgesPerHour", "many")
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"path", ["tools.web.proxy", "tools.media.proxy", "providers.openai.apiBase", "permissions.judgeModel"]
|
|
)
|
|
def test_a_setting_that_redirects_keyed_traffic_stays_with_the_user(path):
|
|
"""Smart mode's reviewer settles anything not marked sensitive, and each of
|
|
these sends Raven's keys and traffic to a host the call names."""
|
|
assert surface.touches_sensitive({"action": "set", "path": path, "value": "http://127.0.0.1:9"})
|
|
|
|
|
|
@pytest.mark.parametrize("spelled", [" {}", "{} ", "{}.", ".{}", " {}. "])
|
|
def test_the_gate_classifies_the_path_the_tool_writes(spelled):
|
|
"""The tool trims spaces and dots before it writes; classifying the raw
|
|
argument let one trailing space turn a secret into an ordinary setting."""
|
|
from raven.permissions.rules import self_config_tier
|
|
|
|
sensitive = {"action": "set", "path": spelled.format("tools.restrictToWorkspace"), "value": False}
|
|
assert surface.touches_sensitive(sensitive)
|
|
secret = {"action": "set", "path": spelled.format("channels.telegram.token"), "value": "123:PLAINTEXT"}
|
|
assert self_config_tier("raven_config", secret).value == "deny"
|
|
assert "PLAINTEXT" not in surface.change_line(secret)
|
|
|
|
|
|
def test_a_batch_names_its_settings_the_way_the_tool_writes_them():
|
|
assert surface.touches_sensitive({"action": "set", "path": " ", "value": {"tools.restrictToWorkspace": False}})
|
|
assert surface.touches_sensitive({"action": "set", "value": {"tools.restrictToWorkspace ": False}})
|
|
|
|
|
|
def test_every_field_a_channel_declares_secret_is_secret_to_the_gate():
|
|
"""The adapter's spec decides; Feishu's encrypt_key names no credential marker."""
|
|
from pydantic.alias_generators import to_camel
|
|
|
|
from raven.config.update_channels import channel_field_specs, channel_names
|
|
|
|
declared = [
|
|
f"channels.{name}.{to_camel(field)}"
|
|
for name in channel_names()
|
|
for field, spec in channel_field_specs(name).items()
|
|
if spec.get("is_secret")
|
|
]
|
|
assert "channels.feishu.encryptKey" in declared
|
|
assert [path for path in declared if not surface.is_secret_path(path)] == []
|
|
assert not surface.is_secret_path("channels.feishu.appId")
|
|
assert not surface.is_secret_path("channels.nosuchchannel.encryptKey")
|
|
|
|
|
|
def test_a_channel_secret_inside_an_object_is_refused_and_never_shown():
|
|
from raven.permissions.rules import self_config_tier
|
|
|
|
whole = {"action": "set", "path": "channels.feishu", "value": {"encryptKey": "FEISHU-PLAINTEXT", "appId": "cli_1"}}
|
|
assert self_config_tier("raven_config", whole).value == "deny"
|
|
shown = surface.change_line(whole)
|
|
assert "FEISHU-PLAINTEXT" not in shown and "cli_1" in shown
|
|
|
|
|
|
def _wrappings(core: str) -> list[str]:
|
|
import itertools
|
|
|
|
ends = ["".join(chars) for n in range(3) for chars in itertools.product(" \t.", repeat=n)]
|
|
return [f"{before}{core}{after}" for before in ends for after in ends]
|
|
|
|
|
|
def test_the_path_spelling_settles_in_one_pass_whatever_wraps_it():
|
|
"""Trimming spaces then dots left ``token .`` as ``token `` -- a secret read as
|
|
an ordinary setting -- so every order of them must come off at once."""
|
|
from raven.permissions.rules import self_config_tier
|
|
|
|
for spelled in _wrappings("channels.telegram.token"):
|
|
assert surface.canonical_path(spelled) == "channels.telegram.token", repr(spelled)
|
|
call = {"action": "set", "path": spelled, "value": "123:PLAINTEXT"}
|
|
assert self_config_tier("raven_config", call).value == "deny", repr(spelled)
|
|
assert "PLAINTEXT" not in surface.change_line(call), repr(spelled)
|
|
for spelled in _wrappings("tools.restrictToWorkspace"):
|
|
assert surface.touches_sensitive({"action": "set", "path": spelled, "value": False}), repr(spelled)
|
|
|
|
|
|
def test_every_field_the_provider_schema_treats_as_secret_is_secret_to_the_gate(monkeypatch, tmp_path):
|
|
"""The provider writer redacts by the schema's own marker (``extraHeaders``) and
|
|
its patch list (Gemini's ``apiKeyList``); the gate and the scrub read the same."""
|
|
from pydantic.alias_generators import to_camel
|
|
|
|
from raven.config import held_secrets
|
|
from raven.config.schema import GeminiProviderConfig, ProviderConfig
|
|
from raven.config.update_providers import _is_secret_field
|
|
|
|
declared = [
|
|
name
|
|
for model in (ProviderConfig, GeminiProviderConfig)
|
|
for name, info in model.model_fields.items()
|
|
if _is_secret_field(name, info)
|
|
]
|
|
assert {"extra_headers", "api_key_list"} <= set(declared)
|
|
assert [n for n in declared if not surface.is_secret_path(f"providers.gemini.{to_camel(n)}")] == []
|
|
assert not surface.is_secret_path("providers.gemini.models")
|
|
|
|
config = tmp_path / "config.json"
|
|
header, listed, per_endpoint = "hdr-0123456789abcdef", "AIza-listed-0123456789", "hdr-endpoint-0123456789"
|
|
config.write_text(
|
|
json.dumps(
|
|
{
|
|
"providers": {
|
|
"aihubmix": {
|
|
"extraHeaders": {"APP-Code": header},
|
|
"endpoints": [{"label": "b", "extraHeaders": {"APP-Code": per_endpoint}}],
|
|
},
|
|
"gemini": {"apiKeyList": [listed]},
|
|
}
|
|
}
|
|
),
|
|
encoding="utf-8",
|
|
)
|
|
monkeypatch.setattr(held_secrets, "get_config_path", lambda: config)
|
|
monkeypatch.setattr(held_secrets, "_cache", None)
|
|
scrubbed = held_secrets.scrub_held_secrets(f"APP-Code: {header}; key {listed}; {per_endpoint}")
|
|
assert header not in scrubbed and listed not in scrubbed and per_endpoint not in scrubbed
|
|
assert not surface.is_secret_path("providers.aihubmix.endpoints.0.label")
|
|
|
|
|
|
def test_a_channel_field_that_sends_its_traffic_somewhere_stays_with_the_user():
|
|
"""A proxy or server address carries the channel's credential to whatever host
|
|
it names; the adapter declares it, the way it declares a secret."""
|
|
import re
|
|
|
|
from pydantic.alias_generators import to_camel
|
|
|
|
from raven.config.update_channels import channel_field_specs, channel_names
|
|
|
|
addresses = [
|
|
f"channels.{name}.{to_camel(field)}"
|
|
for name in channel_names()
|
|
for field in channel_field_specs(name)
|
|
if re.search(r"(url|host|proxy|homeserver)$", field)
|
|
]
|
|
assert "channels.telegram.proxy" in addresses and "channels.matrix.homeserver" in addresses
|
|
unmarked = [p for p in addresses if not surface.touches_sensitive({"action": "set", "path": p, "value": "x"})]
|
|
assert unmarked == [], "declare these sensitive in the adapter's spec"
|
|
line = surface.change_line({"action": "set", "path": "channels.telegram.proxy", "value": "http://h:1"})
|
|
assert "Note: sends this channel's credentials" in line
|
|
assert not surface.touches_sensitive({"action": "set", "path": "channels.telegram.replyToMessage", "value": True})
|
|
|
|
|
|
_TRIMMED_NOT_JSON = [c for c in map(chr, range(0x3001)) if c.isspace() and c not in " \t\n\r"]
|
|
|
|
|
|
@pytest.mark.parametrize("lead", _TRIMMED_NOT_JSON, ids=lambda c: f"U+{ord(c):04X}")
|
|
def test_the_gate_decodes_a_value_the_way_the_tool_does(lead):
|
|
"""The tool trimmed before parsing and the gate did not, so a batch led by a
|
|
character JSON does not count as space was an object to one and text to the
|
|
other -- and switched approval to full with only the reviewer asked."""
|
|
from raven.agent.tools.raven_config import _parse_value
|
|
from raven.permissions.rules import self_config_tier
|
|
|
|
raw = lead + '{"permissions.mode": "full", "tools.restrictToWorkspace": false}'
|
|
assert (
|
|
_parse_value(raw)
|
|
== surface.decode_value(raw)
|
|
== {"permissions.mode": "full", "tools.restrictToWorkspace": False}
|
|
)
|
|
assert surface.touches_sensitive({"action": "set", "value": raw})
|
|
keyed = lead + '{"providers.openai.apiKey": "sk-LEAKED-123"}'
|
|
assert self_config_tier("raven_config", {"action": "set", "value": keyed}).value == "deny"
|
|
lent = lead + '{"preset": "claude-code", "lend_key": "anthropic", "model": null}'
|
|
assert surface.touches_sensitive({"action": "add", "path": "subagents", "value": lent})
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"call",
|
|
[
|
|
{"path": "channels.telegram.allow_from", "value": '["*"]'},
|
|
{"path": "channels.telegram.AllowFrom", "value": '["*"]'},
|
|
{"path": "channels.Telegram.allowFrom", "value": '["*"]'},
|
|
{"path": "channels.telegram", "value": '{"allow_from": ["*"]}'},
|
|
{"value": '{"channels.telegram.allow_from": ["*"]}'},
|
|
{"path": "channels.slack", "value": '{"dm.allow_from": ["*"], "dm.policy": "open"}'},
|
|
{"path": "channels.slack.groupPolicy", "value": "open"},
|
|
{"path": "channels.telegram.enabled", "value": "true"},
|
|
{"path": "channels.telegram.workspace", "value": "/"},
|
|
{"path": "channels.email.imapUseSsl", "value": "false"},
|
|
{"path": "channels.matrix.e2ee_enabled", "value": "false"},
|
|
{"path": "channels.slack.userTokenReadOnly", "value": "false"},
|
|
{"path": "channels.weixin.state_dir", "value": '"/tmp/x"'},
|
|
],
|
|
)
|
|
def test_who_may_instruct_raven_on_a_channel_stays_with_the_user_however_it_is_spelled(call):
|
|
"""The catalog's camelCase ``allowFrom`` was the only spelling the gate knew;
|
|
the adapter's declaration now decides, read through the tool's own spelling."""
|
|
assert surface.touches_sensitive({"action": "set", **call}), call
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"path",
|
|
[
|
|
"tools.disabledTools",
|
|
"tools.mcpServers.gh.enabled",
|
|
"skillForge.blocklist",
|
|
"skillForge.autoInstall",
|
|
"subagents.pi.description",
|
|
],
|
|
)
|
|
def test_a_setting_that_hands_back_something_the_user_took_away_stays_with_them(path):
|
|
assert surface.touches_sensitive({"action": "set", "path": path, "value": "x"})
|
|
assert surface.touches_sensitive({"action": "unset", "path": path}) or path.startswith("subagents.")
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("path", "secret"),
|
|
[
|
|
("tools.mcpServers.gh.env.AWS_SECRET_ACCESS_KEY", True),
|
|
("tools.mcpServers.gh.env.GH_PAT", True),
|
|
("tools.mcpServers.gh.env.LANGFUSE_SECRET_KEY", True),
|
|
("subagents.agents.0.env.OPENAI_KEY", True),
|
|
("tools.mcpServers.gh.headers.Authorization", True),
|
|
("tools.mcpServers.gh.headers.X-Anything", True),
|
|
("channels.FEISHU.encryptKey", True),
|
|
("a2a.peers.0.credential", True),
|
|
("tools.mcpServers.gh.env.BEARER", True),
|
|
("tools.mcpServers.gh.env.JWT", True),
|
|
("tools.mcpServers.gh.env.SENTRY_DSN", True),
|
|
("tools.mcpServers.gh.env.SESSION_DIR", False),
|
|
("tools.mcpServers.gh.env.PATH", False),
|
|
("tools.mcpServers.gh.env.NODE_OPTIONS", False),
|
|
("tools.mcpServers.gh.command", False),
|
|
],
|
|
)
|
|
def test_a_credential_is_found_wherever_the_config_keeps_one(path, secret):
|
|
assert surface.is_secret_path(path) is secret
|
|
|
|
|
|
def test_a_call_carrying_a_credential_anywhere_in_its_value_is_refused_and_never_shown():
|
|
from raven.permissions.rules import self_config_tier
|
|
|
|
calls = [
|
|
{"action": "set", "path": "providers.openai", "value": {"apiKey": "PLAINTEXT-k1"}},
|
|
{"action": "set", "value": {"providers.openai": {"apiKey": "PLAINTEXT-k2"}}},
|
|
{
|
|
"action": "add",
|
|
"path": "subagents",
|
|
"value": {"preset": "codex", "env": {"AWS_SECRET_ACCESS_KEY": "PLAINTEXT-k5"}},
|
|
},
|
|
{
|
|
"action": "add",
|
|
"path": "tools.mcpServers",
|
|
"value": {"x": {"headers": {"Authorization": "Bearer PLAINTEXT-k6"}}},
|
|
},
|
|
{"action": "set", "path": "channels.FEISHU.encryptKey", "value": "PLAINTEXT-k8"},
|
|
]
|
|
for call in calls:
|
|
assert self_config_tier("raven_config", call).value == "deny", call
|
|
assert "PLAINTEXT" not in surface.change_line(call), call
|
|
assert "PLAINTEXT" not in json.dumps(surface.change_view(call, {})), call
|
|
|
|
|
|
def test_a_key_named_with_only_spaces_is_asked_for_on_the_card():
|
|
from raven.permissions.rules import self_config_tier
|
|
|
|
call = {"action": "set", "path": "providers.openai.apiKey", "value": " "}
|
|
assert self_config_tier("raven_config", call).value != "deny"
|
|
assert surface.only_asks_for_secrets(call)
|
|
|
|
|
|
def test_every_credential_the_config_holds_is_scrubbed_in_every_spelling_it_prints_in(monkeypatch, tmp_path):
|
|
"""Measured: an MCP server's AWS key, a Bearer header, a key in a URL's query
|
|
or userinfo, a seven-character mailbox password and a password JSON escapes
|
|
all came back through `jq . config.json` untouched."""
|
|
from raven.config import held_secrets
|
|
|
|
config = tmp_path / "config.json"
|
|
raw = {
|
|
"tools": {
|
|
"mcpServers": {
|
|
"gh": {
|
|
"env": {"AWS_SECRET_ACCESS_KEY": "aws-secret-value-1", "PATH": "/usr/bin:/bin"},
|
|
"headers": {"Authorization": "Bearer tok-abcdef123"},
|
|
"url": "https://mcp.example/x?api_key=urlkey12345",
|
|
}
|
|
}
|
|
},
|
|
"channels": {
|
|
"email": {"imapPassword": "hunter2", "smtpPassword": 'pa"ss\\word'},
|
|
"telegram": {"proxy": "http://user:proxypass99@h:1"},
|
|
},
|
|
"providers": {"openai": {"apiBase": "https://h/v1?key=basekey9876"}, "vllm": {"apiKey": "EMPTY"}},
|
|
}
|
|
config.write_text(json.dumps(raw), encoding="utf-8")
|
|
monkeypatch.setattr(held_secrets, "get_config_path", lambda: config)
|
|
monkeypatch.setattr(held_secrets, "_cache", None)
|
|
|
|
printed = held_secrets.scrub_held_secrets(json.dumps(raw, indent=1))
|
|
for value in ("aws-secret-value-1", "tok-abcdef123", "urlkey12345", "proxypass99", "basekey9876", "hunter2"):
|
|
assert value not in printed, value
|
|
assert 'pa\\"ss\\\\word' not in printed
|
|
assert "/usr/bin:/bin" in printed and '"EMPTY"' in printed
|
|
|
|
|
|
def test_a_url_with_a_credential_in_it_is_one_to_the_gate_the_card_and_the_scrub(monkeypatch, tmp_path):
|
|
"""The scrub alone knew `mongodb://u:pw@host` held a password, so the gate asked
|
|
and the card printed it; a Sentry DSN keeps its key as the username."""
|
|
from raven.config import held_secrets
|
|
from raven.permissions.rules import self_config_tier
|
|
|
|
call = {"action": "set", "path": "providers.openai.apiBase", "value": "https://u:PLAINTEXT-c1@h/v1"}
|
|
assert self_config_tier("raven_config", call).value == "deny"
|
|
assert "PLAINTEXT" not in surface.change_line(call)
|
|
assert surface.redacted({"uri": "mongodb://u:PLAINTEXT-c2@h/db"}) == {"uri": "mongodb://u:***@h/db"}
|
|
|
|
dsn = "https://0123456789abcdef0123456789abcdef@o1.ingest.sentry.io/42"
|
|
config = tmp_path / "config.json"
|
|
config.write_text(json.dumps({"tools": {"mcpServers": {"s": {"url": dsn}}}}), encoding="utf-8")
|
|
monkeypatch.setattr(held_secrets, "get_config_path", lambda: config)
|
|
monkeypatch.setattr(held_secrets, "_cache", None)
|
|
assert "0123456789abcdef0123456789abcdef" not in held_secrets.scrub_held_secrets(f"dsn={dsn}")
|
|
assert "https://api.openai.com/v1" == held_secrets.scrub_held_secrets("https://api.openai.com/v1")
|
|
|
|
|
|
def test_a_wildcard_segment_is_an_identity_not_a_field_name(tmp_path, monkeypatch):
|
|
"""``tools.mcpServers.<name>`` names a server; the name is not a schema field.
|
|
|
|
Below the top level the helper falls back to the other spelling of a key,
|
|
which is right for a schema field (``apiBase`` under ``api_base`` is one
|
|
field read twice) and wrong here: the map is read by exact key, so a path
|
|
naming ``foo_bar`` reaches the server called ``foo_bar`` or nothing -- never
|
|
the server called ``fooBar``, which is a different entry with its own
|
|
command, credentials and enabled flag.
|
|
"""
|
|
from raven.config.live import LiveConfig, mcp_server_configs
|
|
|
|
path = _home(tmp_path, monkeypatch, {"tools": {"mcpServers": {"fooBar": {"enabled": True, "command": "a"}}}})
|
|
|
|
assert surface.lookup(surface.read_raw(path), "tools.mcpServers.foo_bar.enabled") == (False, None)
|
|
assert surface.lookup(surface.read_raw(path), "tools.mcpServers.fooBar.enabled") == (True, True)
|
|
|
|
assert surface.write_value("tools.mcpServers.foo_bar.enabled", False) is None
|
|
assert surface.write_value("tools.mcpServers.foo_bar.args", ["--b"]) is None
|
|
|
|
data = json.loads(path.read_text(encoding="utf-8"))
|
|
assert data["tools"]["mcpServers"]["fooBar"] == {"enabled": True, "command": "a"}
|
|
assert data["tools"]["mcpServers"]["foo_bar"] == {"enabled": False, "args": ["--b"]}
|
|
|
|
servers = mcp_server_configs(LiveConfig(path))
|
|
assert servers["fooBar"].enabled is True and servers["fooBar"].command == "a"
|
|
assert servers["foo_bar"].enabled is False and servers["foo_bar"].args == ["--b"]
|
|
|
|
|
|
def test_a_wildcard_segment_updates_the_entry_it_names(tmp_path, monkeypatch):
|
|
"""And when the entry is there, the write lands on it rather than beside it."""
|
|
from raven.config.live import LiveConfig, mcp_server_configs
|
|
|
|
path = _home(
|
|
tmp_path,
|
|
monkeypatch,
|
|
{"tools": {"mcpServers": {"fooBar": {"enabled": True, "command": "a"}, "foo_bar": {"enabled": True}}}},
|
|
)
|
|
|
|
assert surface.write_value("tools.mcpServers.foo_bar.enabled", False) is True
|
|
|
|
data = json.loads(path.read_text(encoding="utf-8"))
|
|
assert data["tools"]["mcpServers"]["fooBar"] == {"enabled": True, "command": "a"}
|
|
assert data["tools"]["mcpServers"]["foo_bar"] == {"enabled": False}
|
|
assert mcp_server_configs(LiveConfig(path))["fooBar"].enabled is True
|
|
|
|
|
|
def test_a_schema_segment_keeps_its_spelling_tolerance(tmp_path, monkeypatch):
|
|
"""The rule is per segment, not per file: a field is still read either way.
|
|
|
|
``tools.mcp_servers`` is the snake_case name of a declared field, so a path
|
|
spelling it that way reads the same block -- the exactness above is for the
|
|
segment standing in for a map entry, and applying it to every segment would
|
|
have stopped this working.
|
|
"""
|
|
path = _home(tmp_path, monkeypatch, {"tools": {"mcpServers": {"fooBar": {"enabled": True}}}})
|
|
assert surface.lookup(surface.read_raw(path), "tools.mcp_servers.fooBar.enabled") == (True, True)
|
|
assert surface.write_value("tools.mcp_servers.fooBar.enabled", False) is True
|
|
data = json.loads(path.read_text(encoding="utf-8"))
|
|
assert data["tools"]["mcpServers"]["fooBar"]["enabled"] is False
|
|
|
|
|
|
def test_a_provider_segment_still_folds_its_spellings(tmp_path, monkeypatch):
|
|
"""``providers.<name>`` is the one map the runtime itself matches loosely.
|
|
|
|
``ProvidersConfig.get`` folds a name through ``names_same_provider``, so a
|
|
section filed as ``jina`` answers a lookup for ``Jina``. Exactness there
|
|
would be a second rule for one map, and the wrong one: the section the
|
|
runtime reads is the section the write has to update.
|
|
"""
|
|
path = _home(tmp_path, monkeypatch, {"providers": {"jina": {"apiBase": "https://a"}}})
|
|
assert surface.lookup(surface.read_raw(path), "providers.Jina.apiBase") == (True, "https://a")
|
|
assert surface.write_value("providers.jina.apiBase", "https://b") == "https://a"
|
|
assert surface.write_value("providers.Jina.apiKey", "k") is None
|
|
data = json.loads(path.read_text(encoding="utf-8"))
|
|
assert data["providers"] == {"jina": {"apiBase": "https://b", "apiKey": "k"}}
|