Skip to main content

SDK em Python para integrar com o Gates para autenticação via Cognito e gestão de usuários

Project description

Gates SDK (Python)

PyPI version Python versions License: MIT Code style: 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

pip install gates-sdk

Quick Start

Token Verification

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

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

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]

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"
exp `int None`
iat `int None`
email `str None`
name `str None`
role `str None`

GetAllUsersResponse

Field Type
users List[UserDetails]
next_pagination_token `str
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)
|  `- 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

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 for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

gates_sdk-0.3.0.tar.gz (21.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

gates_sdk-0.3.0-py3-none-any.whl (14.9 kB view details)

Uploaded Python 3

File details

Details for the file gates_sdk-0.3.0.tar.gz.

File metadata

  • Download URL: gates_sdk-0.3.0.tar.gz
  • Upload date:
  • Size: 21.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.5

File hashes

Hashes for gates_sdk-0.3.0.tar.gz
Algorithm Hash digest
SHA256 f23e90648e020a589e893e7e03ce8405893e1fe8b1105eae7d5d5866d88679a9
MD5 2c8bbe04f381c8f84b264ec3d178df4b
BLAKE2b-256 d2d80cd96482b9dbb4dd86f851f9d76ab45d8789bc4254d5b785eed600427cb2

See more details on using hashes here.

File details

Details for the file gates_sdk-0.3.0-py3-none-any.whl.

File metadata

  • Download URL: gates_sdk-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 14.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.5

File hashes

Hashes for gates_sdk-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 84322f407686a772fec944359ad005d5ab31e2fde1ae6d9f3aa3106f17003079
MD5 bc6a046e2508e0ddb1b8cd18ccf2c442
BLAKE2b-256 7caecf761898979d9ddc8f32581cc207571aae7e2f84fc8488c56be2f2139b34

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page