diff --git a/sdk/src/unplug/config/guard.py b/sdk/src/unplug/config/guard.py index cee350b..c7e7e74 100644 --- a/sdk/src/unplug/config/guard.py +++ b/sdk/src/unplug/config/guard.py @@ -54,9 +54,11 @@ class ThresholdConfig(BaseModel): model_config = {"frozen": True} - block: float = 0.8 - redact: float = 0.5 - review: float = 0.3 + # Ranges match ScanPolicy's. Without them a block of 5.0 loaded happily and + # then no score could ever reach it, so the pipeline allowed everything. + block: float = Field(default=0.8, ge=0.0, le=1.0) + redact: float = Field(default=0.5, ge=0.0, le=1.0) + review: float = Field(default=0.3, ge=0.0, le=1.0) class ScannerConfig(BaseModel): diff --git a/sdk/src/unplug/config/loader.py b/sdk/src/unplug/config/loader.py index ebcfa44..85cbbdc 100644 --- a/sdk/src/unplug/config/loader.py +++ b/sdk/src/unplug/config/loader.py @@ -178,19 +178,24 @@ def _build_pipeline(data: dict[str, Any]) -> PipelineConfig: **{k: v for k, v in ml_gate_data.items() if k in MlGateConfig.model_fields} ) pipeline = PipelineConfig(**kwargs) - if "thresholds" in data: + if "thresholds" in data and "policy" not in data: + # Only when this table did not name a policy of its own: an explicit + # [pipeline.policy] is the more specific statement and used to be + # silently overwritten here. + # + # Constructed, not `model_copy(update=...)`. model_copy writes the value + # in unchecked, which is how a block of 5.0 reached pipeline.policy and + # made every score decide ALLOW. t = pipeline.thresholds - pipeline = pipeline.model_copy( - update={ - "policy": pipeline.policy.model_copy( - update={ - "block_threshold": t.block, - "redact_threshold": t.redact, - "review_threshold": t.review, - } - ) + policy = ScanPolicy( + **{ + **pipeline.policy.model_dump(), + "block_threshold": t.block, + "redact_threshold": t.redact, + "review_threshold": t.review, } ) + pipeline = pipeline.model_copy(update={"policy": policy}) return pipeline @@ -203,11 +208,36 @@ def _build_messages(data: dict[str, Any]) -> MessageConfig: def _build_scanner_configs(data: dict[str, Any]) -> dict[str, ScannerConfig]: - return { - name: ScannerConfig(**{k: v for k, v in cfg.items() if k in ScannerConfig.model_fields}) - for name, cfg in data.items() - if isinstance(cfg, dict) - } + """Per-scanner overrides, applied on top of the bundled defaults. + + `data/defaults/scanners.toml` describes itself as something you override per + key, so a table naming one field has to leave the rest of that scanner alone. + Building a fresh `ScannerConfig` from the subset dropped every unnamed field + to the pydantic class default instead, which moved `secrets` from 0.99 to + 0.85 and turned `injection` normalization off for anyone who set only + `base_score`. Both silent, both in the weakening direction. + + A scanner with no bundled entry keeps the old behaviour, since there is + nothing to merge onto. + """ + from unplug.data.maps_loader import default_scanner_config + + out: dict[str, ScannerConfig] = {} + for name, cfg in data.items(): + if not isinstance(cfg, dict): + continue + overrides = {k: v for k, v in cfg.items() if k in ScannerConfig.model_fields} + try: + base = default_scanner_config(name) + except KeyError: + out[name] = ScannerConfig(**overrides) + continue + # Constructed, not `model_copy(update=...)`: model_copy writes the value + # straight in, so a mistyped or out-of-range override would land as a + # scan-time error instead of a config error. Merging the dumped defaults + # keeps the bundled values while every field still goes through pydantic. + out[name] = ScannerConfig(**{**base.model_dump(), **overrides}) + return out def _build_models(data: dict[str, Any]) -> dict[str, Any]: @@ -281,8 +311,45 @@ def build_config(data: dict[str, Any]) -> GuardConfig: kwargs["server_url"] = guard_data["server_url"] if "server_api_key" in guard_data: kwargs["server_api_key"] = guard_data["server_api_key"] - if "policy" in guard_data: - kwargs["policy"] = _build_policy(guard_data["policy"]) + + # Top-level fallback, as `pipeline`, `limits`, `messages`, `tools` and + # `boundaries` all already have. `unplug.example.toml` ships `[policy]` at + # top level, so without this the whole block is dead for anyone who copied + # the example: thresholds, abstain, decision mode and the sensitive-context + # switches all silently keep their defaults. + # Merged per key rather than whole-table, so a partial [guard.policy] does + # not discard a top-level [policy] that names different settings. [guard] + # wins wherever both name the same key, since it is the more specific place + # to say it and it is what Guard already honoured. + def _policy_table(source: dict[str, Any], label: str) -> dict[str, Any]: + # Present but not a table is a mistake, not an absence. Treating it as {} + # boots a Guard on default thresholds when the operator thought they had + # set them, which is the fail-open version of the bug this whole change + # is about. On dev this raised, and it should keep raising. + if label not in source: + return {} + value = source[label] + if not isinstance(value, dict): + msg = f"[{label}] must be a table, got {type(value).__name__}" + raise ConfigError(msg) + return value + + # Precedence, least to most specific: [pipeline.policy], [policy], [guard.policy]. + # [pipeline.thresholds] is folded in further down and fills only what none of + # these named. + _pipeline_table = guard_data.get("pipeline", data.get("pipeline", {})) + pipeline_policy = ( + _policy_table(_pipeline_table, "policy") if isinstance(_pipeline_table, dict) else {} + ) + top_policy = _policy_table(data, "policy") + guard_policy = _policy_table(guard_data, "policy") + policy_data: dict[str, Any] = { + **(pipeline_policy or {}), + **(top_policy or {}), + **(guard_policy or {}), + } + if policy_data: + kwargs["policy"] = _build_policy(policy_data) if "cache" in guard_data: kwargs["cache"] = CacheConfig( **{k: v for k, v in guard_data["cache"].items() if k in CacheConfig.model_fields} @@ -295,6 +362,65 @@ def build_config(data: dict[str, Any]) -> GuardConfig: pipeline_data = guard_data.get("pipeline", data.get("pipeline", {})) if pipeline_data: kwargs["pipeline"] = _build_pipeline(pipeline_data) + # `_build_pipeline` folds `[pipeline.thresholds]` into `pipeline.policy`, + # and nothing scans with that policy: `Guard` builds every request policy + # from the guard-level one, and `BasePipeline._resolve_policy` prefers the + # context policy over `self._config.policy`. A pipeline run without a + # context is the only path that saw the thresholds, and the public API + # never takes it, so the same file gave `Guard.scan` and `Pipeline.run` + # two different actions for one input. + # + # Folding them into the guard policy as well makes one policy govern. + # `[policy]` wins on any key it names, since it is the more specific + # place to say it and it is what `Guard` already honoured. + thresholds = pipeline_data.get("thresholds") + if isinstance(thresholds, dict): + named = { + field: thresholds[key] + for key, field in ( + ("block", "block_threshold"), + ("redact", "redact_threshold"), + ("review", "review_threshold"), + ) + if key in thresholds + } + explicit = policy_data if isinstance(policy_data, dict) else {} + named = {k: v for k, v in named.items() if k not in explicit} + if named: + # Same reason as the scanner overrides above: these values come + # straight out of the raw TOML, and block/redact/review are + # declared ge=0.0 le=1.0. `model_copy` would install a string or + # a 5.0 unchecked. + base = kwargs.get("policy") or ScanPolicy() + kwargs["policy"] = ScanPolicy(**{**base.model_dump(), **named}) + + # One file must not produce two block bars. Folding the thresholds up into the + # guard policy fixed the direction Guard.scan reads, but left pipeline.policy + # and pipeline.thresholds holding whatever [pipeline] said, so [policy] + # block_threshold = 0.9 next to [pipeline.thresholds] block = 0.2 gave + # Guard.scan REDACT, a bare Pipeline.run BLOCK, and the ML gate a gray_high of + # 0.2. Push the resolved policy back down so all three agree. + # + # Outside the [pipeline] branch on purpose: a file with [policy] and no + # [pipeline] table at all still has to reconcile, and running this only when + # [pipeline] was present left exactly that case split. + # + # This does not take away the independent ML cutoff. The only consumer of + # pipeline.thresholds is the gate's fallback block threshold, and + # pipeline.ml_gate.gray_high still overrides it. + resolved_policy = kwargs.get("policy") + if resolved_policy is not None: + built = kwargs.get("pipeline") or PipelineConfig() + kwargs["pipeline"] = built.model_copy( + update={ + "policy": resolved_policy, + "thresholds": ThresholdConfig( + block=resolved_policy.block_threshold, + redact=resolved_policy.redact_threshold, + review=resolved_policy.review_threshold, + ), + } + ) scanner_data = guard_data.get("scanners_config", data.get("scanners_config", {})) if not scanner_data: diff --git a/sdk/tests/unit/config/test_config_loader.py b/sdk/tests/unit/config/test_config_loader.py index e33430f..801aea8 100644 --- a/sdk/tests/unit/config/test_config_loader.py +++ b/sdk/tests/unit/config/test_config_loader.py @@ -285,6 +285,233 @@ def test_messages_from_toml(self, tmp_path: Path) -> None: assert "Custom block" in cfg.messages.blocked_template +class TestDeadConfigSurfaces: + """#169: three surfaces that parsed without error and then did nothing.""" + + def test_top_level_policy_applies_alongside_a_guard_table(self) -> None: + # unplug.example.toml ships [guard] and [policy] as siblings, so before + # this the whole block was dead for anyone who copied the example. + cfg = build_config( + { + "guard": {"mode": "local"}, + "policy": {"block_threshold": 0.1, "sensitive_context_enabled": False}, + } + ) + assert cfg.policy.block_threshold == 0.1 + assert cfg.policy.sensitive_context_enabled is False + + def test_guard_policy_still_wins_over_top_level(self) -> None: + cfg = build_config( + { + "guard": {"policy": {"block_threshold": 0.2}}, + "policy": {"block_threshold": 0.7}, + } + ) + assert cfg.policy.block_threshold == 0.2 + + def test_pipeline_thresholds_reach_the_guard_policy(self) -> None: + # Guard builds every request policy from the guard-level one, so + # thresholds that only landed on pipeline.policy never scanned. + cfg = build_config( + {"pipeline": {"thresholds": {"block": 0.2, "redact": 0.15, "review": 0.1}}} + ) + assert cfg.policy.block_threshold == 0.2 + assert cfg.policy.redact_threshold == 0.15 + assert cfg.policy.review_threshold == 0.1 + assert cfg.pipeline.policy.block_threshold == 0.2 + + def test_explicit_policy_beats_pipeline_thresholds(self) -> None: + cfg = build_config( + { + "policy": {"block_threshold": 0.9}, + "pipeline": {"thresholds": {"block": 0.2, "review": 0.1}}, + } + ) + assert cfg.policy.block_threshold == 0.9 + assert cfg.policy.review_threshold == 0.1 + + def test_thresholds_left_alone_when_nothing_names_them(self) -> None: + cfg = build_config({}) + assert cfg.policy.block_threshold == 0.8 + assert cfg.policy.redact_threshold == 0.5 + assert cfg.policy.review_threshold == 0.3 + + def test_partial_scanner_override_keeps_the_bundled_rest(self) -> None: + # Setting one field used to reset the others to the pydantic class + # defaults, which moved secrets from 0.99 to 0.85 and turned injection + # normalization off. Both silent, both weakening. + from unplug.data.maps_loader import default_scanner_config + + cfg = build_config( + { + "guard": { + "scanners_config": { + "injection": {"base_score": 0.9}, + "secrets": {"enabled": True}, + } + } + } + ) + assert cfg.scanner_configs["injection"].base_score == 0.9 + assert cfg.scanner_configs["injection"].normalize is True + assert ( + cfg.scanner_configs["secrets"].base_score + == default_scanner_config("secrets").base_score + ) + + def test_scanner_with_no_bundled_default_still_builds(self) -> None: + cfg = build_config({"guard": {"scanners_config": {"nosuch": {"base_score": 0.5}}}}) + assert cfg.scanner_configs["nosuch"].base_score == 0.5 + + def test_both_policy_tables_merge_per_key(self) -> None: + # A partial [guard.policy] must not discard a top-level [policy] that + # names different settings. + cfg = build_config( + { + "guard": {"policy": {"block_threshold": 0.2}}, + "policy": {"sensitive_context_enabled": False}, + } + ) + assert cfg.policy.block_threshold == 0.2 + assert cfg.policy.sensitive_context_enabled is False + + def test_scanner_override_is_still_validated(self) -> None: + # Merging onto the bundled defaults must not cost the config-time error. + import pydantic + + with pytest.raises(pydantic.ValidationError): + build_config({"guard": {"scanners_config": {"injection": {"base_score": "high"}}}}) + + def test_out_of_range_threshold_is_rejected(self) -> None: + import pydantic + + with pytest.raises(pydantic.ValidationError): + build_config({"pipeline": {"thresholds": {"block": 5.0}}}) + + def test_string_threshold_is_coerced(self) -> None: + cfg = build_config({"pipeline": {"thresholds": {"block": "0.2"}}}) + assert cfg.policy.block_threshold == 0.2 + + +class TestOnePolicyGoverns: + """One file must not produce two different block bars.""" + + def test_policy_and_pipeline_thresholds_resolve_to_one_value(self) -> None: + cfg = build_config( + { + "policy": {"block_threshold": 0.9}, + "pipeline": {"thresholds": {"block": 0.2}}, + } + ) + # [policy] is the more specific statement and wins. Before this, Guard.scan + # decided on 0.9, a bare Pipeline.run decided on 0.2, and the ML gate read + # 0.2 as its gray_high, all from the same file. + assert cfg.policy.block_threshold == 0.9 + assert cfg.pipeline.policy.block_threshold == 0.9 + assert cfg.pipeline.thresholds.block == 0.9 + + def test_guard_policy_also_governs_the_pipeline(self) -> None: + cfg = build_config( + { + "guard": {"policy": {"block_threshold": 0.7}}, + "pipeline": {"thresholds": {"block": 0.3}}, + } + ) + assert cfg.pipeline.policy.block_threshold == 0.7 + assert cfg.pipeline.thresholds.block == 0.7 + + def test_thresholds_alone_still_drive_both(self) -> None: + cfg = build_config({"pipeline": {"thresholds": {"block": 0.2}}}) + assert cfg.policy.block_threshold == 0.2 + assert cfg.pipeline.policy.block_threshold == 0.2 + + def test_an_explicit_pipeline_policy_is_not_overwritten_by_thresholds(self) -> None: + cfg = build_config( + {"pipeline": {"policy": {"block_threshold": 0.6}, "thresholds": {"block": 0.2}}} + ) + assert cfg.pipeline.policy.block_threshold == 0.6 + + +class TestPolicyTablesFailClosed: + def test_a_non_table_policy_raises(self) -> None: + from unplug.exceptions import ConfigError + + with pytest.raises(ConfigError, match=r"\[policy\] must be a table"): + build_config({"policy": "strict"}) + + def test_a_non_table_guard_policy_raises(self) -> None: + from unplug.exceptions import ConfigError + + with pytest.raises(ConfigError, match=r"\[policy\] must be a table"): + build_config({"guard": {"policy": "strict"}}) + + def test_out_of_range_threshold_is_rejected_even_when_policy_shadows_it(self) -> None: + """The shadowed value still reached pipeline.thresholds unchecked.""" + from pydantic import ValidationError + + with pytest.raises(ValidationError): + build_config( + { + "policy": {"block_threshold": 0.8}, + "pipeline": {"thresholds": {"block": 5.0}}, + } + ) + + +class TestEveryPolicySourceCombination: + """All 16 combinations of the four sources must agree on one block bar. + + The push-down originally ran only inside the `[pipeline]` branch, so a file + with `[policy]` and no `[pipeline]` table left cfg.policy at the configured + value while the pipeline kept the default. Three of these sixteen failed. + """ + + @staticmethod + def _build(pipeline_policy: bool, top: bool, guard: bool, thresholds: bool): + data: dict = {} + if pipeline_policy: + data.setdefault("pipeline", {})["policy"] = {"block_threshold": 0.1} + if thresholds: + data.setdefault("pipeline", {})["thresholds"] = {"block": 0.4} + if top: + data["policy"] = {"block_threshold": 0.2} + if guard: + data.setdefault("guard", {})["policy"] = {"block_threshold": 0.3} + return build_config(data) + + @pytest.mark.parametrize("pipeline_policy", [False, True]) + @pytest.mark.parametrize("top", [False, True]) + @pytest.mark.parametrize("guard", [False, True]) + @pytest.mark.parametrize("thresholds", [False, True]) + def test_all_three_layers_agree( + self, pipeline_policy: bool, top: bool, guard: bool, thresholds: bool + ) -> None: + cfg = self._build(pipeline_policy, top, guard, thresholds) + assert ( + cfg.policy.block_threshold + == cfg.pipeline.policy.block_threshold + == cfg.pipeline.thresholds.block + ) + + def test_the_most_specific_source_wins(self) -> None: + # guard.policy > policy > pipeline.policy > pipeline.thresholds + assert self._build(True, True, True, True).policy.block_threshold == 0.3 + assert self._build(True, True, False, True).policy.block_threshold == 0.2 + assert self._build(True, False, False, True).policy.block_threshold == 0.1 + assert self._build(False, False, False, True).policy.block_threshold == 0.4 + + def test_the_ml_gate_can_still_differ_from_the_block_bar(self) -> None: + """Forcing thresholds to the policy must not remove the gray_high knob.""" + cfg = build_config( + { + "policy": {"block_threshold": 0.9}, + "pipeline": {"ml_gate": {"gray_high": 0.7}}, + } + ) + assert cfg.pipeline.thresholds.block == 0.9 + assert cfg.pipeline.ml_gate.gray_high == 0.7 + + class TestFlatEnvWithGuardTable: """Flat UNPLUG_* vars must survive a config file that has a [guard] table (#168)."""