multicloud-cli 0.10.1__tar.gz → 0.12.0__tar.gz

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 (44) hide show
  1. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/PKG-INFO +4 -3
  2. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/README.md +3 -2
  3. multicloud_cli-0.12.0/multicloud_cli/__init__.py +1 -0
  4. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/multicloud_cli/extend.py +124 -3
  5. multicloud_cli-0.12.0/multicloud_cli/kube.py +89 -0
  6. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/multicloud_cli/pool.py +2 -1
  7. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/tests/test_account_extend.py +9 -0
  8. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/tests/test_pool.py +5 -1
  9. multicloud_cli-0.12.0/tests/test_proxy_key.py +228 -0
  10. multicloud_cli-0.10.1/multicloud_cli/__init__.py +0 -1
  11. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/.gitignore +0 -0
  12. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/LICENSE +0 -0
  13. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/multicloud_cli/account.py +0 -0
  14. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/multicloud_cli/api.py +0 -0
  15. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/multicloud_cli/auth.py +0 -0
  16. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/multicloud_cli/catalog.py +0 -0
  17. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/multicloud_cli/cloud_account.py +0 -0
  18. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/multicloud_cli/config.py +0 -0
  19. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/multicloud_cli/duration.py +0 -0
  20. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/multicloud_cli/exitcodes.py +0 -0
  21. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/multicloud_cli/main.py +0 -0
  22. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/multicloud_cli/net.py +0 -0
  23. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/multicloud_cli/node.py +0 -0
  24. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/multicloud_cli/orgopt.py +0 -0
  25. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/multicloud_cli/output.py +0 -0
  26. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/multicloud_cli/ssh.py +0 -0
  27. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/multicloud_cli/ssh_cert.py +0 -0
  28. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/multicloud_cli/sso.py +0 -0
  29. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/multicloud_cli/version_check.py +0 -0
  30. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/pyproject.toml +0 -0
  31. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/tests/__init__.py +0 -0
  32. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/tests/conftest.py +0 -0
  33. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/tests/helpers.py +0 -0
  34. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/tests/test_apply.py +0 -0
  35. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/tests/test_auth.py +0 -0
  36. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/tests/test_catalog.py +0 -0
  37. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/tests/test_cloud_account.py +0 -0
  38. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/tests/test_conventions.py +0 -0
  39. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/tests/test_net.py +0 -0
  40. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/tests/test_ssh.py +0 -0
  41. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/tests/test_ssh_cert.py +0 -0
  42. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/tests/test_sso.py +0 -0
  43. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/tests/test_sso_session.py +0 -0
  44. {multicloud_cli-0.10.1 → multicloud_cli-0.12.0}/tests/test_version_check.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: multicloud-cli
3
- Version: 0.10.1
3
+ Version: 0.12.0
4
4
  Summary: mctl: the Multicloud command line: sign in, connect your cloud account, run pools
5
5
  Project-URL: Homepage, https://multicloud.io
6
6
  Author-email: Multicloud Team <info@multicloud.io>
@@ -50,7 +50,7 @@ upgrades itself. Turn the check off with `MCTL_NO_UPDATE_CHECK=1`.
50
50
  ## Connect an AWS account
51
51
 
52
52
  You need to be an owner of your organization on multicloud.io, an AWS login that can create IAM roles, and
53
- OpenTofu or Terraform 1.5 or later.
53
+ OpenTofu or Terraform 1.10 or later.
54
54
 
