tahamajs/Sysmem2_in_AI / ComputerAssignments /CA9_test_time_scaling /src /security_authentication.py
#!/usr/bin/env python3
"""
Advanced Security and Authentication with Gemini API
This module provides sophisticated security and authentication capabilities for AI reasoning systems
"""
import os
import asyncio
import logging
from typing import List, Dict, Any, Optional, Union, Callable
from dataclasses import dataclass, field
from abc import ABC, abstractmethod
import json
import time
import hashlib
import hmac
import secrets
import base64
from enum import Enum
from collections import defaultdict, deque
import numpy as np
from pathlib import Path
import jwt
from datetime import datetime, timedelta
import sqlite3
import bcrypt
# LangChain imports
from langchain_core.prompts import PromptTemplate
from langchain_google_genai import ChatGoogleGenerativeAI
# Google Generative AI
import google.generativeai as genai
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class SecurityLevel(Enum):
"""Security levels"""
LOW = "low"
MEDIUM = "medium"
HIGH = "high"
CRITICAL = "critical"
class PermissionType(Enum):
"""Permission types"""
READ = "read"
WRITE = "write"
EXECUTE = "execute"
ADMIN = "admin"
DELETE = "delete"
class AuthenticationMethod(Enum):
"""Authentication methods"""
PASSWORD = "password"
TOKEN = "token"
API_KEY = "api_key"
OAUTH = "oauth"
MULTI_FACTOR = "multi_factor"
@dataclass
class User:
"""User structure"""
user_id: str
username: str
email: str
password_hash: str
permissions: List[PermissionType] = field(default_factory=list)
security_level: SecurityLevel = SecurityLevel.MEDIUM
enabled: bool = True
created_at: float = field(default_factory=time.time)
last_login: float = 0
failed_attempts: int = 0
locked_until: float = 0
metadata: Dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary"""
return {
"user_id": self.user_id,
"username": self.username,
"email": self.email,
"permissions": [p.value for p in self.permissions],
"security_level": self.security_level.value,
"enabled": self.enabled,
"created_at": self.created_at,
"last_login": self.last_login,
"failed_attempts": self.failed_attempts,
"locked_until": self.locked_until,
"metadata": self.metadata,
}
@dataclass
class APIKey:
"""API key structure"""
key_id: str
user_id: str
key_hash: str
name: str
permissions: List[PermissionType] = field(default_factory=list)
expires_at: float = 0
last_used: float = 0
usage_count: int = 0
enabled: bool = True
created_at: float = field(default_factory=time.time)
metadata: Dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary"""
return {
"key_id": self.key_id,
"user_id": self.user_id,
"name": self.name,
"permissions": [p.value for p in self.permissions],
"expires_at": self.expires_at,
"last_used": self.last_used,
"usage_count": self.usage_count,
"enabled": self.enabled,
"created_at": self.created_at,
"metadata": self.metadata,
}
@dataclass
class SecurityPolicy:
"""Security policy structure"""
policy_id: str
name: str
description: str
rules: List[Dict[str, Any]] = field(default_factory=list)
enabled: bool = True
created_at: float = field(default_factory=time.time)
updated_at: float = field(default_factory=time.time)
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary"""
return {
"policy_id": self.policy_id,
"name": self.name,
"description": self.description,
"rules": self.rules,
"enabled": self.enabled,
"created_at": self.created_at,
"updated_at": self.updated_at,
}
class PasswordManager:
"""Manages password hashing and validation"""
def __init__(self):
self.min_length = 8
self.require_uppercase = True
self.require_lowercase = True
self.require_numbers = True
self.require_special = True
logger.info("Password Manager initialized")
def hash_password(self, password: str) -> str:
"""Hash a password"""
try:
# Generate salt
salt = bcrypt.gensalt()
# Hash password
password_hash = bcrypt.hashpw(password.encode("utf-8"), salt)
return password_hash.decode("utf-8")
except Exception as e:
logger.error(f"Password hashing failed: {e}")
return ""
def verify_password(self, password: str, password_hash: str) -> bool:
"""Verify a password"""
try:
return bcrypt.checkpw(
password.encode("utf-8"), password_hash.encode("utf-8")
)
except Exception as e:
logger.error(f"Password verification failed: {e}")
return False
def validate_password_strength(self, password: str) -> Dict[str, Any]:
"""Validate password strength"""
result = {"valid": True, "score": 0, "issues": []}
# Check length
if len(password) < self.min_length:
result["valid"] = False
result["issues"].append(
f"Password must be at least {self.min_length} characters long"
)
else:
result["score"] += 1
# Check uppercase
if self.require_uppercase and not any(c.isupper() for c in password):
result["valid"] = False
result["issues"].append(
"Password must contain at least one uppercase letter"
)
else:
result["score"] += 1
# Check lowercase
if self.require_lowercase and not any(c.islower() for c in password):
result["valid"] = False
result["issues"].append(
"Password must contain at least one lowercase letter"
)
else:
result["score"] += 1
# Check numbers
if self.require_numbers and not any(c.isdigit() for c in password):
result["valid"] = False
result["issues"].append("Password must contain at least one number")
else:
result["score"] += 1
# Check special characters
if self.require_special and not any(
c in "!@#$%^&*()_+-=[]{}|;:,.<>?" for c in password
):
result["valid"] = False
result["issues"].append(
"Password must contain at least one special character"
)
else:
result["score"] += 1
return result
class TokenManager:
"""Manages JWT tokens"""
def __init__(self, secret_key: str = None):
self.secret_key = secret_key or os.getenv(
"JWT_SECRET_KEY", "default-secret-key"
)
self.algorithm = "HS256"
self.access_token_expiry = 3600 # 1 hour
self.refresh_token_expiry = 86400 * 7 # 7 days
logger.info("Token Manager initialized")
def generate_access_token(
self, user_id: str, permissions: List[PermissionType]
) -> str:
"""Generate access token"""
try:
payload = {
"user_id": user_id,
"permissions": [p.value for p in permissions],
"token_type": "access",
"exp": datetime.utcnow() + timedelta(seconds=self.access_token_expiry),
"iat": datetime.utcnow(),
}
token = jwt.encode(payload, self.secret_key, algorithm=self.algorithm)
return token
except Exception as e:
logger.error(f"Access token generation failed: {e}")
return ""
def generate_refresh_token(self, user_id: str) -> str:
"""Generate refresh token"""
try:
payload = {
"user_id": user_id,
"token_type": "refresh",
"exp": datetime.utcnow() + timedelta(seconds=self.refresh_token_expiry),
"iat": datetime.utcnow(),
}
token = jwt.encode(payload, self.secret_key, algorithm=self.algorithm)
return token
except Exception as e:
logger.error(f"Refresh token generation failed: {e}")
return ""
def verify_token(self, token: str) -> Dict[str, Any]:
"""Verify token"""
try:
payload = jwt.decode(token, self.secret_key, algorithms=[self.algorithm])
return {"valid": True, "payload": payload}
except jwt.ExpiredSignatureError:
return {"valid": False, "error": "Token expired"}
except jwt.InvalidTokenError:
return {"valid": False, "error": "Invalid token"}
except Exception as e:
logger.error(f"Token verification failed: {e}")
return {"valid": False, "error": str(e)}
def refresh_access_token(self, refresh_token: str) -> str:
"""Refresh access token"""
try:
verification_result = self.verify_token(refresh_token)
if not verification_result["valid"]:
return ""
payload = verification_result["payload"]
if payload.get("token_type") != "refresh":
return ""
user_id = payload["user_id"]
# Generate new access token
# Note: In a real implementation, you'd need to get user permissions from database
new_access_token = self.generate_access_token(
user_id, [PermissionType.READ]
)
return new_access_token
except Exception as e:
logger.error(f"Token refresh failed: {e}")
return ""
class APIKeyManager:
"""Manages API keys"""
def __init__(self):
self.key_length = 32
self.key_prefix = "ak_"
logger.info("API Key Manager initialized")
def generate_api_key(self) -> str:
"""Generate API key"""
try:
# Generate random bytes
random_bytes = secrets.token_bytes(self.key_length)
# Encode to base64
key = base64.urlsafe_b64encode(random_bytes).decode("utf-8")
# Add prefix
api_key = f"{self.key_prefix}{key}"
return api_key
except Exception as e:
logger.error(f"API key generation failed: {e}")
return ""
def hash_api_key(self, api_key: str) -> str:
"""Hash API key"""
try:
return hashlib.sha256(api_key.encode("utf-8")).hexdigest()
except Exception as e:
logger.error(f"API key hashing failed: {e}")
return ""
def verify_api_key(self, api_key: str, key_hash: str) -> bool:
"""Verify API key"""
try:
computed_hash = self.hash_api_key(api_key)
return hmac.compare_digest(computed_hash, key_hash)
except Exception as e:
logger.error(f"API key verification failed: {e}")
return False
class SecurityDatabase:
"""Database for security-related data"""
def __init__(self, db_path: str = "security.db"):
self.db_path = db_path
self.connection = None
self._init_database()
logger.info("Security Database initialized")
def _init_database(self):
"""Initialize database tables"""
try:
self.connection = sqlite3.connect(self.db_path, check_same_thread=False)
cursor = self.connection.cursor()
# Create users table
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS users (
user_id TEXT PRIMARY KEY,
username TEXT UNIQUE NOT NULL,
email TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
permissions TEXT NOT NULL,
security_level TEXT NOT NULL,
enabled BOOLEAN DEFAULT TRUE,
created_at REAL NOT NULL,
last_login REAL DEFAULT 0,
failed_attempts INTEGER DEFAULT 0,
locked_until REAL DEFAULT 0,
metadata TEXT
)
"""
)
# Create api_keys table
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS api_keys (
key_id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
key_hash TEXT NOT NULL,
name TEXT NOT NULL,
permissions TEXT NOT NULL,
expires_at REAL DEFAULT 0,
last_used REAL DEFAULT 0,
usage_count INTEGER DEFAULT 0,
enabled BOOLEAN DEFAULT TRUE,
created_at REAL NOT NULL,
metadata TEXT,
FOREIGN KEY (user_id) REFERENCES users (user_id)
)
"""
)
# Create security_policies table
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS security_policies (
policy_id TEXT PRIMARY KEY,
name TEXT NOT NULL,
description TEXT NOT NULL,
rules TEXT NOT NULL,
enabled BOOLEAN DEFAULT TRUE,
created_at REAL NOT NULL,
updated_at REAL NOT NULL
)
"""
)
# Create audit_logs table
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS audit_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp REAL NOT NULL,
user_id TEXT,
action TEXT NOT NULL,
resource TEXT,
result TEXT NOT NULL,
ip_address TEXT,
user_agent TEXT,
metadata TEXT
)
"""
)
# Create indexes
cursor.execute(
"CREATE INDEX IF NOT EXISTS idx_users_username ON users(username)"
)
cursor.execute("CREATE INDEX IF NOT EXISTS idx_users_email ON users(email)")
cursor.execute(
"CREATE INDEX IF NOT EXISTS idx_api_keys_user_id ON api_keys(user_id)"
)
cursor.execute(
"CREATE INDEX IF NOT EXISTS idx_api_keys_key_hash ON api_keys(key_hash)"
)
cursor.execute(
"CREATE INDEX IF NOT EXISTS idx_audit_logs_timestamp ON audit_logs(timestamp)"
)
cursor.execute(
"CREATE INDEX IF NOT EXISTS idx_audit_logs_user_id ON audit_logs(user_id)"
)
self.connection.commit()
except Exception as e:
logger.error(f"Security database initialization failed: {e}")
def create_user(self, user: User) -> bool:
"""Create user"""
try:
cursor = self.connection.cursor()
cursor.execute(
"""
INSERT INTO users (user_id, username, email, password_hash, permissions,
security_level, enabled, created_at, last_login,
failed_attempts, locked_until, metadata)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
user.user_id,
user.username,
user.email,
user.password_hash,
json.dumps([p.value for p in user.permissions]),
user.security_level.value,
user.enabled,
user.created_at,
user.last_login,
user.failed_attempts,
user.locked_until,
json.dumps(user.metadata),
),
)
self.connection.commit()
return True
except Exception as e:
logger.error(f"User creation failed: {e}")
return False
def get_user_by_username(self, username: str) -> Optional[User]:
"""Get user by username"""
try:
cursor = self.connection.cursor()
cursor.execute(
"""
SELECT user_id, username, email, password_hash, permissions, security_level,
enabled, created_at, last_login, failed_attempts, locked_until, metadata
FROM users WHERE username = ?
""",
(username,),
)
row = cursor.fetchone()
if not row:
return None
user = User(
user_id=row[0],
username=row[1],
email=row[2],
password_hash=row[3],
permissions=[PermissionType(p) for p in json.loads(row[4])],
security_level=SecurityLevel(row[5]),
enabled=bool(row[6]),
created_at=row[7],
last_login=row[8],
failed_attempts=row[9],
locked_until=row[10],
metadata=json.loads(row[11]) if row[11] else {},
)
return user
except Exception as e:
logger.error(f"User retrieval failed: {e}")
return None
def update_user(self, user: User) -> bool:
"""Update user"""
try:
cursor = self.connection.cursor()
cursor.execute(
"""
UPDATE users SET username = ?, email = ?, password_hash = ?, permissions = ?,
security_level = ?, enabled = ?, last_login = ?,
failed_attempts = ?, locked_until = ?, metadata = ?
WHERE user_id = ?
""",
(
user.username,
user.email,
user.password_hash,
json.dumps([p.value for p in user.permissions]),
user.security_level.value,
user.enabled,
user.last_login,
user.failed_attempts,
user.locked_until,
json.dumps(user.metadata),
user.user_id,
),
)
self.connection.commit()
return True
except Exception as e:
logger.error(f"User update failed: {e}")
return False
def create_api_key(self, api_key: APIKey) -> bool:
"""Create API key"""
try:
cursor = self.connection.cursor()
cursor.execute(
"""
INSERT INTO api_keys (key_id, user_id, key_hash, name, permissions,
expires_at, last_used, usage_count, enabled, created_at, metadata)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
api_key.key_id,
api_key.user_id,
api_key.key_hash,
api_key.name,
json.dumps([p.value for p in api_key.permissions]),
api_key.expires_at,
api_key.last_used,
api_key.usage_count,
api_key.enabled,
api_key.created_at,
json.dumps(api_key.metadata),
),
)
self.connection.commit()
return True
except Exception as e:
logger.error(f"API key creation failed: {e}")
return False
def get_api_key_by_hash(self, key_hash: str) -> Optional[APIKey]:
"""Get API key by hash"""
try:
cursor = self.connection.cursor()
cursor.execute(
"""
SELECT key_id, user_id, key_hash, name, permissions, expires_at,
last_used, usage_count, enabled, created_at, metadata
FROM api_keys WHERE key_hash = ?
""",
(key_hash,),
)
row = cursor.fetchone()
if not row:
return None
api_key = APIKey(
key_id=row[0],
user_id=row[1],
key_hash=row[2],
name=row[3],
permissions=[PermissionType(p) for p in json.loads(row[4])],
expires_at=row[5],
last_used=row[6],
usage_count=row[7],
enabled=bool(row[8]),
created_at=row[9],
metadata=json.loads(row[10]) if row[10] else {},
)
return api_key
except Exception as e:
logger.error(f"API key retrieval failed: {e}")
return None
def log_audit_event(
self,
user_id: str,
action: str,
resource: str,
result: str,
ip_address: str = None,
user_agent: str = None,
metadata: Dict[str, Any] = None,
):
"""Log audit event"""
try:
cursor = self.connection.cursor()
cursor.execute(
"""
INSERT INTO audit_logs (timestamp, user_id, action, resource, result,
ip_address, user_agent, metadata)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""",
(
time.time(),
user_id,
action,
resource,
result,
ip_address,
user_agent,
json.dumps(metadata) if metadata else None,
),
)
self.connection.commit()
except Exception as e:
logger.error(f"Audit logging failed: {e}")
def close(self):
"""Close database connection"""
if self.connection:
self.connection.close()
class AdvancedSecuritySystem:
"""Advanced security and authentication system"""
def __init__(self, db_path: str = "security.db"):
self.db = SecurityDatabase(db_path)
self.password_manager = PasswordManager()
self.token_manager = TokenManager()
self.api_key_manager = APIKeyManager()
# Security policies
self.security_policies = {}
self._load_default_policies()
logger.info("Advanced Security System initialized")
def _load_default_policies(self):
"""Load default security policies"""
# Password policy
password_policy = SecurityPolicy(
policy_id="password_policy",
name="Password Policy",
description="Default password requirements",
rules=[
{"type": "min_length", "value": 8},
{"type": "require_uppercase", "value": True},
{"type": "require_lowercase", "value": True},
{"type": "require_numbers", "value": True},
{"type": "require_special", "value": True},
],
)
self.security_policies["password_policy"] = password_policy
# Account lockout policy
lockout_policy = SecurityPolicy(
policy_id="account_lockout",
name="Account Lockout Policy",
description="Account lockout after failed attempts",
rules=[
{"type": "max_failed_attempts", "value": 5},
{"type": "lockout_duration", "value": 300}, # 5 minutes
],
)
self.security_policies["account_lockout"] = lockout_policy
def register_user(
self,
username: str,
email: str,
password: str,
permissions: List[PermissionType] = None,
) -> Dict[str, Any]:
"""Register a new user"""
try:
# Validate password strength
password_validation = self.password_manager.validate_password_strength(
password
)
if not password_validation["valid"]:
return {
"success": False,
"error": "Password does not meet requirements",
"issues": password_validation["issues"],
}
# Check if user already exists
existing_user = self.db.get_user_by_username(username)
if existing_user:
return {"success": False, "error": "Username already exists"}
# Hash password
password_hash = self.password_manager.hash_password(password)
if not password_hash:
return {"success": False, "error": "Password hashing failed"}
# Create user
user = User(
user_id=f"user_{int(time.time())}",
username=username,
email=email,
password_hash=password_hash,
permissions=permissions or [PermissionType.READ],
security_level=SecurityLevel.MEDIUM,
)
# Save to database
if self.db.create_user(user):
# Log audit event
self.db.log_audit_event(
user.user_id, "user_registration", "user", "success"
)
return {
"success": True,
"user_id": user.user_id,
"message": "User registered successfully",
}
else:
return {"success": False, "error": "User creation failed"}
except Exception as e:
logger.error(f"User registration failed: {e}")
return {"success": False, "error": str(e)}
def authenticate_user(self, username: str, password: str) -> Dict[str, Any]:
"""Authenticate user"""
try:
# Get user
user = self.db.get_user_by_username(username)
if not user:
return {"success": False, "error": "Invalid username or password"}
# Check if user is enabled
if not user.enabled:
return {"success": False, "error": "User account is disabled"}
# Check if account is locked
if user.locked_until > time.time():
return {
"success": False,
"error": "Account is locked due to too many failed attempts",
}
# Verify password
if not self.password_manager.verify_password(password, user.password_hash):
# Increment failed attempts
user.failed_attempts += 1
# Check lockout policy
lockout_policy = self.security_policies.get("account_lockout")
if (
lockout_policy
and user.failed_attempts >= lockout_policy.rules[0]["value"]
):
user.locked_until = time.time() + lockout_policy.rules[1]["value"]
self.db.update_user(user)
# Log audit event
self.db.log_audit_event(
user.user_id, "authentication", "user", "failed"
)
return {"success": False, "error": "Invalid username or password"}
# Reset failed attempts
user.failed_attempts = 0
user.locked_until = 0
user.last_login = time.time()
self.db.update_user(user)
# Generate tokens
access_token = self.token_manager.generate_access_token(
user.user_id, user.permissions
)
refresh_token = self.token_manager.generate_refresh_token(user.user_id)
# Log audit event
self.db.log_audit_event(user.user_id, "authentication", "user", "success")
return {
"success": True,
"user_id": user.user_id,
"access_token": access_token,
"refresh_token": refresh_token,
"permissions": [p.value for p in user.permissions],
}
except Exception as e:
logger.error(f"User authentication failed: {e}")
return {"success": False, "error": str(e)}
def create_api_key(
self, user_id: str, name: str, permissions: List[PermissionType] = None
) -> Dict[str, Any]:
"""Create API key for user"""
try:
# Generate API key
api_key = self.api_key_manager.generate_api_key()
if not api_key:
return {"success": False, "error": "API key generation failed"}
# Hash API key
key_hash = self.api_key_manager.hash_api_key(api_key)
# Create API key record
api_key_record = APIKey(
key_id=f"key_{int(time.time())}",
user_id=user_id,
key_hash=key_hash,
name=name,
permissions=permissions or [PermissionType.READ],
expires_at=0, # Never expires
)
# Save to database
if self.db.create_api_key(api_key_record):
# Log audit event
self.db.log_audit_event(
user_id, "api_key_creation", "api_key", "success"
)
return {
"success": True,
"api_key": api_key,
"key_id": api_key_record.key_id,
}
else:
return {"success": False, "error": "API key creation failed"}
except Exception as e:
logger.error(f"API key creation failed: {e}")
return {"success": False, "error": str(e)}
def authenticate_api_key(self, api_key: str) -> Dict[str, Any]:
"""Authenticate API key"""
try:
# Hash API key
key_hash = self.api_key_manager.hash_api_key(api_key)
# Get API key record
api_key_record = self.db.get_api_key_by_hash(key_hash)
if not api_key_record:
return {"success": False, "error": "Invalid API key"}
# Check if API key is enabled
if not api_key_record.enabled:
return {"success": False, "error": "API key is disabled"}
# Check if API key is expired
if (
api_key_record.expires_at > 0
and api_key_record.expires_at < time.time()
):
return {"success": False, "error": "API key has expired"}
# Update usage statistics
api_key_record.last_used = time.time()
api_key_record.usage_count += 1
# Log audit event
self.db.log_audit_event(
api_key_record.user_id, "api_key_authentication", "api_key", "success"
)
return {
"success": True,
"user_id": api_key_record.user_id,
"permissions": [p.value for p in api_key_record.permissions],
"key_id": api_key_record.key_id,
}
except Exception as e:
logger.error(f"API key authentication failed: {e}")
return {"success": False, "error": str(e)}
def verify_permissions(
self, user_id: str, required_permission: PermissionType
) -> bool:
"""Verify user permissions"""
try:
# Get user
user = self.db.get_user_by_username(user_id)
if not user:
return False
# Check if user has required permission
return required_permission in user.permissions
except Exception as e:
logger.error(f"Permission verification failed: {e}")
return False
def get_security_stats(self) -> Dict[str, Any]:
"""Get security system statistics"""
try:
# Get user count
cursor = self.db.connection.cursor()
cursor.execute("SELECT COUNT(*) FROM users")
user_count = cursor.fetchone()[0]
# Get API key count
cursor.execute("SELECT COUNT(*) FROM api_keys")
api_key_count = cursor.fetchone()[0]
# Get audit log count
cursor.execute("SELECT COUNT(*) FROM audit_logs")
audit_log_count = cursor.fetchone()[0]
return {
"total_users": user_count,
"total_api_keys": api_key_count,
"total_audit_logs": audit_log_count,
"security_policies": len(self.security_policies),
"policy_names": list(self.security_policies.keys()),
}
except Exception as e:
logger.error(f"Security stats calculation failed: {e}")
return {"error": str(e)}
def shutdown(self):
"""Shutdown security system"""
self.db.close()
logger.info("Security system shutdown")
# Example usage and testing functions
def test_security_system():
"""Test the security and authentication system"""
print("🧪 Testing Security and Authentication System")
print("=" * 50)
# Test security system
print("\n1. Testing Security System:")
security_system = AdvancedSecuritySystem("test_security.db")
# Test user registration
print("\n2. Testing User Registration:")
registration_result = security_system.register_user(
"testuser",
"test@example.com",
"TestPassword123!",
[PermissionType.READ, PermissionType.WRITE],
)
print(f"Registration Success: {registration_result['success']}")
if registration_result["success"]:
print(f"User ID: {registration_result['user_id']}")
# Test user authentication
print("\n3. Testing User Authentication:")
auth_result = security_system.authenticate_user("testuser", "TestPassword123!")
print(f"Authentication Success: {auth_result['success']}")
if auth_result["success"]:
print(f"Access Token: {auth_result['access_token'][:50]}...")
print(f"Permissions: {auth_result['permissions']}")
# Test API key creation
print("\n4. Testing API Key Creation:")
if auth_result["success"]:
api_key_result = security_system.create_api_key(
auth_result["user_id"], "Test API Key", [PermissionType.READ]
)
print(f"API Key Creation Success: {api_key_result['success']}")
if api_key_result["success"]:
print(f"API Key: {api_key_result['api_key'][:50]}...")
# Test API key authentication
print("\n5. Testing API Key Authentication:")
if api_key_result["success"]:
api_auth_result = security_system.authenticate_api_key(
api_key_result["api_key"]
)
print(f"API Key Authentication Success: {api_auth_result['success']}")
if api_auth_result["success"]:
print(f"User ID: {api_auth_result['user_id']}")
print(f"Permissions: {api_auth_result['permissions']}")
# Test permission verification
print("\n6. Testing Permission Verification:")
if auth_result["success"]:
has_read_permission = security_system.verify_permissions(
auth_result["user_id"], PermissionType.READ
)
has_admin_permission = security_system.verify_permissions(
auth_result["user_id"], PermissionType.ADMIN
)
print(f"Has READ permission: {has_read_permission}")
print(f"Has ADMIN permission: {has_admin_permission}")
# Test security stats
print("\n7. Testing Security Stats:")
stats = security_system.get_security_stats()
print(f"Total Users: {stats['total_users']}")
print(f"Total API Keys: {stats['total_api_keys']}")
print(f"Total Audit Logs: {stats['total_audit_logs']}")
print(f"Security Policies: {stats['security_policies']}")
# Test password validation
print("\n8. Testing Password Validation:")
weak_password = "123"
strong_password = "StrongPassword123!"
weak_validation = security_system.password_manager.validate_password_strength(
weak_password
)
strong_validation = security_system.password_manager.validate_password_strength(
strong_password
)
print(f"Weak password valid: {weak_validation['valid']}")
print(f"Weak password issues: {weak_validation['issues']}")
print(f"Strong password valid: {strong_validation['valid']}")
print(f"Strong password score: {strong_validation['score']}")
# Shutdown
print("\n9. Shutting down security system...")
security_system.shutdown()
print("\n✅ Security and authentication system test completed!")
if __name__ == "__main__":
test_security_system()
#!/usr/bin/env python3
"""
Advanced Security and Authentication with Gemini API
This module provides sophisticated security and authentication capabilities for AI reasoning systems
"""
import os
import asyncio
import logging
from typing import List, Dict, Any, Optional, Union, Callable
from dataclasses import dataclass, field
from abc import ABC, abstractmethod
import json
import time
import hashlib
import hmac
import secrets
import base64
from enum import Enum
from collections import defaultdict, deque
import numpy as np
from pathlib import Path
import jwt
from datetime import datetime, timedelta
import sqlite3
import bcrypt
# LangChain imports
from langchain_core.prompts import PromptTemplate
from langchain_google_genai import ChatGoogleGenerativeAI
# Google Generative AI
import google.generativeai as genai
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class SecurityLevel(Enum):
"""Security levels"""
LOW = "low"
MEDIUM = "medium"
HIGH = "high"
CRITICAL = "critical"
class PermissionType(Enum):
"""Permission types"""
READ = "read"
WRITE = "write"
EXECUTE = "execute"
ADMIN = "admin"
DELETE = "delete"
class AuthenticationMethod(Enum):
"""Authentication methods"""
PASSWORD = "password"
TOKEN = "token"
API_KEY = "api_key"
OAUTH = "oauth"
MULTI_FACTOR = "multi_factor"
class User:
"""User structure"""
user_id: str
username: str
email: str
password_hash: str
permissions: List[PermissionType] = field(default_factory=list)
security_level: SecurityLevel = SecurityLevel.MEDIUM
enabled: bool = True
created_at: float = field(default_factory=time.time)
last_login: float = 0
failed_attempts: int = 0
locked_until: float = 0
metadata: Dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary"""
return {
"user_id": self.user_id,
"username": self.username,
"email": self.email,
"permissions": [p.value for p in self.permissions],
"security_level": self.security_level.value,
"enabled": self.enabled,
"created_at": self.created_at,
"last_login": self.last_login,
"failed_attempts": self.failed_attempts,
"locked_until": self.locked_until,
"metadata": self.metadata,
}
Xet Storage Details
- Size:
- 37.3 kB
- Xet hash:
- cd05280ca9a9c8644f5d0f35d472f677a56b539c83ad7e00b4b6b9253f60f7dc
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.