keycase-agent-sdk 0.1.0b2__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.
keycase_agent/auth.py ADDED
@@ -0,0 +1,271 @@
1
+ """Authentication service with token refresh and retry logic."""
2
+
3
+ import logging
4
+ import threading
5
+ import time
6
+ from dataclasses import dataclass
7
+ from datetime import datetime, timedelta
8
+ from typing import List, Optional
9
+
10
+ from .utils.auth_helper import (
11
+ authenticate_agent,
12
+ refresh_access_token,
13
+ )
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+ # Constants
18
+ DEFAULT_TOKEN_VALIDITY_HOURS = 24
19
+ DEFAULT_TOKEN_REFRESH_THRESHOLD_SECONDS = 3600 # 1 hour before expiry
20
+ DEFAULT_MAX_RETRY_ATTEMPTS = 3
21
+ MAX_RETRY_DELAY_SECONDS = 30
22
+ TOKEN_CHECK_INTERVAL_SECONDS = 300 # 5 minutes
23
+
24
+
25
+ @dataclass
26
+ class AuthCredentials:
27
+ """Authentication credentials and connection info."""
28
+
29
+ agent_id: int
30
+ organization_id: int
31
+ access_token: str
32
+ refresh_token: str
33
+ session_id: str
34
+ ws_url: str
35
+ token_expires_at: Optional[datetime] = None
36
+
37
+
38
+ class AuthService:
39
+ """Authentication service using AgentToken-based authentication."""
40
+
41
+ def __init__(
42
+ self,
43
+ http_url: str,
44
+ agent_token: str,
45
+ agent_name: str,
46
+ version: str = "1.0.0",
47
+ capabilities: Optional[List[str]] = None,
48
+ tags: Optional[List[str]] = None,
49
+ token_refresh_threshold: int = DEFAULT_TOKEN_REFRESH_THRESHOLD_SECONDS,
50
+ max_retry_attempts: int = DEFAULT_MAX_RETRY_ATTEMPTS,
51
+ ) -> None:
52
+ """Initialize authentication service.
53
+
54
+ Args:
55
+ http_url: HTTP API base URL
56
+ agent_token: AgentToken (must start with 'agt_')
57
+ agent_name: Unique agent name within organization
58
+ version: Agent version
59
+ capabilities: List of capabilities the agent supports
60
+ tags: List of labels for categorization
61
+ token_refresh_threshold: Seconds before expiry to refresh token
62
+ max_retry_attempts: Maximum authentication retry attempts
63
+ """
64
+ self.http_url = http_url
65
+ self.agent_token = agent_token
66
+ self.agent_name = agent_name
67
+ self.version = version
68
+ self.capabilities = capabilities or []
69
+ self.tags = tags or []
70
+ self.token_refresh_threshold = token_refresh_threshold
71
+ self.max_retry_attempts = max_retry_attempts
72
+
73
+ self._credentials: Optional[AuthCredentials] = None
74
+ self._token_lock = threading.Lock()
75
+ self._refresh_thread: Optional[threading.Thread] = None
76
+ self._shutdown_event = threading.Event()
77
+
78
+ def authenticate(self) -> AuthCredentials:
79
+ """Authenticate with AgentToken and get credentials.
80
+
81
+ Returns:
82
+ AuthCredentials with access token, agent ID, ws URL, etc.
83
+
84
+ Raises:
85
+ SystemExit: If all authentication attempts fail
86
+ """
87
+ with self._token_lock:
88
+ for attempt in range(1, self.max_retry_attempts + 1):
89
+ try:
90
+ logger.info(
91
+ f"Attempting authentication "
92
+ f"(attempt {attempt}/{self.max_retry_attempts})"
93
+ )
94
+
95
+ auth_response = authenticate_agent(
96
+ http_url=self.http_url,
97
+ agent_token=self.agent_token,
98
+ agent_name=self.agent_name,
99
+ version=self.version,
100
+ capabilities=self.capabilities,
101
+ tags=self.tags,
102
+ )
103
+
104
+ self._credentials = AuthCredentials(
105
+ agent_id=auth_response.agent_id,
106
+ organization_id=auth_response.organization_id,
107
+ access_token=auth_response.access_token,
108
+ refresh_token=auth_response.refresh_token,
109
+ session_id=auth_response.session_id,
110
+ ws_url=auth_response.ws_url,
111
+ token_expires_at=datetime.now()
112
+ + timedelta(hours=DEFAULT_TOKEN_VALIDITY_HOURS),
113
+ )
114
+
115
+ logger.info(
116
+ "Authentication successful, "
117
+ f"agent ID: {self._credentials.agent_id}"
118
+ )
119
+ logger.info(f"WebSocket URL: {self._credentials.ws_url}")
120
+ logger.info(
121
+ f"Token expires at: {self._credentials.token_expires_at}"
122
+ )
123
+
124
+ self._start_token_refresh_monitor()
125
+ return self._credentials
126
+
127
+ except Exception as e:
128
+ logger.error(f"Authentication attempt {attempt} failed: {e}")
129
+
130
+ if attempt < self.max_retry_attempts:
131
+ delay = min(MAX_RETRY_DELAY_SECONDS, 2**attempt)
132
+ logger.info(f"Retrying authentication in {delay} seconds...")
133
+ time.sleep(delay)
134
+
135
+ logger.critical("All authentication attempts failed")
136
+ raise SystemExit("Authentication failed after all attempts")
137
+
138
+ def get_token(self) -> Optional[str]:
139
+ """Get current access token, refreshing if necessary.
140
+
141
+ Returns:
142
+ Current valid access token or None if authentication failed
143
+ """
144
+ with self._token_lock:
145
+ if self._should_refresh_token():
146
+ try:
147
+ self._refresh_token()
148
+ except Exception as e:
149
+ logger.error(f"Token refresh failed: {e}")
150
+ return None
151
+ return self._credentials.access_token if self._credentials else None
152
+
153
+ def get_credentials(self) -> Optional[AuthCredentials]:
154
+ """Get full credentials including agent ID, ws URL, etc."""
155
+ return self._credentials
156
+
157
+ def get_agent_id(self) -> Optional[int]:
158
+ """Get the agent ID assigned by server."""
159
+ return self._credentials.agent_id if self._credentials else None
160
+
161
+ def get_ws_url(self) -> Optional[str]:
162
+ """Get the WebSocket URL to connect to."""
163
+ return self._credentials.ws_url if self._credentials else None
164
+
165
+ def get_session_id(self) -> Optional[str]:
166
+ """Get the session ID for tracking."""
167
+ return self._credentials.session_id if self._credentials else None
168
+
169
+ def _should_refresh_token(self) -> bool:
170
+ """Check if token should be refreshed."""
171
+ if not self._credentials or not self._credentials.access_token:
172
+ return True
173
+
174
+ if not self._credentials.token_expires_at:
175
+ return False
176
+
177
+ time_until_expiry = (
178
+ self._credentials.token_expires_at - datetime.now()
179
+ ).total_seconds()
180
+ return time_until_expiry <= self.token_refresh_threshold
181
+
182
+ def _refresh_token(self) -> None:
183
+ """Refresh the authentication token using refresh token."""
184
+ if not self._credentials or not self._credentials.refresh_token:
185
+ logger.warning("No refresh token available, re-authenticating")
186
+ self.authenticate()
187
+ return
188
+
189
+ logger.info("Refreshing access token")
190
+
191
+ try:
192
+ tokens = refresh_access_token(
193
+ http_url=self.http_url,
194
+ refresh_token=self._credentials.refresh_token,
195
+ )
196
+
197
+ self._credentials.access_token = tokens["accessToken"]
198
+ self._credentials.refresh_token = tokens["refreshToken"]
199
+ self._credentials.token_expires_at = datetime.now() + timedelta(
200
+ hours=DEFAULT_TOKEN_VALIDITY_HOURS
201
+ )
202
+
203
+ logger.info(
204
+ f"Token refreshed, expires at: {self._credentials.token_expires_at}"
205
+ )
206
+
207
+ except Exception as e:
208
+ logger.warning(f"Token refresh failed: {e}, re-authenticating")
209
+ # Clear credentials and re-authenticate with AgentToken
210
+ self._credentials = None
211
+ self.authenticate()
212
+
213
+ def _start_token_refresh_monitor(self) -> None:
214
+ """Start background token refresh monitoring."""
215
+ if self._refresh_thread and self._refresh_thread.is_alive():
216
+ return
217
+
218
+ self._refresh_thread = threading.Thread(
219
+ target=self._token_refresh_worker,
220
+ name="TokenRefreshWorker",
221
+ daemon=True,
222
+ )
223
+ self._refresh_thread.start()
224
+
225
+ def _token_refresh_worker(self) -> None:
226
+ """Background worker for token refresh."""
227
+ while not self._shutdown_event.is_set():
228
+ try:
229
+ if self._should_refresh_token():
230
+ with self._token_lock:
231
+ if self._should_refresh_token(): # Double-check with lock
232
+ self._refresh_token()
233
+
234
+ # Check periodically
235
+ time.sleep(TOKEN_CHECK_INTERVAL_SECONDS)
236
+
237
+ except Exception as e:
238
+ logger.error(f"Token refresh worker error: {e}")
239
+ time.sleep(TOKEN_CHECK_INTERVAL_SECONDS)
240
+
241
+ def is_token_valid(self) -> bool:
242
+ """Check if current token is valid."""
243
+ if not self._credentials or not self._credentials.access_token:
244
+ return False
245
+ if not self._credentials.token_expires_at:
246
+ return True
247
+ return datetime.now() < self._credentials.token_expires_at
248
+
249
+ def get_token_info(self) -> dict:
250
+ """Get token information for debugging."""
251
+ return {
252
+ "has_token": bool(self._credentials and self._credentials.access_token),
253
+ "agent_id": self._credentials.agent_id if self._credentials else None,
254
+ "session_id": self._credentials.session_id if self._credentials else None,
255
+ "ws_url": self._credentials.ws_url if self._credentials else None,
256
+ "expires_at": (
257
+ self._credentials.token_expires_at.isoformat()
258
+ if self._credentials and self._credentials.token_expires_at
259
+ else None
260
+ ),
261
+ "is_valid": self.is_token_valid(),
262
+ "should_refresh": self._should_refresh_token(),
263
+ }
264
+
265
+ def stop(self) -> None:
266
+ """Stop the authentication service."""
267
+ logger.info("Stopping authentication service")
268
+ self._shutdown_event.set()
269
+
270
+ if self._refresh_thread and self._refresh_thread.is_alive():
271
+ self._refresh_thread.join(timeout=5)
@@ -0,0 +1,135 @@
1
+ import os
2
+ from typing import Any, Dict, List, Optional
3
+ from urllib.parse import urlparse
4
+
5
+
6
+ def require_env(name: str) -> str:
7
+ """Get required environment variable or raise error.
8
+
9
+ Args:
10
+ name: Environment variable name
11
+
12
+ Returns:
13
+ Environment variable value
14
+
15
+ Raises:
16
+ EnvironmentError: If variable is not set
17
+ """
18
+ value = os.getenv(name)
19
+ if value is None:
20
+ raise EnvironmentError(f"Missing required environment variable: {name}")
21
+ return value
22
+
23
+
24
+ def get_env(name: str, default: Optional[str] = None) -> Optional[str]:
25
+ """Get optional environment variable with default.
26
+
27
+ Args:
28
+ name: Environment variable name
29
+ default: Default value if not set
30
+
31
+ Returns:
32
+ Environment variable value or default
33
+ """
34
+ return os.getenv(name, default)
35
+
36
+
37
+ def validate_url(url: str, name: str) -> str:
38
+ """Validate URL format.
39
+
40
+ Args:
41
+ url: URL to validate
42
+ name: Name of the URL for error messages
43
+
44
+ Returns:
45
+ Validated URL
46
+
47
+ Raises:
48
+ ValueError: If URL is invalid
49
+ """
50
+ try:
51
+ parsed = urlparse(url)
52
+ if not parsed.scheme or not parsed.netloc:
53
+ raise ValueError(f"Invalid {name}: missing scheme or netloc")
54
+ return url
55
+ except Exception as e:
56
+ raise ValueError(f"Invalid {name}: {e}")
57
+
58
+
59
+ def validate_agent_token(token: str) -> str:
60
+ """Validate AgentToken format.
61
+
62
+ Args:
63
+ token: AgentToken to validate
64
+
65
+ Returns:
66
+ Validated token
67
+
68
+ Raises:
69
+ ValueError: If token format is invalid
70
+ """
71
+ if not token.startswith("agt_"):
72
+ raise ValueError("AGENT_TOKEN must start with 'agt_'")
73
+ if len(token) < 10:
74
+ raise ValueError("AGENT_TOKEN is too short")
75
+ return token
76
+
77
+
78
+ def parse_list(value: Optional[str]) -> List[str]:
79
+ """Parse comma-separated string into list.
80
+
81
+ Args:
82
+ value: Comma-separated string or None
83
+
84
+ Returns:
85
+ List of strings (empty if value is None)
86
+ """
87
+ if not value:
88
+ return []
89
+ return [item.strip() for item in value.split(",") if item.strip()]
90
+
91
+
92
+ def load_config() -> Dict[str, Any]:
93
+ """Load configuration from environment variables.
94
+
95
+ Required:
96
+ HTTP_URL: Base HTTP API URL
97
+ AGENT_TOKEN: AgentToken (must start with 'agt_')
98
+ AGENT_NAME: Unique agent name within organization
99
+
100
+ Optional:
101
+ AGENT_VERSION: Agent version (default: "1.0.0")
102
+ AGENT_CAPABILITIES: Comma-separated list of capabilities
103
+ AGENT_TAGS: Comma-separated list of tags
104
+
105
+ Returns:
106
+ Configuration dictionary
107
+
108
+ Raises:
109
+ EnvironmentError: If required variables are missing
110
+ ValueError: If configuration values are invalid
111
+ """
112
+ http_url = require_env("HTTP_URL")
113
+ agent_token = require_env("AGENT_TOKEN")
114
+ agent_name = require_env("AGENT_NAME")
115
+
116
+ # Optional configuration
117
+ agent_version = get_env("AGENT_VERSION", "1.0.0")
118
+ capabilities_str = get_env("AGENT_CAPABILITIES", "")
119
+ tags_str = get_env("AGENT_TAGS", "")
120
+
121
+ # Validate configuration
122
+ validate_url(http_url, "HTTP_URL")
123
+ validate_agent_token(agent_token)
124
+
125
+ if not agent_name.strip():
126
+ raise ValueError("AGENT_NAME cannot be empty")
127
+
128
+ return {
129
+ "HTTP_URL": http_url,
130
+ "AGENT_TOKEN": agent_token,
131
+ "AGENT_NAME": agent_name,
132
+ "AGENT_VERSION": agent_version,
133
+ "AGENT_CAPABILITIES": parse_list(capabilities_str),
134
+ "AGENT_TAGS": parse_list(tags_str),
135
+ }