55
55
  ```bash
56
56
  mctl auth login # opens your browser; sign in as you do on multicloud.io
@@ -84,6 +84,7 @@ mctl cloud-account verify 7 --wait
84
84
  | `mctl cloud-account list` / `show <id> [--json]` | The connections of your organization. |
85
85
  | `mctl overview` / `billing` | Setup checklist, alerts and pool counts; payment gate status. Read access or a member sign-in. |
86
86
  | `mctl extend create NAME` | Make an Extend pool. Owner sign-in only. |
87
+ | `mctl extend proxy-key create --pool POOL --kube-context CTX` | Make the `extend:proxy` key of the Extend proxy and write it to its Secret with kubectl. Never prints the key. Owner sign-in only. |
87
88
  | `mctl peering create\|list\|show\|revoke POOL ...` | Manage the peerings of an Extend pool. Owner sign-in only. |
88
89
  | `mctl ssh allow\|list\|revoke`, `mctl node list`, `mctl ssh NODE [-y] [-- ssh args]` | Operators (role `multicloud-admins`): open tcp/22 on a node for your own IPv4 address, list the nodes and the grants, connect. Organization owners: `mctl ssh NODE` logs in to a node of your pool with a 30-minute certificate. Details: `mctl ssh --help`. |
89
90
  | `mctl ssh support allow --pool POOL [--for 4h]`, `support list`, `support revoke ID` | Organization owner: let Multicloud support log in to one pool for up to 7 days, see the consents and the certificates issued, end a consent. A support certificate already issued stays valid up to 30 minutes after a revoke. |
@@ -155,7 +156,7 @@ mctl pool wake ci --wait --timeout 15m # exit 0 ready, 5 timeout, 6
155
156
  | Command | What it does |
156
157
  |---|---|
157
158
  | `mctl pool create <name>` | Make a pool. Use `--from-file pool.json` for the full request, or the flags `--github-org`, `--clouds`, `--classes`, `--max-cost-per-hour`, `--spot-policy`, `--cpu-units-requests`, `--image-by-class`, `--egress-by-class`, `--class-headroom`. A repeated run with the same `--idempotency-key` makes one pool. Put cloud keys in the file, not on the command line. |
158
- | `mctl pool update <pool>` | Change `--max-cost-per-hour`, `--max-servers`, `--classes`, `--spot-policy`, `--cpu-units-requests`, `--clouds` or settings: `--set NAME=VALUE` (repeat; VALUE is JSON, else text; the name lists `instance_types`, `excluded_instance_types`, `accelerator_names` and `excluded_accelerator_names` also take comma-separated names; `grant.cpu` for grant fields), `--reset NAME`, `--settings JSON\|@file`. Only the options you give change. `mctl pool show` prints the settings, or `default: X` where a setting is unset. |
159
+ | `mctl pool update <pool>` | Change `--max-cost-per-hour`, `--max-servers`, `--classes`, `--spot-policy`, `--cpu-units-requests`, `--clouds` or settings: `--set NAME=VALUE` (repeat; VALUE is JSON, else text; the name lists `instance_types`, `excluded_instance_types`, `accelerator_names`, `excluded_accelerator_names`, `accelerator_vendors` and `excluded_accelerator_vendors` also take comma-separated names; `grant.cpu` for grant fields), `--reset NAME`, `--settings JSON\|@file`. Only the options you give change. `mctl pool show` prints the settings, or `default: X` where a setting is unset. On an Extend pool with a `PENDING` or `READY` peering, a change of `accelerator_names` or `excluded_accelerator_names` fails with 409 `POOL_HAS_PEERINGS`: revoke the peering first, or create a second pool. |
159
160
  | `mctl pool show <pool>` / `cluster <pool>` | The pool, or its machines and their cost. |
160
161
  | `mctl pool hibernate <pool>` / `wake <pool>` | Pause or resume a pool. |
161
162
  | `mctl pool delete <pool> [-y]` | Delete a pool for good. It asks first; without a terminal, `-y` is required. To pause a pool, use `hibernate`. |
@@ -19,7 +19,7 @@ upgrades itself. Turn the check off with `MCTL_NO_UPDATE_CHECK=1`.
19
19
  ## Connect an AWS account
20
20
 
21
21
  You need to be an owner of your organization on multicloud.io, an AWS login that can create IAM roles, and
22
- OpenTofu or Terraform 1.5 or later.
22
+ OpenTofu or Terraform 1.10 or later.
23
23
 
24
24
  ```bash
25
25
  mctl auth login # opens your browser; sign in as you do on multicloud.io
@@ -53,6 +53,7 @@ mctl cloud-account verify 7 --wait
53
53
  | `mctl cloud-account list` / `show <id> [--json]` | The connections of your organization. |
54
54
  | `mctl overview` / `billing` | Setup checklist, alerts and pool counts; payment gate status. Read access or a member sign-in. |
55
55
  | `mctl extend create NAME` | Make an Extend pool. Owner sign-in only. |
56
+ | `mctl extend proxy-key create --pool POOL --kube-context CTX` | Make the `extend:proxy` key of the Extend proxy and write it to its Secret with kubectl. Never prints the key. Owner sign-in only. |
56
57
  | `mctl peering create\|list\|show\|revoke POOL ...` | Manage the peerings of an Extend pool. Owner sign-in only. |
57
58
  | `mctl ssh allow\|list\|revoke`, `mctl node list`, `mctl ssh NODE [-y] [-- ssh args]` | Operators (role `multicloud-admins`): open tcp/22 on a node for your own IPv4 address, list the nodes and the grants, connect. Organization owners: `mctl ssh NODE` logs in to a node of your pool with a 30-minute certificate. Details: `mctl ssh --help`. |
58
59
  | `mctl ssh support allow --pool POOL [--for 4h]`, `support list`, `support revoke ID` | Organization owner: let Multicloud support log in to one pool for up to 7 days, see the consents and the certificates issued, end a consent. A support certificate already issued stays valid up to 30 minutes after a revoke. |
@@ -124,7 +125,7 @@ mctl pool wake ci --wait --timeout 15m # exit 0 ready, 5 timeout, 6
124
125
  | Command | What it does |
125
126
  |---|---|
126
127
  | `mctl pool create <name>` | Make a pool. Use `--from-file pool.json` for the full request, or the flags `--github-org`, `--clouds`, `--classes`, `--max-cost-per-hour`, `--spot-policy`, `--cpu-units-requests`, `--image-by-class`, `--egress-by-class`, `--class-headroom`. A repeated run with the same `--idempotency-key` makes one pool. Put cloud keys in the file, not on the command line. |
