|
| 1 | +"""Security utilities and validation for agentic_security.""" |
| 2 | + |
| 3 | +from functools import wraps |
| 4 | +from collections.abc import Callable |
| 5 | +from urllib.parse import urlparse |
| 6 | +import hashlib |
| 7 | +import hmac |
| 8 | +import os |
| 9 | +import re |
| 10 | + |
| 11 | + |
| 12 | +class SecurityValidator: |
| 13 | + """Input validation and sanitization.""" |
| 14 | + |
| 15 | + ALLOWED_URL_SCHEMES = {"http", "https"} |
| 16 | + MAX_URL_LENGTH = 2048 |
| 17 | + MAX_FILE_SIZE = 10 * 1024 * 1024 # 10MB |
| 18 | + |
| 19 | + @staticmethod |
| 20 | + def validate_url(url: str, allowed_hosts: list[str] | None = None) -> bool: |
| 21 | + """Validate URL for SSRF prevention.""" |
| 22 | + if len(url) > SecurityValidator.MAX_URL_LENGTH: |
| 23 | + return False |
| 24 | + |
| 25 | + try: |
| 26 | + parsed = urlparse(url) |
| 27 | + |
| 28 | + if parsed.scheme not in SecurityValidator.ALLOWED_URL_SCHEMES: |
| 29 | + return False |
| 30 | + |
| 31 | + if not parsed.netloc: |
| 32 | + return False |
| 33 | + |
| 34 | + if parsed.netloc in ["localhost", "127.0.0.1", "0.0.0.0"]: |
| 35 | + return False |
| 36 | + |
| 37 | + if parsed.netloc.startswith("169.254."): |
| 38 | + return False |
| 39 | + |
| 40 | + if parsed.netloc.startswith("10.") or parsed.netloc.startswith("192.168."): |
| 41 | + return False |
| 42 | + |
| 43 | + if allowed_hosts and parsed.netloc not in allowed_hosts: |
| 44 | + return False |
| 45 | + |
| 46 | + return True |
| 47 | + except Exception: |
| 48 | + return False |
| 49 | + |
| 50 | + @staticmethod |
| 51 | + def sanitize_filename(filename: str) -> str: |
| 52 | + """Sanitize filename to prevent path traversal.""" |
| 53 | + filename = os.path.basename(filename) |
| 54 | + filename = re.sub(r"[^\w\s.-]", "", filename) |
| 55 | + filename = filename.strip() |
| 56 | + |
| 57 | + if not filename or filename in [".", ".."]: |
| 58 | + raise ValueError("Invalid filename") |
| 59 | + |
| 60 | + return filename |
| 61 | + |
| 62 | + @staticmethod |
| 63 | + def validate_file_size(size: int) -> bool: |
| 64 | + """Validate file size.""" |
| 65 | + return 0 < size <= SecurityValidator.MAX_FILE_SIZE |
| 66 | + |
| 67 | + @staticmethod |
| 68 | + def validate_csv_content(content: str) -> bool: |
| 69 | + """Basic CSV validation.""" |
| 70 | + if not content or len(content) > SecurityValidator.MAX_FILE_SIZE: |
| 71 | + return False |
| 72 | + |
| 73 | + lines = content.split("\n", 2) |
| 74 | + if not lines: |
| 75 | + return False |
| 76 | + |
| 77 | + return True |
| 78 | + |
| 79 | + |
| 80 | +class SecretManager: |
| 81 | + """Secure secret handling.""" |
| 82 | + |
| 83 | + @staticmethod |
| 84 | + def get_secret(key: str, default: str | None = None) -> str | None: |
| 85 | + """Get secret from environment.""" |
| 86 | + value = os.getenv(key, default) |
| 87 | + if value and value.startswith("$"): |
| 88 | + env_key = value[1:] |
| 89 | + value = os.getenv(env_key, default) |
| 90 | + return value |
| 91 | + |
| 92 | + @staticmethod |
| 93 | + def hash_secret(secret: str, salt: str | None = None) -> str: |
| 94 | + """Hash a secret value.""" |
| 95 | + if salt is None: |
| 96 | + salt = os.urandom(32).hex() |
| 97 | + |
| 98 | + hashed = hashlib.pbkdf2_hmac("sha256", secret.encode(), salt.encode(), 100000) |
| 99 | + return f"{salt}${hashed.hex()}" |
| 100 | + |
| 101 | + @staticmethod |
| 102 | + def verify_secret(secret: str, hashed: str) -> bool: |
| 103 | + """Verify a secret against its hash.""" |
| 104 | + try: |
| 105 | + salt, expected = hashed.split("$", 1) |
| 106 | + actual = hashlib.pbkdf2_hmac( |
| 107 | + "sha256", secret.encode(), salt.encode(), 100000 |
| 108 | + ) |
| 109 | + return hmac.compare_digest(actual.hex(), expected) |
| 110 | + except Exception: |
| 111 | + return False |
| 112 | + |
| 113 | + |
| 114 | +class RateLimiter: |
| 115 | + """Simple in-memory rate limiter.""" |
| 116 | + |
| 117 | + def __init__(self, max_requests: int, window_seconds: int): |
| 118 | + self.max_requests = max_requests |
| 119 | + self.window_seconds = window_seconds |
| 120 | + self._requests: dict[str, list[float]] = {} |
| 121 | + |
| 122 | + def is_allowed(self, key: str) -> bool: |
| 123 | + """Check if request is allowed.""" |
| 124 | + import time |
| 125 | + |
| 126 | + now = time.time() |
| 127 | + |
| 128 | + if key not in self._requests: |
| 129 | + self._requests[key] = [] |
| 130 | + |
| 131 | + self._requests[key] = [ |
| 132 | + ts for ts in self._requests[key] if now - ts < self.window_seconds |
| 133 | + ] |
| 134 | + |
| 135 | + if len(self._requests[key]) >= self.max_requests: |
| 136 | + return False |
| 137 | + |
| 138 | + self._requests[key].append(now) |
| 139 | + return True |
| 140 | + |
| 141 | + def reset(self, key: str): |
| 142 | + """Reset rate limit for key.""" |
| 143 | + self._requests.pop(key, None) |
| 144 | + |
| 145 | + |
| 146 | +def require_auth(func: Callable) -> Callable: |
| 147 | + """Decorator to require authentication.""" |
| 148 | + |
| 149 | + @wraps(func) |
| 150 | + async def wrapper(*args, **kwargs): |
| 151 | + # TODO: Implement actual auth check |
| 152 | + # For now, check if API key is present |
| 153 | + api_key = kwargs.get("api_key") or os.getenv("API_KEY") |
| 154 | + if not api_key: |
| 155 | + from fastapi import HTTPException |
| 156 | + |
| 157 | + raise HTTPException(status_code=401, detail="Authentication required") |
| 158 | + return await func(*args, **kwargs) |
| 159 | + |
| 160 | + return wrapper |
| 161 | + |
| 162 | + |
| 163 | +def sanitize_log_output(data: str | dict) -> str: |
| 164 | + """Remove sensitive data from logs.""" |
| 165 | + if isinstance(data, dict): |
| 166 | + data = str(data) |
| 167 | + |
| 168 | + patterns = [ |
| 169 | + (r'(api[_-]?key["\s:=]+)["\']?[\w-]+', r"\1***"), |
| 170 | + (r'(token["\s:=]+)["\']?[\w-]+', r"\1***"), |
| 171 | + (r'(password["\s:=]+)["\']?[\w-]+', r"\1***"), |
| 172 | + (r'(secret["\s:=]+)["\']?[\w-]+', r"\1***"), |
| 173 | + (r"Bearer\s+[\w-]+", "Bearer ***"), |
| 174 | + ] |
| 175 | + |
| 176 | + for pattern, replacement in patterns: |
| 177 | + data = re.sub(pattern, replacement, data, flags=re.IGNORECASE) |
| 178 | + |
| 179 | + return data |
0 commit comments