Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions sdk/src/unplug/config/guard.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
160 changes: 143 additions & 17 deletions sdk/src/unplug/config/loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand All @@ -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}
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
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]:
Expand Down Expand Up @@ -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}
Expand All @@ -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()
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
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:
Expand Down
Loading