127
- | `mctl pool update <pool>` | Change `--max-cost-per-hour`, `--max-servers`, `--classes`, `--spot-policy`, `--cpu-units-requests`, `--clouds` or settings: `--set NAME=VALUE` (repeat; VALUE is JSON, else text; the name lists `instance_types`, `excluded_instance_types`, `accelerator_names` and `excluded_accelerator_names` also take comma-separated names; `grant.cpu` for grant fields), `--reset NAME`, `--settings JSON\|@file`. Only the options you give change. `mctl pool show` prints the settings, or `default: X` where a setting is unset. |
128
+ | `mctl pool update <pool>` | Change `--max-cost-per-hour`, `--max-servers`, `--classes`, `--spot-policy`, `--cpu-units-requests`, `--clouds` or settings: `--set NAME=VALUE` (repeat; VALUE is JSON, else text; the name lists `instance_types`, `excluded_instance_types`, `accelerator_names`, `excluded_accelerator_names`, `accelerator_vendors` and `excluded_accelerator_vendors` also take comma-separated names; `grant.cpu` for grant fields), `--reset NAME`, `--settings JSON\|@file`. Only the options you give change. `mctl pool show` prints the settings, or `default: X` where a setting is unset. On an Extend pool with a `PENDING` or `READY` peering, a change of `accelerator_names` or `excluded_accelerator_names` fails with 409 `POOL_HAS_PEERINGS`: revoke the peering first, or create a second pool. |
128
129
  | `mctl pool show <pool>` / `cluster <pool>` | The pool, or its machines and their cost. |
129
130
  | `mctl pool hibernate <pool>` / `wake <pool>` | Pause or resume a pool. |
130
131
  | `mctl pool delete <pool> [-y]` | Delete a pool for good. It asks first; without a terminal, `-y` is required. To pause a pool, use `hibernate`. |
@@ -0,0 +1 @@
1
+ __version__ = "0.12.0"
@@ -13,7 +13,7 @@ from urllib.parse import quote
13
13
 
14
14
  import click
15
15
 
16
- from . import api, exitcodes
16
+ from . import api, exitcodes, kube
17
17
  from .cloud_account import quota_lines
18
18
  from .orgopt import org_group, org_option
