Welcome to Project Documentation of CryptoFolio

Contents

Detailed Module Documentation

app

configuration.config

CryptoCache: Advanced Security Framework for Flask Applications Version: 1.0 Author: Gabriel Cellammare Last Modified: 05/01/2025

This module implements a comprehensive security framework for Flask applications with defense-in-depth measures and robust security controls. It provides multi-layered protection against various attack vectors while ensuring data integrity and secure cross-origin communications.

Core Security Features: 1. Origin Validation

  • Strict origin validation with DNS rebinding protection

  • Null byte injection prevention

  • IP-based origin validation

  • Protocol enforcement

  1. Environment Security * Secure environment variable handling * Runtime modification prevention * Default security fallbacks * Configuration immutability

  2. CORS Protection * Header injection prevention * Strict CORS policy enforcement * Secure credential handling * Cache poisoning protection

  3. Audit & Logging * Secure audit logging * Log sanitization * Rotation policies * Sensitive data masking

Security Considerations: - All environment variables must be securely configured - SSL/TLS must be properly configured on the server - Regular security audits should be performed - Security updates should be monitored and applied

Dependencies: - flask>=2.0.0: Web framework - urllib3>=2.0.0: HTTP client - cryptography>=41.0.0: Cryptographic operations - python-dotenv>=1.0.0: Environment management

exception SecurityError[source]

Bases: Exception

Base exception for security-related errors.

exception ConfigurationError[source]

Bases: SecurityError

Specific exception for configuration security issues.

class SecurityHeaders(HSTS: str = 'max-age=31536000; includeSubDomains', CONTENT_TYPE_OPTIONS: str = 'nosniff', FRAME_OPTIONS: str = 'DENY', XSS_PROTECTION: str = '1; mode=block', REFERRER_POLICY: str = 'strict-origin-when-cross-origin', PERMITTED_CROSS_DOMAIN_POLICIES: str = 'none', CSP: str = "default-src 'self'; img-src 'self' data: https:; style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://cdnjs.cloudflare.com; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net https://cdnjs.cloudflare.com https://code.jquery.com; font-src 'self' https://cdnjs.cloudflare.com; connect-src 'self' https://*.ngrok-free.app https://*.ngrok.io; frame-ancestors 'none';")[source]

Bases: object

Immutable security headers configuration.

HSTS: str = 'max-age=31536000; includeSubDomains'
CONTENT_TYPE_OPTIONS: str = 'nosniff'
FRAME_OPTIONS: str = 'DENY'
XSS_PROTECTION: str = '1; mode=block'
REFERRER_POLICY: str = 'strict-origin-when-cross-origin'
PERMITTED_CROSS_DOMAIN_POLICIES: str = 'none'
CSP: str = "default-src 'self'; img-src 'self' data: https:; style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://cdnjs.cloudflare.com; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net https://cdnjs.cloudflare.com https://code.jquery.com; font-src 'self' https://cdnjs.cloudflare.com; connect-src 'self' https://*.ngrok-free.app https://*.ngrok.io; frame-ancestors 'none';"
__init__(HSTS: str = 'max-age=31536000; includeSubDomains', CONTENT_TYPE_OPTIONS: str = 'nosniff', FRAME_OPTIONS: str = 'DENY', XSS_PROTECTION: str = '1; mode=block', REFERRER_POLICY: str = 'strict-origin-when-cross-origin', PERMITTED_CROSS_DOMAIN_POLICIES: str = 'none', CSP: str = "default-src 'self'; img-src 'self' data: https:; style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://cdnjs.cloudflare.com; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net https://cdnjs.cloudflare.com https://code.jquery.com; font-src 'self' https://cdnjs.cloudflare.com; connect-src 'self' https://*.ngrok-free.app https://*.ngrok.io; frame-ancestors 'none';") None
class EnvironmentConfig(origins: ~typing.List[str] = <factory>, max_requests: int = 100, request_window: int = 3600)[source]

Bases: object

Immutable environment-specific configuration.

origins: List[str]
max_requests: int = 100
request_window: int = 3600
__init__(origins: ~typing.List[str] = <factory>, max_requests: int = 100, request_window: int = 3600) None
class SecureConfig[source]

Bases: object

Enhanced secure configuration manager for Flask applications.

This class manages secure configuration settings including CORS policies, security headers, and environment-specific settings. It implements multiple layers of security controls and validation.

DEFAULT_CORS_MAX_AGE: int = 3600
DEFAULT_HSTS_MAX_AGE: int = 31536000
SUPPORTED_ENVIRONMENTS: Set[str] = frozenset({'development', 'production'})
ORIGIN_PATTERN: Pattern = re.compile('^https?://(?:(?:\\*\\.)?(?:[a-zA-Z0-9-]+\\.)*[a-zA-Z0-9-]+\\.[a-zA-Z]{2,}(?::\\d{1,5})?|localhost(?::\\d{1,5})?|127\\.0\\.0\\.1(?::\\d{1,5})?|\\[::1\\](?::\\d{1,5})?)$')
__init__()[source]

Initialize secure configuration with audit logging and encryption.

initialize_app(app: Flask) None[source]
get_allowed_origins() List[str][source]

Get cached list of allowed origins for current environment.

Returns:

List of allowed origins

Return type:

List[str]

add_security_headers(response: Response) Response[source]

Add comprehensive security headers to response.

configuration.init_app

Enhanced Flask Application Initializer Version: 1.0 Author: Gabriel Cellammare Last Modified: 05/01/2025

This module implements a secure Flask application initialization system with strong focus on configuration security, authentication protection, and secure environment management.

Security Features: 1. Environment Protection

  • Secure secret key management

  • Protected environment variables

  • Encryption key validation

  • Configuration isolation

  1. Authentication Security - OAuth provider protection - Secure callback handling - Protected client credentials - Token management safety

  2. Server Security - CORS protection - Firebase security - Development tunnel safety - Session management

  3. Configuration Management - Protected variable handling - Secure initialization - Error isolation - Safe defaults

Security Considerations: - All sensitive configuration is validated - OAuth credentials are protected - Environment variables are verified - Development modes are isolated - Error states provide safe defaults - CORS is strictly configured - Firebase credentials are protected - Tunneling is secured in development

Dependencies: - flask: Web application framework - authlib: OAuth implementation - firebase_admin: Firebase operations - python-dotenv: Environment management - os

validate_environment_variables(required_vars: list) None[source]

Securely validate presence and format of required environment variables.

Parameters:

required_vars – List of required environment variable names

