โ† pod_step15_v1

fastapi_14786

resolved RESOLVED PASS ยท 9 tool calls ยท 42 s ยท fastapi/fastapi

Task input

๐Ÿ› Strip whitespaces from `Authorization` header credentials

## Description

Fixes whitespace handling in authorization header parameter extraction to comply with [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750#section-2.1).

## Problem

The current implementation preserves leading/trailing whitespace in the extracted credential parameter. While RFC 6750 allows one or more spaces (`1*SP`) between "Bearer" and the token, the token definition (`b64token`) doesn't include whitespace characters, meaning spaces should be treated as separators only.

This causes the extracted credentials to include extraneous whitespace, which can lead to authentication failures.

## Solution

Added `.strip()` to the parameter extraction to remove leading and trailing whitespace:
```python
return scheme, param.strip()
```

## Reproduction

### Before the fix:
```python
from typing import Annotated
from fastapi import Depends, FastAPI
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer

app = FastAPI()
security = HTTPBearer()

@app.get("/users/me")
def read_current_user(
    credentials: Annotated[HTTPAuthorizationCredentials, Depends(security)]
):
    return {"scheme": credentials.scheme, "credentials": credentials.credentials}
```

**Test case 1: Single space (correct)**
```bash
curl -X 'GET' \
  'http://127.0.0.1:8000/users/me' \
  -H 'Authorization: Bearer xxx'
```
Response: `{"scheme":"Bearer","credentials":"xxx"}` โœ“

**Test case 2: Multiple spaces**
```bash
curl -X 'GET' \
  'http://127.0.0.1:8000/users/me' \
  -H 'Authorization: Bearer   xxx'
```
Response: `{"scheme":"Bearer","credentials":"  xxx"}` โœ—

**Test case 3: Trailing whitespace**
```bash
curl -X 'GET' \
  'http://127.0.0.1:8000/users/me' \
  -H 'Authorization: Bearer xxx '
```
Response: `{"scheme":"Bearer","credentials":"xxx "}` โœ—

### After the fix:

All three test cases now return: `{"scheme":"Bearer","credentials":"xxx"}` โœ“

## Changes

- Modified `get_authorization_scheme_param()` in `fastapi/security/utils.py` to strip whitespace from the parameter
- Added test cases to verify the fix handles multiple spaces and trailing whitespace correctly

## Checklist

- [x] Tests added to cover the bug fix
- [x] Existing tests pass

Tool calls (10)

#ToolArgumentsResult
1run_command
{
 "command": "grep -rn \"get_authorization_scheme_param\" fastapi/security/utils.py"
}
{"status": "ok", "stdout": "fastapi/security/utils.py:4:def get_authorization_scheme_param(\n", "stderr": "", "exit_code": 0}
full
{"status": "ok", "stdout": "fastapi/security/utils.py:4:def get_authorization_scheme_param(\n", "stderr": "", "exit_code": 0}
2read_file
{
 "filepath": "fastapi/security/utils.py",
 "start_line": "4"
}
{"status": "error", "error_type": "FileReadError", "error_message": "'>' not supported between instances of 'int' and 'str'"}
full
{"status": "error", "error_type": "FileReadError", "error_message": "'>' not supported between instances of 'int' and 'str'"}
3read_file
{
 "filepath": "fastapi/security/utils.py"
}
{"status": "ok", "filepath": "fastapi/security/utils.py", "content": "from typing import Optional\n\n\ndef get_authorization_scheme_param(\n authorization_heade
full
{"status": "ok", "filepath": "fastapi/security/utils.py", "content": "from typing import Optional\n\n\ndef get_authorization_scheme_param(\n    authorization_header_value: Optional[str],\n) -> tuple[str, str]:\n    if not authorization_header_value:\n        return \"\", \"\"\n    scheme, _, param = authorization_header_value.partition(\" \")\n    return scheme, param", "start_line": 1, "end_line": 10, "total_lines": 10, "is_truncated": false}
4write_file
{
 "content": "from typing import Annotated\nfrom fastapi import Depends, FastAPI\nfrom fastapi.security import HTTPAuthorizationCredentials, HTTPBearer\nfrom fastapi.testclient import TestClient\n\napp = FastAPI()\nsecurity = HTTPBearer()\n\n@app.get(\"/users/me\")\ndef read_current_user(\n    credentials: Annotated[HTTPAuthorizationCredentials, Depends(security)]\n):\n    return {\"scheme\": credentials.scheme, \"credentials\": credentials.credentials}\n\nclient = TestClient(app)\n\ndef test_authorization_header_whitespace():\n    # Test case 1: Single space (correct)\n    response = client.get(\"/users/me\", headers={\"Authorization\": \"Bearer xxx\"})\n    assert response.json() == {\"scheme\": \"Bearer\", \"credentials\": \"xxx\"}\n\n    # Test case 2: Multiple spaces\n    response = client.get(\"/users/me\", headers={\"Authorization\": \"Bearer   xxx\"})\n    assert response.json() == {\"scheme\": \"Bearer\", \"credentials\": \"xxx\"}\n\n    # Test case 3: Trailing whitespace\n    response = client.get(\"/users/me\", headers={\"Authorization\": \"Bearer xxx \"})\n    assert response.json() == {\"scheme\": \"Bearer\", \"credentials\": \"xxx\"}\n\nif __name__ == \"__main__\":\n    try:\n        test_authorization_header_whitespace()\n        print(\"Tests passed!\")\n    except AssertionError as e:\n        print(f\"Test failed: {e}\")\n        exit(1)\n",
 "filepath": "/tmp/repro_whitespace.py"
}
{"status": "error", "error_type": "FileWriteError", "error_message": "Path traversal detected: '/tmp/repro_whitespace.py' escapes workspace root."}
full
{"status": "error", "error_type": "FileWriteError", "error_message": "Path traversal detected: '/tmp/repro_whitespace.py' escapes workspace root."}
5write_file
{
 "content": "from typing import Annotated\nfrom fastapi import Depends, FastAPI\nfrom fastapi.security import HTTPAuthorizationCredentials, HTTPBearer\nfrom fastapi.testclient import TestClient\n\napp = FastAPI()\nsecurity = HTTPBearer()\n\n@app.get(\"/users/me\")\ndef read_current_user(\n    credentials: Annotated[HTTPAuthorizationCredentials, Depends(security)]\n):\n    return {\"scheme\": credentials.scheme, \"credentials\": credentials.credentials}\n\nclient = TestClient(app)\n\ndef test_authorization_header_whitespace():\n    # Test case 1: Single space (correct)\n    response = client.get(\"/users/me\", headers={\"Authorization\": \"Bearer xxx\"})\n    assert response.json() == {\"scheme\": \"Bearer\", \"credentials\": \"xxx\"}\n\n    # Test case 2: Multiple spaces\n    response = client.get(\"/users/me\", headers={\"Authorization\": \"Bearer   xxx\"})\n    assert response.json() == {\"scheme\": \"Bearer\", \"credentials\": \"xxx\"}\n\n    # Test case 3: Trailing whitespace\n    response = client.get(\"/users/me\", headers={\"Authorization\": \"Bearer xxx \"})\n    assert response.json() == {\"scheme\": \"Bearer\", \"credentials\": \"xxx\"}\n\nif __name__ == \"__main__\":\n    try:\n        test_authorization_header_whitespace()\n        print(\"Tests passed!\")\n    except AssertionError as e:\n        print(f\"Test failed: {e}\")\n        exit(1)\n",
 "filepath": "repro_whitespace.py"
}
{"status": "ok", "filepath": "repro_whitespace.py", "size": 1275}
full
{"status": "ok", "filepath": "repro_whitespace.py", "size": 1275}
6run_command
{
 "command": "python repro_whitespace.py"
}
{"status": "error", "error_type": "CommandError", "error_message": "Test failed: \n", "details": {"stdout": "Test failed: \n", "stderr": "", "exit_code": 1}}
full
{"status": "error", "error_type": "CommandError", "error_message": "Test failed: \n", "details": {"stdout": "Test failed: \n", "stderr": "", "exit_code": 1}}
7edit_file
{
 "filepath": "fastapi/security/utils.py",
 "new_string": "    return scheme, param.strip()",
 "old_string": "    return scheme, param"
}
{"status": "ok", "filepath": "fastapi/security/utils.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/fastapi/security/utils.py\n+++ b/fastapi/securit
full
{"status": "ok", "filepath": "fastapi/security/utils.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/fastapi/security/utils.py\n+++ b/fastapi/security/utils.py\n@@ -7,4 +7,4 @@\n     if not authorization_header_value:\n         return \"\", \"\"\n     scheme, _, param = authorization_header_value.partition(\" \")\n-    return scheme, param\n+    return scheme, param.strip()\n", "is_truncated": false}
8run_command
{
 "command": "python repro_whitespace.py"
}
{"status": "ok", "stdout": "Tests passed!\n", "stderr": "", "exit_code": 0}
full
{"status": "ok", "stdout": "Tests passed!\n", "stderr": "", "exit_code": 0}
9run_command
{
 "command": "rm repro_whitespace.py"
}
{"status": "ok", "stdout": "", "stderr": "", "exit_code": 0}
full
{"status": "ok", "stdout": "", "stderr": "", "exit_code": 0}
10submit_patch
{}
{"status": "ok", "patch_size": 404, "files_changed": 1}
full
{"status": "ok", "patch_size": 404, "files_changed": 1}

Patch

diff --git a/fastapi/security/utils.py b/fastapi/security/utils.py
index 002e68b4..fd349aec 100644
--- a/fastapi/security/utils.py
+++ b/fastapi/security/utils.py
@@ -7,4 +7,4 @@ def get_authorization_scheme_param(
     if not authorization_header_value:
         return "", ""
     scheme, _, param = authorization_header_value.partition(" ")
-    return scheme, param
+    return scheme, param.strip()

Test output

show
.........                                                                [100%]
=============================== warnings summary ===============================
../../../../../../../Users/jp/repos/kaggle-gemini-coding-agent-post-training/.envs/overlays/starlette-0.50.0-py3-none-any/starlette/testclient.py:45
  /Users/jp/repos/kaggle-gemini-coding-agent-post-training/.envs/overlays/starlette-0.50.0-py3-none-any/starlette/testclient.py:45: DeprecationWarning: The anyio.abc.BlockingPortal alias is deprecated, use anyio.from_thread.BlockingPortal instead.
    _PortalFactoryType = Callable[[], AbstractContextManager[anyio.abc.BlockingPortal]]

-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
9 passed, 1 warning in 0.42s