Skip to content

Security Examples

Comprehensive examples for secret management, authentication, and encryption.

Overview

The security module provides production-ready utilities for managing secrets, handling authentication, and performing encryption operations.

Examples

1. Secret Management

File: examples/security/01_secret_management.py

Demonstrates secret storage and retrieval.

Topics: - Environment Variable Secrets: Store secrets in environment variables - File-Based Secrets: Development-friendly file-based storage - Auto-Detection: Automatic backend selection (Vault → AWS → Env) - Common Patterns: Configuration loading, secret namespacing

Run:

python examples/security/01_secret_management.py

2. Authentication

File: examples/security/02_authentication.py

Shows authentication providers and token management.

Topics: - Static Tokens: Simple API key authentication - JWT Tokens: JSON Web Token generation and validation - Token Rotation: Automatic token refresh before expiry - Callbacks: React to token refresh events - Production Patterns: Service-to-service authentication

Run:

python examples/security/02_authentication.py

3. Encryption

File: examples/security/03_encryption.py

Covers encryption and cryptographic operations.

Topics: - Fernet Encryption: Simple symmetric encryption - AES-256-GCM: Advanced authenticated encryption - Password Hashing: Secure password storage with PBKDF2 - Token Generation: Cryptographically secure random tokens - Constant-Time Comparison: Timing attack prevention - Data Hashing: Integrity verification with SHA-256/512 - Production Patterns: Database field encryption, config files

Run:

python examples/security/03_encryption.py

Quick Start

# Secret management
from dspu.security import SecretManager

secrets = SecretManager.from_env()
api_key = await secrets.get("api/key")

# Authentication
from dspu.security import create_auth_provider

auth = create_auth_provider("jwt", secret_key="secret")
token = await auth.get_token(scopes=["read", "write"])

# Encryption
from dspu.security import Fernet

key = Fernet.generate_key()
cipher = Fernet(key)
encrypted = cipher.encrypt(b"secret data")
decrypted = cipher.decrypt(encrypted)

Common Patterns

Pattern 1: Loading Application Secrets

import os
from dspu.security import SecretManager

# Auto-detect backend from environment
secrets = SecretManager.from_env()

# Load database credentials
db_password = await secrets.get("database/password")
db_url = f"postgresql://user:{db_password}@host/db"

# Load API keys
api_key = await secrets.get("api/key")

Pattern 2: Service Authentication

from dspu.security import JWTProvider, RotatingToken, TokenData

# JWT provider
auth = JWTProvider(
    secret_key=await secrets.get("jwt/secret"),
    issuer="my-service",
    expiry_seconds=900
)

# Auto-rotating token for long-running service
async def fetch_token() -> TokenData:
    token = await auth.get_token(scopes=["api:read", "api:write"])
    # Parse JWT for expiry...
    return TokenData(token=token, expires_at=expiry_time)

async with RotatingToken(fetch_fn=fetch_token) as rotating:
    # Use rotating.current for API calls
    headers = {"Authorization": f"Bearer {rotating.current}"}

Pattern 3: Encrypting Sensitive Data

from dspu.security import Fernet

# Get encryption key from secrets
key = await secrets.get("encryption/key")
cipher = Fernet(key.encode())

# Encrypt before storing
user.email_encrypted = cipher.encrypt(user.email)
user.phone_encrypted = cipher.encrypt(user.phone)

# Decrypt when needed
email = cipher.decrypt_str(user.email_encrypted)

Pattern 4: Password Hashing

from dspu.security import hash_password, verify_password

# Hash password before storing
hashed = hash_password("user_password")
user.password_hash = hashed

# Verify password on login
if verify_password("user_password", user.password_hash):
    # Login successful
    ...

Backend Support

Backend Production Ready Use Case
Environment Variables ✅ Yes Simple deployments, containers
File-Based ❌ No Development only
HashiCorp Vault ✅ Yes Enterprise secret management
AWS Secrets Manager ✅ Yes AWS deployments
Azure Key Vault 🚧 Planned Azure deployments
GCP Secret Manager 🚧 Planned GCP deployments

Secret Management

Environment Variables

from dspu.security import SecretManager

# From environment
secrets = SecretManager.from_env()
api_key = await secrets.get("API_KEY")

HashiCorp Vault

# From Vault
vault_secrets = SecretManager.from_vault(
    url="http://vault:8200",
    token="s.abc123"
)
db_password = await vault_secrets.get("database/password")

AWS Secrets Manager

# From AWS
aws_secrets = SecretManager.from_aws(region="us-east-1")
secret = await aws_secrets.get("prod/api/key")

Authentication Providers

Static Token

from dspu.security import StaticTokenProvider

auth = StaticTokenProvider(token="sk_live_abc123")
token = await auth.get_token()

JWT

from dspu.security import JWTProvider

auth = JWTProvider(
    secret_key="your-secret-key",
    issuer="my-service",
    expiry_seconds=3600
)
token = await auth.get_token(scopes=["read", "write"])

OAuth2

from dspu.security import OAuth2Provider

auth = OAuth2Provider(
    client_id="client_id",
    client_secret="client_secret",
    token_url="https://auth.example.com/token"
)
token = await auth.get_token()

Encryption

Fernet (Simple)

from dspu.security import Fernet

# Generate key
key = Fernet.generate_key()
cipher = Fernet(key)

# Encrypt
encrypted = cipher.encrypt(b"sensitive data")

# Decrypt
decrypted = cipher.decrypt(encrypted)

AES-256-GCM (Advanced)

from dspu.security import AES

# Generate key
key = AES.generate_key()
cipher = AES(key)

# Encrypt with authentication
encrypted = cipher.encrypt(b"sensitive data")

# Decrypt and verify
decrypted = cipher.decrypt(encrypted)

Password Hashing

from dspu.security import hash_password, verify_password

# Hash password
hashed = hash_password("my_password")

# Verify password
is_valid = verify_password("my_password", hashed)  # True
is_valid = verify_password("wrong_password", hashed)  # False

Security Best Practices

Secret Management

DO: - Use Vault or cloud secret managers in production - Rotate secrets regularly - Use strong encryption for stored secrets - Never commit secrets to version control

DON'T: - Don't use file-based secrets in production - Don't log secrets - Don't hardcode secrets in source code - Don't share secrets between environments

Authentication

DO: - Use short-lived tokens (15-60 minutes) - Implement token rotation for long-running services - Store JWT secrets securely (secret manager) - Use HTTPS for all token transmission

DON'T: - Don't store tokens in localStorage without encryption - Don't use weak secrets for JWT signing - Don't skip token expiry validation - Don't use same secret across environments

Encryption

DO: - Generate keys using cryptographically secure methods - Store encryption keys separately from encrypted data - Use AES-256-GCM for authenticated encryption - Implement key rotation strategy

DON'T: - Don't hardcode encryption keys in source code - Don't use weak encryption (DES, RC4, etc.) - Don't roll your own cryptography - Don't skip integrity verification

Installation

# Install with security extras
pip install 'dspu[security]'

This includes: - cryptography - Encryption algorithms - pyjwt - JWT token support - hvac - HashiCorp Vault integration

See Also