Raises:

ValueError – If any required variable is missing or invalid

Security measures: - Presence verification - Format validation - Error isolation

validate_secret_key(key: str) None[source]

Validate the security of the Flask secret key.

Parameters:

key – Secret key to validate

Raises:

ValueError – If key doesn’t meet security requirements

Security measures: - Length verification - Entropy checking - Format validation

secure_firebase_init() None[source]

Securely initialize Firebase with proper credential handling.

Raises:
  • FileNotFoundError – If credential file is missing

  • ValueError – If credentials are invalid

Security measures: - Path validation - Credential verification - Error isolation

create_app(secure_config) Flask[source]

Creates and configures a secure Flask application instance.

Returns:

Configured Flask application

Return type:

Flask

Raises:
  • ValueError – On security configuration failures

  • ConfigurationError – On CORS configuration failures

Security measures: - Secure initialization - Protected configuration - Error isolation

configure_development_environment(app: Flask) None[source]

Configure secure development environment settings.

Parameters:

app – Flask application instance

Security measures: - Tunnel protection - URL validation - Error isolation

configure_oauth(app: Flask) OAuth[source]

Configure secure OAuth providers for authentication.

Parameters:

app – Flask application instance

Returns:

Configured OAuth instance

Return type:

OAuth

Security measures: - Credential validation - URL verification - Scope restriction

determine_callback_base_url() str[source]

Securely determine the base URL for OAuth callbacks.

Returns:

Validated base URL

Return type:

str

Security measures: - URL validation - Protocol verification - Environment isolation

configuration.ngrok_manager

Enhanced Ngrok Tunnel Manager Version: 1.0 Author: Gabriel Cellammare Last Modified: 05/01/2025

This module implements secure ngrok tunnel management with a strong focus on memory safety, secure state persistence, and protected network operations.

Security Features: 1. Connection Protection

  • Secure tunnel establishment

  • Protected URL management

  • SSL/TLS verification

  • Timeout protection

  1. State Management Security - Secure file operations - Protected state persistence - Memory-safe operations - Automatic cleanup

  2. Configuration Security - Protected environment variables - Secure token handling - Region validation - Safe defaults

  3. Error Management - Secure error recovery - Non-revealing messages - Protected logging - Failsafe defaults

Security Considerations: - All sensitive data is automatically cleaned up - Network operations are protected - Logging excludes sensitive information - File operations are secure - Error states provide safe defaults

Dependencies: - pyngrok: For ngrok tunnel operations - requests: For secure HTTP operations - flask: For application integration - pathlib: For secure file operations

class NgrokManager(app=None)[source]

Bases: object

Manages ngrok tunnel configuration and persistence with security focus. Implements secure tunnel creation, URL management, and state persistence.

Security Features: - Protected tunnel operations - Secure state management - Memory-safe cleanup - Protected logging

__init__(app=None)[source]

Initialize NgrokManager with security considerations.

Parameters:

app – Optional Flask application instance

Security measures: - Secure logger initialization - Protected file operations - Safe defaults

init_app(app)[source]

Initialize with Flask app instance securely.

Parameters:

app – Flask application instance

Security measures: - Token validation - Region verification - Protected configuration

start_tunnel(port: int = 5000)[source]

Start ngrok tunnel securely for the specified port.

Parameters:

port – Local port to tunnel

Returns:

Public ngrok URL

Return type:

str

Security measures: - Port validation - Secure health check - Protected tunnel creation - Error handling

doc_generator

Documentation Generator Security Framework Version: 1.0 Author: Gabriel Cellammare Last Modified: 05/01/2025

This module implements a secure and robust documentation generation system with a strong focus on module discovery protection, configuration security, and safe file system operations.

Security Features: 1. File System Protection

  • Secure path traversal prevention

  • Protected file operations

  • Safe directory creation

  • Path validation and sanitization

  1. Module Security - Protected module discovery - Secure import handling - Module isolation - Safe module resolution

  2. Documentation Security - Protected configuration generation - Secure theme handling - Safe template management - Output isolation

  3. Configuration Management - Protected variable handling - Secure initialization - Error isolation - Safe defaults

Security Considerations: - All file paths are validated and sanitized - Module imports are protected - Configuration files are isolated - Development artifacts are protected - Error states provide safe defaults - Directory traversal is prevented - Module resolution is secured - Output paths are protected

Dependencies: - sphinx: Documentation generation framework - pdoc: Alternative documentation generator - pathlib: Secure path operations - importlib: Protected module importing

class DocGenerator(project_dir: str, output_dir: str)[source]

Bases: object

A class that automates documentation generation from Python source files.

This class provides functionality to: 1. Discover Python modules in a project directory 2. Generate documentation using either Sphinx or pdoc 3. Handle configuration and setup for documentation generation 4. Provide error handling and fallback options

project_dir

Root directory containing Python source files

Type:

Path

output_dir

Directory where documentation will be generated

Type:

Path

has_rtd_theme

Flag indicating if sphinx_rtd_theme is available

Type:

bool

python_files

Mapping of module names to file paths

Type:

Dict[str, Path]

__init__(project_dir: str, output_dir: str)[source]

Initialize the documentation generator with project and output directories.

Parameters:
  • project_dir – Root directory containing Python source files

  • output_dir – Directory where documentation will be generated

Raises:
  • ValueError – If no Python files are found in the project directory

  • TypeError – If input parameters are not str or Path objects

setup_sphinx() None[source]

Set up Sphinx configuration and create necessary directory structure.

This method: 1. Creates required Sphinx directories 2. Generates conf.py with project configuration 3. Creates index.rst with module documentation structure 4. Configures theme and extensions

Raises:

IOError – If unable to create necessary files or directories

generate_sphinx_docs() None[source]

Generate Sphinx documentation for all discovered Python files.

This method: 1. Sets up Sphinx configuration 2. Builds HTML documentation 3. Handles errors and provides theme fallback

Raises:

Exception – If documentation generation fails after fallback attempts

generate_pdoc_docs() None[source]

Generate pdoc documentation for all discovered Python files.

This method: 1. Adds project directory to Python path 2. Generates HTML documentation using pdoc 3. Outputs documentation to specified directory

Raises:

Exception – If pdoc documentation generation fails

run(doc_type: str = 'sphinx') None[source]

Execute the documentation generation process.

Parameters:

doc_type – Type of documentation to generate (‘sphinx’ or ‘pdoc’)

Raises:

ValueError – Unsupported documentation type

main()[source]

