Repository navigation
test(integration): cover guardrails_policies endpoint contracts - #44722
Conversation
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
|
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
bugbot run |
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
bugbot run |
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
Devin seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account. You have signed the CLA already but the status is still pending? Let us recheck it. |
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
| assert tuple(response.status_code for response in plain_responses) == (401, 401, 401, 401), tuple( | ||
| response.text for response in plain_responses | ||
| ) | ||
| expected_routes: Final = tuple( | ||
| f"/guardrails/submissions/{guardrail_id}/{action}" for action in ("approve", "reject", "approve", "reject") | ||
| ) | ||
| expected_user_ids: Final = (team_admin, team_admin, member, member) | ||
| expected_plain_errors: Final = tuple( | ||
| _ErrorResponse( | ||
| error=_ProxyError( | ||
| message=( | ||
| "Authentication Error, Only proxy admin can be used to generate, delete, update info for " | ||
| f"new keys/users/teams. Route={route}. Your role=internal_user. " | ||
| f"Your user_id={_mask_user_id(user_id)}" | ||
| ), | ||
| type="auth_error", | ||
| param="None", | ||
| code="401", | ||
| ) | ||
| ) | ||
| for route, user_id in zip(expected_routes, expected_user_ids, strict=True) | ||
| ) | ||
| parsed_plain_errors: Final = tuple( | ||
| _ErrorResponse.model_validate_json(response.content) for response in plain_responses | ||
| ) | ||
| assert parsed_plain_errors == expected_plain_errors, tuple(response.text for response in plain_responses) |
There was a problem hiding this comment.
For plain team-admin and member keys, this test now requires the route check’s 401 response and exact error text. The adjacent skipped test says these approve/reject requests should return 403. When authorization is fixed to return that intended 403, this live test will fail and block the fix.
There was a problem hiding this comment.
Fixed in 258f613: plain keys now pass on either the current route-layer 401 body or the intended handler 403, and the BUG skip keeps the 403 contract
| assert matched.headers.get("x-litellm-applied-policies") == ",".join(expected_order), matched.text | ||
| matched_model_guardrail_requests: Final = model_guardrail.drain() | ||
| matched_global_guardrail_requests: Final = global_guardrail.drain() | ||
| assert len(matched_model_guardrail_requests) == 1 | ||
| assert len(matched_global_guardrail_requests) == 1 | ||
| _assert_guardrail_request(matched_model_guardrail_requests[0], _PROMPT, model, key, response=matched) | ||
| _assert_guardrail_request(matched_global_guardrail_requests[0], _PROMPT, model, key, response=matched) |
There was a problem hiding this comment.
Priority execution goes unchecked
The header shows policy order, but it is recorded separately from guardrail execution. Both guardrails return NONE, and draining each server only shows that it ran once. The test could therefore pass if the guardrails run in the wrong priority order, leaving that part of the contract unprotected.
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
There was a problem hiding this comment.
Execution order is not a contract here: policy_resolver.py unions every matched policy guardrail into a set, so priority only orders the applied-policy list this header pins
There was a problem hiding this comment.
You’re right — thanks for the clarification. Since policy_resolver.py unions matched guardrails into a set, execution order is not part of the contract; priority only determines the x-litellm-applied-policies ordering, which this test already verifies. The separate drains correctly assert that each matched guardrail ran, so this is not a valid finding.
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…racts_guardrails_policies
|
bugbot run |
… tag scope Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
@litereview code-review |
|
bugbot run |
✅ code-review5/5 · Ready for human reviewScope: full · Full PR review. Completed · Some checks not run. No correctness findings. This PR only adds integration tests under Checks and execution details
View review · Reviewed |
…racts_guardrails_policies
…n merge Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
@litereview code-review |
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 42c7ba6. Configure here.
TLDR
Problem this solves:
policiesstripping before the provider was never asserted, streaming or notHow it solves it:
litellm/, then revertedlitellm/orenterprise/is modifiedUser Flow
Before: an admin attaches a policy or a team submits a guardrail, and nothing pins what happens to live traffic
models: [M]After: each of these flows is pinned by an integration test that reads what the upstream, the guardrail and Postgres actually received
metadata.tags, thex-litellm-tagsheader, top-leveltags, the key or the team) or*, two matching attachments both apply in explicit priority order, leaves model N untouched, and a blocking guardrail stops the call before the provider. Adefault: trueattachment applies only when no other attachment matches"policies": ["p"]sent through the OpenAI SDKextra_body, streaming or not, and a publishedpolicy_<id>after a resync, run the policy's guardrail, setx-litellm-applied-policies, and never reach the provider bodypending_reviewCoverage
A policy attachment created through POST /policies/attachments goes live on the serving worker without a restart, and the test checks the attachment readback and the
LiteLLM_PolicyAttachmentTablerow for each scope spelling, includingtagsmatched from requestmetadata.tags, thex-litellm-tagsheader and top-leveltags, from a key created withmetadata.tags, and from a team created withmetadata.tagswith no request tags, anddefault: true. When a global attachment and a model attachment both match, both guardrails get the prompt andx-litellm-applied-policieslists both policies in explicit priority order, checked with the priorities in both directions, while another model gets only the global policy. The streaming spelling (stream=Truethrough the OpenAI SDK) is covered for a model attachment and for request-bodypolicies: the guardrail gets the prompt, the streamed response carriesx-litellm-applied-policies, and the provider body is exactlymodel,messages,streamandstream_optionswith nopolicieskey. When the attached guardrail replies BLOCKED the client gets a 400 naming the reason and the provider receives nothing. Ageneric_guardrail_apiguardrail created through POST /guardrails stores its api_key encrypted, comes back masked from/guardrails/{id}and/guardrails/{id}/info, is absent from/v2/guardrails/list, and reaches only the guardrail'sx-api-keyheader. Team guardrail submissions stay inactive until an admin approves them, stay inactive after rejection, are listed only to their own team, and fall back to the key's team whenteam_idis omitted. A team admin or internal user whose key is scoped to/guardrails/submissionsreaches the handler and gets 403Admin access requiredon approve and reject, with the row stillpending_review, and the same team admin and member with plain keys are refused on all four actions with one of exactly two whole parsed bodies: today's 401Only proxy adminroute-check error naming the route, role and masked user id, or the intended 403Admin access required, so the fix for the BUG below does not break this live test. Both apply_guardrail aliases mask identically for the master key asAuthorization: Bearerandx-litellm-api-key, the long alias serves akey_type: llm_apikey throughapply_guardrail_routeswith the same analyzer and anonymizer bodies, and both return 401 without a key. A blocking guardrail returns a 400 that names the block. Requestmetadatareaches a custom-code guardrail exactly, and requestmessagesreach an Akto guardrail's payload exactlyLine numbers are at
83d2447bf8, except the rows marked (new), which are at258f613c45tests/integration/management/test_policy_attachment_runtime.py::test_policy_attachments_match_live_models_teams_keys_and_global_scope[models],[teams],[keys],[*]attachment_registry.py:self.add_attachment(attachment)->passx-litellm-applied-policieswasNone...::test_streaming_chat_on_an_attached_model_runs_the_policy_guardrailattachment_registry.py: deleteself.add_attachment(attachment)x-litellm-applied-policies...::test_policy_attachment_with_a_blocking_guardrail_stops_the_request_before_the_providerattachment_registry.py:self.add_attachment(attachment)->passblocked.status_code == 400got 200 and the request reached the provider...::test_policy_attachment_tag_scope_matches_only_tagged_requestspolicy_matcher.py:87:if scope_tags:->if False:x-litellm-applied-policies: <policy>...::test_matching_model_and_global_attachments_apply_by_priority[model-priority-first],[global-priority-first]callback_utils.py:505:",".join(_metadata["applied_policies"])->",".join(_metadata["applied_policies"][:1])attachment_registry.py_attachment_sort_key:return (0, attachment.priority, *specificity)->return (0, -attachment.priority, *specificity)...::test_policy_attachment_tag_scope_matches_only_tagged_requests[header], which sendsx-litellm-tags: unmatched-<hex>, <prefix>-prodso only the second tag matcheslitellm_pre_call_utils.py:1893:tags = [tag.strip() for tag in _tags]->tags = [_tags[0].strip()]alonex-litellm-applied-policies...[top_level_tags], which now also reads the spend row and asserts its caller tags exactlylitellm_pre_call_utils.py:1897:if "tags" in data and isinstance(data["tags"], list):->if False:alone[]instead of[<prefix>-prod]...[top_level_tags]http_parsing_utils.py:658:request_body.get("tags", [])->[]alone stays greenmetadata.tags, which the policy match and the spend row both read...[header]litellm_pre_call_utils.py:1973:if not raw_header_tags:->if True:alone stays greenmetadata.tagsfrom the header, as the line 1893 mutant shows by turning the test red on its own. The pre-auth copy only feeds the tag budget check before auth, which is outside this area...[metadata_tags],[header],[top_level_tags]litellm_pre_call_utils.py:all_tags: Final = get_tags_from_request_body(data) or None->all_tags: Final = Nonex-litellm-applied-policies...::test_policy_attachment_tag_scope_matches_tags_from_the_key_and_teamlitellm_pre_call_utils.py:1750:tags_to_add=key_metadata["tags"],->tags_to_add=None,x-litellm-applied-policieslitellm_pre_call_utils.py:1799:tags_to_add=team_tags if isinstance(team_tags, list) else None,->tags_to_add=None,x-litellm-applied-policies...::test_default_policy_attachment_applies_only_when_no_other_attachment_matchesattachment_registry.py:165:non_default or tuple(attachment for attachment in in_scope if attachment.default),->in_scope,default,scopedinstead ofscoped...::test_request_policy_name_selects_its_production_guardrail_and_is_removed_from_provider_body,...::test_request_published_policy_version_id_resolves_after_force_synclitellm_pre_call_utils.py:data.pop("policies", None)->data.get("policies")_assert_provider_requestline 256, provider body carried"policies"...::test_streaming_request_body_policies_run_the_guardrail_and_are_removed_from_the_provider_body_assert_streaming_provider_requestline 355 via line 1130, provider body carried"policies"...::test_request_policy_version_id_selects_its_published_guardrail(BUG skip)x-litellm-applied-policiestests/integration/security/test_stored_config_slots.py::test_api_created_guardrail_api_key_is_encrypted_at_rest_and_reaches_only_the_guardrail[success],[provider_4xx]guardrail_registry.py:safe_dumps(encrypt_guardrail_litellm_params(litellm_params_dict))->safe_dumps(litellm_params_dict)_assert_stored_without_canaryline 176,Slot E1 stored in plaintexttests/integration/authorization/test_guardrail_submissions.py::test_team_guardrail_submissions_require_admin_approvalregistry_read_through.py: delete"status": "active",tests/integration/authorization/test_guardrail_submissions.py::test_non_admin_keys_scoped_to_the_submission_routes_get_403_from_the_admin_checkguardrail_endpoints.py: deleteraise HTTPException(status_code=403, detail="Admin access required")inapprove_guardrail_submission(200, 403, 400, 403), the team admin self-approvedreject_guardrail_submission(403, 200, 403, 400)tests/integration/authorization/test_guardrail_submissions.py::test_non_admin_keys_scoped_to_the_submission_routes_get_403_from_the_admin_check_types.pyadd"/guardrails/submissions/{guardrail_id}/approve",to the non-admin allowed routes andguardrail_endpoints.pydeleteraise HTTPException(status_code=403, detail="Admin access required")inapprove_guardrail_submission{"status":"active","message":"Guardrail approved"}_types.pyline above only(403, 401, 403, 401), approve and reject refused by different layers...test_guardrail_submissions.py::test_team_admins_and_internal_users_get_403_on_guardrail_submission_actions(BUG skip)Only proxy admininstead of 403tests/integration/observability/test_presidio_entity_masking.py::test_long_apply_guardrail_alias_accepts_an_llm_api_scoped_key_types.py: remove"/guardrails/apply_guardrail",fromapply_guardrail_routesVirtual key is not allowed to call this route...test_presidio_entity_masking.py::test_apply_guardrail_aliases_accept_admin_authguardrail_endpoints.py: delete@router.post("/apply_guardrail", response_model=ApplyGuardrailResponse)(404, 401) == (401, 401)x-litellm-api-key)user_api_key_auth.py:832:isinstance(custom_litellm_key_header, str)->isinstance(custom_litellm_key_header, bytes)(200, 200, 401, 401)...::test_short_apply_guardrail_alias_accepts_an_llm_api_scoped_key(BUG skip)/apply_guardrail...::test_apply_guardrail_aliases_accept_internal_user_auth(BUG skip)Only proxy adminon both aliaseslanguage,entities)...::test_apply_guardrail_forwards_documented_language_and_entities_to_presidio(BUG skip){"text": ..., "language": "en"}with noentitiestests/integration/observability/test_apply_guardrail_endpoint.py::test_apply_guardrail_returns_a_block_error_for_generic_guardrailsguardrail_endpoints.py:raise handle_exception_on_proxy(e)->return ApplyGuardrailResponse(response_text=request.text)200 == 400with the original text returned...test_apply_guardrail_endpoint.py::test_apply_guardrail_forwards_metadata_to_custom_codeguardrail_endpoints.py:**({"metadata": request.metadata} if request.metadata is not None else {}),->**({}),{}messages)...test_apply_guardrail_endpoint.py::test_apply_guardrail_forwards_messages_to_the_guardrailguardrail_endpoints.py:2429:**({"messages": request.messages} if request.messages is not None else {}),->**({}),textas a user messageScreenshots / Proof of Fix
This PR only adds tests and has no before or after product behavior. The proof is the rig runs below plus the mutation table. Every run used Postgres, Redis 7, the owned upstream and two directly addressed proxies (gateway and peer) as CircleCI starts them, with real provider credentials stripped from the environment
managementwithtests/integration/management/test_policy_attachment_runtime.py tests/integration/authorization/test_guardrail_submissions.py: run 1 and run 2 each14 passed, 2 skippedat440d846a20extensionswithtests/integration/observability/test_presidio_entity_masking.py tests/integration/observability/test_apply_guardrail_endpoint.py: run 1 and run 2 each8 passed, 3 skippedat440d846a20securitywithtests/integration/security/test_stored_config_slots.py: run 120 passed in 882.30s, run 220 passed in 837.53sat89f5ab31d0, the file is unchanged since70ecc1475fonly drops an unused helper, an f-prefix and a duplicated SDK call; the two streaming tests and the llm_api alias test reran green on it andmake checkpassed there83d2447bf8adds plain team-admin and member keys to the route-scoped submission test, and the row stayspending_review4077f2c221adds the two-match priority test and runs the tag test over all three request spellings.258f613c45makes the plain-key refusal accept exactly the current 401 body or the intended 403 body.managementwith the two files above: run 1 and run 2 each18 passed, 2 skippedat both commits, andmake checkpassed at both4077f2c221each of the five BUG skips was removed, run once and restored, and each is still red with the symptom in its skip message: the short alias 403Virtual key is not allowed to call this route(presidio line 120), internal-user 401Only proxy adminon both aliases (line 385), the analyzer missing the documentedentities(line 230), team admin and internal user 401 instead of 403 on approve and reject (submissions line 367), and the just-published version id with no guardrail and no header (policy runtime line 765)7971c244e9mergesorigin/mainbecausedocumentationandcode-qualityfailed onDEFER_PYDANTIC_BUILD, an env var main reads inlitellm/constants.pywithout documenting it, in files this PR does not touch030d0e3b78sends two comma-separated header tags with the match second and pins the spend row's caller tags for every spelling.managementwith the two files above: run 1 and run 2 each18 passed, 2 skipped, andmake checkpassed3e77f92998mergesorigin/mainagain and42c7ba6ae1drops the duplicate pydantic import that merge left.managementwith the two files above:18 passed, 2 skippedat42c7ba6ae1Type
Test
Caveats (if any)
Medium
Five product bugs on main are pinned as BUG skips that assert the intended contract, so those halves of gaps 2, 5 and 6 and the
language/entitiesspelling stay partial until the product fixes land, and each was reconfirmed red at4077f2c221. Non-admin virtual keys get 401 on both apply_guardrail aliases, becauseapply_guardrail_routessits inllm_api_routesbutis_llm_api_routenever reads it. Akey_type: llm_apikey is served on/guardrails/apply_guardrailbut refused with 403 on/apply_guardrail, since only the long alias is listed. Team admins and internal users get 401 from the route check instead of the documented 403 on submission approve and reject; the handler's own 403 is pinned by the route-scoped key test, and the current plain-key 401 is pinned exactly next to it so either layer moving is caught. A just-published policy version id applies no guardrail until a DB resync, so the hard version-id test callsforce_sync=truefirst./guardrails/apply_guardraildrops the documentedlanguageandentitiesfields before PresidioLow
The streaming provider body includes
stream_options: {"include_usage": true}, which the proxy adds for usage accounting; the test pins it because it is a documented OpenAI parameter the provider must accept. Themessageshalf of gap 8 is proven through an Akto guardrail, since the custom-code guardrail hidesmessagesfrom its code. The API-created guardrail test reuses the existing E1 canary slot, because a new slot would need an edit under_support/.osv-scanfails on lockfiles identical tomain, unrelated to this diffNote
Low Risk
Test-only changes under
tests/integration/; production behavior is unchanged, though skipped tests document existing auth and policy-sync bugs on main.Overview
Adds integration tests only (no
litellm/changes) that drive the proxy against wire doubles and assert upstream bodies, response headers, Postgres rows, and auth outcomes for guardrails and policies.Policy attachments and request
policies: New coverage intest_policy_attachment_runtime.pychecks that attachments take effect on the next chat (including streaming), match model/team/key/tag/global/defaultscopes, order multiple matches by priority, strippoliciesbefore the provider, run blocking guardrails before upstream, and resolve publishedpolicy_<version_id>afterforce_sync. One test is skipped for a known resync bug.Team guardrail submissions:
test_guardrail_submissions.pypins pending/rejected guardrails as inactive on chat and/apply_guardrail, admin approve/reject flows, team-scoped listing, and non-admin 403 (or current 401) on submission actions, with a skip for team-admin 401 vs documented 403.Apply guardrail and storage:
test_apply_guardrail_endpoint.pycovers generic BLOCKED → 400, Aktomessagesforwarding, and custom-codemetadata. Presidio tests gain alias/auth cases (plus BUG skips for short alias, internal users, andlanguage/entities).test_stored_config_slots.pyadds a case that API-created guardrailapi_keyis encrypted at rest, masked on read, and sent only to the guardrail upstream.Reviewed by Cursor Bugbot for commit 7971c24. Bugbot is set up for automated code reviews on this repo. Configure here.