19
19
  from .output import (collect as _collect, dump as _dump, echo as _echo, json_option, load_body, no_headers_option, quiet_option,
@@ -140,14 +140,17 @@ def _peering_readable(p: Dict[str, Any]) -> str:
140
140
  @peering.command(name="create")
141
141
  @click.argument("pool", metavar="POOL")
142
142
  @_grant_options
143
+ @click.option("--consumer-cluster-id", "consumer_cluster_id", default=None, metavar="ID",
144
+ help="Reuse the consumer id (c-xxxxxxxx) of an existing peering: adds this pool to the same "
145
+ "consumer cluster. The result carries a helm upgrade command.")
143
146
  @click.option("--from-file", "from_file", type=click.Path(dir_okay=False, allow_dash=True), default=None,
144
147
  help="JSON file with the request body (- for standard input); flags override its fields")
145
148
  @json_option
146
149
  @click.pass_context
147
- def create_peering(ctx, pool, from_file, as_json, **grant):
150
+ def create_peering(ctx, pool, from_file, as_json, consumer_cluster_id, **grant):
148
151
  """Create a peering for an Extend pool (name). Optional options ask for a resource grant."""
149
152
  body = load_body(from_file)
150
- body.update(_collect(**grant))
153
+ body.update(_collect(consumer_cluster_id=consumer_cluster_id, **grant))
151
154
 
152
155
  def go(org):
153
156
  try:
@@ -202,6 +205,124 @@ def show(ctx, pool, peering_id, as_json):
202
205
  click.echo(_peering_readable(data))
203
206
 
204
207
 
208
+ PROXY_NAMESPACE = "multicloud-extend-proxy"
209
+ PROXY_SECRET = "extend-proxy-api-key"
210
+ KEY_ID_ANNOTATION = "multicloud.io/api-key-id"
211
+ KEY_PREFIX_ANNOTATION = "multicloud.io/api-key-prefix"
212
+
213
+
214
+ @extend.group(name="proxy-key", cls=org_group("extend_org"))
215
+ def proxy_key():
216
+ """The API key of the Extend proxy (section 3.9 of the Extend guide)."""
217
+
218
+
219
+ def _sso_call(org, method: str, path: str, **kw) -> Dict[str, Any]:
220
+ # The key routes refuse every API key: use the SSO sign-in even when MULTICLOUD_API_KEY is set.
221
+ try:
222
+ return api.call(method, org, path, prefer_sso=True, **kw)
223
+ except api.ApiError as ex:
224
+ raise _fail(ex)
225
+
226
+
227
+ def _drop_key(org, key_id: str) -> Optional[str]:
228
+ """Revoke, then delete, a key this command made. Returns an error text, or None when both worked."""
229
+ try:
230
+ api.call("POST", org, f"/keys/{quote(key_id, safe='')}/revoke", prefer_sso=True)
231
+ except api.ApiError as ex:
232
+ return f"could not revoke it ({ex})"
233
+ try:
234
+ api.call("DELETE", org, f"/keys/{quote(key_id, safe='')}", accept=(204,), prefer_sso=True)
235
+ except api.ApiError as ex:
236
+ return f"revoked it, could not delete it ({ex})"
237
+ return None
238
+
239
+
240
+ @proxy_key.command(name="create")
241
+ @click.option("--pool", required=True, metavar="POOL", help="The Extend pool name. It names the key only: the key "
242
+ "works for every Extend pool of the organization")
243
+ @click.option("--kube-context", "kube_context", required=True, metavar="CONTEXT",
244
+ help="The kubectl context of the cluster that runs the proxy")
245
+ @click.option("--namespace", default=PROXY_NAMESPACE, show_default=True, help="Namespace of the proxy; it must exist")
246
+ @click.option("--secret", "secret_name", default=PROXY_SECRET, show_default=True, help="Name of the Secret")
247
+ @click.option("--replace", is_flag=True, help="Overwrite an existing Secret with a new key. The old key stays valid "
248
+ "until you revoke it")
249
+ @json_option
250
+ @click.pass_context
251
+ def create_proxy_key(ctx, pool, kube_context, namespace, secret_name, replace, as_json):
252
+ """Create an extend:proxy API key and write it to the proxy Secret (data key "key").
253
+
254
+ The key goes from the API to kubectl standard input only. mctl never prints it, and it is never in a
255
+ command line. Needs kubectl on PATH and an SSO sign-in as an organization owner (mctl auth login).
256
+ """
257
+ def go(org):
258
+ # Every check before the key exists: the rollback below is the rare path.
259
+ kube.require_namespace(kube_context, namespace)
260
+ old_id = kube.secret_annotation(kube_context, namespace, secret_name, KEY_ID_ANNOTATION)
261
+ if old_id is not None and not replace:
262
+ raise ExtendError(f"Secret {namespace}/{secret_name} exists in context {kube_context}. "
263
+ "Nothing was created. To write a new key, run again with --replace.")
264
+ old_prefix = (kube.secret_annotation(kube_context, namespace, secret_name, KEY_PREFIX_ANNOTATION)
265
+ if old_id is not None else None)
266
+ _sso_call(org, "GET", _pool_path(pool)) # the pool exists and you are its owner
267
+ try:
268
+ made = api.call("POST", org, "/keys", prefer_sso=True, body={
269
+ "name": f"extend-proxy-{pool}"[:256],
270
+ "description": f"Extend proxy, Secret {namespace}/{secret_name}, kubectl context {kube_context}"[:1000],
271
+ "scopes": ["extend:proxy"]})
272
+ except api.ApiError as ex:
273
+ if ex.status is None or ex.status >= 500:
274
+ raise _fail(ex, f"{ex} A key named extend-proxy-{pool} may exist without a Secret. "
275
+ "Check the console (Account, API keys) and revoke it.")
276
+ raise _fail(ex)
277
+ raw, key_id = made.pop("key", None), made.get("id")
278
+ if not raw or not key_id:
279
+ raise ExtendError("The API answer holds no key. Nothing was written.")
280
+ try:
281
+ kube.write_secret(
282
+ kube_context, namespace, secret_name, {"key": raw}, replace=old_id is not None,
283
+ labels={"app.kubernetes.io/name": "extend-proxy", "app.kubernetes.io/managed-by": "mctl"},
284
+ annotations={KEY_ID_ANNOTATION: key_id, KEY_PREFIX_ANNOTATION: str(made.get("key_prefix") or "")})
285
+ except kube.KubeTimeout as ex:
286
+ # The write may have landed: read the Secret back before a rollback could revoke the key it holds.
287
+ try:
288
+ landed = kube.secret_annotation(kube_context, namespace, secret_name, KEY_ID_ANNOTATION) == key_id
289
+ except kube.KubeError:
290
+ raise ExtendError(f"{ex} The Secret may hold the new key {made.get('key_prefix')} (id {key_id}). "
291
+ f"Check the annotation {KEY_ID_ANNOTATION} of Secret {namespace}/{secret_name}; "
292
+ "if it shows another id, revoke the new key in the console: Account, API keys.")
293
+ if not landed:
294
+ problem = _drop_key(org, key_id)
295
+ raise ExtendError(f"{ex} The Secret is unchanged. The new key {made.get('key_prefix')} "
296
+ + ("was revoked and deleted." if problem is None else
297
+ f"(id {key_id}): {problem}. Revoke it in the console: Account, API keys."))
298
+ except BaseException as ex: # also Ctrl-C: a key that reached no Secret must not stay valid
299
+ interrupted = isinstance(ex, KeyboardInterrupt)
300
+ first = "Interrupted." if interrupted else str(ex)
301
+ code = exitcodes.INTERRUPTED if interrupted else exitcodes.ERROR
302
+ problem = _drop_key(org, key_id)
303
+ if problem is None:
304
+ state = "" if interrupted else " The Secret is unchanged."
305
+ raise ExtendError(f"{first}{state} The new key {made.get('key_prefix')} was revoked and deleted.",
306
+ code)
307
+ raise ExtendError(f"{first} The new key {made.get('key_prefix')} (id {key_id}): {problem}. "
308
+ "Revoke it in the console: Account, API keys.", code)
309
+ return {"id": key_id, "key_prefix": made.get("key_prefix"), "name": made.get("name"),
310
+ "scopes": made.get("scopes"), "kube_context": kube_context, "namespace": namespace,
311
+ "secret": secret_name, "replaced": old_id is not None, "replaced_key_id": old_id or None,
312
+ "replaced_key_prefix": old_prefix or None}
313
+ out = run(ctx.obj.get("extend_org"), go, (ExtendError, api.ApiError, kube.KubeError))
314
+ if as_json:
315
+ return _dump(out)
316
+ click.echo(f"Key {out['key_prefix']} ({out['name']}) written to Secret {namespace}/{secret_name} "
317
+ f"in context {kube_context}.")
318
+ click.echo("The key works for every Extend pool of the organization.")
319
+ if out["replaced"]:
320
+ old = " ".join(p for p in (out["replaced_key_prefix"], out["replaced_key_id"] and f"(id {out['replaced_key_id']})")
321
+ if p)
322
+ click.echo(f"Next: kubectl --context {kube_context} -n {namespace} rollout restart deployment")
323
+ click.echo(f"Then revoke the old key{' ' + old if old else ''} in the console: Account, API keys.")
324
+
325
+
205
326
  @peering.command(name="revoke")
206
327
  @click.argument("pool", metavar="POOL")
207
328
  @click.argument("peering_id", metavar="ID", type=click.IntRange(min=1))
@@ -0,0 +1,89 @@
1
+ """Small kubectl helpers: write a secret value to a Kubernetes Secret without putting it on a command line.
2
+
3
+ ``mctl`` runs the ``kubectl`` that is on PATH, with the ``--context`` the user names. A secret value goes to
4
+ ``kubectl`` only on standard input, never in argv (``ps`` shows argv to every local user) and never in an
5
+ ``-o yaml``/``-o json`` read. The Secret is written with ``create`` or ``replace``, not ``apply``: ``apply`` copies
6
+ the whole object, the value included, into the ``last-applied-configuration`` annotation.
7
+ """
8
+ import json
9
+ import shutil
10
+ import subprocess
11
+ from typing import Dict, List, Optional
12
+
13
+ from . import exitcodes
14
+
15
+ TIMEOUT_S = 60
16
+
17
+
18
+ class KubeError(exitcodes.CliError):
19
+ pass
20
+
21
+
22
+ class KubeTimeout(KubeError):
23
+ """kubectl did not answer: the change may or may not have reached the cluster."""
24
+
25
+
26
+ def _redact(text: str, secrets: List[str]) -> str:
27
+ for s in secrets:
28
+ if s:
29
+ text = text.replace(s, "<redacted>")
30
+ return text.strip()
31
+
32
+
33
+ def kubectl(context: str, args: List[str], stdin: Optional[str] = None,
34
+ secrets: List[str] = ()) -> subprocess.CompletedProcess:
35
+ """Run ``kubectl --context CONTEXT ARGS``. ``stdin`` is the only way a secret value reaches kubectl."""
36
+ tool = shutil.which("kubectl")
37
+ if not tool:
38
+ raise KubeError("kubectl is not on PATH. Install it, or run this command where kubectl reaches your cluster.")
39
+ argv = [tool, "--context", context, *args]
40
+ try:
41
+ return subprocess.run(argv, input=stdin, capture_output=True, text=True, timeout=TIMEOUT_S)
42
+ except subprocess.TimeoutExpired:
43
+ raise KubeTimeout(f"kubectl did not answer in {TIMEOUT_S} s (context {context}).")
44
+ except OSError as ex:
45
+ raise KubeError(f"Could not run kubectl: {_redact(str(ex), list(secrets))}")
46
+
47
+
48
+ def _fail(done: subprocess.CompletedProcess, what: str, secrets: List[str] = ()) -> KubeError:
49
+ text = _redact(done.stderr or done.stdout or f"exit code {done.returncode}", list(secrets))
50
+ return KubeError(f"{what}: {text}")
51
+
52
+
53
+ def require_namespace(context: str, namespace: str) -> None:
54
+ """Fail unless the context answers and the namespace exists."""
55
+ done = kubectl(context, ["get", "namespace", namespace, "-o", "name"])
56
+ if done.returncode == 0:
57
+ return
58
+ if "NotFound" in (done.stderr or ""):
59
+ raise KubeError(f"Namespace {namespace} does not exist in context {context}.")
60
+ raise _fail(done, f"Could not read namespace {namespace} in context {context}")
61
+
62
+
63
+ def secret_annotation(context: str, namespace: str, name: str, annotation: str) -> Optional[str]:
64
+ """None when the Secret does not exist; else the value of one annotation ("" when it has none).
65
+ Reads only the name and the annotation, never the data."""
66
+ path = annotation.replace(".", "\\.")
67
+ done = kubectl(context, ["-n", namespace, "get", "secret", name, "--ignore-not-found",
68
+ "-o", "jsonpath={.metadata.name}{\"\\t\"}{.metadata.annotations." + path + "}"])
69
+ if done.returncode != 0:
70
+ raise _fail(done, f"Could not read Secret {namespace}/{name}")
71
+ if not done.stdout.strip():
72
+ return None
73
+ return done.stdout.split("\t", 1)[1].strip() if "\t" in done.stdout else ""
74
+
75
+
76
+ def write_secret(context: str, namespace: str, name: str, data: Dict[str, str], *,
77
+ replace: bool = False, labels: Optional[Dict[str, str]] = None,
78
+ annotations: Optional[Dict[str, str]] = None) -> None:
79
+ """Create the Secret, or with ``replace`` overwrite it. Without ``replace`` an existing Secret makes it fail:
80
+ ``kubectl create`` refuses atomically, so nothing written between a check and this call is lost."""
81
+ manifest = {"apiVersion": "v1", "kind": "Secret", "type": "Opaque",
82
+ "metadata": {"name": name, "namespace": namespace, "labels": labels or {},
83
+ "annotations": annotations or {}},
84
+ "stringData": data}
85
+ secrets = list(data.values())
86
+ verb = "replace" if replace else "create"
87
+ done = kubectl(context, ["-n", namespace, verb, "-f", "-"], stdin=json.dumps(manifest), secrets=secrets)
88
+ if done.returncode != 0:
89
+ raise _fail(done, f"Could not write Secret {namespace}/{name}", secrets)
@@ -315,7 +315,8 @@ def _put(settings: Dict[str, Any], name: str, value: Any) -> None:
315
315
 
316
316
 
317
317
  _LIST_SETTINGS = ("instance_types", "excluded_instance_types", "accelerator_names",
318
- "excluded_accelerator_names", "regions")
318
+ "excluded_accelerator_names", "accelerator_vendors", "excluded_accelerator_vendors",
319
+ "regions")
319
320
 
