-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Python: surface mid-run oauth_consent_request items from ResponsesHostServer #7659
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Giles Odigwe (giles17)
wants to merge
8
commits into
microsoft:main
from
giles17:fix-hosting-oauth-consent
Closed
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
b452dd7
Python: surface mid-run oauth_consent_request items from ResponsesHos…
giles17 9b33db9
Python: address review feedback on mid-run OAuth consent surfacing
giles17 fbc4b98
Merge remote-tracking branch 'upstream/main' into fix-hosting-oauth-c…
giles17 8f77520
Python: harden consent link validation and fail on unusable consent l…
giles17 62b83ce
Address maintainer review on OAuth consent surfacing
giles17 52e6da1
Merge branch 'main' into fix-hosting-oauth-consent
giles17 8665c57
Merge branch 'main' into fix-hosting-oauth-consent
giles17 5d95e48
Python: report workflow OAuth consent turns as not resumable
giles17 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| # Copyright (c) Microsoft. All rights reserved. | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import logging | ||
| import re | ||
| from urllib.parse import urlparse | ||
|
|
||
| logger = logging.getLogger("agent_framework") | ||
|
|
||
| __all__ = ["validate_oauth_consent_link"] | ||
|
|
||
| # Characters allowed in a registered host name, and in the bracketed IPv6 form that | ||
| # ``urlparse`` reports with its brackets already stripped. | ||
| _HOST_PATTERN = re.compile(r"^[A-Za-z0-9._~%-]+$") | ||
| _IPV6_HOST_PATTERN = re.compile(r"^[0-9A-Fa-f:.%-]+$") | ||
|
|
||
|
|
||
| def _is_valid_host(hostname: str) -> bool: | ||
| """Return whether *hostname* is syntactically usable by a standard URL client. | ||
|
|
||
| ``urlparse`` does not reject hosts containing illegal characters, so values such as | ||
| ``exa mple.com`` are reported as a hostname even though no client can resolve them. | ||
| """ | ||
| pattern = _IPV6_HOST_PATTERN if ":" in hostname else _HOST_PATTERN | ||
| return bool(pattern.match(hostname)) | ||
|
|
||
|
|
||
| def validate_oauth_consent_link(consent_link: str | None, *, item_id: str | None = None) -> str | None: | ||
| """Return *consent_link* when it is an absolute HTTPS URL a client can open, else ``None``. | ||
|
|
||
| A consent link is rendered as a clickable prompt by the client, so anything that is not | ||
| an absolute ``https`` URL is dropped rather than surfaced. Validation is shared by every | ||
| package that parses or re-emits ``oauth_consent_request`` content so the accepted shape | ||
| cannot drift between the provider that parses a link and the host that renders it. | ||
|
|
||
| ``urlparse`` is permissive in three ways that matter here, all handled below: | ||
|
|
||
| * it raises ``ValueError`` for malformed authorities (``https://[broken``) and for invalid | ||
| ports, but the port is only validated when it is read; | ||
| * a non-empty ``netloc`` does not imply a host (``https://@`` has one but no host), and a | ||
| non-empty ``hostname`` does not imply a usable one (``https://exa mple.com`` reports one); | ||
| * it silently strips tab and newline, so control characters must be rejected up front. | ||
|
|
||
| Args: | ||
| consent_link: The candidate consent URL, which may be ``None`` or empty. | ||
|
|
||
| Keyword Args: | ||
| item_id: Optional identifier of the source item, included in warning logs. | ||
|
|
||
| Returns: | ||
| The link unchanged when it is usable, otherwise ``None``. | ||
| """ | ||
| if not consent_link: | ||
| return None | ||
|
|
||
| log_id = item_id or "<unknown>" | ||
|
|
||
| if any(char.isspace() or ord(char) < 0x20 or ord(char) == 0x7F for char in consent_link): | ||
| logger.warning( | ||
| "Skipping oauth_consent_request with whitespace or control characters in consent_link (item id=%s)", | ||
| log_id, | ||
| ) | ||
| return None | ||
| try: | ||
| parsed = urlparse(consent_link) | ||
| hostname = parsed.hostname | ||
| # Reading ``port`` is what validates it; ``https://host:bad`` raises here. | ||
| _ = parsed.port | ||
| except ValueError: | ||
| logger.warning("Skipping oauth_consent_request with malformed consent_link (item id=%s)", log_id) | ||
| return None | ||
| if parsed.scheme.lower() != "https" or not hostname: | ||
| logger.warning("Skipping oauth_consent_request with non-HTTPS consent_link (item id=%s)", log_id) | ||
| return None | ||
| if not _is_valid_host(hostname): | ||
| logger.warning("Skipping oauth_consent_request with an invalid consent_link host (item id=%s)", log_id) | ||
| return None | ||
| return consent_link | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| # Copyright (c) Microsoft. All rights reserved. | ||
|
|
||
| import pytest | ||
|
|
||
| from agent_framework._oauth import validate_oauth_consent_link | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "link", | ||
| [ | ||
| "https://login.example.com/consent", | ||
| "https://login.example.com:8443/consent?state=abc#frag", | ||
| "https://192.0.2.10/consent", | ||
| "https://[2001:db8::1]:8443/consent", | ||
| "HTTPS://login.example.com/consent", | ||
| ], | ||
| ) | ||
| def test_usable_links_are_returned_unchanged(link: str) -> None: | ||
| assert validate_oauth_consent_link(link) == link | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| ("link", "reason"), | ||
| [ | ||
| (None, "missing"), | ||
| ("", "empty"), | ||
| (" ", "whitespace only"), | ||
| ("http://login.example.com/consent", "non-HTTPS scheme"), | ||
| ("ftp://login.example.com/consent", "non-HTTPS scheme"), | ||
| ("/consent", "relative, so no scheme or host"), | ||
| ("https://", "no host"), | ||
| ("https://@", "netloc present but no host"), | ||
| ("https://[broken", "malformed authority, urlparse raises"), | ||
| ("https://login.example.com:bad/consent", "port only validated when read"), | ||
| ("https://login.example.com:99999/consent", "port out of range"), | ||
| ("https://exa mple.com/consent", "space in host, unresolvable"), | ||
| ("https://cons|ent.example.com/", "illegal character in host"), | ||
| ("https://login.example.com/consent\n", "trailing newline, silently stripped by urlparse"), | ||
| ("https://login.example.com/\tconsent", "embedded tab, silently stripped by urlparse"), | ||
| ], | ||
| ) | ||
| def test_unusable_links_are_rejected(link: str | None, reason: str) -> None: | ||
| assert validate_oauth_consent_link(link) is None, reason | ||
|
|
||
|
|
||
| def test_rejection_is_logged_with_the_item_id(caplog: pytest.LogCaptureFixture) -> None: | ||
| with caplog.at_level("WARNING"): | ||
| assert validate_oauth_consent_link("http://login.example.com", item_id="item-5") is None | ||
| assert "non-HTTPS" in caplog.text | ||
| assert "item-5" in caplog.text | ||
|
|
||
|
|
||
| def test_rejection_without_an_item_id_still_logs(caplog: pytest.LogCaptureFixture) -> None: | ||
| with caplog.at_level("WARNING"): | ||
| assert validate_oauth_consent_link("http://login.example.com") is None | ||
| assert "non-HTTPS" in caplog.text |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.