atlascloudsdk 0.1.1__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.
Files changed (47) hide show
  1. atlas/__init__.py +57 -0
  2. atlas/_http/__init__.py +1 -0
  3. atlas/_http/transport.py +352 -0
  4. atlas/auth.py +245 -0
  5. atlas/cli/__init__.py +1 -0
  6. atlas/cli/commands/__init__.py +1 -0
  7. atlas/cli/commands/auth.py +62 -0
  8. atlas/cli/commands/gpu.py +1 -0
  9. atlas/cli/commands/instances.py +188 -0
  10. atlas/cli/commands/kubernetes.py +1 -0
  11. atlas/cli/commands/network.py +41 -0
  12. atlas/cli/commands/projects.py +53 -0
  13. atlas/cli/commands/security_groups.py +177 -0
  14. atlas/cli/commands/ssh.py +88 -0
  15. atlas/cli/commands/vdc.py +37 -0
  16. atlas/cli/context.py +23 -0
  17. atlas/cli/main.py +26 -0
  18. atlas/cli/output.py +6 -0
  19. atlas/cli/token_store.py +72 -0
  20. atlas/client.py +216 -0
  21. atlas/config.py +1 -0
  22. atlas/connection.py +85 -0
  23. atlas/exceptions.py +139 -0
  24. atlas/models/__init__.py +1 -0
  25. atlas/models/gpu.py +1 -0
  26. atlas/models/kubernetes.py +1 -0
  27. atlas/models/project.py +1 -0
  28. atlas/pagination.py +1 -0
  29. atlas/resources/__init__.py +5 -0
  30. atlas/resources/base.py +25 -0
  31. atlas/resources/compute.py +35 -0
  32. atlas/resources/compute_units.py +27 -0
  33. atlas/resources/gpu.py +1 -0
  34. atlas/resources/instances.py +82 -0
  35. atlas/resources/kubernetes.py +1 -0
  36. atlas/resources/networks.py +69 -0
  37. atlas/resources/projects.py +42 -0
  38. atlas/resources/security_groups.py +115 -0
  39. atlas/resources/ssh_keys.py +44 -0
  40. atlas/resources/vdc.py +39 -0
  41. atlas/version.py +3 -0
  42. atlascloudsdk-0.1.1.dist-info/METADATA +222 -0
  43. atlascloudsdk-0.1.1.dist-info/RECORD +47 -0
  44. atlascloudsdk-0.1.1.dist-info/WHEEL +5 -0
  45. atlascloudsdk-0.1.1.dist-info/entry_points.txt +2 -0
  46. atlascloudsdk-0.1.1.dist-info/licenses/LICENSE +21 -0
  47. atlascloudsdk-0.1.1.dist-info/top_level.txt +1 -0
