Buckets:

download
raw
3.16 kB
"""Security utilities for session management."""
import hashlib
import hmac
import logging
from .models import Session
logger = logging.getLogger(__name__)
class SecurityManager:
"""Handles session security operations."""
def __init__(self, secret_key: str) -> None:
"""Initialize security manager.
Args:
secret_key: Secret key for signing tokens
"""
if len(secret_key) < 32: # noqa: PLR2004
msg = "Secret key must be at least 32 characters"
raise ValueError(msg)
self._secret_key_bytes = secret_key.encode("utf-8")
logger.debug(
"SecurityManager initialized with secret length=%s", len(secret_key)
)
def sign_session_id(self, session_id: str) -> str:
"""Sign a session ID using HMAC-SHA256.
Args:
session_id: The session ID to sign
Returns:
The signature as a hex string
"""
return hmac.new(
self._secret_key_bytes,
session_id.encode("utf-8"),
hashlib.sha256,
).hexdigest()
def verify_signature(self, session_id: str, signature: str) -> bool:
"""Verify a session signature.
Args:
session_id: The session ID
signature: The signature to verify
Returns:
True if signature is valid, False otherwise
"""
expected_signature = self.sign_session_id(session_id)
# Use constant-time comparison to prevent timing attacks
valid = hmac.compare_digest(expected_signature, signature)
if not valid:
logger.debug("Signature verification failed; id=%s", session_id)
return valid
def check_ip_match(self, session: Session, current_ip: str | None) -> bool:
"""Check if session IP matches current request IP.
Args:
session: The session to check
current_ip: Current request IP address
Returns:
True if IPs match or session has no IP binding
"""
if session.ip_address is None:
return True
if current_ip is None:
return False
return session.ip_address == current_ip
def check_user_agent_match(
self,
session: Session,
current_user_agent: str | None,
) -> bool:
"""Check if session User-Agent matches current request.
Args:
session: The session to check
current_user_agent: Current request User-Agent
Returns:
True if User-Agents match or session has no UA binding
"""
if session.user_agent is None:
return True
if current_user_agent is None:
return False
return session.user_agent == current_user_agent
def hash_data(self, data: str) -> str:
"""Hash data using SHA-256.
Args:
data: Data to hash
Returns:
Hex digest of the hash
"""
digest = hashlib.sha256(data.encode("utf-8")).hexdigest()
logger.debug("Data hashed for session operations")
return digest

Xet Storage Details

Size:
3.16 kB
·
Xet hash:
64bfd085b08d204bb96c09ce06a73dde2257c87642998aa5072f6e2026db153b

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.