320
321
 
321
322
  def _settings_body(sets, resets, settings_json) -> Dict[str, Any]:
@@ -253,6 +253,15 @@ def test_peering_create_with_gpu(monkeypatch):
253
253
  assert calls[0][2]["json"] == {"gpu": 1}
254
254
 
255
255
 
256
+ def test_peering_create_consumer_cluster_id_goes_verbatim_and_absent_is_omitted(monkeypatch):
257
+ r, calls = run(["peering", "create", "edge", "--consumer-cluster-id", "c-0a1b2c3d"],
258
+ [reply(202, PEERING)], monkeypatch)
259
+ assert r.exit_code == 0, r.output
260
+ assert calls[0][2]["json"] == {"consumer_cluster_id": "c-0a1b2c3d"}
261
+ r, calls = run(["peering", "create", "edge", "--pods", "5"], [reply(202, PEERING)], monkeypatch)
262
+ assert "consumer_cluster_id" not in calls[0][2]["json"]
263
+
264
+
256
265
  def test_peering_create_no_grant_sends_empty_body_and_file(monkeypatch, tmp_path):
257
266
  r, calls = run(["peering", "create", "edge"], [reply(202, PEERING)], monkeypatch)
258
267
  assert calls[0][2]["json"] == {}
@@ -473,11 +473,15 @@ def test_org_at_both_positions_prefers_the_subcommand(monkeypatch):
473
473
  def test_set_name_lists_split_on_commas(monkeypatch):
