cezzis-oauth 0.0.18__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,59 @@
1
+ Metadata-Version: 2.4
2
+ Name: cezzis_oauth
3
+ Version: 0.0.18
4
+ Summary: A lightweight, production-ready Python library for OAuth 2.0 authentication. Provides both **token acquisition** and **JWT verification** with enterprise-grade features including automatic token caching, refresh management, JWKS-based verification, and scope validation.
5
+ License: MIT
6
+ Author: mtnvencenzo
7
+ Author-email: rvecchi@gmail.com
8
+ Requires-Python: >=3.12,<3.15
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Classifier: Programming Language :: Python :: 3.13
13
+ Classifier: Programming Language :: Python :: 3.14
14
+ Requires-Dist: authlib (>=1.4.0,<2.0.0)
15
+ Requires-Dist: httpx (>=0.28.1,<0.29.0)
16
+ Requires-Dist: python-jose[cryptography] (>=3.5.0,<4.0.0)
17
+ Description-Content-Type: text/markdown
18
+
19
+ # Cezzis OAuth
20
+
21
+ [![Python Version](https://img.shields.io/badge/python-3.12%2B-blue.svg)](https://www.python.org/downloads/)
22
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
23
+ [![PyPI version](https://img.shields.io/pypi/v/cezzis-oauth.svg)](https://pypi.org/project/cezzis-oauth/)
24
+ [![CI/CD](https://github.com/mtnvencenzo/cezzis-pycore/actions/workflows/cezzis-oauth-cicd.yaml/badge.svg)](https://github.com/mtnvencenzo/cezzis-pycore/actions/workflows/cezzis-oauth-cicd.yaml)
25
+
26
+ A lightweight, production-ready Python library for OAuth 2.0 authentication. Provides both **token acquisition** and **JWT verification** with enterprise-grade features including automatic token caching, refresh management, JWKS-based verification, and scope validation.
27
+
28
+ ## 🚀 Installation
29
+
30
+ Install `cezzis-oauth` from PyPI:
31
+
32
+ ```bash
33
+ pip install cezzis-oauth
34
+ ```
35
+
36
+ Or using Poetry:
37
+
38
+ ```bash
39
+ poetry add cezzis-oauth
40
+ ```
41
+
42
+ ## 📋 Requirements
43
+
44
+ - Python 3.12 or higher
45
+
46
+ ## 📖 Documentation & Examples
47
+
48
+ Complete documentation, examples, and guides are available in the GitHub repository:
49
+
50
+ [Full Documentation & Examples](https://github.com/mtnvencenzo/cezzis-pycore/blob/main/oauth-packages/README.md)
51
+
52
+
53
+ ## 📄 License
54
+
55
+ This project is licensed under the MIT License. See the [LICENSE](https://github.com/mtnvencenzo/cezzis-pycore/blob/main/LICENSE) file for details.
56
+
57
+ ---
58
+
59
+
@@ -0,0 +1,40 @@
1
+ # Cezzis OAuth
2
+
3
+ [![Python Version](https://img.shields.io/badge/python-3.12%2B-blue.svg)](https://www.python.org/downloads/)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
+ [![PyPI version](https://img.shields.io/pypi/v/cezzis-oauth.svg)](https://pypi.org/project/cezzis-oauth/)
6
+ [![CI/CD](https://github.com/mtnvencenzo/cezzis-pycore/actions/workflows/cezzis-oauth-cicd.yaml/badge.svg)](https://github.com/mtnvencenzo/cezzis-pycore/actions/workflows/cezzis-oauth-cicd.yaml)
7
+
8
+ A lightweight, production-ready Python library for OAuth 2.0 authentication. Provides both **token acquisition** and **JWT verification** with enterprise-grade features including automatic token caching, refresh management, JWKS-based verification, and scope validation.
9
+
10
+ ## 🚀 Installation
11
+
12
+ Install `cezzis-oauth` from PyPI:
13
+
14
+ ```bash
15
+ pip install cezzis-oauth
16
+ ```
17
+
18
+ Or using Poetry:
19
+
20
+ ```bash
21
+ poetry add cezzis-oauth
22
+ ```
23
+
24
+ ## 📋 Requirements
25
+
26
+ - Python 3.12 or higher
27
+
28
+ ## 📖 Documentation & Examples
29
+
30
+ Complete documentation, examples, and guides are available in the GitHub repository:
31
+
32
+ [Full Documentation & Examples](https://github.com/mtnvencenzo/cezzis-pycore/blob/main/oauth-packages/README.md)
33
+
34
+
35
+ ## 📄 License
36
+
37
+ This project is licensed under the MIT License. See the [LICENSE](https://github.com/mtnvencenzo/cezzis-pycore/blob/main/LICENSE) file for details.
38
+
39
+ ---
40
+
@@ -0,0 +1,21 @@
1
+ """Cezzis OAuth - A lightweight library for OAuth authentication and utilities."""
2
+
3
+ from cezzis_oauth.oauth_openapi import generate_openapi_oauth2_scheme
4
+ from cezzis_oauth.oauth_token_provider import IOAuthTokenProvider, OAuthTokenProvider
5
+ from cezzis_oauth.oauth_verification import OAuth2TokenVerifier, TokenVerificationError
6
+
7
+ # Dynamically read version from package metadata
8
+ try:
9
+ from importlib.metadata import version
10
+
11
+ __version__ = version("cezzis_oauth")
12
+ except Exception:
13
+ __version__ = "unknown"
14
+
15
+ __all__ = [
16
+ "IOAuthTokenProvider",
17
+ "OAuthTokenProvider",
18
+ "OAuth2TokenVerifier",
19
+ "TokenVerificationError",
20
+ "generate_openapi_oauth2_scheme",
21
+ ]
@@ -0,0 +1,5 @@
1
+ from cezzis_oauth.oauth_openapi import generate_openapi_oauth2_scheme as generate_openapi_oauth2_scheme
2
+ from cezzis_oauth.oauth_token_provider import IOAuthTokenProvider as IOAuthTokenProvider, OAuthTokenProvider as OAuthTokenProvider
3
+ from cezzis_oauth.oauth_verification import OAuth2TokenVerifier as OAuth2TokenVerifier, TokenVerificationError as TokenVerificationError
4
+
5
+ __all__ = ['IOAuthTokenProvider', 'OAuthTokenProvider', 'OAuth2TokenVerifier', 'TokenVerificationError', 'generate_openapi_oauth2_scheme']
@@ -0,0 +1,34 @@
1
+ from typing import Any
2
+
3
+
4
+ def generate_openapi_oauth2_scheme(
5
+ name: str,
6
+ client_id: str,
7
+ domain: str,
8
+ audience: str,
9
+ scopes: dict[str, str] | None = None,
10
+ pkce: str | None = None,
11
+ ) -> dict[str, dict[str, Any]]:
12
+ """
13
+ Generate OpenAPI OAuth2 scheme definition.
14
+
15
+ Returns:
16
+ A dictionary representing the OpenAPI OAuth2 scheme.
17
+ """
18
+ if scopes is None:
19
+ scopes = {}
20
+
21
+ return {
22
+ name: {
23
+ "type": "oauth2",
24
+ "flows": {
25
+ "authorizationCode": {
26
+ "authorizationUrl": f"https://{domain}/authorize?audience={audience}",
27
+ "tokenUrl": f"https://{domain}/oauth/token",
28
+ "scopes": scopes,
29
+ "x-usePkce": pkce,
30
+ "x-defaultClientId": client_id or "",
31
+ }
32
+ },
33
+ }
34
+ }
@@ -0,0 +1,3 @@
1
+ from typing import Any
2
+
3
+ def generate_openapi_oauth2_scheme(name: str, client_id: str, domain: str, audience: str, scopes: dict[str, str] | None = None, pkce: str | None = None) -> dict[str, dict[str, Any]]: ...
@@ -0,0 +1,94 @@
1
+ import asyncio
2
+ import logging
3
+ from datetime import datetime, timedelta, timezone
4
+ from typing import Protocol
5
+
6
+ import httpx
7
+ from authlib.integrations.httpx_client import AsyncOAuth2Client
8
+
9
+
10
+ class IOAuthTokenProvider(Protocol):
11
+ """Protocol for OAuth token providers."""
12
+
13
+ async def get_access_token(self) -> str:
14
+ """Get a valid access token, refreshing if necessary."""
15
+ ...
16
+
17
+
18
+ class OAuthTokenProvider(IOAuthTokenProvider):
19
+ """
20
+ Provides OAuth access tokens using OAuth 2.0 client credentials flow.
21
+ Handles token caching and automatic refresh.
22
+ """
23
+
24
+ def __init__(self, domain: str, client_id: str, client_secret: str, audience: str, scope: str):
25
+ self._domain = domain
26
+ self._client_id = client_id
27
+ self._client_secret = client_secret
28
+ self._audience = audience
29
+ self._scope = scope
30
+ self._logger = logging.getLogger(__name__)
31
+ self._token: str | None = None
32
+ self._token_expiry: datetime | None = None
33
+ self._lock = asyncio.Lock()
34
+
35
+ async def get_access_token(self) -> str:
36
+ """
37
+ Get a valid access token. Fetches a new token if none exists or if expired.
38
+
39
+ Returns:
40
+ str: A valid OAuth access token.
41
+
42
+ Raises:
43
+ RuntimeError: If token acquisition fails.
44
+ """
45
+ async with self._lock:
46
+ # Check if we have a valid cached token
47
+ if self._token and self._token_expiry:
48
+ # Refresh 60 seconds before expiry to avoid edge cases
49
+ if datetime.now(timezone.utc) < (self._token_expiry - timedelta(seconds=60)):
50
+ return self._token
51
+
52
+ # Fetch new token
53
+ self._token = await self._fetch_token()
54
+ return self._token
55
+
56
+ async def _fetch_token(self) -> str:
57
+ """
58
+ Fetch a new access token from OAuth using client credentials flow.
59
+
60
+ Returns:
61
+ str: The access token.
62
+
63
+ Raises:
64
+ RuntimeError: If token acquisition fails.
65
+ """
66
+ token_url = f"https://{self._domain}/oauth/token"
67
+
68
+ try:
69
+ async with AsyncOAuth2Client(
70
+ client_id=self._client_id,
71
+ client_secret=self._client_secret,
72
+ ) as client:
73
+ token = await client.fetch_token(
74
+ token_url,
75
+ grant_type="client_credentials",
76
+ audience=self._audience,
77
+ scope=self._scope,
78
+ )
79
+
80
+ # Cache token and expiry
81
+ access_token: str = token["access_token"]
82
+ self._token = access_token
83
+ expires_in = token.get("expires_in", 3600) # Default to 1 hour
84
+ self._token_expiry = datetime.now(timezone.utc) + timedelta(seconds=expires_in)
85
+
86
+ self._logger.info(f"Successfully fetched OAuth access token, expires in {expires_in} seconds")
87
+ return access_token
88
+
89
+ except httpx.HTTPError as e:
90
+ self._logger.error(f"HTTP error fetching OAuth token: {e}")
91
+ raise RuntimeError(f"Failed to fetch OAuth access token: {e}") from e
92
+ except Exception as e:
93
+ self._logger.error(f"Unexpected error fetching OAuth token: {e}")
94
+ raise RuntimeError(f"Failed to fetch OAuth access token: {e}") from e
@@ -0,0 +1,8 @@
1
+ from typing import Protocol
2
+
3
+ class IOAuthTokenProvider(Protocol):
4
+ async def get_access_token(self) -> str: ...
5
+
6
+ class OAuthTokenProvider(IOAuthTokenProvider):
7
+ def __init__(self, domain: str, client_id: str, client_secret: str, audience: str, scope: str) -> None: ...
8
+ async def get_access_token(self) -> str: ...
@@ -0,0 +1,151 @@
1
+ import logging
2
+ from typing import Any
3
+
4
+ import httpx
5
+ from jose import JWTError, jwt
6
+
7
+ _logger = logging.getLogger("oauth_verification")
8
+
9
+
10
+ class TokenVerificationError(Exception):
11
+ """Exception raised when token verification fails."""
12
+
13
+ pass
14
+
15
+
16
+ class OAuth2TokenVerifier:
17
+ """Verifies OAuth2 JWT tokens from OAuth."""
18
+
19
+ def __init__(self, domain: str, audience: str, algorithms: list[str], issuer: str):
20
+ self._domain = domain
21
+ self._audience = audience
22
+ self._algorithms = algorithms
23
+ self._issuer = issuer
24
+ self._jwks_cache: dict[str, Any] | None = None
25
+
26
+ async def get_jwks(self) -> dict[str, Any]:
27
+ """Fetch JWKS (JSON Web Key Set) from OAuth.
28
+ Returns:
29
+ dict: The JWKS data containing public keys.
30
+ """
31
+ if self._jwks_cache:
32
+ return self._jwks_cache
33
+
34
+ jwks_url = f"https://{self._domain}/.well-known/jwks.json"
35
+
36
+ try:
37
+ async with httpx.AsyncClient() as client:
38
+ response = await client.get(jwks_url, timeout=10.0)
39
+ response.raise_for_status()
40
+ self._jwks_cache = response.json()
41
+ assert self._jwks_cache is not None
42
+ return self._jwks_cache
43
+ except Exception as e:
44
+ _logger.error(f"Failed to fetch JWKS from OAuth: {e}")
45
+ raise TokenVerificationError("Unable to fetch JWKS for token verification")
46
+
47
+ def _get_signing_key(self, token: str, jwks: dict[str, Any]) -> str:
48
+ """Extract the signing key from JWKS based on the token's kid (key ID).
49
+
50
+ Args:
51
+ token: The JWT token
52
+ jwks: The JWKS data
53
+
54
+ Returns:
55
+ str: The RSA public key for verification
56
+
57
+ Raises:
58
+ TokenVerificationError: If the signing key is not found
59
+ """
60
+ try:
61
+ unverified_header = jwt.get_unverified_header(token)
62
+ kid = unverified_header.get("kid")
63
+
64
+ if not kid:
65
+ raise TokenVerificationError("Token header missing 'kid' field")
66
+
67
+ # Find the key with matching kid
68
+ for key in jwks.get("keys", []):
69
+ if key.get("kid") == kid:
70
+ # Construct RSA public key from JWK
71
+ from jose.backends.cryptography_backend import CryptographyRSAKey
72
+
73
+ rsa_key = CryptographyRSAKey(key, algorithm="RS256")
74
+ return rsa_key.to_pem().decode()
75
+
76
+ raise TokenVerificationError(f"Unable to find signing key with kid: {kid}")
77
+ except JWTError as e:
78
+ _logger.error(f"Error extracting signing key: {e}")
79
+ raise TokenVerificationError("Invalid token header")
80
+
81
+ async def verify_token(self, token: str) -> dict[str, Any]:
82
+ """Verify an OAuth JWT token and return its payload.
83
+
84
+ Args:
85
+ token: The JWT token to verify
86
+
87
+ Returns:
88
+ dict: The decoded token payload containing claims
89
+
90
+ Raises:
91
+ TokenVerificationError: If verification fails
92
+ """
93
+ if not self._domain or not self._audience:
94
+ raise TokenVerificationError("OAuth configuration is incomplete")
95
+
96
+ try:
97
+ # Get JWKS
98
+ jwks = await self.get_jwks()
99
+
100
+ # Get the signing key
101
+ rsa_key = self._get_signing_key(token, jwks)
102
+
103
+ # Decode and verify the token
104
+ payload = jwt.decode(
105
+ token,
106
+ rsa_key,
107
+ algorithms=self._algorithms,
108
+ audience=self._audience,
109
+ issuer=self._issuer,
110
+ )
111
+
112
+ return payload
113
+
114
+ except JWTError as e:
115
+ _logger.warning(f"JWT verification failed: {e}")
116
+ raise TokenVerificationError(f"Token verification failed: {str(e)}")
117
+ except Exception as e:
118
+ _logger.error(f"Unexpected error during token verification: {e}")
119
+ raise TokenVerificationError("Token verification failed")
120
+
121
+ def verify_scopes(self, payload: dict[str, Any], required_scopes: list[str]) -> bool:
122
+ """Verify that the token has all required scopes.
123
+
124
+ Args:
125
+ payload: The decoded JWT payload
126
+ required_scopes: List of scope strings that must be present
127
+
128
+ Returns:
129
+ bool: True if all required scopes are present
130
+
131
+ Raises:
132
+ TokenVerificationError: If required scopes are missing
133
+ """
134
+ if not required_scopes:
135
+ return True
136
+
137
+ # OAuth typically puts scopes in the 'scope' claim as a space-separated string
138
+ token_scopes_str = payload.get("scope", "")
139
+ token_scopes = token_scopes_str.split() if token_scopes_str else []
140
+
141
+ # Alternatively, scopes might be in 'permissions' array
142
+ if not token_scopes and "permissions" in payload:
143
+ token_scopes = payload.get("permissions", [])
144
+
145
+ missing_scopes = [scope for scope in required_scopes if scope not in token_scopes]
146
+
147
+ if missing_scopes:
148
+ _logger.warning(f"Token missing required scopes: {missing_scopes}")
149
+ raise TokenVerificationError(f"Missing required scopes: {', '.join(missing_scopes)}")
150
+
151
+ return True
@@ -0,0 +1,9 @@
1
+ from typing import Any
2
+
3
+ class TokenVerificationError(Exception): ...
4
+
5
+ class OAuth2TokenVerifier:
6
+ def __init__(self, domain: str, audience: str, algorithms: list[str], issuer: str) -> None: ...
7
+ async def get_jwks(self) -> dict[str, Any]: ...
8
+ async def verify_token(self, token: str) -> dict[str, Any]: ...
9
+ def verify_scopes(self, payload: dict[str, Any], required_scopes: list[str]) -> bool: ...
@@ -0,0 +1,47 @@
1
+ [project]
2
+ name = "cezzis_oauth"
3
+ version = "0.0.18"
4
+ description = "A lightweight, production-ready Python library for OAuth 2.0 authentication. Provides both **token acquisition** and **JWT verification** with enterprise-grade features including automatic token caching, refresh management, JWKS-based verification, and scope validation."
5
+ authors = [
6
+ {name = "mtnvencenzo",email = "rvecchi@gmail.com"}
7
+ ]
8
+ packages = [{include = "cezzis_oauth", from = "."}]
9
+ license = {text = "MIT"}
10
+ readme = "README-pypi.md"
11
+ requires-python = ">=3.12,<3.15"
12
+ dependencies = [
13
+ "httpx (>=0.28.1,<0.29.0)",
14
+ "authlib (>=1.4.0,<2.0.0)",
15
+ "python-jose[cryptography] (>=3.5.0,<4.0.0)",
16
+ ]
17
+
18
+
19
+ [build-system]
20
+ requires = ["poetry-core>=2.0.0,<3.0.0"]
21
+ build-backend = "poetry.core.masonry.api"
22
+
23
+ [dependency-groups]
24
+ dev = [
25
+ "pytest (>=8.4.2,<9.0.0)",
26
+ "pytest-cov (>=4.0.0,<6.0.0)",
27
+ "ruff (>=0.14.3,<0.15.0)",
28
+ "pytest-mock (>=3.15.1,<4.0.0)",
29
+ "mypy (>=1.18.2,<2.0.0)",
30
+ "pytest-asyncio (>=1.3.0,<2.0.0)"
31
+ ]
32
+
33
+ [tool.pyright]
34
+ # Allow accessing private members in test files
35
+ reportPrivateUsage = "none"
36
+ # More specific: only disable for test directory
37
+ exclude = []
38
+ ignore = []
39
+
40
+ # Alternative: Configure per-directory rules
41
+ [[tool.pyright.executionEnvironments]]
42
+ root = "test"
43
+ reportPrivateUsage = "none"
44
+
45
+ [[tool.pyright.executionEnvironments]]
46
+ root = "."
47
+ reportPrivateUsage = "warning"