{"record":{"id":"5a7fa4a111551a2d","repo":"BerriAI/litellm","slug":"malformed-api-key-passed-in-ensure-key-has-beare","errorCode":null,"errorMessage":"Malformed API Key passed in. Ensure Key has `Bearer ` prefix.","messagePattern":"Malformed API Key passed in\\. Ensure Key has `Bearer ` prefix\\.","errorType":"exception","errorClass":"Exception","httpStatus":null,"severity":"error","filePath":"litellm/proxy/auth/user_api_key_auth.py","lineNumber":1492,"sourceCode":"            elif isinstance(response, UserAPIKeyAuth):\n                return response\n        if master_key is None:\n            if isinstance(api_key, str):\n                return UserAPIKeyAuth(\n                    api_key=api_key,\n                    user_role=LitellmUserRoles.INTERNAL_USER,\n                    parent_otel_span=parent_otel_span,\n                )\n            else:\n                return UserAPIKeyAuth(\n                    user_role=LitellmUserRoles.INTERNAL_USER,\n                    parent_otel_span=parent_otel_span,\n                )\n        elif api_key is None:  # only require api key if master key is set\n            raise Exception(\"No api key passed in.\")\n        elif api_key == \"\":\n            # missing 'Bearer ' prefix\n            raise Exception(\"Malformed API Key passed in. Ensure Key has `Bearer ` prefix.\")\n\n        if route == \"/user/auth\":\n            if general_settings.get(\"allow_user_auth\", False) is True:\n                return UserAPIKeyAuth()\n            else:\n                raise HTTPException(\n                    status_code=status.HTTP_403_FORBIDDEN,\n                    detail=\"'allow_user_auth' not set or set to False\",\n                )\n\n        ## Check END-USER OBJECT\n        _end_user_object = None\n        end_user_params: Final = {}\n\n        raw_end_user_id: Final = get_end_user_id_from_request_body(request_data, _safe_get_request_headers(request))\n        end_user_id = await resolve_and_validate_end_user_id(\n            raw_end_user_id=raw_end_user_id,\n            prisma_client=prisma_client,","sourceCodeStart":1474,"sourceCodeEnd":1510,"githubUrl":"https://github.com/BerriAI/litellm/blob/77b7c6c40c0c5aa5fbcb1d6a1825ac39ca8829b8/litellm/proxy/auth/user_api_key_auth.py#L1474-L1510","documentation":"Raised when the request DID carry an Authorization header but the token is the empty string after stripping the `Bearer ` prefix — i.e. the header is exactly `Bearer` or `Bearer ` (trailing space). Distinguishes a present-but-empty credential (this error) from a completely absent one (`No api key passed in.`).","triggerScenarios":"Header interpolation from an empty variable: `Authorization: Bearer ${API_KEY}` with `API_KEY=\"\"` produces `Bearer ` and an empty extracted token; manually calling `curl -H 'Authorization: Bearer ' ...`; SDK code doing `f\"Bearer {key}\"` with `key = \"\"`.","commonSituations":"`.env` file defines the key but with empty value (`LITELLM_API_KEY=`); CI secrets not injected so `${KEY}` expands to empty; shell scripts with unset-but-`set -u`-unprotected variables; copy-pasted curl commands with the token deleted.","solutions":["Fix the source of the empty value: set the key env var / secret to a real virtual key (`sk-...`) and verify with `printenv` / `echo -n \"${KEY}\" | wc -c`","Guard at call sites: never build the header when the key is empty; fail fast with a clear local error","Confirm no stray whitespace/quote artifacts — the value must be the raw key with no extra `Bearer` duplication"],"exampleFix":"# before\nKEY=\"\"\nheaders = {\"Authorization\": f\"Bearer {KEY}\"}  # -> 'Malformed API Key passed in.'\n\n# after\nassert KEY and KEY.startswith(\"sk-\"), \"proxy key missing or empty\"\nheaders = {\"Authorization\": f\"Bearer {KEY}\"}","handlingStrategy":"validation","validationCode":"key = os.environ.get(\"PROXY_KEY\", \"\")\nif not key.strip():\n    raise RuntimeError(\"PROXY_KEY is empty — would send 'Bearer ' and get malformed-key error\")","typeGuard":"def is_usable_key(key: object) -> bool:\n    return isinstance(key, str) and len(key.strip()) > 0 and not key.startswith(\"Bearer \")","tryCatchPattern":"try:\n    client.chat.completions.create(...)\nexcept Exception as e:\n    if \"Malformed API Key\" in str(e) and \"Bearer\" in str(e):\n        raise RuntimeError(\"auth header built from empty key — check env/secret values\") from e\n    raise","preventionTips":["Fail fast at startup when credential env vars are empty strings, not just missing","Never interpolate unvalidated env vars into Authorization headers","In CI, assert secrets are non-empty before integration tests run"],"tags":["auth","api-key","malformed-header","empty-value","litellm"],"backgroundTag":"malformed-auth-header","analyzedSha":"77b7c6c40c0c5aa5fbcb1d6a1825ac39ca8829b8","analyzedAt":"2026-08-18T11:44:31.656Z","schemaVersion":2},"datasetVersion":"2026-08-21T18:17:14.833Z"}