reference-api-buddy 0.4.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,161 @@
1
+ """Security manager implementation for cryptographic operations."""
2
+
3
+ import base64
4
+ import hmac
5
+ import secrets
6
+ from typing import Any, Dict, Optional, Tuple
7
+
8
+
9
+ class SecurityManager:
10
+ """Handles cryptographic key generation, extraction, and validation.
11
+
12
+ Provides secure key generation, constant-time validation, and key extraction
13
+ from various request locations (path, query parameters, headers).
14
+
15
+ Example:
16
+ >>> manager = SecurityManager({"require_secure_key": True})
17
+ >>> key = manager.generate_secure_key()
18
+ >>> is_valid = manager.validate_request(key)
19
+ >>> print(f"Key valid: {is_valid}")
20
+ """
21
+
22
+ def __init__(self, security_config: Dict[str, Any]) -> None:
23
+ """Initialize SecurityManager with security configuration.
24
+
25
+ Args:
26
+ security_config: Configuration dictionary with security settings
27
+ """
28
+ self.config = security_config or {}
29
+ self.security_enabled = self.config.get("require_secure_key", False)
30
+ self.secure_key = self.config.get("secure_key") or self.generate_secure_key()
31
+
32
+ def generate_secure_key(self) -> str:
33
+ """Generate a cryptographically secure key.
34
+
35
+ Returns:
36
+ A URL-safe base64-encoded 256-bit random key
37
+
38
+ Example:
39
+ >>> manager = SecurityManager({})
40
+ >>> key = manager.generate_secure_key()
41
+ >>> print(f"Generated key: {key}")
42
+ """
43
+ key_bytes = secrets.token_bytes(32)
44
+ return base64.urlsafe_b64encode(key_bytes).decode("ascii").rstrip("=")
45
+
46
+ def validate_request(self, provided_key: Optional[str]) -> bool:
47
+ """Validate the provided key with constant-time comparison.
48
+
49
+ Args:
50
+ provided_key: The key provided in the request, may be None
51
+
52
+ Returns:
53
+ True if key is valid or security is disabled, False otherwise
54
+
55
+ Note:
56
+ Uses constant-time comparison to prevent timing attacks.
57
+ """
58
+ if not self.security_enabled:
59
+ return True
60
+ if not self.secure_key or not provided_key:
61
+ return False
62
+
63
+ return hmac.compare_digest(self.secure_key.encode("utf-8"), provided_key.encode("utf-8"))
64
+
65
+ def validate_secure_key(self, provided_key: Optional[str]) -> bool:
66
+ """Validate the provided key using constant-time comparison.
67
+
68
+ Args:
69
+ provided_key: The key to validate
70
+
71
+ Returns:
72
+ True if the key matches the secure key, False otherwise
73
+
74
+ Note:
75
+ This is an alias for validate_request but with stricter checking -
76
+ it doesn't return True when security is disabled.
77
+ """
78
+ if not provided_key or not self.secure_key:
79
+ return False
80
+ return hmac.compare_digest(self.secure_key.encode("utf-8"), provided_key.encode("utf-8"))
81
+
82
+ def extract_secure_key(
83
+ self, request_path: str, headers: Dict[str, str], query_params: Dict[str, str]
84
+ ) -> Tuple[Optional[str], str]:
85
+ """Extract secure key from path, query, or headers.
86
+
87
+ Args:
88
+ request_path: The HTTP request path
89
+ headers: Dictionary of HTTP headers
90
+ query_params: Dictionary of query parameters
91
+
92
+ Returns:
93
+ Tuple of (extracted_key, sanitized_path) where extracted_key is None
94
+ if no key found, and sanitized_path is the request path with key removed
95
+
96
+ Example:
97
+ >>> manager = SecurityManager({})
98
+ >>> key, path = manager.extract_secure_key("/abc123/api/test", {}, {})
99
+ >>> print(f"Key: {key}, Path: {path}")
100
+ """
101
+ key, new_path = self._extract_from_path(request_path)
102
+ if key:
103
+ return key, new_path
104
+ key, _ = self._extract_from_query(request_path, query_params)
105
+ if key:
106
+ return key, request_path
107
+ key, _ = self._extract_from_header(request_path, headers)
108
+ if key:
109
+ return key, request_path
110
+ return None, request_path
111
+
112
+ def _extract_from_path(self, request_path: str) -> Tuple[Optional[str], str]:
113
+ """Extract key from path prefix: /{key}/domain.com/path.
114
+
115
+ Args:
116
+ request_path: The request path to extract key from
117
+
118
+ Returns:
119
+ Tuple of (key, sanitized_path) where key is None if not found
120
+ """
121
+ if not request_path or not request_path.startswith("/"):
122
+ return None, request_path
123
+ parts = request_path.lstrip("/").split("/", 1)
124
+ if len(parts) < 2:
125
+ return None, request_path
126
+ key_candidate, rest = parts[0], "/" + parts[1]
127
+ # Heuristic: base64url keys are usually 43-44 chars (32 bytes)
128
+ if 32 <= len(key_candidate) <= 44:
129
+ return key_candidate, rest
130
+ return None, request_path
131
+
132
+ def _extract_from_query(self, request_path: str, query_params: Dict[str, str]) -> Tuple[Optional[str], str]:
133
+ """Extract key from query string (?key=...).
134
+
135
+ Args:
136
+ request_path: The request path (returned unchanged)
137
+ query_params: Dictionary of query parameters
138
+
139
+ Returns:
140
+ Tuple of (key, request_path) where key is None if not found
141
+ """
142
+ key = query_params.get("key")
143
+ return (key, request_path) if key else (None, request_path)
144
+
145
+ def _extract_from_header(self, request_path: str, headers: Dict[str, str]) -> Tuple[Optional[str], str]:
146
+ """Extract key from headers (X-API-Buddy-Key or Authorization: Bearer ...).
147
+
148
+ Args:
149
+ request_path: The request path (returned unchanged)
150
+ headers: Dictionary of HTTP headers
151
+
152
+ Returns:
153
+ Tuple of (key, request_path) where key is None if not found
154
+ """
155
+ key = headers.get("X-API-Buddy-Key")
156
+ if key:
157
+ return key, request_path
158
+ auth = headers.get("Authorization")
159
+ if auth and auth.lower().startswith("bearer "):
160
+ return auth[7:].strip(), request_path
161
+ return None, request_path
@@ -0,0 +1 @@
1
+ """Throttling module for API Buddy."""
@@ -0,0 +1,120 @@
1
+ """
2
+ ThrottleManager: Domain-specific rate limiting and progressive throttling.
3
+ """
4
+
5
+ import threading
6
+ import time
7
+ from collections import defaultdict, deque
8
+ from typing import Dict
9
+
10
+
11
+ class ThrottleState:
12
+ """Tracks throttling state for a domain."""
13
+
14
+ def __init__(self, violations=0, delay_seconds=1, last_violation=0.0, total_requests=0):
15
+ self.violations = violations
16
+ self.delay_seconds = delay_seconds
17
+ self.last_violation = last_violation
18
+ self.total_requests = total_requests
19
+ self.request_timestamps: deque = deque()
20
+
21
+
22
+ class ThrottleManager:
23
+ """Manages rate limiting and progressive throttling per domain."""
24
+
25
+ def __init__(self, throttling_config: dict):
26
+ """
27
+ throttling_config example:
28
+ {
29
+ "default_requests_per_hour": 1000,
30
+ "progressive_max_delay": 300,
31
+ "domain_limits": {"api.openai": 500}
32
+ }
33
+ """
34
+ self.config = throttling_config or {}
35
+ self.default_limit = self.config.get("default_requests_per_hour", 1000)
36
+ self.max_delay = self.config.get("progressive_max_delay", 300)
37
+ self.domain_limits = self.config.get("domain_limits", {})
38
+ self.lock = threading.Lock()
39
+ self.states: Dict[str, ThrottleState] = defaultdict(ThrottleState)
40
+ self.time_window = 3600 # 1 hour in seconds
41
+
42
+ def should_throttle(self, domain: str) -> bool:
43
+ """Check if requests to domain should be throttled."""
44
+ with self.lock:
45
+ state = self.states[domain]
46
+ now = time.time()
47
+ self._cleanup_old_requests(domain, now)
48
+ limit = self.domain_limits.get(domain, self.default_limit)
49
+ # Only throttle if requests > limit
50
+ if len(state.request_timestamps) > limit:
51
+ self._apply_progressive_throttling(domain, now)
52
+ return True
53
+ if state.delay_seconds > 1 and (now - state.last_violation) < state.delay_seconds:
54
+ return True
55
+ return False
56
+
57
+ def record_request(self, domain: str):
58
+ """Record a request for throttling purposes."""
59
+ with self.lock:
60
+ now = time.time()
61
+ state = self.states[domain]
62
+ state.request_timestamps.append(now)
63
+ state.total_requests += 1
64
+ self._cleanup_old_requests(domain, now)
65
+
66
+ def get_throttle_delay(self, domain: str) -> int:
67
+ """Get the current throttle delay for a domain."""
68
+ with self.lock:
69
+ return self.states[domain].delay_seconds
70
+
71
+ def _cleanup_old_requests(self, domain: str, current_time: float):
72
+ """Remove request timestamps older than 1 hour."""
73
+ state = self.states[domain]
74
+ while state.request_timestamps and (current_time - state.request_timestamps[0]) > self.time_window:
75
+ state.request_timestamps.popleft()
76
+
77
+ def _apply_progressive_throttling(self, domain: str, now: float):
78
+ """Apply progressive throttling based on consecutive violations."""
79
+ state = self.states[domain]
80
+ state.violations += 1
81
+ state.last_violation = now
82
+ # Exponential backoff: double delay up to max_delay
83
+ state.delay_seconds = min(self.max_delay, state.delay_seconds * 2 if state.delay_seconds > 1 else 2)
84
+
85
+ def reset_throttle(self, domain: str):
86
+ """Reset throttle state for a domain (for testing/admin)."""
87
+ with self.lock:
88
+ self.states[domain] = ThrottleState()
89
+
90
+ def get_state(self, domain: str) -> ThrottleState:
91
+ """Get the current throttle state for a domain."""
92
+ with self.lock:
93
+ return self.states[domain]
94
+
95
+ def persist_state(self) -> dict:
96
+ """Return a serializable snapshot of throttle state (for persistence)."""
97
+ with self.lock:
98
+ return {
99
+ domain: {
100
+ "violations": state.violations,
101
+ "delay_seconds": state.delay_seconds,
102
+ "last_violation": state.last_violation,
103
+ "total_requests": state.total_requests,
104
+ "request_timestamps": list(state.request_timestamps),
105
+ }
106
+ for domain, state in self.states.items()
107
+ }
108
+
109
+ def load_state(self, snapshot: dict):
110
+ """Restore throttle state from a snapshot (for persistence)."""
111
+ with self.lock:
112
+ for domain, data in snapshot.items():
113
+ state = ThrottleState(
114
+ violations=data.get("violations", 0),
115
+ delay_seconds=data.get("delay_seconds", 1),
116
+ last_violation=data.get("last_violation", 0.0),
117
+ total_requests=data.get("total_requests", 0),
118
+ )
119
+ state.request_timestamps = deque(data.get("request_timestamps", []))
120
+ self.states[domain] = state
@@ -0,0 +1 @@
1
+ """Utils module initializer."""
@@ -0,0 +1,225 @@
1
+ """Logger utility for Reference API Buddy.
2
+
3
+ This module provides a configurable logging system that integrates with the
4
+ configuration manager to allow users to customize logging behavior.
5
+ """
6
+
7
+ import logging
8
+ import logging.handlers
9
+ import sys
10
+ from typing import Any, Dict, Optional
11
+
12
+
13
+ class ColorFormatter(logging.Formatter):
14
+ """Custom formatter to add colors to log levels in console output, only if output is a TTY."""
15
+
16
+ COLORS = {
17
+ "DEBUG": "\033[94m", # Blue
18
+ "INFO": "\033[92m", # Green
19
+ "WARNING": "\033[93m", # Yellow
20
+ "ERROR": "\033[91m", # Red
21
+ "CRITICAL": "\033[95m", # Magenta
22
+ }
23
+ RESET = "\033[0m"
24
+
25
+ def format(self, record):
26
+ color = self.COLORS.get(record.levelname, self.RESET)
27
+ msg = super().format(record)
28
+ return f"{color}{msg}{self.RESET}"
29
+
30
+
31
+ class LoggerManager:
32
+ """Manages logger configuration and provides logger instances."""
33
+
34
+ def __init__(self):
35
+ self._loggers: Dict[str, logging.Logger] = {}
36
+ self._configured = False
37
+ self._config = None
38
+
39
+ def configure(self, config: Dict[str, Any]) -> None:
40
+ """Configure the logger with the provided configuration.
41
+
42
+ Args:
43
+ config: Logging configuration dictionary from ConfigurationManager
44
+ """
45
+ self._config = config
46
+ self._configured = True
47
+
48
+ # Configure root logger for the package
49
+ self._configure_root_logger()
50
+
51
+ def _configure_root_logger(self) -> None:
52
+ """Configure the root logger based on the configuration."""
53
+ if not self._config:
54
+ return
55
+
56
+ # Get or create the parent logger
57
+ parent_logger_name = self._config.get("parent_logger")
58
+ if parent_logger_name:
59
+ parent_logger = logging.getLogger(parent_logger_name)
60
+ else:
61
+ parent_logger = logging.getLogger("api_buddy")
62
+
63
+ # Clear existing handlers to avoid duplicates
64
+ parent_logger.handlers.clear()
65
+
66
+ # Set logging level
67
+ level_str = self._config.get("level", "INFO")
68
+ level = getattr(logging, level_str.upper(), logging.INFO)
69
+ parent_logger.setLevel(level)
70
+
71
+ # Create formatter
72
+ log_format = self._config.get("format", "%(asctime)s - %(name)s - %(levelname)s - %(message)s")
73
+ date_format = self._config.get("date_format", "%Y-%m-%d %H:%M:%S")
74
+ formatter = logging.Formatter(log_format, date_format)
75
+ color_formatter = ColorFormatter(log_format, date_format)
76
+
77
+ # Add console handler if enabled
78
+ if self._config.get("enable_console", True):
79
+ console_handler = logging.StreamHandler(sys.stdout)
80
+ console_handler.setFormatter(color_formatter)
81
+ parent_logger.addHandler(console_handler)
82
+
83
+ # Add file handler if enabled
84
+ if self._config.get("enable_file", False):
85
+ file_path = self._config.get("file_path")
86
+ if file_path:
87
+ max_size = self._config.get("max_file_size", 10485760) # 10MB
88
+ backup_count = self._config.get("backup_count", 5)
89
+
90
+ file_handler = logging.handlers.RotatingFileHandler(
91
+ file_path, maxBytes=max_size, backupCount=backup_count
92
+ )
93
+ file_handler.setFormatter(formatter)
94
+ parent_logger.addHandler(file_handler)
95
+
96
+ # Prevent propagation to avoid duplicate logs
97
+ parent_logger.propagate = False
98
+
99
+ def get_logger(self, name: str) -> logging.Logger:
100
+ """Get or create a logger with the specified name.
101
+
102
+ Args:
103
+ name: Name of the logger (will be prefixed with package name)
104
+
105
+ Returns:
106
+ Configured logger instance
107
+ """
108
+ if not self._configured:
109
+ # Use default configuration if not configured
110
+ self._config = {
111
+ "level": "INFO",
112
+ "parent_logger": None,
113
+ "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
114
+ "date_format": "%Y-%m-%d %H:%M:%S",
115
+ "enable_console": True,
116
+ "enable_file": False,
117
+ "file_path": None,
118
+ "max_file_size": 10485760,
119
+ "backup_count": 5,
120
+ }
121
+ self._configure_root_logger()
122
+ self._configured = True
123
+
124
+ # Determine the full logger name
125
+ parent_logger_name = (self._config or {}).get("parent_logger")
126
+ if parent_logger_name:
127
+ full_name = f"{parent_logger_name}.{name}"
128
+ else:
129
+ full_name = f"api_buddy.{name}"
130
+
131
+ # Return cached logger or create new one
132
+ if full_name not in self._loggers:
133
+ logger = logging.getLogger(full_name)
134
+ self._loggers[full_name] = logger
135
+
136
+ return self._loggers[full_name]
137
+
138
+ def reconfigure(self, config: Dict[str, Any]) -> None:
139
+ """Reconfigure all loggers with new configuration.
140
+
141
+ Args:
142
+ config: New logging configuration dictionary
143
+ """
144
+ self.configure(config)
145
+
146
+ # Update all existing loggers
147
+ for logger_name, logger in self._loggers.items():
148
+ # The parent logger configuration will be inherited
149
+ pass
150
+
151
+ def set_level(self, level: str) -> None:
152
+ """Change the logging level for all loggers.
153
+
154
+ Args:
155
+ level: New logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
156
+ """
157
+ if self._config:
158
+ self._config["level"] = level
159
+ self._configure_root_logger()
160
+
161
+
162
+ # Global logger manager instance
163
+ _logger_manager = LoggerManager()
164
+
165
+
166
+ def configure_logging(config: Dict[str, Any]) -> None:
167
+ """Configure the logging system with the provided configuration.
168
+
169
+ This function should be called once during application initialization
170
+ with the logging configuration from ConfigurationManager.
171
+
172
+ Args:
173
+ config: Logging configuration dictionary
174
+ """
175
+ _logger_manager.configure(config)
176
+
177
+
178
+ def get_logger(name: str) -> logging.Logger:
179
+ """Get a logger instance for the specified module/component.
180
+
181
+ Args:
182
+ name: Name of the module or component requesting the logger
183
+
184
+ Returns:
185
+ Configured logger instance
186
+
187
+ Example:
188
+ logger = get_logger(__name__)
189
+ logger.info("This is an info message")
190
+ """
191
+ return _logger_manager.get_logger(name)
192
+
193
+
194
+ def reconfigure_logging(config: Dict[str, Any]) -> None:
195
+ """Reconfigure the logging system with new settings.
196
+
197
+ Args:
198
+ config: New logging configuration dictionary
199
+ """
200
+ _logger_manager.reconfigure(config)
201
+
202
+
203
+ def set_log_level(level: str) -> None:
204
+ """Change the logging level for the entire package.
205
+
206
+ Args:
207
+ level: New logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
208
+ """
209
+ _logger_manager.set_level(level)
210
+
211
+
212
+ # Convenience function for backward compatibility
213
+ def setup_logger(name: str, config: Optional[Dict[str, Any]] = None) -> logging.Logger:
214
+ """Setup and return a logger with optional configuration.
215
+
216
+ Args:
217
+ name: Name of the logger
218
+ config: Optional logging configuration
219
+
220
+ Returns:
221
+ Configured logger instance
222
+ """
223
+ if config:
224
+ configure_logging(config)
225
+ return get_logger(name)