Command-line interface for the documentation generator.

security.cryptography.cryptography_utils

Secure Cryptographic Operations Framework Version: 1.0 Author: Gabriel Cellammare Last Modified: 05/01/2025 This module implements a comprehensive cryptographic system with a strong focus on secure memory management, user identity protection, and robust encryption operations. It provides a defense-in-depth approach to protecting sensitive data through multiple layers of security controls and careful memory handling. Core Security Features:

Memory Protection

Secure byte array implementation for sensitive data Automatic memory zeroing after operations Protected key material handling Managed cleanup of cryptographic artifacts

Encryption Operations

AES-256-CBC encryption with PKCS7 padding Secure initialization vector management Salt generation and validation Protected cipher operations

Key Management

Secure key derivation using PBKDF2-HMAC-SHA3-256 User-specific key isolation Master key protection Salt management for key derivation

Identity Protection

Secure user ID hashing with HMAC-SHA256 Protected hash verification Timing attack prevention Base64 URL-safe encoding

Security Considerations:

All cryptographic operations use constant-time comparisons Memory containing sensitive data is securely erased Side-channel attack protections are implemented Cryptographic error states are safely handled Key material is protected throughout its lifecycle User identities are consistently hashed Encryption operations are isolated per user

Dependencies:

-cryptography: Core cryptographic operations -secure_byte_array: Protected memory management -hashlib: Hashing operations -base64: Secure encoding -typing: Type safety -logging: Security event tracking

exception CryptographicError[source]

Bases: Exception

Custom exception for cryptographic errors.

class AESCipher(master_key: str | bytes | SecureByteArray)[source]

Bases: object

Secure implementation of AES encryption with protected memory management and user ID hashing.

This class provides: - AES-256-CBC encryption with secure key derivation - Secure memory management using SecureByteArray - Protection against timing and side-channel attacks - Automatic PKCS7 padding management - Secure user ID hashing with HMAC-SHA256 and base64 encoding

BLOCK_SIZE

AES block size in bytes

Type:

int

KEY_LENGTH

Key length in bytes

Type:

int

IV_LENGTH

Initialization vector length

Type:

int

SALT_LENGTH

Salt length for key derivation

Type:

int

KDF_ITERATIONS

Number of iterations for key derivation

Type:

int

BLOCK_SIZE = 32
KEY_LENGTH = 32
IV_LENGTH = 16
SALT_LENGTH = 32
KDF_ITERATIONS = 300000
__init__(master_key: str | bytes | SecureByteArray)[source]

Initializes the AES cipher with a master key and optional app secret for user ID hashing.

Parameters:

master_key – Master key as string, bytes, or SecureByteArray

Raises:

CryptographicError – If the master key is invalid

hash_user_id(provider: str, original_id: str) str[source]

Generates a secure and consistent hash of the user ID using HMAC-SHA256, encoded in URL-safe base64 format.

Parameters:
  • provider – OAuth provider identifier (e.g., ‘google’, ‘github’)

  • original_id – Original user ID from the provider

Returns:

Base64 encoded hash, URL-safe without padding

Return type:

str

Raises:
  • ValueError – If provider or original_id is empty

  • CryptographicError – If hashing fails

verify_user_id_hash(provider: str, original_id: str, hashed_id: str) bool[source]

Verifies if a base64 encoded hash matches a given user ID using constant-time comparison.

Parameters:
  • provider – OAuth provider identifier

  • original_id – Original user ID

  • hashed_id – Base64 encoded hash to verify

Returns:

True if the hash matches, False otherwise

Return type:

bool

Raises:

CryptographicError – If verification fails

generate_salt() SecureByteArray[source]

Generates a cryptographically secure salt.

Returns:

Generated salt

Return type:

SecureByteArray

derive_key(user_id: str, salt: bytes | SecureByteArray) SecureByteArray[source]

Derives a user-specific key using PBKDF2-HMAC-SHA3-256.

Parameters:
  • user_id – User identifier

  • salt – Salt for key derivation

Returns:

Derived key

Return type:

SecureByteArray

Raises:

CryptographicError – If key derivation fails

encrypt(data: Any, user_id: str, salt: bytes | SecureByteArray) bytes[source]

Encrypts data using AES-256-CBC with secure memory management.

Parameters:
  • data – Data to encrypt (can be any JSON serializable type)

  • user_id – User identifier

  • salt – Salt for key derivation

Returns:

Encrypted data encoded in base64

Return type:

bytes

Raises:

CryptographicError – If encryption fails

decrypt(encrypted_data: str | bytes | SecureByteArray, user_id: str, salt: bytes | SecureByteArray) Any[source]

Decrypts data with secure memory management.

Parameters:
  • encrypted_data – Encrypted data (can be string, bytes, or SecureByteArray)

  • user_id – User identifier

  • salt – Salt used for encryption

Returns:

Decrypted data (JSON object or string)

Return type:

Any

security.cryptography.portfolio_encryption

Enhanced Portfolio Metrics Calculator Version: 1.0 Author: [Gabriel Cellammare] Last Modified: [05/01/2025]

This module implements secure portfolio data encryption and decryption with a strong focus on memory safety, cryptographic best practices, and secure data handling.

Security Features: 1. Memory Protection

  • Secure memory allocation and deallocation

  • Multiple-pass memory wiping

  • Protected memory regions for sensitive data

  • Automatic cleanup of sensitive information

  1. Cryptographic Security - AES encryption for sensitive data - Secure key and salt handling - Isolation of cryptographic operations - Protection against timing attacks

  2. Error Handling - Secure error recovery - Non-revealing error messages - Protected logging of sensitive data - Failsafe defaults for errors

  3. Input/Output Safety - Strict type validation - Secure conversion operations - Protected field handling - Safe defaults for failures

Security Considerations: - All sensitive data is automatically wiped from memory - Cryptographic operations are isolated - Logging excludes sensitive information - Memory is protected against unauthorized access - Type conversions are handled securely - Error states provide safe defaults

Dependencies: - cryptography_utils.AESCipher: For encryption operations - secure_byte_array.SecureByteArray: For secure memory operations

exception PortfolioEncryptionError[source]

Bases: Exception

Custom exception for portfolio encryption errors.

Security: - Does not expose internal state - Provides generic error messages - Protects against information leakage

class PortfolioEncryption(cipher: AESCipher)[source]

Bases: object

Secure portfolio data encryption implementation.

