Skip to content

Commit 8a05814

Browse files
committed
Avoid matching auth params inside quoted values
1 parent 5de906e commit 8a05814

2 files changed

Lines changed: 18 additions & 7 deletions

File tree

src/mcp/client/auth/utils.py

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -26,13 +26,19 @@ def extract_field_from_www_auth(response: Response, field_name: str) -> str | No
2626
if not www_auth_header:
2727
return None
2828

29-
# Match a complete auth-param name at the header start or after a separator.
30-
pattern = rf'(?:^|[\s,]){re.escape(field_name)}=(?:"([^"]+)"|([^\s,]+))'
31-
match = re.search(pattern, www_auth_header)
32-
33-
if match:
34-
# Return quoted value if present, otherwise unquoted value
35-
return match.group(1) or match.group(2)
29+
# Strip the auth scheme (e.g. "Bearer") so parsing only sees auth-params.
30+
_, separator, auth_params = www_auth_header.partition(" ")
31+
if not separator:
32+
auth_params = www_auth_header
33+
34+
# Match comma-delimited auth-params while respecting quoted values.
35+
pattern = re.compile(
36+
r'(?:^|,\s*)(?P<name>[A-Za-z][A-Za-z0-9_-]*)=(?:"(?P<quoted>[^"]+)"|(?P<unquoted>[^,\s]+))'
37+
)
38+
for match in pattern.finditer(auth_params):
39+
if match.group("name") == field_name:
40+
# Return quoted value if present, otherwise unquoted value
41+
return match.group("quoted") or match.group("unquoted")
3642

3743
return None
3844

tests/client/test_auth.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2017,6 +2017,11 @@ class TestWWWAuthenticate:
20172017
"https://api.example.com/auth/metadata?version=1",
20182018
),
20192019
('Bearer error_scope="decoy", scope="read write"', "scope", "read write"),
2020+
(
2021+
'Bearer error_description="missing scope=write permission", scope="read write"',
2022+
"scope",
2023+
"read write",
2024+
),
20202025
],
20212026
)
20222027
def test_extract_field_from_www_auth_valid_cases(

0 commit comments

Comments
 (0)