-
Notifications
You must be signed in to change notification settings - Fork 0
feat(identity): add bounded GitHub OIDC transport #201
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
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
3d4c90f
feat(identity): add bounded GitHub OIDC transport
aparragithub 1a0a5ee
fix(identity): harden OIDC transport boundaries
aparragithub ce65ad3
refactor(identity): isolate GitHub OIDC adapter
aparragithub 3b85785
fix(identity): validate OIDC redirect hops
aparragithub 7f2f704
refactor(identity): inject bounded HTTP opener
aparragithub 3bfb1d1
test(identity): cover redirects through public API
aparragithub 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
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,17 @@ | ||
| """GitHub identity adapter.""" | ||
|
|
||
| from odoo_forge_identity_github.transport import ( | ||
| BoundedHttpOpener, | ||
| BoundedHttpResponse, | ||
| GitHubOidcHttpsTransport, | ||
| GitHubOidcTransport, | ||
| create_github_oidc_https_transport, | ||
| ) | ||
|
|
||
| __all__ = [ | ||
| "BoundedHttpOpener", | ||
| "BoundedHttpResponse", | ||
| "GitHubOidcHttpsTransport", | ||
| "GitHubOidcTransport", | ||
| "create_github_oidc_https_transport", | ||
| ] |
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,163 @@ | ||
| """Bounded, injectable transport for GitHub OIDC metadata and JWKS.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import http.client | ||
| import json | ||
| import math | ||
| import urllib.request | ||
| from types import TracebackType | ||
| from typing import IO, Protocol, Self, cast, runtime_checkable | ||
| from urllib.parse import urlsplit | ||
|
|
||
| DEFAULT_TIMEOUT_SECONDS = 10.0 | ||
| MAX_RESPONSE_BYTES = 1_048_576 | ||
| _OPENID_CONFIGURATION_PATH = "/.well-known/openid-configuration" | ||
| _JSON_HEADERS = {"Accept": "application/json"} | ||
|
|
||
|
|
||
| @runtime_checkable | ||
| class GitHubOidcTransport(Protocol): | ||
| def get_metadata(self, issuer: str) -> dict[str, object]: | ||
| """Retrieve the issuer's OpenID configuration.""" | ||
| ... | ||
|
aparragithub marked this conversation as resolved.
|
||
|
|
||
| def get_jwks(self, jwks_uri: str) -> dict[str, object]: | ||
| """Retrieve the issuer's JSON Web Key Set.""" | ||
| ... | ||
|
github-advanced-security[bot] marked this conversation as resolved.
Fixed
github-advanced-security[bot] marked this conversation as resolved.
Fixed
aparragithub marked this conversation as resolved.
|
||
|
|
||
|
|
||
| class BoundedHttpResponse(Protocol): | ||
| def __enter__(self) -> Self: ... | ||
|
aparragithub marked this conversation as resolved.
|
||
|
|
||
| def __exit__( | ||
| self, | ||
| exc_type: type[BaseException] | None, | ||
| exc_value: BaseException | None, | ||
| traceback: TracebackType | None, | ||
| ) -> None: ... | ||
|
aparragithub marked this conversation as resolved.
|
||
|
|
||
| def geturl(self) -> str: ... | ||
|
aparragithub marked this conversation as resolved.
|
||
|
|
||
| def read(self, amount: int = -1) -> bytes: ... | ||
|
aparragithub marked this conversation as resolved.
|
||
|
|
||
|
|
||
| class BoundedHttpOpener(Protocol): | ||
| def open(self, request: urllib.request.Request, *, timeout: float) -> BoundedHttpResponse: ... | ||
|
aparragithub marked this conversation as resolved.
|
||
|
|
||
|
|
||
| class GitHubOidcHttpsTransport: | ||
| """Retrieve GitHub OIDC JSON documents using bounded HTTPS requests.""" | ||
|
|
||
| def __init__( | ||
| self, | ||
| *, | ||
| opener: BoundedHttpOpener, | ||
| timeout: float = DEFAULT_TIMEOUT_SECONDS, | ||
| max_response_bytes: int = MAX_RESPONSE_BYTES, | ||
| ) -> None: | ||
| if isinstance(timeout, bool) or not isinstance(timeout, (int, float)): | ||
| raise ValueError("timeout must be a finite number greater than zero") | ||
| if not math.isfinite(timeout) or timeout <= 0: | ||
| raise ValueError("timeout must be greater than zero") | ||
| if isinstance(max_response_bytes, bool) or not isinstance(max_response_bytes, int): | ||
| raise ValueError("response size limit must be a positive integer") | ||
| if max_response_bytes <= 0: | ||
| raise ValueError("response size limit must be greater than zero") | ||
| self._timeout = timeout | ||
| self._max_response_bytes = max_response_bytes | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| self._opener = opener | ||
|
|
||
| def get_metadata(self, issuer: str) -> dict[str, object]: | ||
| """Retrieve the standard OpenID configuration for an HTTPS issuer.""" | ||
| issuer = self._validate_https_url(issuer, allow_query=False) | ||
| return self._get_json(f"{issuer.rstrip('/')}{_OPENID_CONFIGURATION_PATH}") | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| def get_jwks(self, jwks_uri: str) -> dict[str, object]: | ||
| """Retrieve a JSON Web Key Set from an HTTPS URL.""" | ||
| return self._get_json(self._validate_https_url(jwks_uri)) | ||
|
|
||
| def _get_json(self, url: str) -> dict[str, object]: | ||
| return self._decode_json(self._read_response(url)) | ||
|
|
||
| def _read_response(self, url: str) -> bytes: | ||
| request = urllib.request.Request( | ||
| url, | ||
| method="GET", | ||
| headers=_JSON_HEADERS, | ||
| ) | ||
| try: | ||
| with self._opener.open(request, timeout=self._timeout) as response: # noqa: S310 | ||
| self._validate_https_url(response.geturl()) | ||
| body = response.read(self._max_response_bytes + 1) | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| except Exception: | ||
| raise RuntimeError("GitHub OIDC transport request failed") from None | ||
| if not isinstance(body, bytes): | ||
| raise RuntimeError("GitHub OIDC transport returned an invalid response") | ||
| if len(body) > self._max_response_bytes: | ||
| raise RuntimeError("GitHub OIDC transport response exceeds size limit") | ||
| return body | ||
|
|
||
| @staticmethod | ||
| def _decode_json(body: bytes) -> dict[str, object]: | ||
| try: | ||
| payload = json.loads(body) | ||
| except (json.JSONDecodeError, UnicodeDecodeError) as exc: | ||
| raise RuntimeError("GitHub OIDC transport returned malformed JSON") from exc | ||
| if not isinstance(payload, dict): | ||
| raise RuntimeError("GitHub OIDC transport returned malformed JSON") | ||
| return cast(dict[str, object], payload) | ||
|
|
||
| @staticmethod | ||
| def _validate_https_url(url: str, *, allow_query: bool = True) -> str: | ||
| try: | ||
| parsed = urlsplit(url) | ||
| except ValueError as exc: | ||
| raise ValueError("GitHub OIDC transport requires an HTTPS URL") from exc | ||
| if ( | ||
| parsed.scheme != "https" | ||
| or not parsed.hostname | ||
| or parsed.username is not None | ||
| or parsed.password is not None | ||
| or "#" in url | ||
| or (not allow_query and "?" in url) | ||
| ): | ||
| raise ValueError("GitHub OIDC transport requires an HTTPS URL") | ||
| return url | ||
|
|
||
|
|
||
| class _HttpsRedirectHandler(urllib.request.HTTPRedirectHandler): | ||
| def redirect_request( | ||
| self, | ||
| req: urllib.request.Request, | ||
| fp: IO[bytes], | ||
| code: int, | ||
| msg: str, | ||
| headers: http.client.HTTPMessage, | ||
| newurl: str, | ||
| ) -> urllib.request.Request | None: | ||
| GitHubOidcHttpsTransport._validate_https_url(newurl) | ||
| return super().redirect_request(req, fp, code, msg, headers, newurl) | ||
|
|
||
|
|
||
| def create_github_oidc_https_transport( | ||
| *, | ||
| timeout: float = DEFAULT_TIMEOUT_SECONDS, | ||
| max_response_bytes: int = MAX_RESPONSE_BYTES, | ||
| ) -> GitHubOidcHttpsTransport: | ||
| """Compose the production GitHub OIDC transport with urllib.""" | ||
| opener = cast(BoundedHttpOpener, urllib.request.build_opener(_HttpsRedirectHandler())) | ||
| return GitHubOidcHttpsTransport( | ||
| opener=opener, | ||
| timeout=timeout, | ||
| max_response_bytes=max_response_bytes, | ||
| ) | ||
|
|
||
|
|
||
| __all__ = [ | ||
| "BoundedHttpOpener", | ||
| "BoundedHttpResponse", | ||
| "GitHubOidcHttpsTransport", | ||
| "GitHubOidcTransport", | ||
| "create_github_oidc_https_transport", | ||
| ] | ||
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.