litellm/tests/test_litellm/proxy/auth
ryan-crabbe-berri 0300333753
feat(otel): OTel-standard attributes on the proxy SERVER span (status code, route/path, preprocessing latency) (#28040)
* feat(otel): expose http.response.status_code on failure spans

Set the OTel-standard http.response.status_code (integer) on failure
spans alongside the existing OpenInference error.code (kept for
back-compat). error.type is already emitted via ERROR_TYPE.

Crucially, also record structured error attributes on the proxy SERVER
span ('Received Proxy Server Request') from async_post_call_failure_hook
- the only place the SERVER span is in hand. _handle_failure records on
the litellm_request child span (the parent span is not propagated into
its kwargs), so prior to this change the SERVER span that dashboards
query carried only span status, never error.code/error.type. Reuses
_record_exception_on_span + StandardLoggingPayloadSetup.get_error_information
so values match the child span.

Tests: recorder unit coverage + a hook-driven test asserting the SERVER
span is stamped (the gap recorder-only tests missed). Full
test_opentelemetry.py suite: 197 passed.

* feat(otel): set http.route + url.path on the proxy SERVER span

Add the OTel-standard http.route (low-cardinality route template, e.g.
/v1/threads/{thread_id}/runs) and url.path (literal path) to the SERVER
span ('Received Proxy Server Request') so dashboards can group traffic
by endpoint instead of seeing every path param as a unique value.

Same architectural gap as the status-code commit: the success/failure
logging handlers write the litellm_request CHILD span, and
_handle_success explicitly refuses to copy to the SERVER span. Verified
with a console-exporter run that the SERVER span was bare on success.

Unlike error info, route/path are known at request time, so set them
directly on the freshly-created SERVER span in user_api_key_auth (one
edit point, works for success and failure, no hook-ordering risk):
- http.route from the matched FastAPI route (scope['route'].path),
  empirically confirmed populated at auth-dependency time.
- url.path from the existing literal-path variable.
New get_request_route_template helper + set_proxy_request_route_attributes
(no-op on None span, so the Langfuse override stays safe).

Tests: route-attribute setter + route-template helper edges. Full
test_opentelemetry.py and test_auth_utils.py green.

* feat(otel): set litellm.preprocessing.duration_ms on the proxy SERVER span

Expose the total time LiteLLM spends before the upstream provider
request begins (auth + parsing + pre-call hooks) as a single number on
the SERVER span ('Received Proxy Server Request'). Window:
proxy-receive -> FIRST provider handoff.

Retry semantics: first attempt only (pure preprocessing, excludes
retry loops + backoff). api_call_start_time is overwritten on every
attempt, so a set-once first_api_call_start_time pins the first handoff.

Same architectural gap as the prior two commits: the success/failure
logging handlers write the litellm_request CHILD span, not the SERVER
span. Set it instead from the post-call hooks on
user_api_key_dict.parent_otel_span.

Failure-path subtlety: request_data.pop('litellm_logging_obj') runs
before the failure-hook loop, so the failure hook can't read the
logging object. litellm_received_at is propagated via the existing
request->metadata channel, and first_api_call_start_time is mirrored
onto litellm_params.metadata, so both anchors survive into request_data
and the OTel helper reads them uniformly for success and failure.

Edits: user_api_key_auth (stash receive instant), litellm_pre_call_utils
(propagate it), litellm_logging (set-once first handoff + metadata
mirror), opentelemetry (constant + set_preprocessing_duration_attribute,
called from both post-call hooks).

Tests: duration helper (both container shapes, missing/negative/None
edges) + set-once invariant (retry doesn't overwrite, metadata mirror).
test_opentelemetry.py + test_auth_utils.py + test_litellm_logging.py:
447 passed. Verified live: SERVER span carries the attribute on success
and failure, coexisting with the status-code and route attributes.

* fix(otel): MyPy type-narrowing for status-code + preprocessing-duration

No behavior change. MyPy (CI lint) flagged:
- error_information["error_code"] is str|None: narrow via a None-checked
  local before int().
- _to_timestamp returns Optional[float]: resolve both anchors and return
  early if either is None instead of subtracting possibly-None floats.

* fix(otel): stop polluting user request metadata with first_api_call_start_time

The PR3 set-once preprocessing anchor was mirrored into
litellm_params["metadata"] from core litellm_logging.py. That dict is
the caller's request metadata, mutated in place and shared across every
call path including pure SDK (litellm.acreate_batch). It got echoed into
LiteLLMBatch(metadata=...), which the OpenAI batch schema types as
Dict[str, str] -> pydantic ValidationError on a datetime value.

- litellm_logging.py: set first_api_call_start_time only on
  model_call_details (success path reads it there directly).
- proxy/utils.py: post_call_failure_hook lifts it off the logging object
  into request_data (internal top-level key, same convention as the
  other proxy-internal request_data keys) right before the existing
  litellm_logging_obj pop. Never touches user metadata.
- opentelemetry.py: read the anchor from the container top level
  (model_call_details on success, request_data on failure).
- Tests updated; add TestPostCallFailureHookLiftsFirstApiCallStartTime.

Fixes the batches_testing regression introduced on this branch.

* chore(otel): trim verbose comments to concise rationale

Collapse multi-line why-blocks to one or two lines and drop process/plan references (PR-numbering, "the plan") from test comments. No behavior change.
2026-05-16 13:45:08 -07:00
..
test_admin_viewer_handler_access.py fix(rbac): restore admin-viewer read parity for Logs page + settings reads 2026-04-29 19:21:41 -07:00
test_auth_checks.py Fix proxy auth status code tests (#27555) 2026-05-09 14:47:48 -07:00
test_auth_exception_handler.py Fix proxy auth status code tests (#27555) 2026-05-09 14:47:48 -07:00
test_auth_hot_path_network_requests.py fix: update docker test file to right path 2026-02-19 18:44:28 +05:30
test_auth_utils.py feat(otel): OTel-standard attributes on the proxy SERVER span (status code, route/path, preprocessing latency) (#28040) 2026-05-16 13:45:08 -07:00
test_banned_params_extra_body.py chore(tests): drop redundant membership check; trim test comment 2026-05-14 03:39:15 +00:00
test_cli_auth.py cover cli sso start validation 2026-04-29 17:25:32 -07:00
test_custom_auth_end_user_budget.py fix(auth): centralize common_checks to close authorization bypass 2026-04-23 00:04:42 +00:00
test_handle_jwt.py fix(auth): harden JWT routing wildcard iss and merge list team_id claims 2026-05-11 11:35:56 +05:30
test_info_routes.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_litellm_license.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_login_utils.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_mcp_ip_filtering.py Return Clear error message why no tools are available / IP Filtering occured 2026-02-26 09:56:44 +05:30
test_model_checks.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_model_checks_fallbacks.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_multi_budget_windows.py feat: multiple concurrent budget windows per API key and team (#24883) (#25109) 2026-04-06 14:02:04 -07:00
test_oauth2_proxy_hook.py chore(auth): require trusted proxy for header identity auth 2026-04-29 21:20:21 -07:00
test_object_permission_loading.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_onboarding.py chore(auth): address onboarding review follow-ups 2026-04-29 19:10:30 -07:00
test_organization_budget_enforcement.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_password_hashing.py chore: fixes 2026-03-30 18:36:58 -07:00
test_route_checks.py fix: harden /key/update authorization checks (#27878) 2026-05-14 04:16:04 +00:00
test_router_override_fallback_auth.py [Fix] Proxy: Repair Merge Fallout In Router-Override Fallback Auth 2026-05-01 17:48:51 -07:00
test_team_member_budget.py Fix team member budget enforcement without user row (#27273) 2026-05-06 11:42:29 -07:00
test_unmapped_model_budget_enforcement.py perf: eliminate per-request callback scanning on proxy hot path (#27858) 2026-05-14 09:28:31 -07:00
test_user_api_key_auth.py Merge pull request #27422 from BerriAI/shin_agent_oss_staging_05_07_2026 2026-05-11 11:58:05 +05:30