Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 13 additions & 7 deletions src/mcp/client/auth/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,19 @@ def extract_field_from_www_auth(response: Response, field_name: str) -> str | No
if not www_auth_header:
return None

# Pattern matches: field_name="value" or field_name=value (unquoted)
pattern = rf'{field_name}=(?:"([^"]+)"|([^\s,]+))'
match = re.search(pattern, www_auth_header)

if match:
# Return quoted value if present, otherwise unquoted value
return match.group(1) or match.group(2)
# Strip the auth scheme (e.g. "Bearer") so parsing only sees auth-params.
_, separator, auth_params = www_auth_header.partition(" ")
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Outdated
if not separator:
auth_params = www_auth_header

# Match comma-delimited auth-params while respecting quoted values.
pattern = re.compile(
r'(?:^|,\s*)(?P<name>[A-Za-z][A-Za-z0-9_-]*)=(?:"(?P<quoted>[^"]+)"|(?P<unquoted>[^,\s]+))'
)
for match in pattern.finditer(auth_params):
if match.group("name") == field_name:
# Return quoted value if present, otherwise unquoted value
return match.group("quoted") or match.group("unquoted")

return None

Expand Down
12 changes: 12 additions & 0 deletions tests/client/test_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -2016,6 +2016,12 @@ class TestWWWAuthenticate:
"resource_metadata",
"https://api.example.com/auth/metadata?version=1",
),
('Bearer error_scope="decoy", scope="read write"', "scope", "read write"),
(
'Bearer error_description="missing scope=write permission", scope="read write"',
"scope",
"read write",
),
],
)
def test_extract_field_from_www_auth_valid_cases(
Expand Down Expand Up @@ -2047,6 +2053,12 @@ def test_extract_field_from_www_auth_valid_cases(
# Header without requested field
('Bearer realm="api", error="insufficient_scope"', "scope", "no scope parameter"),
('Bearer realm="api", scope="read write"', "resource_metadata", "no resource_metadata parameter"),
('Bearer custom_scope="leaked"', "scope", "field name appears only as a substring"),
(
'Bearer x_resource_metadata="https://decoy.example.com"',
"resource_metadata",
"field name appears only as a substring",
),
# Malformed field (empty value)
("Bearer scope=", "scope", "malformed scope parameter"),
("Bearer resource_metadata=", "resource_metadata", "malformed resource_metadata parameter"),
Expand Down
Loading