Security Architecture: 1. Memory Safety

  • Automatic memory cleanup

  • Protected memory regions

  • Secure memory wiping

  • Isolation of sensitive data

  1. Cryptographic Operations - Secure key management - Protected encryption/decryption - Salt handling - Timing attack protection

  2. Data Protection - Secure type conversion - Protected field handling - Safe default values - Error state handling

  3. Access Control - Initialization verification - Operation isolation - Memory access control - Cleanup guarantees

Usage Warnings: 1. Memory Management

  • Always use with context managers

  • Verify cleanup completion

  • Monitor memory usage

  • Check cleanup logs

  1. Error Handling - Implement proper exception catching - Verify error states - Check return values - Monitor error logs

  2. Cryptographic Safety - Protect key material - Verify salt uniqueness - Monitor operation logs - Check integrity

SENSITIVE_FIELDS = frozenset({'amount', 'purchase_date', 'purchase_price'})
SECURE_MEMORY_WIPE_PASSES = 3
DEFAULT_NUMERIC_VALUE = Decimal('0.0')
DEFAULT_STRING_VALUE = ''
logger = <Logger security.cryptography.portfolio_encryption (INFO)>
__init__(cipher: AESCipher)[source]

Initialize encryption system with security verification.

Security Operations: 1. Cipher validation

  • Verify interface compliance

  • Check method availability

  • Validate initialization

  1. Memory preparation - Initialize secure buffers - Prepare cleanup tracking - Set up protection

  2. State verification - Check initialization status - Verify configurations - Validate security settings

Parameters:

cipher – AESCipher instance for cryptographic operations

Raises:

PortfolioEncryptionError – On security verification failure

Security Checks: - Cipher interface verification - Memory initialization - Protection setup - State validation

encrypt_portfolio_item(item: Dict, user_id: str, salt: SecureByteArray) Dict[source]

Securely encrypts portfolio item data with memory protection.

Parameters:
  • item – Portfolio data to encrypt

  • user_id – User identifier

  • salt – Cryptographic salt

Returns:

Encrypted portfolio data

Return type:

Dict

Raises:

PortfolioEncryptionError – If encryption fails

Security:
  • Validates input parameters

  • Implements secure memory handling

  • Automatic cleanup of sensitive data

decrypt_portfolio_item(encrypted_item: Dict, user_id: str, salt: SecureByteArray) Dict[source]

Securely decrypts portfolio item data with memory protection.

Parameters:
  • encrypted_item – Encrypted portfolio data

  • user_id – User identifier

  • salt – Cryptographic salt

Returns:

Decrypted portfolio data

Return type:

Dict

Security:
  • Validates encrypted data integrity

  • Implements secure memory handling

  • Provides safe defaults for failures

security.csrf_protection

Enhanced CSRF Protection System Version: 2.0 Author: Gabriel Cellammare Last Modified: 09/01/2025

A comprehensive Cross-Site Request Forgery (CSRF) protection system designed for Flask applications with emphasis on security, scalability, and compliance with modern web security standards.

Key Features: 1. JavaScript Origin Validation - Ensures requests originate from legitimate sources using cryptographic signatures 2. Request Origin Binding - Links tokens to specific origins and validates request chains 3. Enhanced Token Protection - Uses encryption and HMAC validation with secure token lifecycle management 4. Anti-Automation Measures - Implements rate limiting and request pattern analysis 5. Request Chain Validation - Tracks and validates request sequences to prevent replay attacks

Security Measures: - Implements double-submit cookie pattern - Uses cryptographic signatures for request validation - Supports both development and production environments with appropriate security levels - Includes comprehensive header security - Implements token expiration and rotation - Provides protection against timing attacks - Includes DOS protection mechanisms

Usage:

from csrf_protection import CSRFProtection

app = Flask(__name__) csrf = CSRFProtection(app)

@app.route(‘/protected’, methods=[‘POST’]) @csrf.csrf_protect def protected_route():

return ‘Protected endpoint’

Dependencies:
  • Flask

  • cryptography

  • Python 3.7+

Environment Variables:
  • FLASK_ENV: ‘development’ or ‘production’

  • DEV_ALLOWED_ORIGINS: Comma-separated list of allowed origins for development

  • PROD_ALLOWED_ORIGINS: Comma-separated list of allowed origins for production

class CSRFProtection(app: Flask | None = None)[source]

Bases: object

__init__(app: Flask | None = None)[source]

Initializes Flask application with comprehensive security configurations.

Parameters:

app (Flask) – The Flask application instance to configure

Security Configurations:
  • Session security settings

  • Origin validation rules

  • HTTPS enforcement

  • Security headers

  • Environment-specific configurations

Environment Handling:
  • Development: Allows local testing and ngrok domains

  • Production: Strict security controls

Implementation Details:
  • Configures session parameters

  • Sets up request hooks for HTTPS and headers

  • Initializes origin validation

  • Establishes environment-specific rate limits

Raises:

Exception – If initialization fails, with detailed error logging

init_app(app: Flask) None[source]

Initialize application with comprehensive security configurations.

This method configures the Flask application with security features, sets up session handling, and initializes OAuth providers.

Parameters:

app (Flask) – The Flask application instance to configure

Security Features:
  • Session security settings

  • Origin validation rules

  • HTTPS enforcement

  • Security headers

  • Environment-specific configurations

Environment Handling:
  • Development: Allows local testing and ngrok domains

  • Production: Strict security controls

Implementation Details:
  • Configures session parameters

  • Sets up request hooks for HTTPS and headers

  • Initializes origin validation

  • Establishes environment-specific rate limits

Raises:

Exception – If initialization fails, with detailed error logging

Sets CSRF token cookie with secure settings and domain binding.

Parameters:
  • response (Response) – Flask response object to modify

  • token (str) – CSRF token to set in cookie

Security Features:
  • Secure flag enabled

  • HttpOnly flag enabled

  • SameSite attribute set to ‘Lax’

  • Domain-bound cookies

  • Appropriate expiration time

Notes

  • Automatically detects and uses appropriate domain from request

  • Implements security best practices for cookie attributes

  • Handles empty token gracefully

generate_token(require_user_id=True) Tuple[str, Response][source]

Generate CSRF token and prepare secure response. Now returns both token and properly configured response.

validate_token_request(token: str) bool[source]

Performs comprehensive validation of CSRF token and associated request headers.

Parameters:

token (str) – The CSRF token to validate

Returns:

True if token and request headers pass all security checks

Return type:

bool

Security Validations:
  • Token cryptographic validation

  • Origin header verification

  • Referrer header checking for same-origin

  • Request chain validation

  • Token usage counting

