cezzis-oauth-fastapi 0.0.20__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,61 @@
1
+ Metadata-Version: 2.4
2
+ Name: cezzis_oauth_fastapi
3
+ Version: 0.0.20
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: cezzis-oauth (>=0.0.19,<0.0.20)
16
+ Requires-Dist: fastapi[standard] (>=0.128.0,<0.129.0)
17
+ Requires-Dist: httpx (>=0.28.1,<0.29.0)
18
+ Requires-Dist: python-jose[cryptography] (>=3.5.0,<4.0.0)
19
+ Description-Content-Type: text/markdown
20
+
21
+ # Cezzis OAuth
22
+
23
+ [![Python Version](https://img.shields.io/badge/python-3.12%2B-blue.svg)](https://www.python.org/downloads/)
24
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
25
+ [![PyPI version](https://img.shields.io/pypi/v/cezzis-oauth-fastapi.svg)](https://pypi.org/project/cezzis-oauth-fastapi/)
26
+ [![CI/CD](https://github.com/mtnvencenzo/cezzis-pycore/actions/workflows/cezzis-oauth-fastapi-cicd.yaml/badge.svg)](https://github.com/mtnvencenzo/cezzis-pycore/actions/workflows/cezzis-oauth-fastapi-cicd.yaml)
27
+
28
+ 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.
29
+
30
+ ## 🚀 Installation
31
+
32
+ Install `cezzis-oauth-fastapi` from PyPI:
33
+
34
+ ```bash
35
+ pip install cezzis-oauth-fastapi
36
+ ```
37
+
38
+ Or using Poetry:
39
+
40
+ ```bash
41
+ poetry add cezzis-oauth-fastapi
42
+ ```
43
+
44
+ ## 📋 Requirements
45
+
46
+ - Python 3.12 or higher
47
+
48
+ ## 📖 Documentation & Examples
49
+
50
+ Complete documentation, examples, and guides are available in the GitHub repository:
51
+
52
+ [Full Documentation & Examples](https://github.com/mtnvencenzo/cezzis-pycore/blob/main/cezzis-oauth-fastapi/README.md)
53
+
54
+
55
+ ## 📄 License
56
+
57
+ This project is licensed under the MIT License. See the [LICENSE](https://github.com/mtnvencenzo/cezzis-pycore/blob/main/LICENSE) file for details.
58
+
59
+ ---
60
+
61
+
@@ -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-fastapi.svg)](https://pypi.org/project/cezzis-oauth-fastapi/)
6
+ [![CI/CD](https://github.com/mtnvencenzo/cezzis-pycore/actions/workflows/cezzis-oauth-fastapi-cicd.yaml/badge.svg)](https://github.com/mtnvencenzo/cezzis-pycore/actions/workflows/cezzis-oauth-fastapi-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-fastapi` from PyPI:
13
+
14
+ ```bash
15
+ pip install cezzis-oauth-fastapi
16
+ ```
17
+
18
+ Or using Poetry:
19
+
20
+ ```bash
21
+ poetry add cezzis-oauth-fastapi
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/cezzis-oauth-fastapi/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,17 @@
1
+ """Cezzis OAuth FastAPI - A lightweight library for OAuth authentication and utilities for fastapi."""
2
+
3
+ from cezzis_oauth_fastapi.oauth_authorization import oauth_authorization
4
+ from cezzis_oauth_fastapi.oauth_config import OAuthConfig
5
+
6
+ # Dynamically read version from package metadata
7
+ try:
8
+ from importlib.metadata import version
9
+
10
+ __version__ = version("cezzis_oauth_fastapi")
11
+ except Exception:
12
+ __version__ = "unknown"
13
+
14
+ __all__ = [
15
+ "oauth_authorization",
16
+ "OAuthConfig",
17
+ ]
@@ -0,0 +1,4 @@
1
+ from cezzis_oauth_fastapi.oauth_authorization import oauth_authorization as oauth_authorization
2
+ from cezzis_oauth_fastapi.oauth_config import OAuthConfig as OAuthConfig
3
+
4
+ __all__ = ['oauth_authorization', 'OAuthConfig']
@@ -0,0 +1,141 @@
1
+ import logging
2
+ import os
3
+ from functools import wraps
4
+ from typing import Callable, Union
5
+
6
+ from cezzis_oauth import (
7
+ OAuth2TokenVerifier,
8
+ TokenVerificationError,
9
+ )
10
+ from fastapi import HTTPException, Request
11
+
12
+ from cezzis_oauth_fastapi.oauth_config import OAuthConfig
13
+
14
+ _logger = logging.getLogger("oauth_authorization")
15
+
16
+ # Cache verifiers by config to avoid recreating them
17
+ _verifiers: dict[tuple, OAuth2TokenVerifier] = {}
18
+
19
+
20
+ def _get_config_key(config: OAuthConfig) -> tuple:
21
+ """Create a hashable key from OAuthConfig for caching verifiers."""
22
+ return (config.domain, config.audience, tuple(config.algorithms), config.issuer)
23
+
24
+
25
+ def oauth_authorization(scopes: list[str], config_provider: Callable[[], OAuthConfig]):
26
+ """Decorator for OAuth2 authorization with OAuth token verification.
27
+
28
+ Can be applied to:
29
+ - Individual endpoint methods (async functions)
30
+ - APIRouter classes (all methods will be protected)
31
+
32
+ Args:
33
+ scopes: List of required OAuth scopes.
34
+ config_provider: A callable that returns an OAuthConfig instance.
35
+
36
+ Example:
37
+ # On a method
38
+ @oauth_authorization(scopes=["write:embeddings"], config_provider=get_oauth_config)
39
+ async def get_cocktails(self, _rq: Request):
40
+ ...
41
+
42
+ # On a class (protects all methods)
43
+ @oauth_authorization(scopes=["admin:cocktails"], config_provider=get_oauth_config)
44
+ class AdminRouter(APIRouter):
45
+ ...
46
+
47
+ # Without scope verification
48
+ @oauth_authorization(scopes=[], config_provider=get_oauth_config)
49
+ async def public_endpoint(self, _rq: Request):
50
+ ...
51
+ """
52
+ required_scopes = scopes or []
53
+
54
+ def decorator(target: Union[Callable, type]) -> Union[Callable, type]:
55
+ # Check if target is a class
56
+ if isinstance(target, type):
57
+ return _wrap_class(target, required_scopes, config_provider())
58
+ else:
59
+ return _wrap_function(target, required_scopes, config_provider())
60
+
61
+ return decorator
62
+
63
+
64
+ def _wrap_function(func: Callable, required_scopes: list[str], oauth_config: OAuthConfig) -> Callable:
65
+ """Wrap an individual async function with OAuth authorization."""
66
+
67
+ @wraps(func)
68
+ async def wrapper(*args, **kwargs):
69
+ global _verifiers
70
+
71
+ # Extract the Request object from kwargs
72
+ request: Request | None = kwargs.get("_rq")
73
+
74
+ if request is None:
75
+ _logger.error("Request object not found in function arguments")
76
+ raise HTTPException(status_code=500, detail="Internal server error")
77
+
78
+ # Check if authorization should be bypassed in local environment
79
+ if os.getenv("ENV") == "local":
80
+ _logger.info("OAuth authorization bypassed in local environment")
81
+ return await func(*args, **kwargs)
82
+
83
+ # Extract token from Authorization header
84
+ auth_header = request.headers.get("Authorization", "")
85
+ if not auth_header or not auth_header.startswith("Bearer "):
86
+ _logger.warning("Missing or invalid Authorization header")
87
+ raise HTTPException(status_code=401, detail="Missing or invalid authorization token")
88
+
89
+ token = auth_header.replace("Bearer ", "").strip()
90
+
91
+ try:
92
+ # Get or create verifier for this config
93
+ config_key = _get_config_key(oauth_config)
94
+ if config_key not in _verifiers:
95
+ _verifiers[config_key] = OAuth2TokenVerifier(
96
+ domain=oauth_config.domain,
97
+ audience=oauth_config.audience,
98
+ algorithms=oauth_config.algorithms,
99
+ issuer=oauth_config.issuer,
100
+ )
101
+
102
+ verifier = _verifiers[config_key]
103
+ payload = await verifier.verify_token(token)
104
+
105
+ # Verify scopes if required
106
+ if required_scopes:
107
+ verifier.verify_scopes(payload, required_scopes)
108
+
109
+ _logger.info(f"OAuth authorization successful for subject: {payload.get('sub', 'unknown')}")
110
+
111
+ # Call the original function
112
+ return await func(*args, **kwargs)
113
+
114
+ except TokenVerificationError as e:
115
+ _logger.warning(f"OAuth authorization failed: {e}")
116
+ raise HTTPException(status_code=403, detail=str(e))
117
+ except Exception as e:
118
+ _logger.error(f"Unexpected error during OAuth authorization: {e}")
119
+ raise HTTPException(status_code=500, detail="Authorization error")
120
+
121
+ return wrapper
122
+
123
+
124
+ def _wrap_class(cls: type, required_scopes: list[str], oauth_config: OAuthConfig) -> type:
125
+ """Wrap all async methods in a class with OAuth authorization."""
126
+
127
+ # Get all methods from the class
128
+ for attr_name in dir(cls):
129
+ # Skip private/magic methods and non-callables
130
+ if attr_name.startswith("_"):
131
+ continue
132
+
133
+ attr = getattr(cls, attr_name)
134
+
135
+ # Check if it's a callable method (not a property or static attribute)
136
+ if callable(attr) and not isinstance(attr, (staticmethod, classmethod, property)):
137
+ # Wrap the method
138
+ wrapped = _wrap_function(attr, required_scopes, oauth_config)
139
+ setattr(cls, attr_name, wrapped)
140
+
141
+ return cls
@@ -0,0 +1,5 @@
1
+ from cezzis_oauth_fastapi.oauth_config import OAuthConfig as OAuthConfig
2
+ from fastapi import Request as Request
3
+ from typing import Callable
4
+
5
+ def oauth_authorization(scopes: list[str], config_provider: Callable[[], OAuthConfig]): ...
@@ -0,0 +1,10 @@
1
+ from typing import Protocol
2
+
3
+
4
+ class OAuthConfig(Protocol):
5
+ """Protocol defining required OAuth configuration properties."""
6
+
7
+ domain: str
8
+ audience: str
9
+ algorithms: list[str]
10
+ issuer: str
@@ -0,0 +1,7 @@
1
+ from typing import Protocol
2
+
3
+ class OAuthConfig(Protocol):
4
+ domain: str
5
+ audience: str
6
+ algorithms: list[str]
7
+ issuer: str
@@ -0,0 +1,49 @@
1
+ [project]
2
+ name = "cezzis_oauth_fastapi"
3
+ version = "0.0.20"
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_fastapi", 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
+ "fastapi[standard] (>=0.128.0,<0.129.0)",
17
+ "cezzis-oauth (>=0.0.19,<0.0.20)",
18
+ ]
19
+
20
+
21
+ [build-system]
22
+ requires = ["poetry-core>=2.0.0,<3.0.0"]
23
+ build-backend = "poetry.core.masonry.api"
24
+
25
+ [dependency-groups]
26
+ dev = [
27
+ "pytest (>=8.4.2,<9.0.0)",
28
+ "pytest-cov (>=4.0.0,<6.0.0)",
29
+ "ruff (>=0.14.3,<0.15.0)",
30
+ "pytest-mock (>=3.15.1,<4.0.0)",
31
+ "mypy (>=1.18.2,<2.0.0)",
32
+ "pytest-asyncio (>=1.3.0,<2.0.0)"
33
+ ]
34
+
35
+ [tool.pyright]
36
+ # Allow accessing private members in test files
37
+ reportPrivateUsage = "none"
38
+ # More specific: only disable for test directory
39
+ exclude = []
40
+ ignore = []
41
+
42
+ # Alternative: Configure per-directory rules
43
+ [[tool.pyright.executionEnvironments]]
44
+ root = "test"
45
+ reportPrivateUsage = "none"
46
+
47
+ [[tool.pyright.executionEnvironments]]
48
+ root = "."
49
+ reportPrivateUsage = "warning"