multicloud-cli 0.12.0__tar.gz → 0.13.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.12.0 → multicloud_cli-0.13.0}/PKG-INFO +2 -1
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/README.md +1 -0
- multicloud_cli-0.13.0/multicloud_cli/__init__.py +1 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/multicloud_cli/api.py +16 -8
- multicloud_cli-0.13.0/multicloud_cli/db_access.py +162 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/multicloud_cli/main.py +2 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/multicloud_cli/net.py +17 -6
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/multicloud_cli/pool.py +73 -0
- multicloud_cli-0.13.0/tests/test_db_access.py +285 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/tests/test_pool.py +94 -0
- multicloud_cli-0.12.0/multicloud_cli/__init__.py +0 -1
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/.gitignore +0 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/LICENSE +0 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/multicloud_cli/account.py +0 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/multicloud_cli/auth.py +0 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/multicloud_cli/catalog.py +0 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/multicloud_cli/cloud_account.py +0 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/multicloud_cli/config.py +0 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/multicloud_cli/duration.py +0 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/multicloud_cli/exitcodes.py +0 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/multicloud_cli/extend.py +0 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/multicloud_cli/kube.py +0 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/multicloud_cli/node.py +0 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/multicloud_cli/orgopt.py +0 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/multicloud_cli/output.py +0 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/multicloud_cli/ssh.py +0 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/multicloud_cli/ssh_cert.py +0 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/multicloud_cli/sso.py +0 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/multicloud_cli/version_check.py +0 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/pyproject.toml +0 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/tests/__init__.py +0 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/tests/conftest.py +0 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/tests/helpers.py +0 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/tests/test_account_extend.py +0 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/tests/test_apply.py +0 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/tests/test_auth.py +0 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/tests/test_catalog.py +0 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/tests/test_cloud_account.py +0 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/tests/test_conventions.py +0 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/tests/test_net.py +0 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/tests/test_proxy_key.py +0 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/tests/test_ssh.py +0 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/tests/test_ssh_cert.py +0 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/tests/test_sso.py +0 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.0}/tests/test_sso_session.py +0 -0
- {multicloud_cli-0.12.0 → multicloud_cli-0.13.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.13.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>
|
|
@@ -158,6 +158,7 @@ mctl pool wake ci --wait --timeout 15m # exit 0 ready, 5 timeout, 6
|
|
|
158
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. |
|
|
159
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. |
|
|
160
160
|
| `mctl pool show <pool>` / `cluster <pool>` | The pool, or its machines and their cost. |
|
|
161
|
+
| `mctl pool diagnose <pool>` | Why a pool or its Extend bridge does not work: the pool's lifecycle and readiness gates, and for each bridge replica what the pool sees of its WireGuard handshake, with a hint. Reads only; it never wakes a hibernated pool. `--json` prints the raw answer. |
|
|
161
162
|
| `mctl pool hibernate <pool>` / `wake <pool>` | Pause or resume a pool. |
|
|
162
163
|
| `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`. |
|
|
163
164
|
| `mctl pool rotate-credentials <pool>` / `rotation-status <pool>` | Renew the pool's access credentials; show the progress of the last renewal. |
|
|
@@ -127,6 +127,7 @@ mctl pool wake ci --wait --timeout 15m # exit 0 ready, 5 timeout, 6
|
|
|
127
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. |
|
|
128
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. |
|
|
129
129
|
| `mctl pool show <pool>` / `cluster <pool>` | The pool, or its machines and their cost. |
|
|
130
|
+
| `mctl pool diagnose <pool>` | Why a pool or its Extend bridge does not work: the pool's lifecycle and readiness gates, and for each bridge replica what the pool sees of its WireGuard handshake, with a hint. Reads only; it never wakes a hibernated pool. `--json` prints the raw answer. |
|
|
130
131
|
| `mctl pool hibernate <pool>` / `wake <pool>` | Pause or resume a pool. |
|
|
131
132
|
| `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`. |
|
|
132
133
|
| `mctl pool rotate-credentials <pool>` / `rotation-status <pool>` | Renew the pool's access credentials; show the progress of the last renewal. |
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.13.0"
|
|
@@ -21,7 +21,10 @@ CONSOLE_SCOPE_NAMES = {"org:read": "Pools: Read", "org:write": "Pools: Manage",
|
|
|
21
21
|
|
|
22
22
|
class ApiError(Exception):
|
|
23
23
|
"""The call failed. ``status`` is the HTTP status, or None when there was no answer.
|
|
24
|
-
``exit_code`` is the exit code of ``mctl`` for it (see ``exitcodes``).
|
|
24
|
+
``exit_code`` is the exit code of ``mctl`` for it (see ``exitcodes``). ``connect_failed`` is True when no
|
|
25
|
+
connection could be made at all (a ``requests.ConnectionError`` other than a TLS or proxy failure)."""
|
|
26
|
+
|
|
27
|
+
connect_failed = False
|
|
25
28
|
|
|
26
29
|
def __init__(self, message: str, status: Optional[int] = None, exit_code: Optional[int] = None):
|
|
27
30
|
super().__init__(message)
|
|
@@ -55,14 +58,19 @@ def _detail_text(data: Any) -> Optional[str]:
|
|
|
55
58
|
|
|
56
59
|
|
|
57
60
|
def _send(method: str, url: str, body: Optional[Dict[str, Any]], headers: Dict[str, str],
|
|
58
|
-
params: Optional[Dict[str, Any]] = None, ipv4_only: bool = False
|
|
61
|
+
params: Optional[Dict[str, Any]] = None, ipv4_only: bool = False,
|
|
62
|
+
ipv6_only: bool = False) -> requests.Response:
|
|
59
63
|
extra = {"params": params} if params else {} # a list value becomes one repeated key
|
|
60
64
|
try:
|
|
61
65
|
# No redirects: requests would carry the credential header to another host.
|
|
62
66
|
return net.request(method, url, json=body, timeout=TIMEOUT_S, allow_redirects=False, headers=headers,
|
|
63
|
-
ipv4_only=ipv4_only, **extra)
|
|
67
|
+
ipv4_only=ipv4_only, ipv6_only=ipv6_only, **extra)
|
|
64
68
|
except requests.RequestException as ex:
|
|
65
|
-
|
|
69
|
+
error = ApiError(f"Could not reach the API: {ex}")
|
|
70
|
+
# A TLS or proxy failure is a ConnectionError too, but not "no route over this family": keep it an error.
|
|
71
|
+
error.connect_failed = (isinstance(ex, requests.ConnectionError)
|
|
72
|
+
and not isinstance(ex, (requests.exceptions.SSLError, requests.exceptions.ProxyError)))
|
|
73
|
+
raise error
|
|
66
74
|
|
|
67
75
|
|
|
68
76
|
def _sso_org(slug: Optional[str], token: str, explicit: bool = True) -> str:
|
|
@@ -88,14 +96,14 @@ def call(method: str, org: Optional[str], path: str = "", *, body: Optional[Dict
|
|
|
88
96
|
headers: Optional[Dict[str, str]] = None, accept: Iterable[int] = (200, 201, 202),
|
|
89
97
|
scope: Optional[str] = None, pass_codes: Iterable[str] = (),
|
|
90
98
|
params: Optional[Dict[str, Any]] = None, org_scoped: bool = True,
|
|
91
|
-
ipv4_only: bool = False, prefer_sso: bool = False) -> Dict[str, Any]:
|
|
99
|
+
ipv4_only: bool = False, ipv6_only: bool = False, prefer_sso: bool = False) -> Dict[str, Any]:
|
|
92
100
|
"""One API call. Returns the JSON body with ``_status`` added; raises ``ApiError`` on other statuses.
|
|
93
101
|
|
|
94
102
|
``scope`` names the API key scope this call needs; a 401 or 403 then says that it may be missing.
|
|
95
103
|
A failed answer whose error code is in ``pass_codes`` is returned like a success.
|
|
96
104
|
``params`` are query parameters. ``org_scoped=False`` calls ``/api/v1{path}`` with no organization in the URL:
|
|
97
105
|
an SSO call then needs no organization, and ``MULTICLOUD_API_KEY`` needs none either (a stored key still
|
|
98
|
-
needs one to be found). ``ipv4_only``
|
|
106
|
+
needs one to be found). ``ipv4_only`` / ``ipv6_only`` connect over one address family only (the grant routes). ``prefer_sso`` keeps the
|
|
99
107
|
SSO token on a platform route even when the named org has a stored key or ``MULTICLOUD_API_KEY`` is set: the
|
|
100
108
|
operator routes check a realm role,
|
|
101
109
|
which an API key never holds."""
|
|
@@ -134,7 +142,7 @@ def call(method: str, org: Optional[str], path: str = "", *, body: Optional[Dict
|
|
|
134
142
|
except config.ConfigError as ex:
|
|
135
143
|
raise ApiError(str(ex))
|
|
136
144
|
url = f"{base}/api/v1/orgs/{quote(slug, safe='')}{path}" if org_scoped else f"{base}/api/v1{path}"
|
|
137
|
-
r = _send(method, url, body, {**credential, **(headers or {})}, params, ipv4_only)
|
|
145
|
+
r = _send(method, url, body, {**credential, **(headers or {})}, params, ipv4_only, ipv6_only)
|
|
138
146
|
if r.status_code == 401 and use_sso:
|
|
139
147
|
# The access token was refused (the session may have ended on the server): refresh once and retry once.
|
|
140
148
|
try:
|
|
@@ -142,7 +150,7 @@ def call(method: str, org: Optional[str], path: str = "", *, body: Optional[Dict
|
|
|
142
150
|
except auth.AuthError as ex:
|
|
143
151
|
raise ApiError(str(ex), 401)
|
|
144
152
|
r = _send(method, url, body, {"Authorization": f"Bearer {token}", **(headers or {})}, params,
|
|
145
|
-
ipv4_only)
|
|
153
|
+
ipv4_only, ipv6_only)
|
|
146
154
|
try:
|
|
147
155
|
data = r.json() if r.text else {}
|
|
148
156
|
except ValueError:
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"""``mctl db-access``: open the database allow-list (tcp/5432) for your own IP. For Multicloud platform admins.
|
|
2
|
+
|
|
3
|
+
These commands call ``/api/v1/db-access`` (not scoped to an organization). They need the SSO sign-in of an operator
|
|
4
|
+
(realm role ``multicloud-admins``); an API key never reaches them. The group is hidden: it is not in ``mctl --help``.
|
|
5
|
+
The API takes the address of the caller from the connection, and ``api.multicloud.io`` has A and AAAA records, so
|
|
6
|
+
``allow`` makes one call over IPv4 and one over IPv6 and opens both addresses. A host with no IPv6 route gets IPv4 only.
|
|
7
|
+
"""
|
|
8
|
+
from datetime import datetime, timezone
|
|
9
|
+
from typing import Any, Dict, List, Optional
|
|
10
|
+
|
|
11
|
+
import click
|
|
12
|
+
|
|
13
|
+
from . import api, exitcodes
|
|
14
|
+
from .duration import duration_option
|
|
15
|
+
from .output import dump as _dump, echo as _echo, json_option, no_headers_option, plain as _plain, quiet_option, run, table as _table
|
|
16
|
+
|
|
17
|
+
MIN_TTL_S, MAX_TTL_S = 300, 86400 # the API accepts 5 minutes to 24 hours
|
|
18
|
+
APPLY_NOTE = "The scheduler applies it within about a minute."
|
|
19
|
+
IPV6_WARNING = ("Warning: the /64 covers every device on this network. On a shared network (cafe, hotel) "
|
|
20
|
+
"use --ipv4-only.")
|
|
21
|
+
NO_IPV6_NOTE = "No IPv6 route to the API: IPv4 only."
|
|
22
|
+
NO_IPV4_NOTE = "No IPv4 route to the API: IPv6 only."
|
|
23
|
+
REVOKE_NOTE = ("The scheduler removes the rule after its removal grace (10 minutes), so access ends within "
|
|
24
|
+
"about 11 minutes.")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class DbAccessError(exitcodes.CliError):
|
|
28
|
+
connect_failed = False # no connection at all (no route to the API over this address family)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _call(method: str, path: str, **kw) -> Dict[str, Any]:
|
|
32
|
+
try:
|
|
33
|
+
return api.call(method, None, path, org_scoped=False, prefer_sso=True, **kw)
|
|
34
|
+
except api.ApiError as ex:
|
|
35
|
+
text = str(ex)
|
|
36
|
+
if ex.status == 403:
|
|
37
|
+
text += " (db-access needs the multicloud-admins role.)"
|
|
38
|
+
error = DbAccessError(text, ex.exit_code)
|
|
39
|
+
error.connect_failed = ex.connect_failed
|
|
40
|
+
raise error
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _run(fn):
|
|
44
|
+
return run(None, lambda org: fn(), (DbAccessError, api.ApiError))
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _when(iso: Any) -> Optional[datetime]:
|
|
48
|
+
try:
|
|
49
|
+
at = datetime.fromisoformat(str(iso).replace("Z", "+00:00"))
|
|
50
|
+
except ValueError:
|
|
51
|
+
return None
|
|
52
|
+
return at if at.tzinfo is not None else at.replace(tzinfo=timezone.utc)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _span(seconds: float) -> str:
|
|
56
|
+
minutes = int(abs(seconds) // 60)
|
|
57
|
+
hours, minutes = divmod(minutes, 60)
|
|
58
|
+
return f"{hours}h{minutes:02d}m" if hours else f"{minutes}m"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _expires_text(iso: Any) -> str:
|
|
62
|
+
"""``2026-11-18 21:30 CET (in 11h59m)`` in local time."""
|
|
63
|
+
at = _when(iso)
|
|
64
|
+
if at is None:
|
|
65
|
+
return str(iso)
|
|
66
|
+
left = (at - datetime.now(timezone.utc)).total_seconds()
|
|
67
|
+
relative = f"in {_span(left)}" if left > 0 else f"{_span(left)} ago"
|
|
68
|
+
return f"{at.astimezone().strftime('%Y-%m-%d %H:%M %Z')} ({relative})"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@click.group(hidden=True)
|
|
72
|
+
def db_access():
|
|
73
|
+
"""Open the database allow-list for your own IP (platform admins; sign in first: mctl auth login).
|
|
74
|
+
|
|
75
|
+
allow opens your IPv4 address and, when you have a route to the API over IPv6, your IPv6 /64 network.
|
|
76
|
+
list shows the active grants of every admin. revoke ends one."""
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@db_access.command()
|
|
80
|
+
@click.option("--ttl", "ttl", default="12h", show_default=True, callback=duration_option,
|
|
81
|
+
help="How long the access lasts: 5m to 24h (30m, 12h, 90s)")
|
|
82
|
+
@click.option("--ipv4-only", is_flag=True, help="Open only your IPv4 address (use it on a shared network)")
|
|
83
|
+
@json_option
|
|
84
|
+
def allow(ttl, ipv4_only, as_json):
|
|
85
|
+
"""Open DB access for your current public IPs, or extend it."""
|
|
86
|
+
def go():
|
|
87
|
+
if not MIN_TTL_S <= ttl <= MAX_TTL_S:
|
|
88
|
+
raise DbAccessError(f"--ttl must be between 5m and 24h, not {ttl} seconds.", exitcodes.USAGE)
|
|
89
|
+
body = {"ttl_seconds": ttl}
|
|
90
|
+
results: List[Dict[str, Any]] = []
|
|
91
|
+
notes: List[str] = []
|
|
92
|
+
try:
|
|
93
|
+
results.append(_call("POST", "/db-access", body=body, ipv4_only=True))
|
|
94
|
+
except DbAccessError as ex:
|
|
95
|
+
# An IPv6-only network has no IPv4 route: go on with IPv6, unless --ipv4-only.
|
|
96
|
+
if not ex.connect_failed or ipv4_only:
|
|
97
|
+
raise
|
|
98
|
+
notes.append(NO_IPV4_NOTE)
|
|
99
|
+
no_ipv4 = ex
|
|
100
|
+
if not ipv4_only:
|
|
101
|
+
try:
|
|
102
|
+
results.append(_call("POST", "/db-access", body=body, ipv6_only=True))
|
|
103
|
+
except DbAccessError as ex:
|
|
104
|
+
if ex.connect_failed and results:
|
|
105
|
+
notes.append(NO_IPV6_NOTE)
|
|
106
|
+
elif ex.connect_failed:
|
|
107
|
+
raise no_ipv4 from ex # neither family reaches the API
|
|
108
|
+
elif results:
|
|
109
|
+
first = results[0]
|
|
110
|
+
raise DbAccessError(f"{ex} (The IPv4 grant {first.get('id')} for {first.get('cidr')} exists; "
|
|
111
|
+
f"retry, or revoke it: mctl db-access revoke {first.get('id')}.)",
|
|
112
|
+
ex.exit_code) from ex
|
|
113
|
+
else:
|
|
114
|
+
raise
|
|
115
|
+
return results, notes
|
|
116
|
+
results, notes = _run(go)
|
|
117
|
+
if as_json:
|
|
118
|
+
return _dump({"grants": [_plain(r) for r in results]})
|
|
119
|
+
for r in results:
|
|
120
|
+
verb = "extended" if r.get("_status") == 200 else "created"
|
|
121
|
+
click.echo(f"{verb} grant {r.get('id')}: {r.get('cidr')} until {_expires_text(r.get('expires_at'))}")
|
|
122
|
+
for note in notes:
|
|
123
|
+
click.echo(note)
|
|
124
|
+
click.echo(APPLY_NOTE)
|
|
125
|
+
if any(":" in str(r.get("cidr")) for r in results):
|
|
126
|
+
click.echo(IPV6_WARNING)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
@db_access.command("list")
|
|
130
|
+
@click.option("--all", "show_all", is_flag=True, help="Also the grants that ended in the last 7 days")
|
|
131
|
+
@json_option
|
|
132
|
+
@quiet_option
|
|
133
|
+
@no_headers_option
|
|
134
|
+
def list_(show_all, as_json, quiet, no_headers):
|
|
135
|
+
"""List the active grants (all admins)."""
|
|
136
|
+
params = {"include_expired": "true"} if show_all else None
|
|
137
|
+
data = _run(lambda: _call("GET", "/db-access", params=params))
|
|
138
|
+
if as_json:
|
|
139
|
+
return _dump(data)
|
|
140
|
+
grants = data.get("grants", [])
|
|
141
|
+
if quiet:
|
|
142
|
+
return _echo("\n".join(str(g.get("id")) for g in grants))
|
|
143
|
+
|
|
144
|
+
def end(g):
|
|
145
|
+
at = _when(g.get("revoked_at") or g.get("expires_at"))
|
|
146
|
+
if at is not None and at <= datetime.now(timezone.utc):
|
|
147
|
+
return f"ended {_expires_text(g.get('revoked_at') or g.get('expires_at'))}"
|
|
148
|
+
return _expires_text(g.get("expires_at"))
|
|
149
|
+
_echo(_table(("ID", "CIDR", "CREATED_BY", "EXPIRES"), [
|
|
150
|
+
(str(g.get("id")), str(g.get("cidr")), str(g.get("created_by") or "-"), end(g)) for g in grants],
|
|
151
|
+
not no_headers))
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
@db_access.command()
|
|
155
|
+
@click.argument("grant_id", metavar="ID", type=int)
|
|
156
|
+
@json_option
|
|
157
|
+
def revoke(grant_id, as_json):
|
|
158
|
+
"""Revoke a grant."""
|
|
159
|
+
data = _run(lambda: _call("DELETE", f"/db-access/{grant_id}"))
|
|
160
|
+
if as_json:
|
|
161
|
+
return _dump(data)
|
|
162
|
+
click.echo(f"Revoked grant {grant_id}. {REVOKE_NOTE}")
|
|
@@ -14,6 +14,7 @@ from .node import node
|
|
|
14
14
|
from .orgopt import org_option
|
|
15
15
|
from .pool import pool
|
|
16
16
|
from .ssh import ssh
|
|
17
|
+
from .db_access import db_access
|
|
17
18
|
|
|
18
19
|
|
|
19
20
|
def _broken_pipe() -> int:
|
|
@@ -68,6 +69,7 @@ mctl.add_command(billing)
|
|
|
68
69
|
mctl.add_command(extend)
|
|
69
70
|
mctl.add_command(peering)
|
|
70
71
|
mctl.add_command(ssh)
|
|
72
|
+
mctl.add_command(db_access)
|
|
71
73
|
mctl.add_command(node)
|
|
72
74
|
|
|
73
75
|
|
|
@@ -39,14 +39,25 @@ class IPv4Adapter(HTTPAdapter):
|
|
|
39
39
|
super().init_poolmanager(connections, maxsize, block, **pool_kwargs)
|
|
40
40
|
|
|
41
41
|
|
|
42
|
-
|
|
43
|
-
"""
|
|
44
|
-
the
|
|
42
|
+
class IPv6Adapter(HTTPAdapter):
|
|
43
|
+
"""Connects over IPv6 only. Binding the local end to ``::`` makes urllib3 skip every IPv4 (A) address: its socket
|
|
44
|
+
cannot bind there, so the next address is tried. A host with no IPv6 route ends in a ``ConnectionError``."""
|
|
45
|
+
|
|
46
|
+
def init_poolmanager(self, connections, maxsize, block=False, **pool_kwargs):
|
|
47
|
+
pool_kwargs["source_address"] = ("::", 0)
|
|
48
|
+
super().init_poolmanager(connections, maxsize, block, **pool_kwargs)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def request(method: str, url: str, ipv4_only: bool = False, ipv6_only: bool = False,
|
|
52
|
+
**kw: Any) -> requests.Response:
|
|
53
|
+
"""One request. ``ipv4_only`` / ``ipv6_only`` connect over one address family only: the grant routes read the
|
|
54
|
+
address of the caller as the API sees it, and ``api.multicloud.io`` has A and AAAA records."""
|
|
45
55
|
kw["headers"] = {"User-Agent": USER_AGENT, **(kw.get("headers") or {})}
|
|
46
|
-
if ipv4_only:
|
|
56
|
+
if ipv4_only or ipv6_only:
|
|
57
|
+
adapter = IPv6Adapter if ipv6_only else IPv4Adapter
|
|
47
58
|
with requests.Session() as session:
|
|
48
|
-
session.mount("https://",
|
|
49
|
-
session.mount("http://",
|
|
59
|
+
session.mount("https://", adapter())
|
|
60
|
+
session.mount("http://", adapter())
|
|
50
61
|
r = session.request(method, url, **kw)
|
|
51
62
|
else:
|
|
52
63
|
r = requests.request(method, url, **kw)
|
|
@@ -199,6 +199,79 @@ def show(ctx, pool_ref, as_json):
|
|
|
199
199
|
click.echo(json.dumps(_plain(data), indent=2, sort_keys=True) if as_json else _readable(data))
|
|
200
200
|
|
|
201
201
|
|
|
202
|
+
#: Help text of each bridge hint code of GET /pools/{id}/diagnostics. The API sends the code only.
|
|
203
|
+
DIAGNOSE_HINTS = {
|
|
204
|
+
"NO_HANDSHAKE_AT_POOL": "The pool never received a WireGuard handshake from this replica. "
|
|
205
|
+
"Check that outbound UDP 51820 is allowed from the consumer cluster.",
|
|
206
|
+
"STALE_HANDSHAKE_AT_POOL": "The pool saw a handshake from this replica before, but has no recent handshake. "
|
|
207
|
+
"Check that the replica runs and that outbound UDP 51820 is still allowed.",
|
|
208
|
+
"POOL_NODE_AGENT_OUTDATED": "The pool's nodes run an older node agent that does not report WireGuard peers. "
|
|
209
|
+
"The handshake state is unknown until the nodes are replaced.",
|
|
210
|
+
"REPLICA_NOT_A_PEER_YET": "The pool's nodes do not list this replica as a WireGuard peer yet. "
|
|
211
|
+
"Wait a few minutes. If it stays, check the pool's proxy publishing above.",
|
|
212
|
+
"POOL_NOT_RUNNING": "The pool is not running (new, hibernated, hibernating or waking), so its nodes report no "
|
|
213
|
+
"handshake state. Run the check again when the pool is RUNNING.",
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _diagnose_text(d: Dict[str, Any]) -> str:
|
|
218
|
+
"""The readable form of a PoolDiagnosticsView: the pool lines, then one block per bridge replica."""
|
|
219
|
+
pid = d.get("pool_id")
|
|
220
|
+
if d.get("lifecycle") is None:
|
|
221
|
+
out = [f"Pool {pid}: no state recorded yet"]
|
|
222
|
+
else:
|
|
223
|
+
head = f"Pool {pid}: {d['lifecycle']}"
|
|
224
|
+
if d.get("lifecycle_since"):
|
|
225
|
+
head += f" since {d['lifecycle_since']}"
|
|
226
|
+
out = [head]
|
|
227
|
+
if d.get("observed_at"):
|
|
228
|
+
out.append(f"Checked: {d['observed_at']}")
|
|
229
|
+
gates = d.get("gates")
|
|
230
|
+
if gates:
|
|
231
|
+
out.append("Gates: " + ", ".join(f"{k} {'yes' if gates.get(k) else 'no'}"
|
|
232
|
+
for k in ("tcp_ready", "liqo_synced", "rbac_ready")))
|
|
233
|
+
if d.get("gate_code"):
|
|
234
|
+
out.append(f"Waiting for: {d['gate_code']}")
|
|
235
|
+
if d.get("wg_proxy_publish_blocked"):
|
|
236
|
+
out.append(f"Proxy list not published: {d['wg_proxy_publish_blocked']}")
|
|
237
|
+
if d.get("provisioning_breaker"):
|
|
238
|
+
out.append(f"Provisioning breaker: {d['provisioning_breaker']}")
|
|
239
|
+
bridges = d.get("bridges") or []
|
|
240
|
+
if not bridges:
|
|
241
|
+
out.append("Bridges: none")
|
|
242
|
+
for b in bridges:
|
|
243
|
+
out.append("")
|
|
244
|
+
out.append(f"Bridge {b.get('replica')} (peering {b.get('peering_id')}): {b.get('status')}")
|
|
245
|
+
handshake = str(b.get("pool_handshake", "unknown"))
|
|
246
|
+
if b.get("pool_handshake_at"):
|
|
247
|
+
handshake += f" (last {b['pool_handshake_at']})"
|
|
248
|
+
out.append(f" Pool handshake: {handshake}")
|
|
249
|
+
fresh, total = b.get("pool_nodes_fresh"), b.get("pool_nodes_total")
|
|
250
|
+
out.append(" Pool nodes with a fresh handshake: "
|
|
251
|
+
+ ("-" if total is None else f"{0 if fresh is None else fresh} of {total}"))
|
|
252
|
+
out.append(f" Source IP: {b.get('source_ip') or '-'}")
|
|
253
|
+
out.append(f" Last seen: {b.get('last_seen_at') or '-'}")
|
|
254
|
+
if b.get("hint"):
|
|
255
|
+
out.append(f" {b['hint']}: {DIAGNOSE_HINTS[b['hint']]}" if b["hint"] in DIAGNOSE_HINTS
|
|
256
|
+
else f" {b['hint']}")
|
|
257
|
+
return "\n".join(out)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
@pool.command()
|
|
261
|
+
@click.argument("pool_ref", metavar="POOL")
|
|
262
|
+
@json_option
|
|
263
|
+
@click.pass_context
|
|
264
|
+
def diagnose(ctx, pool_ref, as_json):
|
|
265
|
+
"""Explain why a pool or its Extend bridge does not work (id or name).
|
|
266
|
+
|
|
267
|
+
Shows the pool's lifecycle and readiness gates and, for each bridge replica, what the pool sees of its
|
|
268
|
+
WireGuard handshake. Reads only: it never wakes a hibernated pool."""
|
|
269
|
+
def go(org):
|
|
270
|
+
return _call(org, "GET", f"/pools/{resolve(org, pool_ref)}/diagnostics", READ)
|
|
271
|
+
data = _run(ctx, go)
|
|
272
|
+
click.echo(json.dumps(_plain(data), indent=2, sort_keys=True) if as_json else _diagnose_text(data))
|
|
273
|
+
|
|
274
|
+
|
|
202
275
|
def _json_value(ctx, param, value):
|
|
203
276
|
"""A JSON value, or ``@path`` to read it from a file (``@-``: standard input)."""
|
|
204
277
|
if value is None:
|
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
"""mctl db-access: operator access to the database allow-list. The API is faked at the ``api.call`` seam."""
|
|
2
|
+
import json
|
|
3
|
+
from datetime import datetime, timedelta, timezone
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
import requests
|
|
7
|
+
from click.testing import CliRunner
|
|
8
|
+
|
|
9
|
+
from multicloud_cli import api, net
|
|
10
|
+
from multicloud_cli.main import mctl
|
|
11
|
+
|
|
12
|
+
V4 = "46.116.212.65/32"
|
|
13
|
+
V6 = "2a01:4f8:1c1c:1234::/64"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def runner():
|
|
17
|
+
try:
|
|
18
|
+
return CliRunner(mix_stderr=False)
|
|
19
|
+
except TypeError:
|
|
20
|
+
return CliRunner()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def invoke(*args, **kw):
|
|
24
|
+
return runner().invoke(mctl, list(args), **kw)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def iso(seconds_from_now):
|
|
28
|
+
return (datetime.now(timezone.utc) + timedelta(seconds=seconds_from_now)).isoformat()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def grant(gid=7, cidr=V4, left_s=43200, created_by="user:ada", revoked=None):
|
|
32
|
+
return {"id": gid, "cidr": cidr, "family": 6 if ":" in cidr else 4, "created_by": created_by,
|
|
33
|
+
"created_at": iso(-60), "expires_at": iso(left_s), "revoked_at": revoked}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class FakeApi:
|
|
37
|
+
def __init__(self):
|
|
38
|
+
self.calls = []
|
|
39
|
+
self.grants = []
|
|
40
|
+
self.v6_error = None
|
|
41
|
+
self.v4_error = None
|
|
42
|
+
self.status = 201
|
|
43
|
+
|
|
44
|
+
def posts(self):
|
|
45
|
+
return [c for c in self.calls if c[0] == "POST"]
|
|
46
|
+
|
|
47
|
+
def __call__(self, method, org, path, **kw):
|
|
48
|
+
self.calls.append((method, path, kw))
|
|
49
|
+
if method == "POST" and path == "/db-access":
|
|
50
|
+
if kw.get("ipv6_only"):
|
|
51
|
+
if self.v6_error:
|
|
52
|
+
raise self.v6_error
|
|
53
|
+
return {**grant(gid=2, cidr=V6, left_s=kw["body"]["ttl_seconds"]), "_status": self.status}
|
|
54
|
+
if self.v4_error:
|
|
55
|
+
raise self.v4_error
|
|
56
|
+
return {**grant(gid=1, cidr=V4, left_s=kw["body"]["ttl_seconds"]), "_status": self.status}
|
|
57
|
+
if method == "GET" and path == "/db-access":
|
|
58
|
+
return {"grants": self.grants, "_status": 200}
|
|
59
|
+
if method == "DELETE" and path.startswith("/db-access/"):
|
|
60
|
+
return {**grant(gid=int(path.rsplit("/", 1)[1])), "revoked_at": iso(0), "_status": 200}
|
|
61
|
+
raise AssertionError(f"unexpected call {method} {path}")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@pytest.fixture
|
|
65
|
+
def fake(monkeypatch):
|
|
66
|
+
f = FakeApi()
|
|
67
|
+
monkeypatch.setattr(api, "call", f)
|
|
68
|
+
return f
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
# --- allow -------------------------------------------------------------------------------------------------------
|
|
72
|
+
|
|
73
|
+
def test_allow_calls_both_families_and_prints_each_grant(fake):
|
|
74
|
+
r = invoke("db-access", "allow")
|
|
75
|
+
assert r.exit_code == 0, r.stderr
|
|
76
|
+
[(m1, p1, kw1), (m2, p2, kw2)] = fake.posts()
|
|
77
|
+
assert (m1, p1, kw1["body"]) == ("POST", "/db-access", {"ttl_seconds": 43200})
|
|
78
|
+
assert kw1["ipv4_only"] is True and not kw1.get("ipv6_only")
|
|
79
|
+
assert kw2["ipv6_only"] is True and not kw2.get("ipv4_only") and kw2["body"] == {"ttl_seconds": 43200}
|
|
80
|
+
assert all(c[2]["prefer_sso"] is True and c[2]["org_scoped"] is False for c in fake.posts())
|
|
81
|
+
assert V4 in r.stdout and V6 in r.stdout
|
|
82
|
+
assert r.stdout.count("created") == 2 and "in 11h59m" in r.stdout or "in 12h" in r.stdout
|
|
83
|
+
assert "The scheduler applies it within about a minute." in r.stdout
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def test_allow_warns_about_the_ipv6_prefix(fake):
|
|
87
|
+
r = invoke("db-access", "allow")
|
|
88
|
+
assert "/64 covers every device on this network" in r.stdout
|
|
89
|
+
assert "--ipv4-only" in r.stdout
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def test_allow_says_extended_on_200(fake):
|
|
93
|
+
fake.status = 200
|
|
94
|
+
r = invoke("db-access", "allow")
|
|
95
|
+
assert r.stdout.count("extended") == 2 and "created" not in r.stdout
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def test_ipv4_only_skips_ipv6(fake):
|
|
99
|
+
r = invoke("db-access", "allow", "--ipv4-only")
|
|
100
|
+
assert r.exit_code == 0, r.stderr
|
|
101
|
+
assert len(fake.posts()) == 1 and fake.posts()[0][2]["ipv4_only"] is True
|
|
102
|
+
assert V4 in r.stdout and V6 not in r.stdout and "/64" not in r.stdout
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def test_ipv6_connect_error_succeeds_with_a_note(fake):
|
|
106
|
+
err = api.ApiError("Could not reach the API: no route")
|
|
107
|
+
err.connect_failed = True
|
|
108
|
+
fake.v6_error = err
|
|
109
|
+
r = invoke("db-access", "allow")
|
|
110
|
+
assert r.exit_code == 0, r.stderr
|
|
111
|
+
assert V4 in r.stdout and V6 not in r.stdout and "/64 covers" not in r.stdout
|
|
112
|
+
assert "No IPv6 route" in r.stdout and "IPv4 only" in r.stdout
|
|
113
|
+
assert "The scheduler applies it" in r.stdout
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def no_route():
|
|
117
|
+
err = api.ApiError("Could not reach the API: no route")
|
|
118
|
+
err.connect_failed = True
|
|
119
|
+
return err
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def test_ipv6_only_network_grants_ipv6_with_a_note(fake):
|
|
123
|
+
fake.v4_error = no_route()
|
|
124
|
+
r = invoke("db-access", "allow")
|
|
125
|
+
assert r.exit_code == 0, r.stderr
|
|
126
|
+
assert V6 in r.stdout and "No IPv4 route" in r.stdout and "/64 covers" in r.stdout
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def test_no_route_at_all_fails(fake):
|
|
130
|
+
fake.v4_error, fake.v6_error = no_route(), no_route()
|
|
131
|
+
r = invoke("db-access", "allow")
|
|
132
|
+
assert r.exit_code != 0 and "Could not reach the API" in r.stderr
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def test_ipv4_only_with_no_ipv4_route_fails(fake):
|
|
136
|
+
fake.v4_error = no_route()
|
|
137
|
+
r = invoke("db-access", "allow", "--ipv4-only")
|
|
138
|
+
assert r.exit_code != 0 and len(fake.posts()) == 1
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def test_tls_error_is_not_a_missing_route(monkeypatch):
|
|
142
|
+
import requests
|
|
143
|
+
from multicloud_cli import net
|
|
144
|
+
|
|
145
|
+
def boom(*a, **kw):
|
|
146
|
+
raise requests.exceptions.SSLError("certificate verify failed")
|
|
147
|
+
monkeypatch.setattr(net, "request", boom)
|
|
148
|
+
with pytest.raises(api.ApiError) as ei:
|
|
149
|
+
api.call("GET", None, "/db-access", org_scoped=False, ipv6_only=True)
|
|
150
|
+
assert ei.value.connect_failed is False
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def test_ipv6_http_error_still_fails(fake):
|
|
154
|
+
fake.v6_error = api.ApiError("The client address is not a public IPv6 address", 400)
|
|
155
|
+
r = invoke("db-access", "allow")
|
|
156
|
+
assert r.exit_code != 0 and "not a public IPv6 address" in r.stderr
|
|
157
|
+
assert "IPv4 grant" in r.stderr and "mctl db-access revoke" in r.stderr
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def test_ipv4_failure_fails_and_skips_ipv6(monkeypatch):
|
|
161
|
+
calls = []
|
|
162
|
+
|
|
163
|
+
def boom(method, org, path, **kw):
|
|
164
|
+
calls.append(kw)
|
|
165
|
+
raise api.ApiError("The client address 10.0.0.1 is not a public IPv4 address", 400)
|
|
166
|
+
monkeypatch.setattr(api, "call", boom)
|
|
167
|
+
r = invoke("db-access", "allow")
|
|
168
|
+
assert r.exit_code != 0 and len(calls) == 1
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def test_forbidden_names_the_role(monkeypatch):
|
|
172
|
+
def forbidden(method, org, path, **kw):
|
|
173
|
+
raise api.ApiError("Forbidden", 403)
|
|
174
|
+
monkeypatch.setattr(api, "call", forbidden)
|
|
175
|
+
for args in (("allow",), ("list",), ("revoke", "7")):
|
|
176
|
+
r = invoke("db-access", *args)
|
|
177
|
+
assert r.exit_code == 3, args
|
|
178
|
+
assert "(db-access needs the multicloud-admins role.)" in r.stderr
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
@pytest.mark.parametrize("value,seconds", [("2h", 7200), ("30m", 1800), ("300", 300), ("24h", 86400)])
|
|
182
|
+
def test_ttl_parsing(fake, value, seconds):
|
|
183
|
+
r = invoke("db-access", "allow", "--ttl", value)
|
|
184
|
+
assert r.exit_code == 0, r.stderr
|
|
185
|
+
assert {c[2]["body"]["ttl_seconds"] for c in fake.posts()} == {seconds}
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
@pytest.mark.parametrize("value", ["abc", "1m", "25h", "0"])
|
|
189
|
+
def test_bad_ttl_is_a_usage_error(fake, value):
|
|
190
|
+
r = invoke("db-access", "allow", "--ttl", value)
|
|
191
|
+
assert r.exit_code == 2 and not fake.calls
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def test_allow_json(fake):
|
|
195
|
+
r = invoke("db-access", "allow", "--json")
|
|
196
|
+
assert r.exit_code == 0, r.stderr
|
|
197
|
+
assert [g["cidr"] for g in json.loads(r.stdout)["grants"]] == [V4, V6]
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
# --- list, revoke ------------------------------------------------------------------------------------------------
|
|
201
|
+
|
|
202
|
+
def test_list_table(fake):
|
|
203
|
+
fake.grants = [grant(gid=7), grant(gid=8, cidr=V6, created_by="user:bob")]
|
|
204
|
+
r = invoke("db-access", "list")
|
|
205
|
+
assert r.exit_code == 0, r.stderr
|
|
206
|
+
lines = r.stdout.splitlines()
|
|
207
|
+
assert lines[0].split()[:3] == ["ID", "CIDR", "CREATED_BY"]
|
|
208
|
+
assert lines[1].split()[:3] == ["7", V4, "user:ada"] and lines[2].split()[:3] == ["8", V6, "user:bob"]
|
|
209
|
+
assert fake.calls[0][2].get("params") is None
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def test_list_all_asks_for_expired(fake):
|
|
213
|
+
fake.grants = [grant(gid=7, left_s=-3600, revoked=None)]
|
|
214
|
+
r = invoke("db-access", "list", "--all")
|
|
215
|
+
assert r.exit_code == 0, r.stderr
|
|
216
|
+
assert fake.calls[0][2]["params"] == {"include_expired": "true"}
|
|
217
|
+
assert "ended" in r.stdout
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def test_revoke(fake):
|
|
221
|
+
r = invoke("db-access", "revoke", "7")
|
|
222
|
+
assert r.exit_code == 0, r.stderr
|
|
223
|
+
assert fake.calls[0][:2] == ("DELETE", "/db-access/7")
|
|
224
|
+
assert "Revoked grant 7" in r.stdout and "removal grace" in r.stdout
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
# --- transport ---------------------------------------------------------------------------------------------------
|
|
228
|
+
|
|
229
|
+
def test_ipv6_adapter_binds_the_wildcard_v6_address():
|
|
230
|
+
adapter = net.IPv6Adapter()
|
|
231
|
+
assert adapter.poolmanager.connection_pool_kw["source_address"] == ("::", 0)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def test_net_request_ipv6_only_uses_the_adapter(monkeypatch):
|
|
235
|
+
seen = {}
|
|
236
|
+
|
|
237
|
+
def session_request(self, method, url, **kw):
|
|
238
|
+
seen["adapter"] = self.get_adapter(url)
|
|
239
|
+
seen["kw"] = kw
|
|
240
|
+
return "r"
|
|
241
|
+
monkeypatch.setattr(requests.Session, "request", session_request)
|
|
242
|
+
monkeypatch.setattr(requests, "request", lambda *a, **kw: pytest.fail("plain path used"))
|
|
243
|
+
assert net.request("GET", "https://api.multicloud.io/x", ipv6_only=True, timeout=1) == "r"
|
|
244
|
+
assert isinstance(seen["adapter"], net.IPv6Adapter) and "ipv6_only" not in seen["kw"]
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def test_api_call_passes_ipv6_only_to_the_transport(monkeypatch):
|
|
248
|
+
from .helpers import reply
|
|
249
|
+
monkeypatch.setenv("MULTICLOUD_API_KEY", "fake-key-0000")
|
|
250
|
+
seen = []
|
|
251
|
+
monkeypatch.setattr(net, "request", lambda m, u, **kw: seen.append(kw) or reply(200, {}))
|
|
252
|
+
api.call("GET", None, "/db-access", org_scoped=False, ipv6_only=True)
|
|
253
|
+
api.call("GET", None, "/db-access", org_scoped=False)
|
|
254
|
+
assert [kw["ipv6_only"] for kw in seen] == [True, False]
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def test_connection_error_is_marked_connect_failed(monkeypatch):
|
|
258
|
+
monkeypatch.setenv("MULTICLOUD_API_KEY", "fake-key-0000")
|
|
259
|
+
|
|
260
|
+
def refuse(m, u, **kw):
|
|
261
|
+
raise requests.ConnectionError("Network is unreachable")
|
|
262
|
+
monkeypatch.setattr(net, "request", refuse)
|
|
263
|
+
with pytest.raises(api.ApiError) as ex:
|
|
264
|
+
api.call("GET", None, "/db-access", org_scoped=False, ipv6_only=True)
|
|
265
|
+
assert ex.value.connect_failed is True
|
|
266
|
+
|
|
267
|
+
def timeout(m, u, **kw):
|
|
268
|
+
raise requests.ReadTimeout("slow")
|
|
269
|
+
monkeypatch.setattr(net, "request", timeout)
|
|
270
|
+
with pytest.raises(api.ApiError) as ex:
|
|
271
|
+
api.call("GET", None, "/db-access", org_scoped=False)
|
|
272
|
+
assert ex.value.connect_failed is False
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
# --- hidden ------------------------------------------------------------------------------------------------------
|
|
276
|
+
|
|
277
|
+
def test_root_help_does_not_mention_db_access():
|
|
278
|
+
r = invoke("--help")
|
|
279
|
+
assert r.exit_code == 0
|
|
280
|
+
assert "db-access" not in r.stdout and "db_access" not in r.stdout
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def test_group_help_still_works():
|
|
284
|
+
r = invoke("db-access", "--help")
|
|
285
|
+
assert r.exit_code == 0 and "allow" in r.stdout and "revoke" in r.stdout
|
|
@@ -489,3 +489,97 @@ def test_max_servers_outside_1_to_100_is_a_usage_error(monkeypatch):
|
|
|
489
489
|
r, calls, _ = run(["update", "7", "--max-servers", bad], [reply(200, pool_view())], monkeypatch)
|
|
490
490
|
assert r.exit_code == 2 and not calls
|
|
491
491
|
assert "--max-servers" in r.stderr
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
# --- mctl pool diagnose (GET /pools/{id}/diagnostics) ---
|
|
495
|
+
|
|
496
|
+
def diagnostics(**extra):
|
|
497
|
+
"""A PoolDiagnosticsView, as the Multicloud API returns it (the Triple C case: no handshake, 0 of 2 nodes)."""
|
|
498
|
+
body = {"schema_version": 1, "pool_id": 412, "lifecycle": "RUNNING", "lifecycle_since": "2026-11-18T09:00:00Z",
|
|
499
|
+
"observed_at": "2026-11-18T10:02:11Z",
|
|
500
|
+
"gates": {"tcp_ready": True, "liqo_synced": True, "rbac_ready": True}, "gate_code": None,
|
|
501
|
+
"wg_proxy_publish_blocked": None, "provisioning_breaker": None,
|
|
502
|
+
"bridges": [{"peering_id": 77, "replica": "extend-proxy-6c9f-abcde", "status": "ACTIVE",
|
|
503
|
+
"created_at": "2026-11-18T08:00:00Z", "last_seen_at": "2026-11-18T10:02:00Z",
|
|
504
|
+
"pool_handshake": "never", "pool_handshake_at": None, "pool_nodes_fresh": 0,
|
|
505
|
+
"pool_nodes_total": 2, "source_ip": None, "hint": "NO_HANDSHAKE_AT_POOL"}]}
|
|
506
|
+
body.update(extra)
|
|
507
|
+
return body
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
def test_diagnose_by_id_prints_the_pool_and_each_bridge(monkeypatch):
|
|
511
|
+
r, calls, _ = run(["diagnose", "412"], [reply(200, diagnostics())], monkeypatch)
|
|
512
|
+
assert r.exit_code == 0, r.output
|
|
513
|
+
assert len(calls) == 1 and calls[0][:2] == ("GET", f"{BASE}/pools/412/diagnostics")
|
|
514
|
+
assert "Pool 412: RUNNING" in r.stdout
|
|
515
|
+
assert "extend-proxy-6c9f-abcde" in r.stdout and "ACTIVE" in r.stdout
|
|
516
|
+
assert "Pool handshake: never" in r.stdout
|
|
517
|
+
assert "Pool nodes with a fresh handshake: 0 of 2" in r.stdout
|
|
518
|
+
assert "Source IP: -" in r.stdout
|
|
519
|
+
assert "NO_HANDSHAKE_AT_POOL" in r.stdout
|
|
520
|
+
assert "Check that outbound UDP 51820 is allowed from the consumer cluster." in r.stdout
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
def test_diagnose_by_name_resolves_with_one_list_call(monkeypatch):
|
|
524
|
+
listing = {"pools": [pool_view(7, "ci"), pool_view(412, "burst")]}
|
|
525
|
+
r, calls, _ = run(["diagnose", "burst"], [reply(200, listing), reply(200, diagnostics())], monkeypatch)
|
|
526
|
+
assert r.exit_code == 0, r.output
|
|
527
|
+
assert [c[1] for c in calls] == [f"{BASE}/pools", f"{BASE}/pools/412/diagnostics"]
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
def test_diagnose_json_is_the_raw_body(monkeypatch):
|
|
531
|
+
r, _, _ = run(["diagnose", "412", "--json"], [reply(200, diagnostics())], monkeypatch)
|
|
532
|
+
assert r.exit_code == 0, r.output
|
|
533
|
+
assert json.loads(r.stdout) == diagnostics()
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
@pytest.mark.parametrize("hint,text", [
|
|
537
|
+
("POOL_NODE_AGENT_OUTDATED", "older node agent"),
|
|
538
|
+
("STALE_HANDSHAKE_AT_POOL", "no recent handshake"),
|
|
539
|
+
("REPLICA_NOT_A_PEER_YET", "as a WireGuard peer"),
|
|
540
|
+
])
|
|
541
|
+
def test_diagnose_help_text_for_each_hint(monkeypatch, hint, text):
|
|
542
|
+
body = diagnostics()
|
|
543
|
+
body["bridges"][0].update(hint=hint, pool_handshake="unknown" if hint != "STALE_HANDSHAKE_AT_POOL" else "stale")
|
|
544
|
+
r, _, _ = run(["diagnose", "412"], [reply(200, body)], monkeypatch)
|
|
545
|
+
assert hint in r.stdout and text in r.stdout
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
def test_diagnose_healthy_bridge_has_no_hint_and_shows_the_source_ip(monkeypatch):
|
|
549
|
+
body = diagnostics()
|
|
550
|
+
body["bridges"][0].update(pool_handshake="fresh", pool_handshake_at="2026-11-18T10:00:00Z", pool_nodes_fresh=2,
|
|
551
|
+
source_ip="8.8.4.4", hint=None)
|
|
552
|
+
r, _, _ = run(["diagnose", "412"], [reply(200, body)], monkeypatch)
|
|
553
|
+
assert "Pool handshake: fresh" in r.stdout and "Source IP: 8.8.4.4" in r.stdout
|
|
554
|
+
assert "Pool nodes with a fresh handshake: 2 of 2" in r.stdout
|
|
555
|
+
assert "Hint" not in r.stdout and "help" not in r.stdout.lower()
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
def test_diagnose_unknown_hint_prints_the_code_only(monkeypatch):
|
|
559
|
+
body = diagnostics()
|
|
560
|
+
body["bridges"][0]["hint"] = "SOME_FUTURE_CODE"
|
|
561
|
+
r, _, _ = run(["diagnose", "412"], [reply(200, body)], monkeypatch)
|
|
562
|
+
assert r.exit_code == 0 and "SOME_FUTURE_CODE" in r.stdout
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
def test_diagnose_pool_lines_for_gate_breaker_and_publish_block(monkeypatch):
|
|
566
|
+
body = diagnostics(lifecycle="WAKING", gate_code="TCP_NOT_READY", provisioning_breaker="capacity-starved",
|
|
567
|
+
wg_proxy_publish_blocked="policy-write-failed", bridges=[],
|
|
568
|
+
gates={"tcp_ready": False, "liqo_synced": False, "rbac_ready": False})
|
|
569
|
+
r, _, _ = run(["diagnose", "412"], [reply(200, body)], monkeypatch)
|
|
570
|
+
assert "Pool 412: WAKING" in r.stdout
|
|
571
|
+
assert "Waiting for: TCP_NOT_READY" in r.stdout
|
|
572
|
+
assert "Provisioning breaker: capacity-starved" in r.stdout
|
|
573
|
+
assert "Proxy list not published: policy-write-failed" in r.stdout
|
|
574
|
+
assert "Bridges: none" in r.stdout
|
|
575
|
+
|
|
576
|
+
|
|
577
|
+
def test_diagnose_pool_without_a_state_row(monkeypatch):
|
|
578
|
+
body = diagnostics(lifecycle=None, lifecycle_since=None, observed_at=None, gates=None, bridges=[])
|
|
579
|
+
r, _, _ = run(["diagnose", "412"], [reply(200, body)], monkeypatch)
|
|
580
|
+
assert r.exit_code == 0 and "Pool 412: no state recorded yet" in r.stdout
|
|
581
|
+
|
|
582
|
+
|
|
583
|
+
def test_diagnose_404_exits_not_found(monkeypatch):
|
|
584
|
+
r, _, _ = run(["diagnose", "412"], [reply(404, {"detail": {"error": {"message": "No such pool"}}})], monkeypatch)
|
|
585
|
+
assert r.exit_code == 4
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
__version__ = "0.12.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
|