Skip to content

Percent-encode the username in the user realm discovery URL - #994

Open
rumaisaaaaa263 wants to merge 1 commit into
AzureAD:devfrom
rumaisaaaaa263:user-realm-escape-username
Open

rumaisaaaaa263 wants to merge 1 commit into
AzureAD:devfrom
rumaisaaaaa263:user-realm-escape-username

Conversation

@rumaisaaaaa263

Copy link
Copy Markdown

Username is not escaped in the user realm discovery URL

Authority.user_realm_discovery formats the username straight into https://<instance>/common/userrealm/<username>?api-version=1.0, so /, .., ? and # in the username change which URL is requested. For example alice@contoso.com/../bob@fabrikam.com is sent as https://login.microsoftonline.com/common/userrealm/bob@fabrikam.com?api-version=1.0 (urllib3 collapses the dot segments), so realm discovery answers for fabrikam.com, and if that realm is federated, acquire_token_by_username_password posts the WS-Trust username and password to the endpoint from fabrikam's metadata. A # in the username (for example a #EXT# guest UPN) cuts off the rest of the URL, including api-version.

The username is now percent-encoded with quote(username, safe="@"), so ordinary UPNs produce the same URL as before. #901 already escapes the same username in the WS-Trust request body. The new tests in tests/test_authority.py fail without the change and pass with it.

@rumaisaaaaa263
rumaisaaaaa263 requested a review from a team as a code owner November 20, 2026 08:29
Copilot AI balanced review requested due to automatic review settings November 20, 2026 08:29

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues were identified for the change that percent-encodes usernames in user realm discovery URLs.

No open issues 🎉

What changed in this PR

This PR percent-encodes usernames in user realm discovery URLs, preventing embedded URL delimiters from changing the requested path, query, or fragment. It complements the username escaping in WS-Trust requests from #901.

Changes:

  • Encode usernames with quote(username, safe="@"), preserving ordinary UPN URLs.
  • Add regression tests for unchanged ordinary usernames and usernames containing path, query, and fragment delimiters.
File Description
tests/​test_authority.py Adds URL-encoding regression tests for user realm discovery.
msal/​authority.py Imports quote with a Python 2 fallback and encodes the username in the discovery URL.

Review effort: Balanced

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants