From ed99493fac0f5f6d485e4c4e10aa7b1f69f3ca64 Mon Sep 17 00:00:00 2001 From: rumaisa a Date: Fri, 20 Nov 2026 12:12:06 +0530 Subject: [PATCH] percent-encode username in user realm discovery URL --- msal/authority.py | 5 +++-- tests/test_authority.py | 25 +++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/msal/authority.py b/msal/authority.py index ee16868f..21a86ac1 100644 --- a/msal/authority.py +++ b/msal/authority.py @@ -1,8 +1,9 @@ import json try: - from urllib.parse import urlparse + from urllib.parse import urlparse, quote except ImportError: # Fall back to Python 2 from urlparse import urlparse + from urllib import quote import logging logger = logging.getLogger(__name__) @@ -191,7 +192,7 @@ def user_realm_discovery(self, username, correlation_id=None, response=None): if self.instance not in self.__class__._domains_without_user_realm_discovery: resp = response or self._http_client.get( "https://{netloc}/common/userrealm/{username}?api-version=1.0".format( - netloc=self.instance, username=username), + netloc=self.instance, username=quote(username, safe="@")), headers={'Accept': 'application/json', 'client-request-id': correlation_id},) if resp.status_code != 404: diff --git a/tests/test_authority.py b/tests/test_authority.py index 2f9d1605..26dbf5a7 100644 --- a/tests/test_authority.py +++ b/tests/test_authority.py @@ -341,6 +341,31 @@ class MockResponse(object): Authority._domains_without_user_realm_discovery = set([]) +@patch("msal.authority.tenant_discovery", return_value={ + "authorization_endpoint": "https://login.microsoftonline.com/common/oauth2/v2.0/authorize", + "token_endpoint": "https://login.microsoftonline.com/common/oauth2/v2.0/token", + }) +class TestUserRealmDiscoveryEscapesUsername(unittest.TestCase): + def _get_url(self, username): + a = Authority("https://login.microsoftonline.com/common", MinimalHttpClient()) + with patch.object(a._http_client, "get") as mocked_get: + mocked_get.return_value.status_code = 200 + mocked_get.return_value.text = '{"account_type": "Managed"}' + a.user_realm_discovery(username) + return mocked_get.call_args[0][0] + + def test_plain_username_is_unchanged(self, _): + self.assertEqual( + "https://login.microsoftonline.com/common/userrealm/john.doe@example.com?api-version=1.0", + self._get_url("john.doe@example.com")) + + def test_username_cannot_alter_path_or_query(self, _): + self.assertEqual( + "https://login.microsoftonline.com/common/userrealm/" + "alice@contoso.com%2F..%2Fbob@fabrikam.com%3Fx%3D%23?api-version=1.0", + self._get_url("alice@contoso.com/../bob@fabrikam.com?x=#")) + + @patch("msal.authority.tenant_discovery", return_value={ "authorization_endpoint": "https://contoso.com/placeholder", "token_endpoint": "https://contoso.com/placeholder",