sanctum


Namesanctum JSON
Version 0.1.1 PyPI version JSON
download
home_pagehttps://github.com/nerdmonkey/python-sanctum
SummaryDeveloper-friendly AWS Cognito client for Python, with clean APIs for managing user pools and authentication flows.
upload_time2025-07-27 08:48:11
maintainerNone
docs_urlNone
authorSydel Palinlin
requires_python<4.0,>=3.8
licenseMIT
keywords aws cognito authentication rbac jwt user-management
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Sanctum

Developer-friendly AWS Cognito client for Python, with clean APIs for managing user pools and authentication flows.

[![Tests](https://img.shields.io/badge/tests-151_passing-green)](./tests)
[![Coverage](https://img.shields.io/badge/coverage-89%25-brightgreen)](./tests)
[![Python](https://img.shields.io/badge/python-3.8%2B-blue)](https://python.org)
[![License](https://img.shields.io/badge/license-MIT-blue)](./LICENSE)

## Installation

```bash
pip install sanctum
```

## Quick Start

```python
from sanctum import SanctumClient

# Initialize the client
client = SanctumClient(
    user_pool_id="us-east-1_123456789",
    client_id="your-app-client-id",
    region="us-east-1"
)

# User authentication
try:
    auth_result = client.authenticate_user(
        username="user@example.com",
        password="SecurePassword123!"
    )
    print(f"Login successful! Access token: {auth_result['AccessToken']}")
except AuthenticationError as e:
    print(f"Authentication failed: {e}")

# User management
user_info = client.create_user(
    username="newuser@example.com",
    password="TempPassword123!",
    email="newuser@example.com",
    temporary_password=True
)

# RBAC (Role-Based Access Control)
# Create groups and manage permissions
admin_group = client.create_group(
    group_name="admin",
    description="System administrators",
    precedence=1
)

# Add user to group
client.add_user_to_group(
    username="user@example.com",
    group_name="admin"
)

# Check user permissions
has_admin_access = client.user_has_group(
    username="user@example.com",
    group_name="admin"
)
```

## Features

### 🔐 Authentication & Authorization
- **Multiple Auth Flows**: USER_PASSWORD_AUTH, ADMIN_NO_SRP_AUTH, CUSTOM_AUTH
- **MFA Support**: SMS, TOTP, and custom challenge responses
- **Token Management**: Automatic refresh token handling
- **Role-Based Access Control (RBAC)**: AWS Cognito User Pool Groups integration

### 👥 User Management
- **User Lifecycle**: Create, update, delete users
- **Profile Management**: Update user attributes and preferences
- **Admin Operations**: Admin-initiated password changes and user management
- **User Status**: Enable, disable, confirm users

### 🛡️ Security Features
- **JWT Token Processing**: Parse and validate access tokens
- **Group-Based Permissions**: Check user group memberships from tokens
- **Secure Hash Calculation**: HMAC-SHA256 for client secret validation
- **Comprehensive Error Handling**: Detailed error reporting and handling

### 🏗️ Developer Experience
- **Clean, Intuitive API**: Pythonic interface for AWS Cognito operations
- **Comprehensive Testing**: 151 tests with 89% code coverage
- **Type Hints**: Full type annotation support
- **Modular Architecture**: Use individual components or the unified client

## API Overview

### Main Client

```python
from sanctum import SanctumClient

client = SanctumClient(
    user_pool_id="us-east-1_123456789",
    client_id="your-app-client-id",
    region="us-east-1",
    client_secret="your-client-secret"  # Optional
)
```

### Authentication Methods

```python
# User password authentication
auth_result = client.authenticate_user("user@example.com", "password")

# Admin authentication (no SRP)
auth_result = client.admin_authenticate("user@example.com", "password")

# Custom authentication flow
auth_result = client.initiate_custom_auth("user@example.com", auth_parameters={})
```

### User Management

```python
# Create user
user = client.create_user(
    username="user@example.com",
    password="TempPass123!",
    email="user@example.com",
    temporary_password=True
)

# Update user attributes
client.update_user_attributes("user@example.com", {"name": "John Doe"})

# Delete user
client.delete_user("user@example.com")
```

### RBAC Operations

```python
# Group management
client.create_group("admin", "Administrators", precedence=1)
client.add_user_to_group("user@example.com", "admin")

# Permission checking
is_admin = client.user_has_group("user@example.com", "admin")

# JWT token group extraction
groups = client.rbac.get_groups_from_token(access_token)
```

### Token Management

```python
# Refresh tokens
new_tokens = client.refresh_token(refresh_token)

# Respond to auth challenges
challenge_response = client.respond_to_auth_challenge(
    challenge_name="SMS_MFA",
    session="challenge-session",
    challenge_responses={"SMS_MFA_CODE": "123456"}
)
```

## Advanced Usage

### Using Individual Components

If you prefer to use specific components directly:

```python
from sanctum import RBACManager, TokenManager, UserManager

# Direct component usage
rbac = RBACManager(user_pool_id, client_id, region)
tokens = TokenManager(user_pool_id, client_id, region)
users = UserManager(user_pool_id, client_id, region)
```

### Error Handling

```python
from sanctum.exceptions import AuthenticationError, ValidationError, SanctumError

try:
    result = client.authenticate_user("user@example.com", "wrong-password")
except AuthenticationError as e:
    print(f"Authentication failed: {e}")
except ValidationError as e:
    print(f"Validation error: {e}")
except SanctumError as e:
    print(f"General Sanctum error: {e}")
```

## Documentation

- [Installation Guide](./docs/installation.rst)
- [Quick Start Tutorial](./docs/quickstart.rst)
- [API Reference](./docs/api.rst)
- [Examples & Use Cases](./docs/examples.rst)
- [Architecture Overview](./docs/architecture.md)

## Examples

Check out the [examples directory](./examples/) for comprehensive usage examples:

- **[Basic Usage](./examples/basic_usage.py)**: Authentication and user management
- **[Advanced Usage](./examples/advanced_usage.py)**: Complex workflows and error handling
- **[RBAC Examples](./examples/rbac_example.py)**: Role-based access control scenarios
- **[Test Workflows](./examples/test_workflow.py)**: Integration testing patterns

## Development

### Requirements

- Python 3.8+
- AWS account with Cognito User Pool configured
- boto3 and other dependencies (see `requirements.txt`)

### Testing

The project includes comprehensive tests with 89% coverage:

```bash
# Run all tests
python -m pytest tests/ --cov=sanctum --cov-report=term-missing

# Run specific test modules
python -m pytest tests/test_rbac.py -v
python -m pytest tests/test_client.py -v

# Run tests with coverage report
python -m pytest tests/ --cov=sanctum --cov-report=html
```

## Contributing

We welcome contributions! Please see [CONTRIBUTING.md](./CONTRIBUTING.md) for guidelines.

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Make your changes
4. Add tests for new functionality
5. Ensure all tests pass (`python -m pytest`)
6. Submit a pull request

## License

MIT License - see [LICENSE](./LICENSE) file for details.

## Changelog

See [CHANGELOG.md](./CHANGELOG.md) for a detailed history of changes.

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/nerdmonkey/python-sanctum",
    "name": "sanctum",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<4.0,>=3.8",
    "maintainer_email": null,
    "keywords": "aws, cognito, authentication, rbac, jwt, user-management",
    "author": "Sydel Palinlin",
    "author_email": "sydel.palinlin@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/c1/80/295ca1a04e9dd685ba9f3c05ec0d5ccca5dea14c328de0250495ec8236dd/sanctum-0.1.1.tar.gz",
    "platform": null,
    "description": "# Sanctum\n\nDeveloper-friendly AWS Cognito client for Python, with clean APIs for managing user pools and authentication flows.\n\n[![Tests](https://img.shields.io/badge/tests-151_passing-green)](./tests)\n[![Coverage](https://img.shields.io/badge/coverage-89%25-brightgreen)](./tests)\n[![Python](https://img.shields.io/badge/python-3.8%2B-blue)](https://python.org)\n[![License](https://img.shields.io/badge/license-MIT-blue)](./LICENSE)\n\n## Installation\n\n```bash\npip install sanctum\n```\n\n## Quick Start\n\n```python\nfrom sanctum import SanctumClient\n\n# Initialize the client\nclient = SanctumClient(\n    user_pool_id=\"us-east-1_123456789\",\n    client_id=\"your-app-client-id\",\n    region=\"us-east-1\"\n)\n\n# User authentication\ntry:\n    auth_result = client.authenticate_user(\n        username=\"user@example.com\",\n        password=\"SecurePassword123!\"\n    )\n    print(f\"Login successful! Access token: {auth_result['AccessToken']}\")\nexcept AuthenticationError as e:\n    print(f\"Authentication failed: {e}\")\n\n# User management\nuser_info = client.create_user(\n    username=\"newuser@example.com\",\n    password=\"TempPassword123!\",\n    email=\"newuser@example.com\",\n    temporary_password=True\n)\n\n# RBAC (Role-Based Access Control)\n# Create groups and manage permissions\nadmin_group = client.create_group(\n    group_name=\"admin\",\n    description=\"System administrators\",\n    precedence=1\n)\n\n# Add user to group\nclient.add_user_to_group(\n    username=\"user@example.com\",\n    group_name=\"admin\"\n)\n\n# Check user permissions\nhas_admin_access = client.user_has_group(\n    username=\"user@example.com\",\n    group_name=\"admin\"\n)\n```\n\n## Features\n\n### \ud83d\udd10 Authentication & Authorization\n- **Multiple Auth Flows**: USER_PASSWORD_AUTH, ADMIN_NO_SRP_AUTH, CUSTOM_AUTH\n- **MFA Support**: SMS, TOTP, and custom challenge responses\n- **Token Management**: Automatic refresh token handling\n- **Role-Based Access Control (RBAC)**: AWS Cognito User Pool Groups integration\n\n### \ud83d\udc65 User Management\n- **User Lifecycle**: Create, update, delete users\n- **Profile Management**: Update user attributes and preferences\n- **Admin Operations**: Admin-initiated password changes and user management\n- **User Status**: Enable, disable, confirm users\n\n### \ud83d\udee1\ufe0f Security Features\n- **JWT Token Processing**: Parse and validate access tokens\n- **Group-Based Permissions**: Check user group memberships from tokens\n- **Secure Hash Calculation**: HMAC-SHA256 for client secret validation\n- **Comprehensive Error Handling**: Detailed error reporting and handling\n\n### \ud83c\udfd7\ufe0f Developer Experience\n- **Clean, Intuitive API**: Pythonic interface for AWS Cognito operations\n- **Comprehensive Testing**: 151 tests with 89% code coverage\n- **Type Hints**: Full type annotation support\n- **Modular Architecture**: Use individual components or the unified client\n\n## API Overview\n\n### Main Client\n\n```python\nfrom sanctum import SanctumClient\n\nclient = SanctumClient(\n    user_pool_id=\"us-east-1_123456789\",\n    client_id=\"your-app-client-id\",\n    region=\"us-east-1\",\n    client_secret=\"your-client-secret\"  # Optional\n)\n```\n\n### Authentication Methods\n\n```python\n# User password authentication\nauth_result = client.authenticate_user(\"user@example.com\", \"password\")\n\n# Admin authentication (no SRP)\nauth_result = client.admin_authenticate(\"user@example.com\", \"password\")\n\n# Custom authentication flow\nauth_result = client.initiate_custom_auth(\"user@example.com\", auth_parameters={})\n```\n\n### User Management\n\n```python\n# Create user\nuser = client.create_user(\n    username=\"user@example.com\",\n    password=\"TempPass123!\",\n    email=\"user@example.com\",\n    temporary_password=True\n)\n\n# Update user attributes\nclient.update_user_attributes(\"user@example.com\", {\"name\": \"John Doe\"})\n\n# Delete user\nclient.delete_user(\"user@example.com\")\n```\n\n### RBAC Operations\n\n```python\n# Group management\nclient.create_group(\"admin\", \"Administrators\", precedence=1)\nclient.add_user_to_group(\"user@example.com\", \"admin\")\n\n# Permission checking\nis_admin = client.user_has_group(\"user@example.com\", \"admin\")\n\n# JWT token group extraction\ngroups = client.rbac.get_groups_from_token(access_token)\n```\n\n### Token Management\n\n```python\n# Refresh tokens\nnew_tokens = client.refresh_token(refresh_token)\n\n# Respond to auth challenges\nchallenge_response = client.respond_to_auth_challenge(\n    challenge_name=\"SMS_MFA\",\n    session=\"challenge-session\",\n    challenge_responses={\"SMS_MFA_CODE\": \"123456\"}\n)\n```\n\n## Advanced Usage\n\n### Using Individual Components\n\nIf you prefer to use specific components directly:\n\n```python\nfrom sanctum import RBACManager, TokenManager, UserManager\n\n# Direct component usage\nrbac = RBACManager(user_pool_id, client_id, region)\ntokens = TokenManager(user_pool_id, client_id, region)\nusers = UserManager(user_pool_id, client_id, region)\n```\n\n### Error Handling\n\n```python\nfrom sanctum.exceptions import AuthenticationError, ValidationError, SanctumError\n\ntry:\n    result = client.authenticate_user(\"user@example.com\", \"wrong-password\")\nexcept AuthenticationError as e:\n    print(f\"Authentication failed: {e}\")\nexcept ValidationError as e:\n    print(f\"Validation error: {e}\")\nexcept SanctumError as e:\n    print(f\"General Sanctum error: {e}\")\n```\n\n## Documentation\n\n- [Installation Guide](./docs/installation.rst)\n- [Quick Start Tutorial](./docs/quickstart.rst)\n- [API Reference](./docs/api.rst)\n- [Examples & Use Cases](./docs/examples.rst)\n- [Architecture Overview](./docs/architecture.md)\n\n## Examples\n\nCheck out the [examples directory](./examples/) for comprehensive usage examples:\n\n- **[Basic Usage](./examples/basic_usage.py)**: Authentication and user management\n- **[Advanced Usage](./examples/advanced_usage.py)**: Complex workflows and error handling\n- **[RBAC Examples](./examples/rbac_example.py)**: Role-based access control scenarios\n- **[Test Workflows](./examples/test_workflow.py)**: Integration testing patterns\n\n## Development\n\n### Requirements\n\n- Python 3.8+\n- AWS account with Cognito User Pool configured\n- boto3 and other dependencies (see `requirements.txt`)\n\n### Testing\n\nThe project includes comprehensive tests with 89% coverage:\n\n```bash\n# Run all tests\npython -m pytest tests/ --cov=sanctum --cov-report=term-missing\n\n# Run specific test modules\npython -m pytest tests/test_rbac.py -v\npython -m pytest tests/test_client.py -v\n\n# Run tests with coverage report\npython -m pytest tests/ --cov=sanctum --cov-report=html\n```\n\n## Contributing\n\nWe welcome contributions! Please see [CONTRIBUTING.md](./CONTRIBUTING.md) for guidelines.\n\n1. Fork the repository\n2. Create a feature branch (`git checkout -b feature/amazing-feature`)\n3. Make your changes\n4. Add tests for new functionality\n5. Ensure all tests pass (`python -m pytest`)\n6. Submit a pull request\n\n## License\n\nMIT License - see [LICENSE](./LICENSE) file for details.\n\n## Changelog\n\nSee [CHANGELOG.md](./CHANGELOG.md) for a detailed history of changes.\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Developer-friendly AWS Cognito client for Python, with clean APIs for managing user pools and authentication flows.",
    "version": "0.1.1",
    "project_urls": {
        "Documentation": "https://github.com/nerdmonkey/python-sanctum/tree/main/docs",
        "Homepage": "https://github.com/nerdmonkey/python-sanctum",
        "Repository": "https://github.com/nerdmonkey/python-sanctum"
    },
    "split_keywords": [
        "aws",
        " cognito",
        " authentication",
        " rbac",
        " jwt",
        " user-management"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "b82cb1b5beaa7545da479ae7191a779d53e5e75cb4e883142f96c0e6d20e834a",
                "md5": "9975a1ab9f235241b6db4e0f97a1b1d0",
                "sha256": "6e4a76295c411c7b16d92ad2aea2ea4d5bf73aa69d3323453d8e29e37e532020"
            },
            "downloads": -1,
            "filename": "sanctum-0.1.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "9975a1ab9f235241b6db4e0f97a1b1d0",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<4.0,>=3.8",
            "size": 16857,
            "upload_time": "2025-07-27T08:48:10",
            "upload_time_iso_8601": "2025-07-27T08:48:10.203445Z",
            "url": "https://files.pythonhosted.org/packages/b8/2c/b1b5beaa7545da479ae7191a779d53e5e75cb4e883142f96c0e6d20e834a/sanctum-0.1.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "c180295ca1a04e9dd685ba9f3c05ec0d5ccca5dea14c328de0250495ec8236dd",
                "md5": "9aca455c71e2b24547d06825f1b74a87",
                "sha256": "0b712b3757bc2c33b7db55b62c0ba1a90a6819e71d0fbd260830d38b61aeadf7"
            },
            "downloads": -1,
            "filename": "sanctum-0.1.1.tar.gz",
            "has_sig": false,
            "md5_digest": "9aca455c71e2b24547d06825f1b74a87",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<4.0,>=3.8",
            "size": 15161,
            "upload_time": "2025-07-27T08:48:11",
            "upload_time_iso_8601": "2025-07-27T08:48:11.532813Z",
            "url": "https://files.pythonhosted.org/packages/c1/80/295ca1a04e9dd685ba9f3c05ec0d5ccca5dea14c328de0250495ec8236dd/sanctum-0.1.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-07-27 08:48:11",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "nerdmonkey",
    "github_project": "python-sanctum",
    "github_not_found": true,
    "lcname": "sanctum"
}
        
Elapsed time: 1.86332s