Skip to content

Commit

Permalink
Merge pull request #2 from feteu/develop
Browse files Browse the repository at this point in the history
v1.0.1
  • Loading branch information
feteu authored Jan 12, 2025
2 parents 8dd7591 + 5c535f6 commit b806f96
Show file tree
Hide file tree
Showing 17 changed files with 446 additions and 70 deletions.
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Contributing to ASGI Claim Validator

Thanks for thinking about contributing to ASGI Request Duration! I welcome your help and can't wait to see what you'll bring to the table.
Thanks for thinking about contributing to ASGI Claim Validator! I welcome your help and can't wait to see what you'll bring to the table.

## How to Contribute

Expand Down
215 changes: 169 additions & 46 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,58 +8,98 @@
[![Build Status build/pypi](https://img.shields.io/github/actions/workflow/status/feteu/asgi-claim-validator/publish-pypi.yaml?label=publish-pypi)](https://github.com/feteu/asgi-claim-validator/actions/workflows/publish-pypi.yaml)
[![Build Status test](https://img.shields.io/github/actions/workflow/status/feteu/asgi-claim-validator/test.yaml?label=test)](https://github.com/feteu/asgi-claim-validator/actions/workflows/test.yaml)

# asgi-claim-validator
# asgi-claim-validator 🚀

A focused ASGI middleware for validating additional claims within JWT tokens to enhance token-based workflows.

## Overview
> **Note:** If you find this project useful, please consider giving it a star ⭐ on GitHub. This helps prioritize its maintenance and development. If you encounter any typos, bugs 🐛, or have new feature requests, feel free to open an issue. I will be happy to address them.

## Table of Contents 📑

1. [Overview 📖](#overview-)
1. [Purpose 🎯](#purpose-)
2. [Key Features ✨](#key-features-)
3. [Use Cases 💡](#use-cases-)
4. [Compatibility 🤝](#compatibility-)
2. [Installation 🛠️](#installation-)
3. [Usage 📚](#usage-)
1. [Basic Usage 🌟](#basic-usage)
2. [Configuration ⚙️](#configuration-)
3. [Error Handlers 🚨](#error-handlers-)
4. [Examples 📝](#examples-)
5. [Testing 🧪](#testing-)
6. [Contributing 🤝](#contributing-)
7. [License 📜](#license-)


## Overview 📖

`asgi-claim-validator` is an ASGI middleware designed to validate additional claims within JWT tokens. Built in addition to the default JWT verification implementation of Connexion, it enhances token-based workflows by ensuring that specific claims are present and meet certain criteria before allowing access to protected endpoints. This middleware allows consumers to validate claims on an endpoint/method level and is compatible with popular ASGI frameworks such as Starlette, FastAPI, and Connexion.

## Features
### Purpose 🎯

The primary purpose of `asgi-claim-validator` is to provide an additional layer of security by validating specific claims within JWT tokens. This ensures that only requests with valid and authorized tokens can access protected resources. The middleware is highly configurable, allowing developers to define essential claims, allowed values, and whether blank values are permitted. It also supports path and method filtering, enabling claim validation to be applied selectively based on the request path and HTTP method.

### Key Features ✨

- **Claim Validation**: Validate specific claims within JWT tokens, such as `sub`, `iss`, `aud`, `exp`, `iat`, and `nbf`.
- **Customizable Claims**: Define essential claims, allowed values, and whether blank values are permitted.
- **Path and Method Filtering**: Apply claim validation to specific paths and HTTP methods.
- **Exception Handling**: Integrate with custom exception handlers to provide meaningful error responses.
- **Logging**: Log validation errors for debugging and monitoring purposes.
- **Flexible Configuration**: Easily configure the middleware using a variety of options to suit different use cases.
- **Middleware Positioning**: Integrate the middleware at different positions within the ASGI application stack.
- **Token Extraction**: Extract tokens from various parts of the request, such as headers, cookies, or query parameters.
- **Custom Claim Validators**: Implement custom claim validation logic by providing your own validation functions.
- **Support for Multiple Frameworks**: Compatible with popular ASGI frameworks such as Starlette, FastAPI, and Connexion.
- **Performance Optimization**: Efficiently handle claim validation with minimal impact on request processing time.
- **Extensive Test Coverage**: Comprehensive test suite to ensure reliability and correctness of the middleware.

### Use Cases 💡

## Installation
- **API Security**: Enhance the security of your API by ensuring that only requests with valid JWT tokens and specific claims can access protected endpoints.
- **Role-Based Access Control**: Implement role-based access control by validating claims that represent user roles and permissions.
- **Compliance**: Ensure compliance with security policies by enforcing the presence and validity of specific claims within JWT tokens.
- **Custom Authentication Logic**: Implement custom authentication logic by providing your own claim validation functions.

Install the package using pip:
### Compatibility 🤝

`asgi-claim-validator` is compatible with popular ASGI frameworks such as Starlette, FastAPI, and Connexion. It can be easily integrated into existing ASGI applications and configured to suit various use cases and requirements.

By using `asgi-claim-validator`, you can enhance the security and flexibility of your token-based authentication workflows, ensuring that only authorized requests can access your protected resources.


## Installation 🛠️

To install the `asgi-claim-validator` package, use the following pip command:

```sh
pip install asgi-claim-validator
```

## Usage

### Basic Usage
## Usage 📚

Here's an example of how to use `asgi-claim-validator` with Starlette:
### Basic Usage 🌟

```python
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.routing import Route
from asgi_claim_validator import ClaimValidatorMiddleware
Below is an example of how to integrate `ClaimValidatorMiddleware` with a Connexion application. This middleware validates specific claims within JWT tokens for certain endpoints.

async def secured_endpoint(request: Request) -> JSONResponse:
return JSONResponse({"message": "secured"})
The `ClaimValidatorMiddleware` requires several parameters to function correctly. The `claims_callable` parameter is a callable that extracts token information from the Connexion context. This parameter must be specified and is typically dependent on the framework being used. The `secured` parameter is a dictionary that defines the secured paths and the claims that need to be validated. For instance, in the provided example, the `/secured` path requires the `sub` claim to be `admin` and the `iss` claim to be `https://example.com` for GET requests. The `skipped` parameter is a dictionary that specifies the paths and methods that should be excluded from validation. In the example, the `/skipped` path is skipped for GET requests.

```python
from asgi_claim_validator.middleware import ClaimValidatorMiddleware
from connexion import AsyncApp

app = Starlette(routes=[
Route("/secured", secured_endpoint, methods=["GET"]),
])
# Create a Connexion application
app = AsyncApp(__name__, specification_dir="spec")

# Add the ClaimValidatorMiddleware
app.add_middleware(
ClaimValidatorMiddleware,
claims_callable=lambda: {
"sub": "admin",
"iss": "https://example.com",
},
claims_callable=lambda scope: scope["extensions"]["connexion_context"]["token_info"],
secured={
"^/secured$": {
"^/secured/?$": {
"GET": {
"sub": {
"essential": True,
Expand All @@ -72,52 +112,135 @@ app.add_middleware(
"values": ["https://example.com"],
},
},
}
},
},
skipped={
"^/skipped/?$": ["GET"],
},
)
```

## Advanced Usage

### Custom Exception Handlers
### Configuration ⚙️

The `ClaimValidatorMiddleware` requires two main configuration pieces: `secured` and `skipped`. These configurations are validated using JSON schemas to ensure correctness.

> **Note:** The path regex patterns provided in the `secured` and `skipped` parameters will be automatically escaped by the middleware.
#### Secured Configuration

The `secured` configuration is a dictionary that defines the paths and the claims that need to be validated. Each path is associated with a dictionary of HTTP methods, and each method is associated with a dictionary of claims. Each claim can have the following properties:
- `essential`: A boolean indicating whether the claim is essential.
- `allow_blank`: A boolean indicating whether blank values are allowed.
- `values`: A list of allowed values for the claim.

Example:
```python
secured={
"^/secured/?$": {
"GET": {
"sub": {
"essential": True,
"allow_blank": False,
"values": ["admin"],
},
"iss": {
"essential": True,
"allow_blank": False,
"values": ["https://example.com"],
},
},
},
}
```

#### Skipped Configuration

The `skipped` configuration is a dictionary that defines the paths and methods that should be excluded from validation. Each path is associated with a list of HTTP methods.

Integrate `asgi-claim-validator` with custom exception handlers to provide meaningful error responses. Below are examples for Starlette and Connexion. Refer to the specific framework examples in the [examples](examples) directory for detailed implementation.
Example:
```python
skipped={
"^/skipped/?$": ["GET"],
}
```

### Middleware Configuration
#### JSON Schema Validation

Configure the middleware with the following options:
Both `secured` and `skipped` configurations are validated using JSON schemas to ensure their correctness. This validation helps catch configuration errors early and ensures that the middleware behaves as expected.

- **claims_callable**: A callable that returns the JWT claims to be validated.
- **secured**: A dictionary defining the paths and methods that require claim validation.
- **skipped**: A dictionary defining the paths and methods to be excluded from claim validation.
- **raise_on_unspecified_path**: Raise an exception if the path is not specified in the `secured` or `skipped` dictionaries.
- **raise_on_unspecified_method**: Raise an exception if the method is not specified for a secured path.

### Claim Validation Options
### Error Handlers 🚨

Configure claims with the following options:
To handle exceptions raised by this middleware, you can configure your framework (such as Starlette or Connexion) to catch and process them dynamically. For security reasons, the exception messages are kept generic, but you can customize them using the exception parameters.

- **essential**: Indicates if the claim is essential (default: `False`).
- **allow_blank**: Indicates if blank values are allowed (default: `True`).
- **values**: A list of allowed values for the claim.
#### Connexion

```python
from asgi_claim_validator import ClaimValidatorMiddleware, ClaimValidatorException
from connexion import AsyncApp
from connexion.lifecycle import ConnexionRequest, ConnexionResponse

## Examples
# [...]

def claim_validator_error_handler(request: ConnexionRequest, exc: ClaimValidatorException) -> ConnexionResponse:
return problem(detail=exc.detail, status=exc.status, title=exc.title)

app = AsyncApp(__name__, specification_dir="spec")
app.add_error_handler(ClaimValidatorException, claim_validator_error_handler)

# [...]
```

#### Starlette

```python
from asgi_claim_validator import ClaimValidatorMiddleware, ClaimValidatorException
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import JSONResponse

# [...]

async def claim_validator_error_handler(request: Request, exc: ClaimValidatorException) -> JSONResponse:
return JSONResponse({"error": f"{exc.title}"}, status_code=exc.status)

exception_handlers = {
ClaimValidatorException: claim_validator_error_handler
}

app = Starlette(routes=routes, exception_handlers=exception_handlers)

# [...]
```

## Examples 📝

### Starlette Example
Refer to the [app.py](examples/starlette/simple/app.py) file for a complete example using Starlette.
To see a complete example using Starlette, refer to the [app.py](examples/starlette/simple/app.py) file.

### Connexion Example
Refer to the [app.py](examples/connexion/simple/app.py) file for a complete example using Connexion.
Check out the [app.py](examples/connexion/simple/app.py) file for a simple example using Connexion. For a comprehensive example that demonstrates automatic extraction and validation of token claims with Connexion, see the [app.py](examples/connexion/complex/app.py) file.

## Testing
## Testing 🧪
Run the tests using `pytest`:

```sh
poetry run pytest
```

## Contributing
### Scope:

- **Middleware Functionality**: Ensures correct validation of JWT claims and proper handling of secured and skipped paths.
- **Exception Handling**: Verifies that custom exceptions are raised and handled appropriately.
- **Configuration Validation**: Checks the correctness of middleware configuration for secured and skipped paths.
- **Integration with Frameworks**: Confirms seamless integration with ASGI frameworks like Starlette and Connexion.
- **Custom Claim Validators**: Tests the implementation and usage of custom claim validation logic.


## Contributing 🤝
Contributions are welcome! Please refer to the [CONTRIBUTING.md](CONTRIBUTING.md) file for guidelines on how to contribute to this project.

## License

## License 📜
This project is licensed under the GNU GPLv3 License. See the [LICENSE](LICENSE) file for more details.
19 changes: 16 additions & 3 deletions asgi_claim_validator/__init__.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,35 @@
from asgi_claim_validator.decorators import validate_claims_callable
from asgi_claim_validator.exceptions import (
ClaimValidatorException,
InvalidClaimsConfigurationException,
InvalidClaimsTypeException,
InvalidClaimValueException,
InvalidSecuredConfigurationException,
InvalidSkippedConfigurationException,
MissingEssentialClaimException,
UnauthenticatedRequestException,
UnspecifiedMethodAuthenticationException,
UnspecifiedPathAuthenticationException,
)
from asgi_claim_validator.middleware import ClaimValidatorMiddleware
from asgi_claim_validator.types import SecuredCompiledType, SecuredType, SkippedCompiledType, SkippedType
from asgi_claim_validator.types import (
ClaimsCallableType,
ClaimsType,
SecuredCompiledType,
SecuredType,
SkippedCompiledType,
SkippedType,
)

__all__ = (
"ClaimsCallableType",
"ClaimsType",
"ClaimValidatorException",
"ClaimValidatorMiddleware",
"InvalidClaimsConfigurationException",
"InvalidClaimsTypeException",
"InvalidClaimValueException",
"InvalidSecuredConfigurationException",
"InvalidSkippedConfigurationException",
"MissingEssentialClaimException",
"SecuredCompiledType",
"SecuredType",
Expand All @@ -24,5 +38,4 @@
"UnauthenticatedRequestException",
"UnspecifiedMethodAuthenticationException",
"UnspecifiedPathAuthenticationException",
"validate_claims_callable",
)
2 changes: 1 addition & 1 deletion asgi_claim_validator/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
"TRACE",
]
_DEFAULT_ALL_HTTP_METHODS_REGEX_GROUP: str = f"({'|'.join(map(escape, (*_DEFAULT_ALL_HTTP_METHODS, *_DEFAULT_ANY_HTTP_METHODS)))})"
_DEFAULT_CLAIMS_CALLABLE: ClaimsCallableType = lambda: dict()
_DEFAULT_CLAIMS_CALLABLE: ClaimsCallableType = lambda scope: scope.get("", dict())
_DEFAULT_RAISE_ON_INVALID_CLAIM: bool = True
_DEFAULT_RAISE_ON_INVALID_CLAIMS_TYPE: bool = True
_DEFAULT_RAISE_ON_MISSING_CLAIM: bool = True
Expand Down
24 changes: 21 additions & 3 deletions asgi_claim_validator/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,13 @@
log = getLogger(__name__)

def validate_claims_callable() -> Callable:
def decorator(func) -> Callable:
"""
Decorator to validate the claims_callable attribute of a class.
Raises:
InvalidClaimsConfigurationException: If claims_callable is not a callable.
"""
def decorator(func: Callable) -> Callable:
def wrapper(self, *args, **kwargs) -> Callable:
claims = getattr(self, 'claims_callable', _DEFAULT_CLAIMS_CALLABLE)
if not isinstance(claims, Callable):
Expand All @@ -26,7 +32,13 @@ def wrapper(self, *args, **kwargs) -> Callable:
return decorator

def validate_secured() -> Callable:
def decorator(func) -> Callable:
"""
Decorator to validate the secured attribute of a class against a JSON schema.
Raises:
InvalidSecuredConfigurationException: If the secured attribute does not conform to the schema.
"""
def decorator(func: Callable) -> Callable:
def wrapper(self, *args, **kwargs) -> Callable:
secured = getattr(self, 'secured', None)
try:
Expand All @@ -39,7 +51,13 @@ def wrapper(self, *args, **kwargs) -> Callable:
return decorator

def validate_skipped() -> Callable:
def decorator(func) -> Callable:
"""
Decorator to validate the skipped attribute of a class against a JSON schema.
Raises:
InvalidSkippedConfigurationException: If the skipped attribute does not conform to the schema.
"""
def decorator(func: Callable) -> Callable:
def wrapper(self, *args, **kwargs) -> Callable:
skipped = getattr(self, 'skipped', None)
try:
Expand Down
Loading

0 comments on commit b806f96

Please sign in to comment.