Metadata-Version: 2.4
Name: gates-sdk
Version: 0.3.0
Summary: SDK em Python para integrar com o Gates para autenticação via Cognito e gestão de usuários
Author: Intelicity
License: MIT License
        
        Copyright (c) 2025 Intelicity
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Project-URL: Homepage, https://github.com/intelicity/gates-python-sdk
Project-URL: Repository, https://github.com/intelicity/gates-python-sdk
Project-URL: Documentation, https://github.com/intelicity/gates-python-sdk#readme
Project-URL: Bug Reports, https://github.com/intelicity/gates-python-sdk/issues
Project-URL: Source Code, https://github.com/intelicity/gates-python-sdk
Keywords: aws,cognito,jwt,authentication,gates,sdk
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: System :: Systems Administration :: Authentication/Directory
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pyjwt[crypto]>=2.8
Requires-Dist: httpx<1.0,>=0.27
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
Requires-Dist: black>=23.0; extra == "dev"
Requires-Dist: flake8>=6.0; extra == "dev"
Requires-Dist: mypy>=1.0; extra == "dev"
Requires-Dist: isort>=5.0; extra == "dev"
Requires-Dist: twine>=4.0; extra == "dev"
Requires-Dist: build>=0.10; extra == "dev"
Provides-Extra: test
Requires-Dist: pytest>=7.0; extra == "test"
Requires-Dist: pytest-cov>=4.0; extra == "test"
Requires-Dist: pytest-asyncio>=0.21; extra == "test"
Dynamic: license-file

# Gates SDK (Python)