474
474
  r, calls, _ = run(["update", "7", "--set", "instance_types=m5.large, c5.large,,",
475
475
  "--set", 'excluded_instance_types=["x.large"]', "--set", "accelerator_names=A100",
476
+ "--set", "accelerator_vendors=NVIDIA", "--set", "excluded_accelerator_vendors=AMD,AWS",
476
477
  "--set", "affinity=a,b"], [reply(200, pool_view())], monkeypatch)
477
478
  assert r.exit_code == 0, r.output
478
479
  assert calls[0][2]["json"] == {"settings": {"instance_types": ["m5.large", "c5.large"],
479
480
  "excluded_instance_types": ["x.large"],
480
- "accelerator_names": ["A100"], "affinity": "a,b"}}
481
+ "accelerator_names": ["A100"],
482
+ "accelerator_vendors": ["NVIDIA"],
483
+ "excluded_accelerator_vendors": ["AMD", "AWS"],
484
+ "affinity": "a,b"}}
481
485
 
482
486
 
483
487
  def test_max_servers_outside_1_to_100_is_a_usage_error(monkeypatch):
@@ -0,0 +1,228 @@
1
+ """mctl extend proxy-key create: the key goes from the API to kubectl stdin only, never to argv or output."""
2
+ import json
3
+ import subprocess
4
+
5
+ import pytest
6
+ import requests
7
+ from click.testing import CliRunner
8
+
9
+ from multicloud_cli import auth, kube, sso
10
+ from multicloud_cli.main import mctl
11
+ from tests.helpers import ISSUER, access, reply
12
+
13
+ BASE = "https://api.multicloud.io/api/v1/orgs/acme"
14
+ RAW = "fake-proxy-key-value-0000"
15
+ MADE = {"id": "k-1", "key": RAW, "key_prefix": "mca_new-1", "name": "extend-proxy-edge",
16
+ "scopes": ["extend:proxy"], "created_at": "2026-11-17"}
17
+ ARGS = ["extend", "proxy-key", "create", "--org", "acme", "--pool", "edge", "--kube-context", "prod"]
18
+
19
+
20
+ def runner():
21
+ try:
22
+ return CliRunner(mix_stderr=False)
23
+ except TypeError:
24
+ return CliRunner()
25
+
26
+
27
+ class Kube:
28
+ """Fake kubectl: records argv and stdin; ``secret`` is the existing Secret's key-id annotation (None: absent)."""
29
+
30
+ def __init__(self, secret=None, namespace=True, write_rc=0):
31
+ self.secret, self.namespace, self.write_rc, self.calls = secret, namespace, write_rc, []
32
+
33
+ def __call__(self, argv, input=None, **kw):
34
+ self.calls.append((argv, input))
35
+ args = argv[3:]
36
+ assert argv[1:3] == ["--context", "prod"]
37
+ if args[:2] == ["get", "namespace"]:
38
+ ok = self.namespace
39
+ return subprocess.CompletedProcess(argv, 0 if ok else 1, "namespace/x" if ok else "",
40
+ "" if ok else 'Error from server (NotFound): namespaces "x" not found')
41
+ if "secret" in args and "get" in args:
42
+ ann = self.secret if "api-key-id" in args[-1] else ("mca_old-1" if self.secret else "")
43
+ out = "" if self.secret is None else f"extend-proxy-api-key\t{ann}"
44
+ return subprocess.CompletedProcess(argv, 0, out, "")
45
+ if args[2] in ("create", "replace"):
46
+ err = "" if self.write_rc == 0 else f"error: forbidden, value {RAW}"
47
+ return subprocess.CompletedProcess(argv, self.write_rc, "secret/extend-proxy-api-key created", err)
48
+ raise AssertionError(args)
49
+
50
+ def writes(self):
51
+ return [(a, i) for a, i in self.calls if any(v in a for v in ("create", "replace"))]
52
+
53
+
54
+ @pytest.fixture
55
+ def env(monkeypatch):
56
+ tok = access(orgs=("acme",))
57
+ auth.store_sso(ISSUER, sso.Tokens(access=tok, refresh="fake-refresh"))
58
+ # An API key in the environment must not win: the key routes refuse every API key.
59
+ monkeypatch.setenv("MULTICLOUD_API_KEY", "fake-env-key")
60
+ state = {"answers": {}, "calls": [], "kube": Kube(), "token": tok}
61
+
62
+ def fake(method, url, **kw):
63
+ state["calls"].append((method, url, kw))
64
+ for (m, suffix), r in state["answers"].items():
65
+ if m == method and url == BASE + suffix:
66
+ return r
67
+ raise AssertionError(f"unexpected {method} {url}")
68
+ monkeypatch.setattr(requests, "request", fake)
69
+ monkeypatch.setattr(kube.shutil, "which", lambda name: "/usr/bin/kubectl")
70
+ monkeypatch.setattr(kube.subprocess, "run", lambda *a, **kw: state["kube"](*a, **kw))
71
+ state["answers"] = {("GET", "/pools/edge/peerings"): reply(200, {"peerings": []}),
72
+ ("POST", "/keys"): reply(201, MADE),
73
+ ("POST", "/keys/k-1/revoke"): reply(200, {"id": "k-1", "state": "revoked"}),
74
+ ("DELETE", "/keys/k-1"): reply(204)}
75
+ return state
76
+
77
+
78
+ def no_leak(r, env):
79
+ assert RAW not in r.stdout and RAW not in (r.stderr or "")
80
+ for argv, _ in env["kube"].calls:
81
+ assert all(RAW not in a for a in argv)
82
+
83
+
84
+ def test_creates_key_and_secret_without_printing_it(env):
85
+ r = runner().invoke(mctl, ARGS)
86
+ assert r.exit_code == 0, r.output + (r.stderr or "")
87
+ post = [c for c in env["calls"] if c[0] == "POST"][0]
88
+ assert post[2]["json"] == {"name": "extend-proxy-edge", "scopes": ["extend:proxy"],
89
+ "description": "Extend proxy, Secret multicloud-extend-proxy/extend-proxy-api-key, "
90
+ "kubectl context prod"}
91
+ assert post[2]["headers"]["Authorization"] == f"Bearer {env['token']}"
92
+ assert "X-API-Key" not in post[2]["headers"]
93
+ [(argv, stdin)] = env["kube"].writes()
94
+ assert argv[3:] == ["-n", "multicloud-extend-proxy", "create", "-f", "-"]
95
+ secret = json.loads(stdin)
96
+ assert secret["stringData"] == {"key": RAW}
97
+ assert secret["metadata"]["name"] == "extend-proxy-api-key"
98
+ assert secret["metadata"]["annotations"]["multicloud.io/api-key-id"] == "k-1"
99
+ assert "every Extend pool" in r.stdout and "mca_new-1" in r.stdout
100
+ no_leak(r, env)
101
+
102
+
103
+ def test_json_output_holds_no_key(env):
104
+ r = runner().invoke(mctl, ARGS + ["--json"])
105
+ assert r.exit_code == 0
106
+ out = json.loads(r.stdout)
107
+ assert "key" not in out and out["id"] == "k-1" and out["replaced_key_id"] is None
108
+ no_leak(r, env)
109
+
110
+
111
+ def test_existing_secret_refuses_before_minting(env):
112
+ env["kube"].secret = "k-0"
113
+ r = runner().invoke(mctl, ARGS)
114
+ assert r.exit_code == 1 and "--replace" in r.stderr
115
+ assert not [c for c in env["calls"] if c[0] == "POST"]
116
+ assert not env["kube"].writes()
117
+
118
+
119
+ def test_replace_overwrites_and_names_the_old_key(env):
120
+ env["kube"].secret = "k-0"
121
+ r = runner().invoke(mctl, ARGS + ["--replace"])
122
+ assert r.exit_code == 0, r.stderr
123
+ [(argv, _)] = env["kube"].writes()
124
+ assert "replace" in argv and "create" not in argv
125
+ assert "rollout restart" in r.stdout and "mca_old-1 (id k-0)" in r.stdout
126
+ assert not [c for c in env["calls"] if c[1].endswith("/revoke")] # the old key stays until the restart
127
+ no_leak(r, env)
128
+
129
+
130
+ def test_replace_without_secret_creates(env):
131
+ r = runner().invoke(mctl, ARGS + ["--replace"])
132
+ assert r.exit_code == 0
133
+ [(argv, _)] = env["kube"].writes()
134
+ assert "create" in argv
135
+ assert "rollout restart" not in r.stdout
136
+
137
+
138
+ def test_failed_write_revokes_and_deletes_the_new_key(env):
139
+ env["kube"].write_rc = 1
140
+ r = runner().invoke(mctl, ARGS)
141
+ assert r.exit_code == 1
142
+ assert [(c[0], c[1]) for c in env["calls"]][-2:] == [("POST", BASE + "/keys/k-1/revoke"),
143
+ ("DELETE", BASE + "/keys/k-1")]
144
+ assert "revoked and deleted" in r.stderr and "<redacted>" in r.stderr
145
+ no_leak(r, env)
146
+
147
+
148
+ def test_failed_rollback_says_what_to_revoke(env):
149
+ env["kube"].write_rc = 1
150
+ env["answers"][("POST", "/keys/k-1/revoke")] = reply(500, {"detail": "down"})
151
+ r = runner().invoke(mctl, ARGS)
152
+ assert r.exit_code == 1 and "k-1" in r.stderr and "console" in r.stderr
153
+ no_leak(r, env)
154
+
155
+
156
+ def test_missing_namespace_mints_nothing(env):
157
+ env["kube"].namespace = False
158
+ r = runner().invoke(mctl, ARGS)
159
+ assert r.exit_code == 1 and "does not exist" in r.stderr
160
+ assert not env["calls"]
161
+
162
+
163
+ def test_no_kubectl_mints_nothing(env, monkeypatch):
164
+ monkeypatch.setattr(kube.shutil, "which", lambda name: None)
165
+ r = runner().invoke(mctl, ARGS)
166
+ assert r.exit_code == 1 and "kubectl is not on PATH" in r.stderr
167
+ assert not env["calls"]
168
+
169
+
170
+ def test_unknown_pool_mints_nothing(env):
171
+ env["answers"][("GET", "/pools/edge/peerings")] = reply(404, {"detail": "No such pool"})
172
+ r = runner().invoke(mctl, ARGS)
173
+ assert r.exit_code == 4
174
+ assert not [c for c in env["calls"] if c[0] == "POST"]
175
+
176
+
177
+ def test_api_key_only_gets_a_sign_in_hint(env, monkeypatch):
178
+ auth.delete_sso(ISSUER)
179
+ r = runner().invoke(mctl, ARGS)
180
+ assert r.exit_code == 3 and "mctl auth login" in r.stderr
181
+ assert not env["calls"]
182
+
183
+
184
+ def test_org_option_on_the_group_works_too(env):
185
+ r = runner().invoke(mctl, ["extend", "--org", "acme", "proxy-key", "create", "--pool", "edge",
186
+ "--kube-context", "prod"])
187
+ assert r.exit_code == 0, r.stderr
188
+
189
+
190
+ def test_replace_of_a_secret_without_annotation_still_says_restart(env):
191
+ env["kube"].secret = ""
192
+ r = runner().invoke(mctl, ARGS + ["--replace"])
193
+ assert r.exit_code == 0, r.stderr
194
+ assert "rollout restart" in r.stdout and "revoke the old key in the console" in r.stdout
195
+
196
+
197
+ def test_no_api_answer_on_mint_says_a_key_may_exist(env):
198
+ env["answers"][("POST", "/keys")] = reply(503, {"detail": "busy"})
199
+ r = runner().invoke(mctl, ARGS)
200
+ assert r.exit_code == 1 and "may exist without a Secret" in r.stderr
201
+ assert not env["kube"].writes()
202
+
203
+
204
+ def test_ctrl_c_during_write_revokes_and_exits_130(env, monkeypatch):
205
+ def interrupt(*a, **kw):
206
+ raise KeyboardInterrupt
207
+ monkeypatch.setattr(kube, "write_secret", interrupt)
208
+ r = runner().invoke(mctl, ARGS)
209
+ assert r.exit_code == 130 and r.stderr.startswith("Error: Interrupted. The new key")
210
+ assert ("POST", BASE + "/keys/k-1/revoke") in [(c[0], c[1]) for c in env["calls"]]
211
+
212
+
213
+ def test_timeout_after_the_write_landed_keeps_the_key(env, monkeypatch):
214
+ def slow(*a, **kw):
215
+ env["kube"].secret = "k-1" # the write reached the cluster before kubectl gave up
216
+ raise kube.KubeTimeout("kubectl did not answer in 60 s (context prod).")
217
+ monkeypatch.setattr(kube, "write_secret", slow)
218
+ r = runner().invoke(mctl, ARGS)
219
+ assert r.exit_code == 0, r.stderr
220
+ assert not [c for c in env["calls"] if c[1].endswith("/revoke")]
221
+
222
+
223
+ def test_timeout_without_the_write_rolls_back(env, monkeypatch):
224
+ def slow(*a, **kw):
225
+ raise kube.KubeTimeout("kubectl did not answer in 60 s (context prod).")
226
+ monkeypatch.setattr(kube, "write_secret", slow)
227
+ r = runner().invoke(mctl, ARGS)
228
+ assert r.exit_code == 1 and "Secret is unchanged" in r.stderr and "revoked and deleted" in r.stderr
@@ -1 +0,0 @@
1
- __version__ = "0.10.1"
File without changes