Notes

  • Implements defense in depth through multiple validation layers

  • Provides detailed logging for security events

  • Handles missing headers gracefully

Example

>>> csrf.validate_token_request("eyJhbGc...")
True  # If token and request are valid
generate_nonce() str[source]

Creates a cryptographically secure, single-use nonce with request binding.

Returns:

Encrypted nonce containing request metadata

Return type:

str

Security Features:
  • Bound to user session

  • Request ID integration

  • Automatic expiration

  • Protection against replay attacks

  • DOS prevention through cleanup

Implementation Details:
  • Uses Fernet symmetric encryption

  • Includes timestamp for expiration

  • Maintains maximum nonce limit

  • Implements automatic cleanup

Raises:

Abort(403) – When JavaScript origin validation fails

validate_nonce(nonce: str) bool[source]

Validates nonce with comprehensive security checks and request chain verification.

Parameters:

nonce (str) – The nonce string to validate

Returns:

True if nonce is valid and unused

Return type:

bool

Security Checks:
  • Existence verification

  • Expiration validation

  • Payload decryption and validation

  • User session binding

  • Single-use enforcement

Implementation Details:
  • Implements one-time use pattern

  • Automatic removal after use

  • Maintains encrypted payload integrity

  • Provides detailed error logging

Notes

  • Used in conjunction with token validation

  • Part of double-submit validation pattern

  • Implements defense against replay attacks

csrf_protect(f: Callable) Callable[source]

Comprehensive CSRF protection decorator implementing multiple security layers.

Parameters:

f (Callable) – The Flask route function to protect

Returns:

Decorated function with CSRF protection

Return type:

Callable

Security Layers:
  1. Nonce validation

  2. Token validation

  3. Origin verification

  4. Request chain validation

Usage:

@app.route(‘/api/data’, methods=[‘POST’]) @csrf_protect def protected_endpoint():

return ‘Protected data’

Raises:

Abort(403) – When any security check fails - Invalid or missing nonce - Invalid or missing token - Invalid origin - Failed request chain validation

security.input_validator

Enhanced Input Validation System Version: 1.0 Author: Gabriel Cellammare Last Modified: 05/01/2025

This module implements a comprehensive input validation system with strong focus on security, data sanitization, and protection against common web vulnerabilities.

Security Features: 1. Input Sanitization

  • NoSQL injection prevention

  • XSS protection

  • HTML encoding

  • Special character handling

  • Data type validation

  1. Validation Protection - Strict type checking - Pattern validation - Range validation - Length constraints - Custom validation hooks

  2. Data Security - Protected field handling - Safe type conversion - Secure date parsing - Protected numeric operations - Field access control

  3. Error Management - Secure error reporting - Non-revealing messages - Protected validation state - Safe error recovery

Security Considerations: - All input is sanitized before processing - Pattern matching is strictly controlled - Type conversions are handled securely - Error messages don’t leak internal details - Validation rules are immutable - Date ranges are strictly enforced - Numeric values are bounded - Custom validators are protected

Dependencies: - validators: For email and URL validation - datetime: For secure date handling - re: For pattern matching - typing: For type validation

exception ValidationError(field: str, message: str)[source]

Bases: Exception

Secure exception class for validation errors.

Security Features: - Sanitized error messages - Protected field names - Safe string representation

