The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(policy_engine): ignore inapplicable non-default attachments when selecting defaults
yuchengef55eb6bdf0c
diff --git a/litellm/proxy/litellm_pre_call_utils.py b/litellm/proxy/litellm_pre_call_utils.pyindex 9a973755894..8aa861e574f 100644--- a/litellm/proxy/litellm_pre_call_utils.py+++ b/litellm/proxy/litellm_pre_call_utils.py@@ -3216,7 +3216,9 @@ def _match_and_track_policies(attachment_registry: Final = (attachment_registry_override if attachment_registry_override is not None else get_attachment_registry())- matches_with_reasons: Final = attachment_registry.get_attached_policies_with_reasons(context)+ matches_with_reasons: Final = attachment_registry.get_attached_policies_with_reasons(+ context, PolicyMatcher.policy_applies(context, policies_override)+ )matching_policy_names: Final = [m["policy_name"] for m in matches_with_reasons]policy_reasons: Final = {m["policy_name"]: m["matched_via"] for m in matches_with_reasons}diff --git a/litellm/proxy/policy_engine/attachment_registry.py b/litellm/proxy/policy_engine/attachment_registry.pyindex 04009151487..d81471b3c1a 100644--- a/litellm/proxy/policy_engine/attachment_registry.py+++ b/litellm/proxy/policy_engine/attachment_registry.py@@ -5,6 +5,7 @@ Attachments define WHERE policies apply, separate from the policy definitions.This allows the same policy to be attached to multiple scopes."""+from collections.abc import Callablefrom datetime import datetime, timezonefrom types import MappingProxyTypefrom typing import TYPE_CHECKING, Any, Final, TypedDict@@ -122,24 +123,34 @@ class AttachmentRegistry:default=attachment_data.get("default", False),)- def get_attached_policies(self, context: PolicyMatchContext) -> list[str]:+ def get_attached_policies(+ self,+ context: PolicyMatchContext,+ policy_applies: Callable[[str], bool] | None = None,+ ) -> list[str]:"""Get list of policy names attached to the given context.Args:context: The request context to match against+ policy_applies: Optional predicate; attachments whose policy does not apply are ignoredReturns:List of policy names that are attached to matching scopes"""- return [r["policy_name"] for r in self.get_attached_policies_with_reasons(context)]+ return [r["policy_name"] for r in self.get_attached_policies_with_reasons(context, policy_applies)]- def get_attached_policies_with_reasons(self, context: PolicyMatchContext) -> list[PolicyAttachmentMatch]:+ def get_attached_policies_with_reasons(+ self,+ context: PolicyMatchContext,+ policy_applies: Callable[[str], bool] | None = None,+ ) -> list[PolicyAttachmentMatch]:"""Get list of policy names and match reasons for the given context.Returns a list of dicts with 'policy_name' and 'matched_via' keys.The 'matched_via' describes which dimension caused the match.+ Attachments whose policy fails `policy_applies` are dropped before defaults are considered."""from litellm.proxy.policy_engine.policy_matcher import PolicyMatcher@@ -147,6 +158,7 @@ class AttachmentRegistry:attachmentfor attachment in self._attachmentsif PolicyMatcher.scope_matches(scope=attachment.to_policy_scope(), context=context)+ and (policy_applies is None or policy_applies(attachment.policy)))non_default: Final = tuple(attachment for attachment in in_scope if not attachment.default)matching_attachments: Final = sorted(diff --git a/litellm/proxy/policy_engine/policy_matcher.py b/litellm/proxy/policy_engine/policy_matcher.pyindex 001e4115374..2f7fcd23b75 100644--- a/litellm/proxy/policy_engine/policy_matcher.py+++ b/litellm/proxy/policy_engine/policy_matcher.py@@ -7,6 +7,7 @@ apply to a given request based on team alias, key alias, and model.Policies are matched via policy_attachments which define WHERE each policy applies."""+from collections.abc import Callablefrom typing import Finalfrom litellm._logging import verbose_proxy_logger@@ -130,6 +131,20 @@ class PolicyMatcher:"""return PolicyMatcher.get_matching_policies(context=context)+ @staticmethod+ def policy_applies(+ context: PolicyMatchContext,+ policies: dict[str, Policy] | None = None,+ ) -> Callable[[str], bool]:+ """Predicate telling whether a policy exists and its condition matches the context."""+ return lambda policy_name: bool(+ PolicyMatcher.get_policies_with_matching_conditions(+ policy_names=[policy_name], # mutable-ok: the matcher takes a list+ context=context,+ policies=policies,+ )+ )+@staticmethoddef get_policies_with_matching_conditions(policy_names: list[str],diff --git a/litellm/proxy/policy_engine/policy_resolve_endpoints.py b/litellm/proxy/policy_engine/policy_resolve_endpoints.pyindex a8a9856b833..898e42635c5 100644--- a/litellm/proxy/policy_engine/policy_resolve_endpoints.py+++ b/litellm/proxy/policy_engine/policy_resolve_endpoints.py@@ -265,7 +265,9 @@ async def resolve_policies_for_context()# Get matching policies with reasons- match_results: Final = get_attachment_registry().get_attached_policies_with_reasons(context=context)+ match_results: Final = get_attachment_registry().get_attached_policies_with_reasons(+ context=context, policy_applies=PolicyMatcher.policy_applies(context)+ )if not match_results:return PolicyResolveResponse(diff --git a/litellm/proxy/policy_engine/response_retrieval.py b/litellm/proxy/policy_engine/response_retrieval.pyindex d284c44397e..0f373b08056 100644--- a/litellm/proxy/policy_engine/response_retrieval.py+++ b/litellm/proxy/policy_engine/response_retrieval.py@@ -84,7 +84,9 @@ def _retrieval_context(def _post_call_pipelines_for_context(context: PolicyMatchContext) -> tuple[PolicyPipelines, Mapping[str, str]]:- matches: Final = get_attachment_registry().get_attached_policies_with_reasons(context)+ matches: Final = get_attachment_registry().get_attached_policies_with_reasons(+ context, PolicyMatcher.policy_applies(context)+ )if not matches:return (), MappingProxyType({})applied_policy_names: Final = PolicyMatcher.get_policies_with_matching_conditions(diff --git a/tests/test_litellm/proxy/policy_engine/test_attachment_registry.py b/tests/test_litellm/proxy/policy_engine/test_attachment_registry.pyindex b419f3db060..faa8d67fe3a 100644--- a/tests/test_litellm/proxy/policy_engine/test_attachment_registry.py+++ b/tests/test_litellm/proxy/policy_engine/test_attachment_registry.py@@ -14,7 +14,8 @@ from litellm.proxy.policy_engine.attachment_registry import (AttachmentRegistry,get_attachment_registry,)-from litellm.types.proxy.policy_engine import PolicyMatchContext+from litellm.proxy.policy_engine.policy_matcher import PolicyMatcher+from litellm.types.proxy.policy_engine import Policy, PolicyCondition, PolicyGuardrails, PolicyMatchContextclass TestGetAttachedPolicies:@@ -561,6 +562,38 @@ class TestDefaultAttachments:assert results == [{"policy_name": "guardrail-y", "matched_via": "default:scope:*"}]+ def test_inapplicable_opt_in_policy_does_not_suppress_default(self):+ context = PolicyMatchContext(team_alias="t", key_alias="k", model="gpt-5.2", tags=["opt-in"])+ policies = {+ "guardrail-y": Policy(guardrails=PolicyGuardrails(add=["y"])),+ "guardrail-x": Policy(guardrails=PolicyGuardrails(add=["x"]), condition=PolicyCondition(model="claude.*")),+ }++ results = self._registry().get_attached_policies_with_reasons(+ context, PolicyMatcher.policy_applies(context, policies)+ )++ assert results == [{"policy_name": "guardrail-y", "matched_via": "default:scope:*"}]++ def test_attachment_to_missing_policy_does_not_suppress_default(self):+ context = PolicyMatchContext(team_alias="t", key_alias="k", model="gpt-5.2", tags=["opt-in"])+ policies = {"guardrail-y": Policy(guardrails=PolicyGuardrails(add=["y"]))}++ assert self._registry().get_attached_policies(context, PolicyMatcher.policy_applies(context, policies)) == [+ "guardrail-y"+ ]++ def test_applicable_opt_in_policy_still_wins_with_predicate(self):+ context = PolicyMatchContext(team_alias="t", key_alias="k", model="gpt-5.2", tags=["opt-in"])+ policies = {+ "guardrail-y": Policy(guardrails=PolicyGuardrails(add=["y"])),+ "guardrail-x": Policy(guardrails=PolicyGuardrails(add=["x"]), condition=PolicyCondition(model="gpt.*")),+ }++ assert self._registry().get_attached_policies(context, PolicyMatcher.policy_applies(context, policies)) == [+ "guardrail-x"+ ]+def test_default_defaults_to_false_when_omitted(self):registry = AttachmentRegistry()registry.load_attachments([{"policy": "p"}])diff --git a/ui/litellm-dashboard/src/app/(dashboard)/policies/_components/add_attachment_form.tsx b/ui/litellm-dashboard/src/app/(dashboard)/policies/_components/add_attachment_form.tsxindex 74c4978392f..5cd240a0838 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/policies/_components/add_attachment_form.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/policies/_components/add_attachment_form.tsx@@ -473,7 +473,7 @@ const AddAttachmentForm: React.FC<AddAttachmentFormProps> = ({</FormField></FieldGroup>- {impactResult && <ImpactPreviewAlert impactResult={impactResult} />}+ {impactResult && <ImpactPreviewAlert impactResult={impactResult} isDefault={form.watch("default")} />}<div className="flex justify-end space-x-2 mt-4"><Button type="button" variant="secondary" onClick={handleClose}>diff --git a/ui/litellm-dashboard/src/app/(dashboard)/policies/_components/impact_preview_alert.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/policies/_components/impact_preview_alert.test.tsxindex 6c405d7492a..6074508b52b 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/policies/_components/impact_preview_alert.test.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/policies/_components/impact_preview_alert.test.tsx@@ -69,6 +69,17 @@ describe("ImpactPreviewAlert", () => {expect(screen.getByText(/1 key\b/i)).toBeInTheDocument();});+ it("should present the counts as an upper bound for a default attachment", () => {+ renderWithProviders(<ImpactPreviewAlert impactResult={specificImpact} isDefault />);+ expect(screen.getByText(/would affect up to/i)).toBeInTheDocument();+ expect(screen.getByText(/no non-default attachment matches/i)).toBeInTheDocument();+ });++ it("should not qualify the counts for a non-default attachment", () => {+ renderWithProviders(<ImpactPreviewAlert impactResult={specificImpact} />);+ expect(screen.queryByText(/up to/i)).not.toBeInTheDocument();+ });+it("should not show a key section when there are no sample keys", () => {const noKeys = { affected_keys_count: 0, affected_teams_count: 2, sample_keys: [], sample_teams: ["t1", "t2"] };renderWithProviders(<ImpactPreviewAlert impactResult={noKeys} />);diff --git a/ui/litellm-dashboard/src/app/(dashboard)/policies/_components/impact_preview_alert.tsx b/ui/litellm-dashboard/src/app/(dashboard)/policies/_components/impact_preview_alert.tsxindex a9264eb9d0d..df8a6987d6f 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/policies/_components/impact_preview_alert.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/policies/_components/impact_preview_alert.tsx@@ -12,6 +12,7 @@ interface ImpactResult {interface ImpactPreviewAlertProps {impactResult: ImpactResult;+ isDefault?: boolean;}interface SampleListProps {@@ -32,8 +33,9 @@ const SampleList: React.FC<SampleListProps> = ({ label, samples, totalCount }) =</div>);-const ImpactPreviewAlert: React.FC<ImpactPreviewAlertProps> = ({ impactResult }) => {+const ImpactPreviewAlert: React.FC<ImpactPreviewAlertProps> = ({ impactResult, isDefault = false }) => {const isGlobal = impactResult.affected_keys_count === -1;+ const qualifier = isDefault ? "up to " : "";return (<Alert className="mb-4">@@ -47,7 +49,7 @@ const ImpactPreviewAlert: React.FC<ImpactPreviewAlertProps> = ({ impactResult })) : (<div><span>- This attachment would affect{" "}+ This attachment would affect {qualifier}<strong>{impactResult.affected_keys_count} key{impactResult.affected_keys_count !== 1 ? "s" : ""}</strong>{" "}@@ -57,6 +59,11 @@ const ImpactPreviewAlert: React.FC<ImpactPreviewAlertProps> = ({ impactResult })</strong>.</span>+ {isDefault && (+ <div className="text-xs text-muted-foreground">+ Default attachments only apply to requests no non-default attachment matches, so fewer may be affected.+ </div>+ )}{impactResult.sample_keys.length > 0 && (<SampleListlabel="Keys"