atlas/__init__.py ADDED
@@ -0,0 +1,57 @@
1
+ from atlas.client import Atlas
2
+ from atlas.connection import Connection
3
+ from atlas.exceptions import (
4
+ APIError,
5
+ AtlasError,
6
+ AuthenticationError,
7
+ BadRequestError,
8
+ ClientAPIError,
9
+ ClientClosedError,
10
+ ConfigurationError,
11
+ ConflictError,
12
+ ConnectionError,
13
+ LogoutError,
14
+ MethodNotAllowedError,
15
+ NetworkError,
16
+ NotFoundError,
17
+ PermissionDeniedError,
18
+ RateLimitError,
19
+ RequestError,
20
+ ResponseError,
21
+ ServerError,
22
+ ServiceUnavailableError,
23
+ TimeoutError,
24
+ TransportError,
25
+ UnprocessableEntityError,
26
+ ValidationError,
27
+ )
28
+ from atlas.version import __version__
29
+
30
+ __all__ = [
31
+ "Atlas",
32
+ "Connection",
33
+ "__version__",
34
+ "AtlasError",
35
+ "ConfigurationError",
36
+ "ClientClosedError",
37
+ "RequestError",
38
+ "ResponseError",
39
+ "AuthenticationError",
40
+ "ClientAPIError",
41
+ "BadRequestError",
42
+ "PermissionDeniedError",
43
+ "NotFoundError",
44
+ "ConflictError",
45
+ "MethodNotAllowedError",
46
+ "ValidationError",
47
+ "UnprocessableEntityError",
48
+ "RateLimitError",
49
+ "APIError",
50
+ "ServerError",
51
+ "ServiceUnavailableError",
52
+ "TransportError",
53
+ "NetworkError",
54
+ "TimeoutError",
55
+ "ConnectionError",
56
+ "LogoutError",
57
+ ]
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,352 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+ from urllib.parse import urlparse
5
+
6
+ import requests
7
+
8
+ from atlas.exceptions import (
9
+ AtlasError,
10
+ AuthenticationError,
11
+ BadRequestError,
12
+ ClientClosedError,
13
+ ConfigurationError,
14
+ ConflictError,
15
+ ConnectionError,
16
+ MethodNotAllowedError,
17
+ NotFoundError,
18
+ PermissionDeniedError,
19
+ RateLimitError,
20
+ ServerError,
21
+ ServiceUnavailableError,
22
+ TimeoutError,
23
+ UnprocessableEntityError,
24
+ )
25
+
26
+
27
+ class HttpTransport:
28
+ """HTTP transport for authenticated Atlas API requests."""
29
+
30
+ REFRESH_PATH = "/api/v1.0/account/access_token"
31
+
32
+ def __init__(
33
+ self,
34
+ base_url: str,
35
+ access_token: str,
36
+ refresh_token: str | None = None,
37
+ timeout: float = 30.0,
38
+ verify: bool | str = True,
39
+ session: requests.Session | None = None,
40
+ ) -> None:
41
+ if not isinstance(base_url, str) or not base_url.strip():
42
+ raise ConfigurationError("base_url must be a non-empty URL.")
43
+
44
+ parsed_url = urlparse(base_url)
45
+ if parsed_url.scheme not in {"http", "https"} or not parsed_url.netloc:
46
+ raise ConfigurationError("base_url must be an absolute HTTP or HTTPS URL.")
47
+
48
+ if not isinstance(access_token, str) or not access_token.strip():
49
+ raise AuthenticationError("A valid access token is required.")
50
+
51
+ if timeout <= 0:
52
+ raise ConfigurationError("timeout must be greater than zero.")
53
+
54
+ if not verify and parsed_url.scheme.lower() == "https":
55
+ raise ConfigurationError(
56
+ "TLS verification cannot be disabled for HTTPS in this client."
57
+ )
58
+
59
+ self.base_url = base_url.rstrip("/")
60
+ self.access_token: str | None = access_token
61
+ self.refresh_token: str | None = refresh_token
62
+ self.timeout = timeout
63
+ self.verify = verify
64
+ self.session = session or requests.Session()
65
+ self._closed = False
66
+
67
+ def _ensure_open(self) -> None:
68
+ if self._closed:
69
+ raise ClientClosedError("The HTTP transport is closed.")
70
+
71
+ def _headers(self, authenticated: bool = True) -> dict[str, str]:
72
+ self._ensure_open()
73
+
74
+ headers = {"Accept": "application/json"}
75
+
76
+ if authenticated:
77
+ if not self.access_token:
78
+ raise AuthenticationError("No access token is available. Log in again.")
79
+ headers["Authorization"] = f"Bearer {self.access_token}"
80
+
81
+ return headers
82
+
83
+ @staticmethod
84
+ def _parse_response(response: requests.Response) -> Any:
85
+ try:
86
+ return response.json()
87
+ except ValueError:
88
+ return {"message": "The server returned a non-JSON response."}
89
+
90
+ @staticmethod
91
+ def _extract_data(body: Any) -> dict[str, Any]:
92
+ if not isinstance(body, dict):
93
+ raise AuthenticationError(
94
+ "The authentication API returned an invalid response."
95
+ )
96
+
97
+ data = body.get("data", body)
98
+
99
+ if not isinstance(data, dict):
100
+ raise AuthenticationError(
101
+ "The authentication API returned an invalid data object."
102
+ )
103
+
104
+ return data
105
+
106
+ def _send(
107
+ self,
108
+ method: str,
109
+ path: str,
110
+ *,
111
+ authenticated: bool = True,
112
+ **kwargs: Any,
113
+ ) -> requests.Response:
114
+ self._ensure_open()
115
+
116
+ if not isinstance(path, str) or not path.startswith("/"):
117
+ raise ValueError("API path must start with '/'.")
118
+
119
+ if path.startswith("//"):
120
+ raise ValueError("Protocol-relative API paths are not allowed.")
121
+
122
+ # Avoid callers overriding security-sensitive transport settings.
123
+ if "verify" in kwargs or "timeout" in kwargs:
124
+ raise ValueError("Configure verify and timeout on HttpTransport itself.")
125
+
126
+ try:
127
+ return self.session.request(
128
+ method=method.upper(),
129
+ url=f"{self.base_url}{path}",
130
+ headers=self._headers(authenticated=authenticated),
131
+ timeout=self.timeout,
132
+ verify=self.verify,
133
+ allow_redirects=False,
134
+ **kwargs,
135
+ )
136
+ except requests.Timeout as exc:
137
+ raise TimeoutError("The Atlas API request timed out.") from exc
138
+ except requests.RequestException as exc:
139
+ raise ConnectionError("Could not connect to the Atlas API.") from exc
140
+
141
+ def _raise_for_status(
142
+ self,
143
+ response: requests.Response,
144
+ body: Any,
145
+ ) -> None:
146
+ status = response.status_code
147
+
148
+ if response.ok:
149
+ return
150
+
151
+ message = (
152
+ body.get("message", "Atlas API request failed.")
153
+ if isinstance(body, dict)
154
+ else "Atlas API request failed."
155
+ )
156
+
157
+ # Avoid exposing raw response bodies in exception messages.
158
+ if not isinstance(message, str):
159
+ message = "Atlas API request failed."
160
+
161
+ details = body
162
+
163
+ if status == 401:
164
+ raise AuthenticationError(
165
+ "Authentication failed or the access token expired.",
166
+ status_code=status,
167
+ details=details,
168
+ )
169
+
170
+ if status == 403:
171
+ raise PermissionDeniedError(
172
+ "You do not have permission to perform this operation.",
173
+ status_code=status,
174
+ details=details,
175
+ )
176
+
177
+ if status == 404:
178
+ raise NotFoundError(
179
+ "The requested resource was not found.",
180
+ status_code=status,
181
+ details=details,
182
+ )
183
+
184
+ if status == 400:
185
+ raise BadRequestError(
186
+ message,
187
+ status_code=status,
188
+ details=details,
189
+ )
190
+
191
+ if status == 405:
192
+ raise MethodNotAllowedError(
193
+ "The API endpoint does not allow this HTTP method.",
194
+ status_code=status,
195
+ details=details,
196
+ )
197
+
198
+ if status == 409:
199
+ raise ConflictError(
200
+ message,
201
+ status_code=status,
202
+ details=details,
203
+ )
204
+
205
+ if status == 422:
206
+ raise UnprocessableEntityError(
207
+ message,
208
+ status_code=status,
209
+ details=details,
210
+ )
211
+
212
+ if status == 429:
213
+ raise RateLimitError(
214
+ "The API rate limit has been exceeded.",
215
+ status_code=status,
216
+ details=details,
217
+ )
218
+
219
+ if status == 503:
220
+ raise ServiceUnavailableError(
221
+ "The Atlas service is temporarily unavailable.",
222
+ status_code=status,
223
+ details=details,
224
+ )
225
+
226
+ if status >= 500:
227
+ raise ServerError(
228
+ "The Atlas server encountered an error.",
229
+ status_code=status,
230
+ details=details,
231
+ )
232
+
233
+ raise AtlasError(
234
+ message,
235
+ status_code=status,
236
+ details=details,
237
+ )
238
+
239
+ def request(self, method: str, path: str, **kwargs: Any) -> Any:
240
+ """Send an authenticated JSON request.
241
+
242
+ Refresh is attempted once after a 401. Automatic replay is limited
243
+ to GET, HEAD and OPTIONS to avoid repeating write operations.
244
+ """
245
+
246
+ method = method.upper()
247
+ response = self._send(method, path, **kwargs)
248
+
249
+ if response.status_code == 401 and self.refresh_token:
250
+ # Do not automatically repeat POST/PATCH/PUT/DELETE requests.
251
+ # The caller can decide whether a write is safe to retry.
252
+ if method not in {"GET", "HEAD", "OPTIONS"}:
253
+ self._raise_for_status(
254
+ response,
255
+ self._parse_response(response),
256
+ )
257
+
258
+ self.refresh_access_token()
259
+ response = self._send(method, path, **kwargs)
260
+
261
+ body = self._parse_response(response)
262
+ self._raise_for_status(response, body)
263
+
264
+ return body
265
+
266
+ def refresh_access_token(self) -> str:
267
+ """Refresh the access token using the configured refresh token.
268
+
269
+ This assumes the backend accepts the existing refresh endpoint and
270
+ returns access_token, optionally inside a data object.
271
+ """
272
+
273
+ self._ensure_open()
274
+
275
+ if not self.refresh_token:
276
+ raise AuthenticationError("No refresh token is available.")
277
+
278
+ try:
279
+ response = self.session.post(
280
+ f"{self.base_url}{self.REFRESH_PATH}",
281
+ json={"refresh_token": self.refresh_token},
282
+ headers={"Accept": "application/json"},
283
+ timeout=self.timeout,
284
+ verify=self.verify,
285
+ allow_redirects=False,
286
+ )
287
+ except requests.Timeout as exc:
288
+ raise TimeoutError("Token refresh timed out.") from exc
289
+ except requests.RequestException as exc:
290
+ raise ConnectionError(
291
+ "Could not connect to the token refresh endpoint."
292
+ ) from exc
293
+
294
+ body = self._parse_response(response)
295
+
296
+ if not response.ok:
297
+ # Do not continue using credentials after a rejected refresh.
298
+ if response.status_code in (400, 401, 403):
299
+ self.clear_auth()
300
+
301
+ self._raise_for_status(response, body)
302
+
303
+ data = self._extract_data(body)
304
+ new_access_token = data.get("access_token")
305
+
306
+ if not isinstance(new_access_token, str) or not new_access_token.strip():
307
+ raise AuthenticationError(
308
+ "The refresh response did not contain a valid access token.",
309
+ status_code=response.status_code,
310
+ )
311
+
312
+ # Support refresh-token rotation when the backend returns a new one.
313
+ new_refresh_token = data.get("refresh_token")
314
+ self.access_token = new_access_token
315
+
316
+ if isinstance(new_refresh_token, str) and new_refresh_token:
317
+ self.refresh_token = new_refresh_token
318
+
319
+ return self.access_token
320
+
321
+ def request_raw(self, method: str, path: str, **kwargs: Any):
322
+ """Send an authenticated request and return its raw response."""
323
+
324
+ response = self._send(method, path, **kwargs)
325
+ if not response.ok:
326
+ self._raise_for_status(
327
+ response,
328
+ self._parse_response(response),
329
+ )
330
+ return response
331
+
332
+ def clear_auth(self) -> None:
333
+ """Clear local credentials and cached authorization headers."""
334
+
335
+ self.access_token = None
336
+ self.refresh_token = None
337
+ self.session.headers.pop("Authorization", None)
338
+
339
+ def close(self) -> None:
340
+ """Close the connection pool and invalidate this transport."""
341
+
342
+ if not self._closed:
343
+ self.clear_auth()
344
+ self.session.close()
345
+ self._closed = True
346
+
347
+ def __enter__(self) -> HttpTransport:
348
+ self._ensure_open()
349
+ return self
350
+
351
+ def __exit__(self, exc_type, exc_value, traceback) -> None:
352
+ self.close()
atlas/auth.py ADDED
@@ -0,0 +1,245 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from typing import Any
5
+
6
+ import requests
7
+
8
+ from atlas.exceptions import (
9
+ AuthenticationError,
10
+ ConfigurationError,
11
+ ConnectionError,
12
+ LogoutError,
13
+ TimeoutError,
14
+ )
15
+
16
+
17
+ @dataclass(frozen=True, repr=False)
18
+ class TokenSet:
19
+ """Authentication tokens returned by the Atlas API."""
20
+
21
+ access_token: str = field(repr=False)
22
+ refresh_token: str | None = field(default=None, repr=False)
23
+ expires_in: int | None = None
24
+
25
+ def __post_init__(self) -> None:
26
+ if not isinstance(self.access_token, str) or not self.access_token.strip():
27
+ raise ValueError("access_token must be a non-empty string.")
28
+
29
+ if self.refresh_token is not None and not isinstance(self.refresh_token, str):
30
+ raise ValueError("refresh_token must be a string or None.")
31
+
32
+ if self.expires_in is not None and (
33
+ isinstance(self.expires_in, bool)
34
+ or not isinstance(self.expires_in, int)
35
+ or self.expires_in <= 0
36
+ ):
37
+ raise ValueError("expires_in must be a positive integer.")
38
+
39
+ def __repr__(self) -> str:
40
+ # Never reveal secrets in logs or debugging output.
41
+ return (
42
+ "TokenSet("
43
+ "access_token=<redacted>, "
44
+ "refresh_token=<redacted>, "
45
+ f"expires_in={self.expires_in!r})"
46
+ )
47
+
48
+
49
+ class AuthClient:
50
+ """Authenticate with the Atlas backend."""
51
+
52
+ LOGIN_PATH = "/api/v1.0/account/get-login-refresh-token"
53
+
54
+ def __init__(
55
+ self,
56
+ base_url: str,
57
+ timeout: float = 30.0,
58
+ verify: bool | str = True,
59
+ session: requests.Session | None = None,
60
+ ) -> None:
61
+ if not isinstance(base_url, str) or not base_url.strip():
62
+ raise ConfigurationError("base_url must be a non-empty URL.")
63
+
64
+ self.base_url = base_url.rstrip("/")
65
+ self.timeout = timeout
66
+ self.verify = verify
67
+
68
+ if timeout <= 0:
69
+ raise ConfigurationError("timeout must be greater than zero.")
70
+
71
+ # Do not disable TLS verification in production.
72
+ if not verify and self.base_url.lower().startswith("https://"):
73
+ raise ConfigurationError(
74
+ "TLS verification cannot be disabled for HTTPS in this client."
75
+ )
76
+
77
+ self._session = session or requests.Session()
78
+ self._owns_session = session is None
79
+ self._closed = False
80
+
81
+ @staticmethod
82
+ def _response_body(response: requests.Response) -> dict[str, Any]:
83
+ try:
84
+ body = response.json()
85
+ except ValueError:
86
+ body = {"message": "The server returned a non-JSON response."}
87
+
88
+ if isinstance(body, dict):
89
+ return body
90
+
91
+ return {"message": "The server returned an unexpected response format."}
92
+
93
+ @staticmethod
94
+ def _message(body: dict[str, Any], default: str) -> str:
95
+ message = body.get("message")
96
+ if isinstance(message, str) and message.strip():
97
+ return message
98
+ return default
99
+
100
+ def login(self, username: str, password: str) -> TokenSet:
101
+ """Exchange username/password for access and refresh tokens."""
102
+
103
+ if self._closed:
104
+ raise AuthenticationError("The authentication client is closed.")
105
+
106
+ if not isinstance(username, str) or not username.strip():
107
+ raise AuthenticationError("username must not be empty.")
108
+
109
+ if not isinstance(password, str) or not password:
110
+ raise AuthenticationError("password must not be empty.")
111
+
112
+ try:
113
+ response = self._session.post(
114
+ f"{self.base_url}{self.LOGIN_PATH}",
115
+ json={
116
+ "user_name": username,
117
+ "password": password,
118
+ },
119
+ timeout=self.timeout,
120
+ verify=self.verify,
121
+ allow_redirects=False,
122
+ )
123
+ except requests.Timeout as exc:
124
+ raise TimeoutError(
125
+ "Login request timed out. Check the API and network."
126
+ ) from exc
127
+ except requests.RequestException as exc:
128
+ raise ConnectionError(
129
+ "Could not connect to the Atlas authentication API."
130
+ ) from exc
131
+
132
+ body = self._response_body(response)
133
+
134
+ if not response.ok:
135
+ raise AuthenticationError(
136
+ self._message(body, "Authentication failed."),
137
+ status_code=response.status_code,
138
+ details=body,
139
+ )
140
+
141
+ data = body.get("data", body)
142
+ if not isinstance(data, dict):
143
+ raise AuthenticationError(
144
+ "The login response has an invalid data structure.",
145
+ status_code=response.status_code,
146
+ )
147
+
148
+ access_token = data.get("access_token")
149
+ if not isinstance(access_token, str) or not access_token.strip():
150
+ raise AuthenticationError(
151
+ "The login response did not contain a valid access token.",
152
+ status_code=response.status_code,
153
+ details={
154
+ "message": self._message(body, "Invalid authentication response.")
155
+ },
156
+ )
157
+
158
+ refresh_token = data.get("refresh_token")
159
+ if refresh_token is not None and not isinstance(refresh_token, str):
160
+ raise AuthenticationError(
161
+ "The login response contains an invalid refresh token.",
162
+ status_code=response.status_code,
163
+ )
164
+
165
+ expires_in = data.get("expires_in")
166
+ if expires_in is not None:
167
+ # Some APIs return this as a string. Accept a numeric string,
168
+ # but reject booleans, decimals, zero, and negative values.
169
+ if isinstance(expires_in, str) and expires_in.isdecimal():
170
+ expires_in = int(expires_in)
171
+
172
+ if (
173
+ isinstance(expires_in, bool)
174
+ or not isinstance(expires_in, int)
175
+ or expires_in <= 0
176
+ ):
177
+ raise AuthenticationError(
178
+ "The login response contains an invalid expires_in value.",
179
+ status_code=response.status_code,
180
+ )
181
+
182
+ return TokenSet(
183
+ access_token=access_token,
184
+ refresh_token=refresh_token,
185
+ expires_in=expires_in,
186
+ )
187
+
188
+ def revoke(
189
+ self,
190
+ tokens: TokenSet,
191
+ logout_path: str,
192
+ ) -> None:
193
+ """
194
+ Request server-side revocation using a backend-confirmed endpoint.
195
+
196
+ Configure logout_path only after confirming the backend contract.
197
+ This method assumes that the endpoint accepts a JSON refresh_token.
198
+ Adapt the payload if the backend expects a different contract.
199
+ """
200
+
201
+ if self._closed:
202
+ raise LogoutError("The authentication client is closed.")
203
+
204
+ if not logout_path.startswith("/") or logout_path.startswith("//"):
205
+ raise ValueError("logout_path must be an absolute API path.")
206
+
207
+ if not tokens.refresh_token:
208
+ raise LogoutError("Server-side logout requires a refresh token.")
209
+
210
+ try:
211
+ response = self._session.post(
212
+ f"{self.base_url}{logout_path}",
213
+ json={"refresh_token": tokens.refresh_token},
214
+ timeout=self.timeout,
215
+ verify=self.verify,
216
+ allow_redirects=False,
217
+ )
218
+ except requests.Timeout as exc:
219
+ raise TimeoutError("The server-side logout request timed out.") from exc
220
+ except requests.RequestException as exc:
221
+ raise ConnectionError("Could not connect to the logout endpoint.") from exc
222
+
223
+ if not response.ok:
224
+ body = self._response_body(response)
225
+ raise LogoutError(
226
+ self._message(body, "Server-side logout failed."),
227
+ status_code=response.status_code,
228
+ details=body,
229
+ )
230
+
231
+ def close(self) -> None:
232
+ """Release the underlying HTTP connection pool."""
233
+
234
+ if not self._closed:
235
+ if self._owns_session:
236
+ self._session.close()
237
+ self._closed = True
238
+
239
+ def __enter__(self) -> AuthClient:
240
+ if self._closed:
241
+ raise AuthenticationError("The authentication client is closed.")
242
+ return self
243
+
244
+ def __exit__(self, exc_type, exc_value, traceback) -> None:
245
+ self.close()
atlas/cli/__init__.py ADDED
@@ -0,0 +1 @@
1
+
@@ -0,0 +1 @@
1
+