Metadata-Version: 2.4
Name: gates-sdk
Version: 0.2.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://badge.fury.io/py/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 (access tokens and id tokens)
- Group-based authorization middleware
- 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

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

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

### Middleware

```python
from gates_sdk import AuthService, HandleAuthConfig, handle_auth

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

# Composable functions
from gates_sdk import extract_token, authenticate, authorize

token = extract_token(request.headers.get("Authorization"))
user = authenticate(token, auth)
authorize(user, ["GAIA", "RECAPE"])  # accepts str or list

# Or all-in-one
user = handle_auth(
    request.headers.get("Authorization"),
    HandleAuthConfig(service=auth, required_groups=["GAIA"]),
)
```

### Admin Operations

```python
from gates_sdk import GatesAdminService

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

# Create a user and add them to a client group
result = admin.create_user(
    id_token,
    email="user@example.com",
    name="User Name",
    role="CLIENT_USER",
    client="GAIA",
)
print(result["sub"])  # new user's Cognito sub

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

# List all users for a client
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)`

Verifies JWT tokens issued by AWS Cognito.

| Parameter | Type | Description |
|-----------|------|-------------|
| `region` | `str` | AWS region (e.g. `"sa-east-1"`) |
| `user_pool_id` | `str` | Cognito User Pool ID |
| `client_id` | `str` | Cognito App Client ID |

**Methods:**
- `verify_token(token: str) -> GatesUser` — verifies the JWT and returns a `GatesUser`

### `GatesAdminService(base_url)`

Calls the Gates API Gateway for user management. All methods receive an `id_token` per call (admin's Cognito id_token).

**Methods:**
- `create_user(id_token, *, email, name, role, client) -> dict` — creates user and adds to client group
- `update_user(id_token, *, user_id, clients_to_add?, clients_to_remove?) -> None`
- `get_all_users(id_token, *, client, pagination_token?, page_size?, name_filter?, email_filter?, role_filter?, enabled_filter?) -> GetAllUsersResponse`

### Middleware Functions

- `extract_token(authorization_header) -> str` — extracts Bearer token; raises `MissingAuthorizationError` if not Bearer scheme
- `authenticate(token, service) -> GatesUser` — verifies token
- `authorize(user, required_groups: str | List[str]) -> None` — checks group membership
- `handle_auth(authorization_header, config: HandleAuthConfig) -> GatesUser` — composes all three

### `GatesUser`

| Field | Type | Description |
|-------|------|-------------|
| `user_id` | `str` | Cognito `sub` |
| `groups` | `List[str]` | `cognito:groups` claim (default `[]`) |
| `token_use` | `"access" \| "id"` | token type |
| `exp` | `int \| None` | expiration timestamp |
| `iat` | `int \| None` | issued-at timestamp |
| `email` | `str \| None` | id_token only |
| `name` | `str \| None` | id_token only |
| `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

```
GatesError
├── AuthenticationError
│   ├── TokenExpiredError          (code: TOKEN_EXPIRED)
│   ├── InvalidTokenError          (code: INVALID_TOKEN)
│   ├── MissingAuthorizationError  (code: MISSING_AUTHORIZATION)
│   └── UnauthorizedGroupError     (code: UNAUTHORIZED_GROUP)
├── 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
# Clone and set up
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]"

# Run tests
pytest

# Format
black src tests && isort src tests

# Lint + type check
flake8 src tests
mypy src

# All checks at once
make check
```

## Requirements

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

## License

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