Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion INSTALL.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

## Requirements

- Python 3.10 or later
- Python 3.11 or later
- `pip`

## Install from a release
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ A command-line tool for managing Credential Engine platform resources.

## Requirements

- Python 3.10 or later
- Python 3.11 or later
- `pip`
## Installation

Expand Down Expand Up @@ -253,7 +253,7 @@ ce-cli/
│ ├── csv_processor.py # Bulk DID upload (bulk-sign + publish)
│ └── did_ops.py # DID validation, challenges, JWT signing
└── utils/
├── http.py # Authenticated httpx wrapper + APIError
├── http.py # Authenticated httpx2 wrapper + APIError
├── output.py # table/json/yaml/tsv renderer + @output_option
└── errors.py # @handle_api_errors decorator
```
131 changes: 71 additions & 60 deletions ce/auth/device_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,18 @@

from __future__ import annotations

import base64
import hashlib
import secrets
import time
from dataclasses import dataclass
from typing import Any, Optional

import httpx
import httpx2
from authlib.common.security import generate_token
from authlib.integrations.base_client.errors import OAuthError
from authlib.integrations.httpx_client import OAuth2Client
from authlib.oauth2.rfc6749.errors import OAuth2Error
from authlib.oauth2.rfc7636 import create_s256_code_challenge

DEVICE_CODE_GRANT = "urn:ietf:params:oauth:grant-type:device_code"


@dataclass
Expand Down Expand Up @@ -57,10 +61,8 @@ class RefreshRejectedError(DeviceFlowError):

def create_pkce_pair() -> tuple[str, str]:
"""Return a new PKCE code verifier and its S256 challenge (RFC 7636)."""
verifier = secrets.token_urlsafe(48)
digest = hashlib.sha256(verifier.encode("ascii")).digest()
challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
return verifier, challenge
verifier = generate_token(64)
return verifier, create_s256_code_challenge(verifier)


class KeycloakDeviceFlowClient:
Expand All @@ -69,10 +71,19 @@ class KeycloakDeviceFlowClient:
def __init__(
self,
env: "ce.config.context.Environment",
transport: Optional[httpx.BaseTransport] = None,
transport: Optional[httpx2.BaseTransport] = None,
) -> None:
self._env = env
self._http = httpx.Client(
self._http = httpx2.Client(
timeout=30,
verify=env.ssl_verify,
transport=transport,
)
# Token grants (the device code and the refresh) go through Authlib, which sends the
# form, reads the answer and decodes OAuth errors. ce-cli is a public client: no secret.
self._oauth = OAuth2Client(
client_id=env.client_id,
token_endpoint_auth_method="none",
timeout=30,
verify=env.ssl_verify,
transport=transport,
Expand Down Expand Up @@ -118,62 +129,62 @@ def poll_for_token(
deadline = time.monotonic() + expires_in
poll_interval = interval

data = {
"grant_type": "urn:ietf:params:oauth:grant-type:device_code",
"device_code": device_code,
"client_id": self._env.client_id,
}
extra: dict[str, str] = {}
if self._device_pkce is not None:
pkce_device_code, verifier = self._device_pkce
if pkce_device_code != device_code:
raise DeviceFlowError("Device code does not match the pending PKCE session.")
data["code_verifier"] = verifier
extra["code_verifier"] = verifier

while time.monotonic() < deadline:
time.sleep(poll_interval)
resp = self._post(self._env.token_url, data, "Token request")
body = self._json(resp, "Token request")

if resp.is_success:
self._device_pkce = None
return self._parse_token_response(body)

error = body.get("error", "unknown_error")

if error == "authorization_pending":
if on_pending:
on_pending()
continue
if error == "slow_down":
poll_interval += 5
if on_pending:
on_pending()
continue
if error == "access_denied":
raise AccessDeniedError("Authorization was denied by the user.")
if error in ("expired_token", "device_code_expired"):
raise TokenExpiredError("The device code has expired. Please try again.")
raise DeviceFlowError(f"Unexpected error from token endpoint: {error}")

try:
body = self._oauth.fetch_token(
self._env.token_url,
grant_type=DEVICE_CODE_GRANT,
device_code=device_code,
**extra,
)
except (OAuthError, OAuth2Error) as exc:
error = exc.error
if error == "authorization_pending":
if on_pending:
on_pending()
continue
if error == "slow_down":
poll_interval += 5
if on_pending:
on_pending()
continue
if error == "access_denied":
raise AccessDeniedError("Authorization was denied by the user.") from exc
if error in ("expired_token", "device_code_expired"):
raise TokenExpiredError("The device code has expired. Please try again.") from exc
raise DeviceFlowError(f"Unexpected error from token endpoint: {error}") from exc
except httpx2.HTTPError as exc:
raise DeviceFlowError(f"Token request failed: {exc}") from exc
except ValueError as exc:
raise DeviceFlowError(f"Token request failed: the answer was not JSON ({exc}).") from exc

self._device_pkce = None
return self._parse_token_response(body)

raise TokenExpiredError("Timed out waiting for user authorization.")

def refresh_access_token(self, refresh_token: str) -> TokenResponse:
resp = self._post(
self._env.token_url,
{
"grant_type": "refresh_token",
"refresh_token": refresh_token,
"client_id": self._env.client_id,
},
"Token refresh",
)

if resp.status_code in (400, 401):
# invalid_grant: the refresh token expired or the session was ended.
raise RefreshRejectedError(f"Token refresh was refused: {self._error_detail(resp)}")
try:
body = self._oauth.refresh_token(self._env.token_url, refresh_token=refresh_token)
except (OAuthError, OAuth2Error) as exc:
# invalid_grant and the like: the refresh token expired or the session was ended.
raise RefreshRejectedError(
f"Token refresh was refused: {exc.description or exc.error}"
) from exc
except httpx2.HTTPError as exc:
raise DeviceFlowError(f"Token refresh failed: {exc}") from exc
except ValueError as exc:
raise DeviceFlowError(f"Token refresh failed: the answer was not JSON ({exc}).") from exc

self._raise_for_status(resp)
body = self._json(resp, "Token refresh")
tokens = self._parse_token_response(body)
if tokens.refresh_token is None:
tokens.refresh_token = refresh_token
Expand All @@ -187,7 +198,7 @@ def get_userinfo(self, access_token: str) -> dict:
userinfo_url,
headers={"Authorization": f"Bearer {access_token}"},
)
except httpx.HTTPError as exc:
except httpx2.HTTPError as exc:
raise DeviceFlowError(f"Account request failed: {exc}") from exc
self._raise_for_status(resp)
return self._json(resp, "Account request")
Expand All @@ -210,15 +221,15 @@ def revoke_token(self, token: str, token_type_hint: str = "refresh_token") -> No
)
self._raise_for_status(resp)

def _post(self, url: str, data: dict[str, str], what: str) -> httpx.Response:
def _post(self, url: str, data: dict[str, str], what: str) -> httpx2.Response:
"""POST a form, turning a transport failure into a DeviceFlowError."""
try:
return self._http.post(url, data=data)
except httpx.HTTPError as exc:
except httpx2.HTTPError as exc:
raise DeviceFlowError(f"{what} failed: {exc}") from exc

@staticmethod
def _json(resp: httpx.Response, what: str) -> dict[str, Any]:
def _json(resp: httpx2.Response, what: str) -> dict[str, Any]:
"""The response body as a JSON object, or a DeviceFlowError (a proxy's HTML error page, for example)."""
try:
body = resp.json()
Expand All @@ -242,7 +253,7 @@ def _parse_token_response(body: dict[str, Any]) -> TokenResponse:
)

@staticmethod
def _error_detail(resp: httpx.Response) -> str:
def _error_detail(resp: httpx2.Response) -> str:
try:
body = resp.json()
except ValueError:
Expand All @@ -252,7 +263,7 @@ def _error_detail(resp: httpx.Response) -> str:
return resp.text

@staticmethod
def _raise_for_status(resp: httpx.Response) -> None:
def _raise_for_status(resp: httpx2.Response) -> None:
if resp.is_error:
detail = KeycloakDeviceFlowClient._error_detail(resp)
raise DeviceFlowError(f"HTTP {resp.status_code} from {resp.url}: {detail}")
Expand Down
4 changes: 2 additions & 2 deletions ce/commands/version.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,11 @@ def version_command(check: bool) -> None:

def _check_for_update() -> None:
"""Query PyPI for the latest published version of ce-cli."""
import httpx
import httpx2

try:
with console.status("[dim]Checking for updates…[/dim]"):
resp = httpx.get(
resp = httpx2.get(
"https://pypi.org/pypi/ce-cli/json",
timeout=5,
follow_redirects=True,
Expand Down
21 changes: 10 additions & 11 deletions ce/iir/api/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ By default, when you're calling an HTTPS API it will attempt to verify that SSL

```python
client = AuthenticatedClient(
base_url="https://internal_api.example.com",
base_url="https://internal_api.example.com",
token="SuperSecretToken",
verify_ssl="/path/to/certificate_bundle.pem",
)
Expand All @@ -56,11 +56,7 @@ client = AuthenticatedClient(
You can also disable certificate validation altogether, but beware that **this is a security risk**.

```python
client = AuthenticatedClient(
base_url="https://internal_api.example.com",
token="SuperSecretToken",
verify_ssl=False
)
client = AuthenticatedClient(base_url="https://internal_api.example.com", token="SuperSecretToken", verify_ssl=False)
```

Things to know:
Expand All @@ -76,37 +72,40 @@ Things to know:

## Advanced customizations

There are more settings on the generated `Client` class which let you control more runtime behavior, check out the docstring on that class for more info. You can also customize the underlying `httpx.Client` or `httpx.AsyncClient` (depending on your use-case):
There are more settings on the generated `Client` class which let you control more runtime behavior, check out the docstring on that class for more info. You can also customize the underlying `httpx2.Client` or `httpx2.AsyncClient` (depending on your use-case):

```python
from iir_client import Client


def log_request(request):
print(f"Request event hook: {request.method} {request.url} - Waiting for response")


def log_response(response):
request = response.request
print(f"Response event hook: {request.method} {request.url} - Status {response.status_code}")


client = Client(
base_url="https://api.example.com",
httpx_args={"event_hooks": {"request": [log_request], "response": [log_response]}},
)

# Or get the underlying httpx client to modify directly with client.get_httpx_client() or client.get_async_httpx_client()
# Or get the underlying httpx2 client to modify directly with client.get_httpx_client() or client.get_async_httpx_client()
```

You can even set the httpx client directly, but beware that this will override any existing settings (e.g., base_url):
You can even set the httpx2 client directly, but beware that this will override any existing settings (e.g., base_url):

```python
import httpx
import httpx2
from iir_client import Client

client = Client(
base_url="https://api.example.com",
)
# Note that base_url needs to be re-set, as would any shared cookies, headers, etc.
client.set_httpx_client(httpx.Client(base_url="https://api.example.com", proxies="http://localhost:8030"))
client.set_httpx_client(httpx2.Client(base_url="https://api.example.com", proxy="http://localhost:8030"))
```

## Building / publishing this package
Expand Down
2 changes: 1 addition & 1 deletion ce/iir/api/iir_client/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""A client library for accessing CTI Directory API"""

""" A client library for accessing CTI Directory API """
from .client import AuthenticatedClient, Client

__all__ = (
Expand Down
2 changes: 1 addition & 1 deletion ce/iir/api/iir_client/api/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
""" Contains methods for accessing the API """
"""Contains methods for accessing the API"""
2 changes: 1 addition & 1 deletion ce/iir/api/iir_client/api/iir_api/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
""" Contains endpoint functions for accessing the API """
"""Contains endpoint functions for accessing the API"""
Loading
Loading