multicloud-cli 0.1.0__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 @@
1
+ __version__ = "0.1.0"
multicloud_cli/api.py ADDED
@@ -0,0 +1,152 @@
1
+ """One HTTP call to the Multicloud API, shared by the command groups.
2
+
3
+ The URL is ``{api_url}/api/v1/orgs/{slug}{path}``, or ``{api_url}/api/v1{path}`` for an ``org_scoped=False`` call
4
+ (the catalog). The credential is, in this order: ``MULTICLOUD_API_KEY``,
5
+ the SSO session (``Authorization: Bearer``), the stored API key (``X-API-Key``). It travels only to the https
6
+ URL that ``config.get_api_url`` accepted.
7
+ """
8
+ import os
9
+ from typing import Any, Dict, Iterable, Optional, Tuple
10
+ from urllib.parse import quote
11
+
12
+ import requests
13
+
14
+ from . import auth, config, exitcodes, sso
15
+
16
+ TIMEOUT_S = 30
17
+
18
+
19
+ class ApiError(Exception):
20
+ """The call failed. ``status`` is the HTTP status, or None when there was no answer.
21
+ ``exit_code`` is the exit code of ``mctl`` for it (see ``exitcodes``)."""
22
+
23
+ def __init__(self, message: str, status: Optional[int] = None, exit_code: Optional[int] = None):
24
+ super().__init__(message)
25
+ self.status = status
26
+ self.exit_code = exit_code if exit_code is not None else exitcodes.for_status(status)
27
+
28
+
29
+ def _detail_text(data: Any) -> Optional[str]:
30
+ """The text of a Multicloud API error body: ``detail: {code, message}``, ``detail: {error: {message}}``,
31
+ ``detail: "<text>"`` or the list of a 422 validation error."""
32
+ detail = data.get("detail") if isinstance(data, dict) else None
33
+ if isinstance(detail, str):
34
+ return detail or None
35
+ if isinstance(detail, dict):
36
+ inner = detail.get("error")
37
+ if isinstance(inner, dict):
38
+ detail = inner
39
+ if detail.get("message"):
40
+ code = detail.get("code")
41
+ return f"{code}: {detail['message']}" if code else str(detail["message"])
42
+ if detail.get("code"):
43
+ return str(detail["code"])
44
+ if isinstance(detail, list):
45
+ parts = []
46
+ for item in detail:
47
+ if isinstance(item, dict) and item.get("msg"):
48
+ where = ".".join(str(p) for p in item.get("loc", []) if p != "body")
49
+ parts.append(f"{where}: {item['msg']}" if where else str(item["msg"]))
50
+ return "; ".join(parts) or None
51
+ return None
52
+
53
+
54
+ def _send(method: str, url: str, body: Optional[Dict[str, Any]], headers: Dict[str, str],
55
+ params: Optional[Dict[str, Any]] = None) -> requests.Response:
56
+ extra = {"params": params} if params else {} # a list value becomes one repeated key
57
+ try:
58
+ # No redirects: requests would carry the credential header to another host.
59
+ return requests.request(method, url, json=body, timeout=TIMEOUT_S, allow_redirects=False, headers=headers,
60
+ **extra)
61
+ except requests.RequestException as ex:
62
+ raise ApiError(f"Could not reach the API: {ex}")
63
+
64
+
65
+ def _sso_org(slug: Optional[str], token: str, explicit: bool = True) -> str:
66
+ """The organization of this call: ``--org`` (or env, or saved) when it is in the token, else the only one.
67
+ A SAVED org that the token lacks (left from an API-key login) is ignored; an explicit one is an error."""
68
+ orgs = sso.orgs_in_token(token)
69
+ if slug and not explicit and slug not in orgs:
70
+ slug = None
71
+ if not orgs:
72
+ raise auth.AuthError("Your sign-in holds no organization. Ask an owner of your organization to add you, "
73
+ "then run: mctl auth login")
74
+ if slug:
75
+ if slug not in orgs:
76
+ raise auth.AuthError(f"You are not a member of '{slug}'. Your organizations: {', '.join(orgs)}.")
77
+ return slug
78
+ if len(orgs) > 1:
79
+ raise auth.AuthError(f"You belong to several organizations ({', '.join(orgs)}). "
80
+ "Name one with --org or MULTICLOUD_ORG.")
81
+ return orgs[0]
82
+
83
+
84
+ def call(method: str, org: Optional[str], path: str = "", *, body: Optional[Dict[str, Any]] = None,
85
+ headers: Optional[Dict[str, str]] = None, accept: Iterable[int] = (200, 201, 202),
86
+ scope: Optional[str] = None, pass_codes: Iterable[str] = (),
87
+ params: Optional[Dict[str, Any]] = None, org_scoped: bool = True) -> Dict[str, Any]:
88
+ """One API call. Returns the JSON body with ``_status`` added; raises ``ApiError`` on other statuses.
89
+
90
+ ``scope`` names the API key scope this call needs; a 401 or 403 then says that it may be missing.
91
+ A failed answer whose error code is in ``pass_codes`` is returned like a success.
92
+ ``params`` are query parameters. ``org_scoped=False`` calls ``/api/v1{path}`` with no organization in the URL:
93
+ an SSO call then needs no organization, and ``MULTICLOUD_API_KEY`` needs none either (a stored key still
94
+ needs one to be found)."""
95
+ slug = config.get_org(org)
96
+ try:
97
+ use_sso = False
98
+ if not os.environ.get("MULTICLOUD_API_KEY"): # the key path needs no issuer
99
+ issuer = config.get_issuer()
100
+ use_sso = auth.load_sso(issuer) is not None
101
+ if use_sso and not org_scoped and slug and auth.get_key(slug)[0]:
102
+ # A stored key of the named org wins for the platform routes (the catalog): it holds its scope
103
+ # explicitly, while an SSO token may not reach them.
104
+ use_sso = False
105
+ base = config.get_api_url()
106
+ if use_sso:
107
+ token = auth.fresh_access_token(issuer)
108
+ if org_scoped:
109
+ slug = _sso_org(slug, token, explicit=config.org_is_explicit(org))
110
+ credential = {"Authorization": f"Bearer {token}"}
111
+ else:
112
+ env_key = os.environ.get("MULTICLOUD_API_KEY")
113
+ if not slug and not org_scoped and not env_key:
114
+ raise ApiError("No sign-in. Run: mctl auth login (or set MULTICLOUD_API_KEY, or name the "
115
+ "organization of a stored key with --org).", exit_code=exitcodes.AUTH)
116
+ if not slug and org_scoped:
117
+ raise ApiError("Name the organization with --org or MULTICLOUD_ORG.")
118
+ key = auth.get_key(slug)[0] if slug else env_key
119
+ if not key:
120
+ raise ApiError(f"No sign-in for {slug}. Run: mctl auth login", exit_code=exitcodes.AUTH)
121
+ credential = {"X-API-Key": key}
122
+ except auth.AuthError as ex:
123
+ raise ApiError(str(ex), exit_code=exitcodes.AUTH)
124
+ except config.ConfigError as ex:
125
+ raise ApiError(str(ex))
126
+ url = f"{base}/api/v1/orgs/{quote(slug, safe='')}{path}" if org_scoped else f"{base}/api/v1{path}"
127
+ r = _send(method, url, body, {**credential, **(headers or {})}, params)
128
+ if r.status_code == 401 and use_sso:
129
+ # The access token was refused (the session may have ended on the server): refresh once and retry once.
130
+ try:
131
+ token = auth.fresh_access_token(issuer, rejected=token)
132
+ except auth.AuthError as ex:
133
+ raise ApiError(str(ex), 401)
134
+ r = _send(method, url, body, {"Authorization": f"Bearer {token}", **(headers or {})}, params)
135
+ try:
136
+ data = r.json() if r.text else {}
137
+ except ValueError:
138
+ data = {}
139
+ if r.status_code not in accept:
140
+ detail = data.get("detail") if isinstance(data, dict) else None
141
+ if isinstance(detail, dict) and detail.get("code") in set(pass_codes):
142
+ data = dict(data)
143
+ data["_status"] = r.status_code
144
+ return data
145
+ text = _detail_text(data) or f"HTTP {r.status_code}"
146
+ # A 401 is a bad or expired credential, not a missing scope.
147
+ if r.status_code == 403 and scope and not use_sso:
148
+ text += f" (HTTP {r.status_code}. The API key may lack the '{scope}' scope.)"
149
+ raise ApiError(text, r.status_code)
150
+ data = dict(data) if isinstance(data, dict) else {"body": data}
151
+ data["_status"] = r.status_code
152
+ return data