multicloud-cli 0.11.0__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.
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/PKG-INFO +2 -1
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/README.md +1 -0
- multicloud_cli-0.12.0/multicloud_cli/__init__.py +1 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/multicloud_cli/extend.py +119 -1
- multicloud_cli-0.12.0/multicloud_cli/kube.py +89 -0
- multicloud_cli-0.12.0/tests/test_proxy_key.py +228 -0
- multicloud_cli-0.11.0/multicloud_cli/__init__.py +0 -1
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/.gitignore +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/LICENSE +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/multicloud_cli/account.py +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/multicloud_cli/api.py +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/multicloud_cli/auth.py +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/multicloud_cli/catalog.py +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/multicloud_cli/cloud_account.py +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/multicloud_cli/config.py +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/multicloud_cli/duration.py +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/multicloud_cli/exitcodes.py +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/multicloud_cli/main.py +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/multicloud_cli/net.py +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/multicloud_cli/node.py +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/multicloud_cli/orgopt.py +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/multicloud_cli/output.py +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/multicloud_cli/pool.py +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/multicloud_cli/ssh.py +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/multicloud_cli/ssh_cert.py +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/multicloud_cli/sso.py +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/multicloud_cli/version_check.py +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/pyproject.toml +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/tests/__init__.py +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/tests/conftest.py +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/tests/helpers.py +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/tests/test_account_extend.py +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/tests/test_apply.py +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/tests/test_auth.py +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/tests/test_catalog.py +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/tests/test_cloud_account.py +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/tests/test_conventions.py +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/tests/test_net.py +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/tests/test_pool.py +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/tests/test_ssh.py +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/tests/test_ssh_cert.py +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/tests/test_sso.py +0 -0
- {multicloud_cli-0.11.0 → multicloud_cli-0.12.0}/tests/test_sso_session.py +0 -0
- {multicloud_cli-0.11.0 → 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.
|
|
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>
|
|
@@ -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. |
|
|
@@ -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. |
|
|
@@ -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,
|
|
@@ -205,6 +205,124 @@ def show(ctx, pool, peering_id, as_json):
|
|
|
205
205
|
click.echo(_peering_readable(data))
|
|
206
206
|
|
|
207
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
|
+
|
|
208
326
|
@peering.command(name="revoke")
|
|
209
327
|
@click.argument("pool", metavar="POOL")
|
|
210
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)
|
|
@@ -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.11.0"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|