[![PyPI version](https://badge.fury.io/py/gates-sdk.svg)](https://pypi.org/project/gates-sdk/)
[![Python versions](https://img.shields.io/pypi/pyversions/gates-sdk.svg)](https://pypi.org/project/gates-sdk/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)

Python SDK for authenticating users with AWS Cognito JWT tokens and managing users via the Gates backend API.

## Features

- JWT verification against AWS Cognito for both access tokens and id tokens
- Optional `client_id` validation, including multiple accepted client IDs
- Group-based authorization middleware
- Scope-based authorization middleware for M2M flows
- Automatic JWKS public key caching (1-hour TTL)
- Admin user management (create, update, list users)
- Framework-agnostic middleware (FastAPI, Flask, etc.)
- Full type hints and strict mypy compliance
- Comprehensive test suite

## Installation

```bash
pip install gates-sdk
```

## Quick Start

### Token Verification

```python
from gates_sdk import AuthService

# With a single client ID
auth = AuthService(
    region="sa-east-1",
    user_pool_id="sa-east-1_xxxxxxxxx",
    client_id="your-cognito-client-id",
)

# With multiple client IDs
auth = AuthService(
    region="sa-east-1",
    user_pool_id="sa-east-1_xxxxxxxxx",
    client_id=["client-id-1", "client-id-2"],
)

# Without client ID (skips client validation)
auth = AuthService(
    region="sa-east-1",
    user_pool_id="sa-east-1_xxxxxxxxx",
)

user = auth.verify_token(token)
print(user.user_id, user.groups, user.scopes)
```

Supports both `access_token` (validates the `client_id` claim) and `id_token` (validates the `aud` claim). The returned `GatesUser` also exposes `scopes`, populated from the token `scope` claim when present.

### Middleware

```python
from gates_sdk import (
    AuthService,
    HandleAuthConfig,
    authenticate,
    authorize,
    authorize_scopes,
    extract_token,
    handle_auth,
)

auth = AuthService(
    region="sa-east-1",
    user_pool_id="sa-east-1_xxxxxxxxx",
    client_id="your-cognito-client-id",
)

token = extract_token(request.headers.get("Authorization"))
user = authenticate(token, auth)
authorize(user, ["GAIA", "RECAPE"])
authorize_scopes(user, "gates/users.read")

user = handle_auth(
    request.headers.get("Authorization"),
    HandleAuthConfig(
        service=auth,
        required_groups=["GAIA"],
        required_scopes=["gates/users.read"],
    ),
)
```

### Admin Operations

```python
from gates_sdk import GatesAdminService

admin = GatesAdminService(base_url="https://api-gateway-url/stage")

result = admin.create_user(
    id_token,
    email="user@example.com",
    name="User Name",
    role="CLIENT_USER",
    client="GAIA",
)
print(result["sub"])

admin.update_user(
    id_token,
    user_id="user-sub-id",
    clients_to_add=["RECAPE"],
    clients_to_remove=["GAIA"],
)

response = admin.get_all_users(
    id_token,
    client="GAIA",
    page_size=20,
    name_filter="Alice",
    enabled_filter=True,
)
for user in response.users:
    print(user.user_id, user.name, user.email)
print(response.next_pagination_token, response.has_more, response.total_count)
```

## API Reference

### `AuthService(region, user_pool_id, client_id=None)`

Verifies JWT tokens issued by AWS Cognito.

| Parameter | Type | Description |
|-----------|------|-------------|
| `region` | `str` | AWS region (for example `"sa-east-1"`) |
| `user_pool_id` | `str` | Cognito User Pool ID |
| `client_id` | `str | List[str] | None` | Accepted Cognito App Client ID(s). Omit to skip client validation. |

Methods:
- `verify_token(token: str) -> GatesUser`

### `GatesAdminService(base_url)`

Calls the Gates API Gateway for user management. Methods currently receive an admin bearer token per call.

Methods:
- `create_user(id_token, *, email, name, role, client) -> dict`
- `update_user(id_token, *, user_id, clients_to_add=None, clients_to_remove=None) -> None`
- `get_all_users(id_token, *, client, pagination_token=None, page_size=None, name_filter=None, email_filter=None, role_filter=None, enabled_filter=None) -> GetAllUsersResponse`

### Middleware Functions

- `extract_token(authorization_header) -> str`
- `authenticate(token, service) -> GatesUser`
- `authorize(user, required_groups: str | List[str]) -> None`
- `authorize_scopes(user, required_scopes: str | List[str]) -> None`
- `handle_auth(authorization_header, config: HandleAuthConfig) -> GatesUser`

### `GatesUser`

| Field | Type | Description |
|-------|------|-------------|
| `user_id` | `str` | Cognito `sub` |
| `groups` | `List[str]` | `cognito:groups` claim, default `[]` |
| `scopes` | `List[str]` | `scope` claim split by spaces, default `[]` |
| `token_use` | `"access" | "id" | None` | Token type |
| `exp` | `int | None` | Expiration timestamp |
| `iat` | `int | None` | Issued-at timestamp |
| `email` | `str | None` | Usually present only in `id_token` |
| `name` | `str | None` | Usually present only in `id_token` |
| `role` | `str | None` | `custom:general_role` claim |

### `GetAllUsersResponse`

| Field | Type |
|-------|------|
| `users` | `List[UserDetails]` |
| `next_pagination_token` | `str | None` |
| `has_more` | `bool` |
| `total_count` | `int` |

### Error Hierarchy

```text
GatesError
|- AuthenticationError
|  |- TokenExpiredError       (code: TOKEN_EXPIRED)
|  |- InvalidTokenError       (code: INVALID_TOKEN)
|  |- MissingAuthorizationError (code: MISSING_AUTHORIZATION)
|  |- UnauthorizedGroupError  (code: UNAUTHORIZED_GROUP)
|  `- UnauthorizedScopeError  (code: UNAUTHORIZED_SCOPE)
|- ApiError
|  `- ApiRequestError         (code: API_REQUEST_ERROR, has .status_code)
|- MissingParameterError      (code: MISSING_PARAMETER)
`- InvalidParameterError      (code: INVALID_PARAMETER)
```

Valid roles: `INTERNAL_ADMIN`, `INTERNAL_USER`, `CLIENT_ADMIN`, `CLIENT_USER`

## Development

```bash
git clone https://github.com/intelicity/gates-python-sdk.git
cd gates-python-sdk
python -m venv venv
source venv/bin/activate  # or venv\Scripts\activate on Windows
pip install -e ".[dev]"

pytest
black src tests && isort src tests
flake8 src tests
mypy src
make check
```

## Requirements

- Python >= 3.9
- pyjwt[crypto] >= 2.8
- httpx >= 0.27, < 1.0

## License

MIT - see [LICENSE](LICENSE) for details.