__init__(field: str, message: str)[source]
class InputType(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: Enum

Secure enumeration of allowed input types.

Security Features: - Immutable type definitions - Protected value access - Controlled type expansion

STRING = 'string'
NUMBER = 'number'
DATE = 'date'
EMAIL = 'email'
URL = 'url'
CRYPTO_ID = 'crypto_id'
CURRENCY = 'currency'
JWT = 'jwt'
class ValidationRule(required: bool = True, type: InputType = InputType.STRING, min_length: int | None = None, max_length: int | None = None, min_value: int | float | None = None, max_value: int | float | None = None, pattern: str | None = None, allowed_values: List[Any] | None = None, custom_validator: callable | None = None)[source]

Bases: object

Immutable validation rule configuration.

Security Features: - Frozen dataclass prevents modification - Type-checked attributes - Protected validator references

required: bool = True
type: InputType = 'string'
min_length: int | None = None
max_length: int | None = None
min_value: int | float | None = None
max_value: int | float | None = None
pattern: str | None = None
allowed_values: List[Any] | None = None
custom_validator: callable | None = None
__init__(required: bool = True, type: InputType = InputType.STRING, min_length: int | None = None, max_length: int | None = None, min_value: int | float | None = None, max_value: int | float | None = None, pattern: str | None = None, allowed_values: List[Any] | None = None, custom_validator: callable | None = None) None
class InputValidator[source]

Bases: object

Secure input validation system with comprehensive protection against common vulnerabilities.

Security Features: - Input sanitization - Type validation - Pattern matching - Range checking - Custom validation hooks

PATTERNS = {'crypto_id': '^[a-z0-9-]+$', 'currency': '^[A-Z]{3}$', 'jwt': '^[A-Za-z0-9-_=]+\\.[A-Za-z0-9-_=]+\\.?[A-Za-z0-9-_.+/=]*$'}
COMMON_RULES = {'auth': {'code': ValidationRule(required=True, type=<InputType.STRING: 'string'>, min_length=20, max_length=None, min_value=None, max_value=None, pattern=None, allowed_values=None, custom_validator=None), 'provider': ValidationRule(required=True, type=<InputType.STRING: 'string'>, min_length=None, max_length=None, min_value=None, max_value=None, pattern=None, allowed_values=['google', 'github'], custom_validator=None), 'state': ValidationRule(required=True, type=<InputType.STRING: 'string'>, min_length=32, max_length=64, min_value=None, max_value=None, pattern=None, allowed_values=None, custom_validator=None)}, 'currency_preference': {'currency': ValidationRule(required=True, type=<InputType.CURRENCY: 'currency'>, min_length=None, max_length=None, min_value=None, max_value=None, pattern='^[A-Z]{3}$', allowed_values=['USD', 'EUR'], custom_validator=None)}, 'portfolio_add': {'amount': ValidationRule(required=True, type=<InputType.NUMBER: 'number'>, min_length=None, max_length=None, min_value=1e-07, max_value=None, pattern=None, allowed_values=None, custom_validator=None), 'crypto_id': ValidationRule(required=True, type=<InputType.CRYPTO_ID: 'crypto_id'>, min_length=None, max_length=None, min_value=None, max_value=None, pattern='^[a-z0-9-]+$', allowed_values=None, custom_validator=None), 'purchase_date': ValidationRule(required=True, type=<InputType.DATE: 'date'>, min_length=None, max_length=None, min_value=None, max_value=None, pattern=None, allowed_values=None, custom_validator=None), 'purchase_price': ValidationRule(required=True, type=<InputType.NUMBER: 'number'>, min_length=None, max_length=None, min_value=0, max_value=None, pattern=None, allowed_values=None, custom_validator=None), 'symbol': ValidationRule(required=True, type=<InputType.STRING: 'string'>, min_length=1, max_length=10, min_value=None, max_value=None, pattern=None, allowed_values=None, custom_validator=None)}, 'portfolio_update': {'amount': ValidationRule(required=True, type=<InputType.NUMBER: 'number'>, min_length=None, max_length=None, min_value=1e-07, max_value=None, pattern=None, allowed_values=None, custom_validator=None), 'purchase_date': ValidationRule(required=True, type=<InputType.DATE: 'date'>, min_length=None, max_length=None, min_value=None, max_value=None, pattern=None, allowed_values=None, custom_validator=None), 'purchase_price': ValidationRule(required=True, type=<InputType.NUMBER: 'number'>, min_length=None, max_length=None, min_value=0, max_value=None, pattern=None, allowed_values=None, custom_validator=None)}}
MIN_ALLOWED_DATE = datetime.datetime(2010, 1, 1, 0, 0)
static sanitize_input(value: str) str[source]

Securely sanitize string input to prevent injection attacks.

Parameters:

value – Input string to sanitize

Returns:

Sanitized string safe for processing

Security measures: - NoSQL operator removal - HTML character encoding - Special character handling - Type checking

classmethod validate_value(value: Any, rule: ValidationRule) Any[source]

Securely validate a single value against defined rules.

Parameters:
  • value – Input value to validate

  • rule – ValidationRule to apply

Returns:

Validated and potentially transformed value

Security measures: - Type validation - Range checking - Pattern matching - Custom validation protection

classmethod validate_request_data(data: Dict[str, Any], rules: Dict[str, ValidationRule]) Dict[str, Any][source]

Securely validate complete request data against defined rules.

Parameters:
  • data – Dictionary of input data

  • rules – Dictionary of validation rules

Returns:

Dictionary of validated data

Security measures: - Unknown field detection - Complete validation coverage - Protected field access - Secure type conversion

classmethod validate_portfolio_add(data: Dict[str, Any]) Dict[str, Any][source]

Secure validation for portfolio additions.

classmethod validate_auth(data: Dict[str, Any]) Dict[str, Any][source]

Secure validation for authentication data.

classmethod validate_currency_preference(data: Dict[str, Any]) Dict[str, Any][source]

Secure validation for currency preferences.

security.rate_limiter

FirebaseRateLimiter: Distributed Rate Limiting Implementation Version: 1.0 Author: [Gabriel Cellammare] Last Modified: [05/01/2025]

This module provides a distributed rate limiting solution using Firebase Firestore: - Scalable rate limiting across multiple instances - Automatic cleanup of expired entries - Transaction-based atomic operations - Probabilistic maintenance

Security Features: 1. Transaction-based updates 2. Automatic data cleanup 3. Error handling and logging 4. Atomic operations 5. Time-window based limiting

Dependencies: - firebase_admin.firestore - flask.current_app - logging - time - random

class FirebaseRateLimitCleaner(db, collection_name: str = 'rate_limits')[source]

Bases: object

Cleanup Manager for Rate Limiting Data

Handles the periodic cleanup of expired rate limiting entries: - Batch processing to avoid timeouts - Configurable window sizes - Error handling and logging

Security Features: - Batched operations - Error isolation - Logging of operations

__init__(db, collection_name: str = 'rate_limits')[source]

Initialize the rate limit cleaner.

Parameters:
  • db – Firestore client instance

  • collection_name – Collection name for rate limits

Security: - Validates inputs - Configures logging

clean_expired_entries(window_seconds: int = 3600, batch_size: int = 500) int[source]

Remove expired rate limit entries.

Parameters:
  • window_seconds – Time window in seconds

  • batch_size – Number of documents per batch

Returns:

Number of deleted documents

Return type:

int

Security: - Batched operations - Transaction safety - Error handling

class FirebaseRateLimiter(db, max_requests: int = 100, window_seconds: int = 3600, ip_max_requests: int = 1000, ip_window_seconds: int = 3600, cleanup_probability: float = 0.001)[source]

Bases: object

__init__(db, max_requests: int = 100, window_seconds: int = 3600, ip_max_requests: int = 1000, ip_window_seconds: int = 3600, cleanup_probability: float = 0.001)[source]

Initialize rate limiter.

Parameters:
  • db – Firestore database instance

  • max_requests – Maximum requests per user window

  • window_seconds – Time window for user limits

  • ip_max_requests – Maximum requests per IP window

  • ip_window_seconds – Time window for IP limits

Security: - Input validation - Configuration logging - Cleanup initialization

maybe_cleanup()[source]

Probabilistic cleanup execution.

Security: - Error isolation - Logging - Non-blocking operation

check_rate_limit(user_id: str, ip_address) Tuple[bool, int, int][source]

security.secure_bye_array

SecureByteArray: Secure Memory Management Implementation Version: 1.0 Author: [Gabriel Cellammare] Last Modified: [05/01/2025]

This module provides a secure implementation for handling sensitive data in memory with: - Protected memory management - Anti-dumping measures - Secure data wiping - Automatic cleanup mechanisms

Security Features: 1. Memory Protection: Implements secure allocation and wiping 2. Anti-Dumping: Uses multiple overwrite passes 3. Context Management: Automatic cleanup 4. Access Control: Locking mechanism 5. Secure Random: Uses secrets module for cryptographic operations

Dependencies: - array (for byte array management) - ctypes (for low-level memory operations) - secrets (for cryptographic random generation) - logging (for security event tracking)

exception MemorySecurityError[source]

Bases: Exception

Custom exception for memory security operations.

Used to distinguish memory security issues from standard exceptions. Provides specific error context for security-related failures.

class SecureByteArray(data: bytes | bytearray | array | None = None)[source]

Bases: object

Secure Memory Management Implementation

Provides protected memory operations for sensitive data handling: - Secure memory allocation and deallocation - Protection against memory dumps - Multi-pass secure data wiping - Automatic memory cleanup - Memory access controls

Security Features: - Uses cryptographic random for overwriting - Implements multiple wipe passes - Verifies memory allocation - Provides memory locking - Implements secure copying

Usage:

# Using as context manager (recommended) with SecureByteArray(sensitive_data) as secure_data:

processed_data = secure_data.to_bytes()

# Direct usage (requires manual cleanup) secure_data = SecureByteArray(sensitive_data) try:

processed_data = secure_data.to_bytes()

finally:

secure_data.secure_zero()

logger = <Logger security.secure_bye_array (INFO)>
SECURE_WIPE_PASSES = 3
MIN_RANDOM_BYTES = 32
__init__(data: bytes | bytearray | array | None = None)[source]

Initialize secure byte array with optional data.

Parameters:

data – Initial sensitive data (optional)

Raises:
  • MemorySecurityError – On memory allocation failure

  • TypeError – On invalid input data type

Security: - Validates input types - Verifies memory allocation - Initializes security state

secure_zero() None[source]

Securely wipe memory contents.

Security Implementation: - Multiple overwrite passes - Cryptographic random data - Final zero overwrite - Memory fence operations

Raises:

MemorySecurityError – If secure wiping fails

to_bytes() bytes[source]

Create secure copy of data.

Returns:

Copy of protected data

Return type:

bytes

Raises:

MemorySecurityError – If array is locked

Security: - Validates lock state - Creates secure copy - Maintains original protection

utils.cryptocache

CryptoCache: Advanced Cryptocurrency Data Security Framework Version: 1.0 Author: Gabriel Cellammare Last Modified: 05/01/2025

This module implements a comprehensive security framework for caching cryptocurrency pricing data with defense-in-depth measures and robust security controls. It provides multi-layered protection against various attack vectors while ensuring data integrity and secure API communications.

Core Security Features:

  1. Data Protection - Secure cache file handling - Data validation and sanitization - Protected memory operations - Integrity verification

  2. API Security - Rate limiting implementation - Request throttling - Secure HTTP headers - Response validation

  3. Cache Management - Secure directory creation - Protected file operations - Timestamp validation - Data expiration controls

  4. Error Handling - Comprehensive exception management - Secure logging practices - Fail-safe defaults - Recovery procedures

Security Considerations:

  1. File System Security: - Cache directory permissions must be properly configured - File operations need atomic write protection - Path traversal prevention required - Temporary file handling must be secure

  2. API Communication: - SSL/TLS verification should be enforced - API keys need secure storage - Request headers should be sanitized - Rate limiting must prevent DOS

  3. Data Validation: - All input parameters require validation - Cache data must be verified - Response data needs sanitization - Type checking should be strict

  4. Memory Management: - Sensitive data needs secure cleanup - Memory limits should be enforced - Large objects require streaming - Garbage collection timing matters

Dependencies: - requests: HTTP client with security features - pathlib: Secure path operations - json: Data serialization - logging: Security event tracking - dotenv: Environment management - hashlib: Cryptographic operations

exception SecurityError[source]

Bases: Exception

Custom exception for security-related errors

initialize_environment() Dict[source]

Initialize and validate environment variables

Returns:

Configuration dictionary containing validated environment variables

Return type:

Dict

Raises:
  • EnvironmentError – If required environment variables are missing

  • SecurityError – If environment variables contain invalid values

class CryptoCache[source]

Bases: object

A cryptocurrency data caching system that provides secure data retrieval and storage. Implements rate limiting, input validation, and proper error handling.

__init__()[source]

Initialize CryptoCache with configuration from environment variables

Raises:
  • SecurityError – If security requirements are not met

  • EnvironmentError – If required configuration is missing

get_available_cryptocurrencies() List[Dict][source]

Retrieve list of available cryptocurrencies with market data

Returns:

List of cryptocurrency information including:
  • id: Unique identifier

  • symbol: Trading symbol (uppercase)

  • name: Full name

  • current_price: Current price in USD

Return type:

List[Dict]

Raises:
  • RequestException – If API request fails

  • SecurityError – If data validation fails

get_crypto_prices(crypto_ids: List[str], currency: str = 'USD') Dict[source]

Get current cryptocurrency prices for specified currencies

Parameters:
  • crypto_ids (List[str]) – List of cryptocurrency IDs to fetch

  • currency (str) – Target currency for prices (default: USD)

Returns:

Dictionary mapping crypto IDs to their prices in the specified currency
Format: {

‘bitcoin’: {‘usd’: 50000.00}, ‘ethereum’: {‘usd’: 3000.00}

}

Return type:

Dict

Raises:
  • SecurityError – If input validation fails

  • RequestException – If API request fails

get_exchange_rate(from_currency: str = 'USD', to_currency: str = 'EUR') float[source]

Get exchange rate between two currencies

Parameters:
  • from_currency (str) – Source currency code (default: USD)

  • to_currency (str) – Target currency code (default: EUR)

Returns:

Exchange rate from source to target currency

Returns 1.0 if request fails

Return type:

float

get(key: str) Dict | None[source]

Retrieve and validate cached data

Parameters:

key (str) – Cache key to retrieve

Returns:

Cached value if valid and not expired, None otherwise

Return type:

Optional[Dict]

set(key: str, value: any) None[source]

Store data in cache

Parameters:
  • key (str) – Cache key

  • value – Value to cache

Raises:

SecurityError – If cache write fails

utils.portfolio_utils

Enhanced Portfolio Metrics Calculator Version: 2.0 Author: [Gabriel Cellammare] Last Modified: [05/01/2025]

This module provides precise financial calculations for cryptocurrency portfolio analysis with comprehensive error handling, input validation, and proper decimal arithmetic.

Financial Calculation Features: 1. Decimal-based precise numerical handling 2. Comprehensive error handling 3. Robust input validation 4. Proper logging 5. Currency validation 6. Threshold-based zero handling 7. Controlled numerical precision 8. Explicit error states

Dependencies: - decimal: For precise numerical calculations - logging: For proper error tracking - typing: For type hints

class Currency(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: Enum

Valid currency denominations

USD = 'USD'
EUR = 'EUR'
exception PortfolioCalculationError[source]

Bases: Exception

Base exception for portfolio calculation errors

exception InvalidInputError[source]

Bases: PortfolioCalculationError

Exception for invalid input data

exception CurrencyError[source]

Bases: PortfolioCalculationError

Exception for currency-related errors

validate_numeric_input(value: str | float | Decimal, field_name: str) Decimal[source]

Validate and convert numeric input to Decimal.

Parameters:
  • value – The value to validate

  • field_name – Name of the field for error messages

Returns:

The validated and converted value

Return type:

Decimal

Raises:

InvalidInputError – If value is invalid

validate_currency(currency: str) str[source]

Validate currency denomination.

Parameters:

currency – Currency code to validate

Returns:

Validated currency code

Return type:

str

Raises:

CurrencyError – If currency is invalid

calculate_portfolio_metrics(portfolio_item: Dict[str, str | float | Decimal], current_price: str | float | Decimal, currency: str = 'USD') Dict[str, Decimal | str | None][source]

Calculate Financial Metrics for Portfolio Position with precise decimal arithmetic.

Processes a portfolio position and calculates key financial metrics including current value, profit/loss, and percentage returns.

Parameters:
  • portfolio_item – Portfolio position containing: - amount: Asset quantity - purchase_price: Entry price

  • current_price – Current market price

  • currency – Currency denomination (default: ‘USD’)

Returns:

Financial metrics including:
  • current_price: Market price

  • current_value: Position value

  • profit_loss: Absolute P/L

  • profit_loss_percentage: Relative P/L

  • currency: Denomination currency

  • error: Error message if calculation failed

Return type:

dict

Financial Safety: - Decimal arithmetic for precision - Comprehensive input validation - Specific error handling - Proper logging - Currency validation - Threshold-based zero handling - Controlled rounding

utils.token_jwt_handling

exception AuthError(error: str, status_code: int)[source]

Bases: Exception

Custom exception class for authentication and token-related errors.

This class provides structured error handling for authentication operations, including status codes for proper HTTP response handling.

error

Descriptive error message

Type:

str

status_code

HTTP status code for the error

Type:

int

Usage:

raise AuthError(“Token expired”, 401)

__init__(error: str, status_code: int)[source]
class TokenJWTHandling(db, cipher)[source]

Bases: object

__init__(db, cipher)[source]

Initialize secure token handling with database and encryption support.

This constructor sets up the token management system with proper security configuration and initializes the required dependencies.

Parameters:
  • db – Firestore database instance for token storage

  • cipher – AESCipher instance for data encryption/decryption

Security Features:
  • Protected configuration loading

  • Secure key management

  • Rate limit configuration

  • Token lifecycle settings

Environment Variables:

JWT_SECRET_KEY: Secret key for token signing

get_user_token_history(user_id: str, since: datetime) list[source]

Retrieve a user’s token generation history with secure filtering.

This method securely queries the database for a user’s token history, applying proper time-based filtering and status validation.

Parameters:
  • user_id (str) – Unique identifier of the user

  • since (datetime) – Starting timestamp for history retrieval

Returns:

Filtered list of token history records

Return type:

List[Dict]

Security:
  • Query parameter validation

  • Status filtering

  • Time-based constraints

check_token_request_eligibility(user_id: str) Tuple[bool, datetime | None, str | None][source]

Validate token request eligibility based on security policies.

This method implements rate limiting and cooldown periods for token generation to prevent abuse and ensure secure token management.

Parameters:

user_id (str) – Unique identifier of the requesting user

Returns:

  • Boolean indicating eligibility

  • Next eligible timestamp if applicable

  • Error message if request is denied

Return type:

Tuple[bool, Optional[datetime], Optional[str]]

Security:
  • Daily limit enforcement

  • Cooldown period validation

  • Request tracking

  • Time-based restrictions

expire_previous_tokens(user_id: str) None[source]

Invalidate all active tokens for a user with secure state transitions.

This method implements secure token expiration with proper audit logging and atomic database operations to maintain token lifecycle integrity.

Parameters:

user_id (str) – User identifier whose tokens should be expired

Security Features:
  • Batch operations for atomicity

  • Secure decryption for validation

  • Status transition logging

  • Time-based validation

  • Audit trail creation

Operations Flow:
  1. Retrieve user’s cryptographic salt

  2. Query active tokens

  3. Validate and decrypt tokens

  4. Batch update expired status

  5. Create audit logs

Protected State Transitions:
  • Active to Expired status

  • Timestamp recording

  • Reason documentation

get_active_token(user_id: str) Dict[str, Any] | None[source]

Retrieve the current active token for a user with validation.

This method securely fetches and validates the most recent active token, performing necessary decryption and expiration checks.

Parameters:

user_id (str) – User identifier to check for active tokens

Returns:

Active token information if valid, None otherwise

Return type:

Optional[Dict[str, Any]]

Security Features:
  • Salt-based decryption

  • Time-based validation

  • Status verification

  • Secure ordering

  • Query limiting

Validation Checks:
  • Token existence

  • Expiration status

  • Decryption integrity

  • Time validity

generate_tokens(user_id: str) Dict[str, Any][source]

Generate new JWT tokens with secure storage and rate limiting.

This method creates new JWT tokens with proper security measures, including rate limiting, encryption, and secure storage operations.

Parameters:

user_id (str) – User identifier for token generation

Returns:

Generated token information including expiration and next request time

Return type:

Dict[str, Any]

Raises:

AuthError – For rate limit violations (429) or generation failures (500)

Security Features:
  • Rate limit enforcement

  • Previous token expiration

  • Secure JWT creation

  • Protected storage

  • Device tracking

Token Properties:
  • Expiration time

  • Creation timestamp

  • User binding

  • Device information

  • Request cooldown

get_token_creation_time(token: str) datetime | None[source]

Extract token creation timestamp from JWT claims securely.

This method safely decodes JWT claims to retrieve the token creation time with proper error handling and validation.

Parameters:

token (str) – JWT token to analyze

Returns:

Token creation timestamp if valid, None otherwise

Return type:

Optional[datetime]

Security Features:
  • Secure JWT decoding

  • Signature validation

  • Time parsing protection

  • Error isolation

jwt_required(f)[source]

Protect routes with comprehensive JWT validation and security checks.

This decorator implements complete token validation including signature verification, database validation, and proper user session binding.

Parameters:

f (Callable) – The route function to protect

Returns:

Protected route function

Return type:

Callable

Security Features:
  • Token presence validation

  • JWT signature verification

  • Database token validation

  • Expiration checking

  • User session binding

  • Error logging

Validation Flow:
  1. Token format verification

  2. JWT signature validation

  3. Token type checking

  4. Database record validation

  5. Expiration verification

  6. User session binding

Raises:

AuthError – Various 401 status codes for different validation failures - Missing token - Invalid signature - Token not found - Token expired - Verification failed

Indices and tables