simple-module-remote 0.0.50__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- simple_module_remote/__init__.py +12 -0
- simple_module_remote/commands/__init__.py +1 -0
- simple_module_remote/commands/api_cmd.py +157 -0
- simple_module_remote/commands/auth_cmd.py +166 -0
- simple_module_remote/commands/doctor_cmd.py +157 -0
- simple_module_remote/commands/env_cmd.py +198 -0
- simple_module_remote/commands/generated.py +50 -0
- simple_module_remote/commands/root.py +186 -0
- simple_module_remote/commands/runtime.py +263 -0
- simple_module_remote/commands/schema_cmd.py +155 -0
- simple_module_remote/commands/schema_fetch.py +129 -0
- simple_module_remote/commands/schema_source.py +181 -0
- simple_module_remote/config/__init__.py +1 -0
- simple_module_remote/config/_file_store.py +182 -0
- simple_module_remote/config/_private_dir.py +191 -0
- simple_module_remote/config/credentials.py +296 -0
- simple_module_remote/config/environments.py +186 -0
- simple_module_remote/config/paths.py +32 -0
- simple_module_remote/config/resolve.py +96 -0
- simple_module_remote/curated/__init__.py +1 -0
- simple_module_remote/generate/__init__.py +1 -0
- simple_module_remote/generate/body.py +198 -0
- simple_module_remote/generate/confirm.py +38 -0
- simple_module_remote/generate/context.py +38 -0
- simple_module_remote/generate/emit.py +278 -0
- simple_module_remote/generate/execute.py +220 -0
- simple_module_remote/generate/naming.py +69 -0
- simple_module_remote/generate/operations.py +181 -0
- simple_module_remote/generate/pagination.py +80 -0
- simple_module_remote/generate/pairs.py +22 -0
- simple_module_remote/generate/params.py +210 -0
- simple_module_remote/generate/prepare.py +134 -0
- simple_module_remote/generate/tree.py +59 -0
- simple_module_remote/generate/trust.py +42 -0
- simple_module_remote/generate/validate.py +136 -0
- simple_module_remote/http/__init__.py +1 -0
- simple_module_remote/http/client.py +292 -0
- simple_module_remote/http/errors.py +59 -0
- simple_module_remote/http/safety.py +124 -0
- simple_module_remote/output/__init__.py +1 -0
- simple_module_remote/output/reasons.py +17 -0
- simple_module_remote/output/render.py +149 -0
- simple_module_remote/output/sanitize.py +32 -0
- simple_module_remote/py.typed +0 -0
- simple_module_remote/schema/__init__.py +1 -0
- simple_module_remote/schema/cache.py +187 -0
- simple_module_remote/schema/loader.py +56 -0
- simple_module_remote-0.0.50.dist-info/METADATA +73 -0
- simple_module_remote-0.0.50.dist-info/RECORD +51 -0
- simple_module_remote-0.0.50.dist-info/WHEEL +4 -0
- simple_module_remote-0.0.50.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""Client-only engine for a per-project CLI over a simple_module app's REST API."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
__version__ = version("simple_module_remote")
|
|
7
|
+
except PackageNotFoundError: # pragma: no cover - source checkout without install
|
|
8
|
+
__version__ = "0.0.0"
|
|
9
|
+
|
|
10
|
+
from simple_module_remote.commands.root import build_cli
|
|
11
|
+
|
|
12
|
+
__all__ = ["__version__", "build_cli"]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""commands area of the remote CLI engine."""
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"""``api METHOD PATH``: call any /api/ endpoint with the same safety rules."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from typing import Any
|
|
7
|
+
from urllib.parse import unquote
|
|
8
|
+
|
|
9
|
+
import click
|
|
10
|
+
|
|
11
|
+
from simple_module_remote.commands.runtime import state_of
|
|
12
|
+
from simple_module_remote.generate.operations import Operation, Param, parse_operations
|
|
13
|
+
from simple_module_remote.generate.pairs import split_pairs
|
|
14
|
+
from simple_module_remote.generate.params import PATH_VAR, click_params_for, param_map
|
|
15
|
+
from simple_module_remote.generate.tree import session_only_operations
|
|
16
|
+
from simple_module_remote.generate.trust import route_key
|
|
17
|
+
from simple_module_remote.http.errors import UnsafePathError
|
|
18
|
+
from simple_module_remote.http.safety import validate_api_path
|
|
19
|
+
from simple_module_remote.output.sanitize import sanitize
|
|
20
|
+
|
|
21
|
+
__all__ = ["api"]
|
|
22
|
+
|
|
23
|
+
METHODS = ("GET", "POST", "PUT", "PATCH", "DELETE")
|
|
24
|
+
BODY_METHODS = ("POST", "PUT", "PATCH", "DELETE")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _matching(root: dict, method: str, path: str) -> list[Operation]:
|
|
28
|
+
"""Schema operations whose path template matches ``path``: they define its risk."""
|
|
29
|
+
found = []
|
|
30
|
+
for op in parse_operations(root):
|
|
31
|
+
pattern = "[^/]+".join(re.escape(part) for part in PATH_VAR.split(op.path)[::2])
|
|
32
|
+
if op.method == method and re.fullmatch(pattern, path):
|
|
33
|
+
found.append(op)
|
|
34
|
+
return found
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _synthetic(
|
|
38
|
+
method: str,
|
|
39
|
+
path: str,
|
|
40
|
+
queries: list[tuple[str, str]],
|
|
41
|
+
root: dict | None = None,
|
|
42
|
+
*,
|
|
43
|
+
trusted: dict | None,
|
|
44
|
+
) -> Operation:
|
|
45
|
+
"""``trusted`` is the bundled schema when ``root`` is a live one: only it may waive."""
|
|
46
|
+
# Risk comes from the endpoint the server will route to: match the decoded path.
|
|
47
|
+
matched = _matching(root, method, unquote(path)) if root else []
|
|
48
|
+
vouched = _matching(trusted, method, unquote(path)) if trusted is not None else matched
|
|
49
|
+
templates = {route_key(op.method, op.path) for op in matched}
|
|
50
|
+
# A waiver needs one unambiguous route that both schemas agree on.
|
|
51
|
+
waivable = len(templates) == 1 and templates == {
|
|
52
|
+
route_key(op.method, op.path) for op in vouched
|
|
53
|
+
}
|
|
54
|
+
names: dict[str, int] = {}
|
|
55
|
+
for key, _ in queries:
|
|
56
|
+
names[key] = names.get(key, 0) + 1
|
|
57
|
+
params = tuple(
|
|
58
|
+
Param(
|
|
59
|
+
name=key,
|
|
60
|
+
location="query",
|
|
61
|
+
required=False,
|
|
62
|
+
schema={"type": "array"} if count > 1 else {},
|
|
63
|
+
description="",
|
|
64
|
+
)
|
|
65
|
+
for key, count in names.items()
|
|
66
|
+
)
|
|
67
|
+
return Operation(
|
|
68
|
+
operation_id="api",
|
|
69
|
+
method=method,
|
|
70
|
+
path=path,
|
|
71
|
+
group="api",
|
|
72
|
+
name="api",
|
|
73
|
+
params=params,
|
|
74
|
+
body_kind="json" if method in BODY_METHODS else "none",
|
|
75
|
+
body_schema=None,
|
|
76
|
+
summary="",
|
|
77
|
+
description="",
|
|
78
|
+
safe=waivable and all(op.safe for op in vouched),
|
|
79
|
+
confirm=any(op.confirm for op in (*matched, *vouched)),
|
|
80
|
+
# A path that only session-only schema operations match gets the session-only hint.
|
|
81
|
+
token_capable=not (matched and not any(op.token_capable for op in matched)),
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _list_session_only(schema: dict) -> None:
|
|
86
|
+
for op in session_only_operations(schema):
|
|
87
|
+
click.echo(sanitize(f"{op.method} {op.path} {op.operation_id}"))
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _options() -> list[click.Parameter]:
|
|
91
|
+
template = _synthetic("POST", "/api/x", [], trusted={})
|
|
92
|
+
shared = [p for p in click_params_for(template) if p.name in _SHARED]
|
|
93
|
+
return [
|
|
94
|
+
click.Argument(["method"], required=False, metavar="METHOD"),
|
|
95
|
+
click.Argument(["path"], required=False, metavar="PATH"),
|
|
96
|
+
click.Option(["--query", "queries"], multiple=True, help="Query parameter: key=value."),
|
|
97
|
+
click.Option(
|
|
98
|
+
["--session-only", "session_only"],
|
|
99
|
+
is_flag=True,
|
|
100
|
+
help="List operations a token cannot call, then exit.",
|
|
101
|
+
),
|
|
102
|
+
*shared,
|
|
103
|
+
]
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
_SHARED = frozenset(
|
|
107
|
+
{
|
|
108
|
+
"json_arg",
|
|
109
|
+
"file_arg",
|
|
110
|
+
"sets",
|
|
111
|
+
"set_jsons",
|
|
112
|
+
"dry_run",
|
|
113
|
+
"output",
|
|
114
|
+
"columns",
|
|
115
|
+
"quiet",
|
|
116
|
+
"out",
|
|
117
|
+
"yes",
|
|
118
|
+
}
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _callback(**values: Any) -> None:
|
|
123
|
+
ctx = click.get_current_context()
|
|
124
|
+
state = state_of(ctx)
|
|
125
|
+
if values.pop("session_only"):
|
|
126
|
+
_list_session_only(state.root)
|
|
127
|
+
return
|
|
128
|
+
method, path = values.pop("method"), values.pop("path")
|
|
129
|
+
if not method or not path:
|
|
130
|
+
raise click.UsageError("usage: api METHOD PATH (or --session-only)")
|
|
131
|
+
method = method.upper()
|
|
132
|
+
if method not in METHODS:
|
|
133
|
+
raise click.UsageError(f"METHOD must be one of: {', '.join(METHODS)}")
|
|
134
|
+
try:
|
|
135
|
+
validate_api_path(path)
|
|
136
|
+
except UnsafePathError as exc:
|
|
137
|
+
raise click.UsageError(str(exc)) from None
|
|
138
|
+
if method not in BODY_METHODS and any(
|
|
139
|
+
values.get(k) for k in ("json_arg", "file_arg", "sets", "set_jsons")
|
|
140
|
+
):
|
|
141
|
+
raise click.UsageError(f"{method} takes no request body: drop --json/--file/--set")
|
|
142
|
+
queries = split_pairs(values.pop("queries"), "--query")
|
|
143
|
+
op = _synthetic(method, path, queries, state.root, trusted=state.bundled_root)
|
|
144
|
+
for dest, param in param_map(op).items():
|
|
145
|
+
found = [v for k, v in queries if k == param.name]
|
|
146
|
+
values[dest] = tuple(found) if len(found) > 1 else found[0]
|
|
147
|
+
code = state.run(op, values, generated=False)
|
|
148
|
+
if code:
|
|
149
|
+
ctx.exit(code)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
api = click.Command(
|
|
153
|
+
"api",
|
|
154
|
+
params=_options(),
|
|
155
|
+
callback=_callback,
|
|
156
|
+
help="Call any /api/ endpoint: api METHOD PATH [--json ... | --set k=v] [--query k=v].",
|
|
157
|
+
)
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""``login``, ``logout`` and ``whoami``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import sys
|
|
6
|
+
|
|
7
|
+
import click
|
|
8
|
+
|
|
9
|
+
from simple_module_remote.commands.runtime import WHOAMI_PATH, CliError, fetch_whoami, state_of
|
|
10
|
+
from simple_module_remote.config.credentials import (
|
|
11
|
+
CredentialError,
|
|
12
|
+
StoredCredential,
|
|
13
|
+
credential_key,
|
|
14
|
+
describe_tenant,
|
|
15
|
+
is_single_tenant,
|
|
16
|
+
login_hint,
|
|
17
|
+
pin_kwargs,
|
|
18
|
+
tenant_matches,
|
|
19
|
+
validate_token,
|
|
20
|
+
)
|
|
21
|
+
from simple_module_remote.config.resolve import find_credential
|
|
22
|
+
from simple_module_remote.http.errors import AUTH_STATUSES, ApiError, exit_code_for
|
|
23
|
+
from simple_module_remote.output.sanitize import sanitize
|
|
24
|
+
|
|
25
|
+
__all__ = ["login", "logout", "whoami"]
|
|
26
|
+
|
|
27
|
+
MAX_TOKEN_CHARS = 4096
|
|
28
|
+
NOT_FOUND = 404
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _stdin_is_tty() -> bool:
|
|
32
|
+
return sys.stdin.isatty()
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _api_failure(exc: ApiError, what: str) -> click.ClickException:
|
|
36
|
+
return CliError(f"{what}: {exc.message}", exit_code_for(exc.status))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class _LoginCommand(click.Command):
|
|
40
|
+
"""Never echoes extra arguments: they may be a token typed on the command line."""
|
|
41
|
+
|
|
42
|
+
def parse_args(self, ctx: click.Context, args: list[str]) -> list[str]:
|
|
43
|
+
try:
|
|
44
|
+
return super().parse_args(ctx, args)
|
|
45
|
+
except click.UsageError:
|
|
46
|
+
raise CliError(
|
|
47
|
+
"login takes no arguments and no token value: use --token (hidden prompt) "
|
|
48
|
+
"or --token-stdin (--env and --tenant go before the word login)"
|
|
49
|
+
) from None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@click.command(
|
|
53
|
+
"login", cls=_LoginCommand, help="Store a personal access token for the selected environment."
|
|
54
|
+
)
|
|
55
|
+
@click.option("--token", "prompt_token", is_flag=True, help="Prompt for the token (hidden input).")
|
|
56
|
+
@click.option("--token-stdin", is_flag=True, help="Read the token from one line of stdin.")
|
|
57
|
+
@click.pass_context
|
|
58
|
+
def login(ctx: click.Context, prompt_token: bool, token_stdin: bool) -> None:
|
|
59
|
+
state = state_of(ctx)
|
|
60
|
+
if prompt_token and token_stdin:
|
|
61
|
+
raise CliError("choose one of --token and --token-stdin")
|
|
62
|
+
if not (prompt_token or token_stdin):
|
|
63
|
+
raise CliError("browser login arrives in a later release: use --token or --token-stdin")
|
|
64
|
+
env, _ = state.select()
|
|
65
|
+
if token_stdin:
|
|
66
|
+
candidate = sys.stdin.readline(MAX_TOKEN_CHARS + 2).strip()
|
|
67
|
+
if len(candidate) > MAX_TOKEN_CHARS:
|
|
68
|
+
raise CliError(f"the token is longer than {MAX_TOKEN_CHARS} characters")
|
|
69
|
+
else:
|
|
70
|
+
if not _stdin_is_tty():
|
|
71
|
+
raise CliError("stdin is not a terminal: pipe the token to --token-stdin instead")
|
|
72
|
+
candidate = click.prompt("Token", hide_input=True, err=True).strip()
|
|
73
|
+
if not candidate:
|
|
74
|
+
raise CliError("no token provided")
|
|
75
|
+
with state.guard():
|
|
76
|
+
validate_token(candidate, source="the token you entered")
|
|
77
|
+
try:
|
|
78
|
+
with state.client(env, candidate) as client:
|
|
79
|
+
who = fetch_whoami(client)
|
|
80
|
+
except ApiError as exc:
|
|
81
|
+
if exc.status == 0:
|
|
82
|
+
raise _api_failure(
|
|
83
|
+
exc, f"cannot reach {env.name} ({env.url}); nothing was stored"
|
|
84
|
+
) from None
|
|
85
|
+
if exc.status == NOT_FOUND:
|
|
86
|
+
raise _api_failure(
|
|
87
|
+
exc,
|
|
88
|
+
f"{env.url} has no {WHOAMI_PATH}: check the URL and any path prefix; "
|
|
89
|
+
"nothing was stored",
|
|
90
|
+
) from None
|
|
91
|
+
raise _api_failure(exc, "the token was not accepted; nothing was stored") from None
|
|
92
|
+
wanted = state.tenant(env)
|
|
93
|
+
single = bool(wanted) and is_single_tenant(who)
|
|
94
|
+
if single:
|
|
95
|
+
click.echo(
|
|
96
|
+
f"note: {env.name} is a single-tenant server; --tenant {sanitize(wanted)} is ignored",
|
|
97
|
+
err=True,
|
|
98
|
+
)
|
|
99
|
+
elif wanted and not tenant_matches(wanted, who):
|
|
100
|
+
raise CliError(
|
|
101
|
+
f"tenant {wanted!r} matches neither the slug nor the id of the token's tenant "
|
|
102
|
+
f"{describe_tenant(who.get('tenant_slug'), who.get('tenant_id'))}; "
|
|
103
|
+
"nothing was stored"
|
|
104
|
+
)
|
|
105
|
+
store = state.store()
|
|
106
|
+
where = credential_key(env.name, None if single else wanted) # the plain slot when ignored
|
|
107
|
+
with state.guard():
|
|
108
|
+
store.put(
|
|
109
|
+
where,
|
|
110
|
+
StoredCredential(candidate, env.origin, **pin_kwargs(who)),
|
|
111
|
+
)
|
|
112
|
+
if store.using_fallback:
|
|
113
|
+
click.echo("warning: no OS keyring; token stored in a 0600 file", err=True)
|
|
114
|
+
click.echo(f"logged in to {where} as {sanitize(str(who.get('email', 'unknown')))}")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@click.command("logout", help="Remove the stored token for the selected environment.")
|
|
118
|
+
@click.pass_context
|
|
119
|
+
def logout(ctx: click.Context) -> None:
|
|
120
|
+
state = state_of(ctx)
|
|
121
|
+
env, _ = state.select()
|
|
122
|
+
tenant = state.tenant(env)
|
|
123
|
+
where = credential_key(env.name, tenant)
|
|
124
|
+
try:
|
|
125
|
+
found = find_credential(state.store(), env, tenant)
|
|
126
|
+
where = found[0] if found else where
|
|
127
|
+
removed = state.store().delete(where)
|
|
128
|
+
except CredentialError as exc:
|
|
129
|
+
raise CliError(str(exc)) from None
|
|
130
|
+
if not removed:
|
|
131
|
+
raise CliError(f"no stored token for {where}")
|
|
132
|
+
click.echo(f"logged out of {where}")
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
@click.command("whoami", help="Show the identity the selected environment sees.")
|
|
136
|
+
@click.pass_context
|
|
137
|
+
def whoami(ctx: click.Context) -> None:
|
|
138
|
+
state = state_of(ctx)
|
|
139
|
+
env, explicit = state.select()
|
|
140
|
+
token = state.token(env, explicit)
|
|
141
|
+
try:
|
|
142
|
+
with state.client(env, token) as client:
|
|
143
|
+
who = fetch_whoami(client)
|
|
144
|
+
except ApiError as exc:
|
|
145
|
+
hint = ""
|
|
146
|
+
if exc.status in AUTH_STATUSES:
|
|
147
|
+
hint = f"\nhint: run `{login_hint(state.cli, env, state.tenant(env))}`"
|
|
148
|
+
raise CliError(f"whoami failed: {exc.message}{hint}", exit_code_for(exc.status)) from None
|
|
149
|
+
if env.protected:
|
|
150
|
+
click.echo("*** PROTECTED ENVIRONMENT ***")
|
|
151
|
+
scopes = who.get("scopes")
|
|
152
|
+
rows = [
|
|
153
|
+
("user", who.get("email")),
|
|
154
|
+
("auth", who.get("auth_kind")),
|
|
155
|
+
("scopes", ", ".join(scopes) if isinstance(scopes, list) else "all"),
|
|
156
|
+
(
|
|
157
|
+
"tenant",
|
|
158
|
+
describe_tenant(who.get("tenant_slug"), who.get("tenant_id"))
|
|
159
|
+
if who.get("tenant_id")
|
|
160
|
+
else "-",
|
|
161
|
+
),
|
|
162
|
+
("env", env.name),
|
|
163
|
+
("url", env.url),
|
|
164
|
+
]
|
|
165
|
+
for label, value in rows:
|
|
166
|
+
click.echo(f"{label + ':':8}{sanitize(str(value))}")
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"""``doctor``: check the setup end to end."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import click
|
|
6
|
+
|
|
7
|
+
from simple_module_remote.commands.runtime import (
|
|
8
|
+
WHOAMI_PATH,
|
|
9
|
+
AppState,
|
|
10
|
+
CliError,
|
|
11
|
+
fetch_whoami,
|
|
12
|
+
state_of,
|
|
13
|
+
)
|
|
14
|
+
from simple_module_remote.commands.schema_cmd import schema_info
|
|
15
|
+
from simple_module_remote.config.credentials import (
|
|
16
|
+
describe_tenant,
|
|
17
|
+
is_single_tenant,
|
|
18
|
+
login_hint,
|
|
19
|
+
tenant_matches,
|
|
20
|
+
token_env_var,
|
|
21
|
+
)
|
|
22
|
+
from simple_module_remote.config.environments import Environment
|
|
23
|
+
from simple_module_remote.config.paths import env_var_name
|
|
24
|
+
from simple_module_remote.http.errors import AUTH_STATUSES, ApiError, UnsafePathError
|
|
25
|
+
from simple_module_remote.http.safety import validate_base_url
|
|
26
|
+
from simple_module_remote.output.sanitize import sanitize
|
|
27
|
+
|
|
28
|
+
__all__ = ["doctor"]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class _Report:
|
|
32
|
+
def __init__(self) -> None:
|
|
33
|
+
self.failed = False
|
|
34
|
+
|
|
35
|
+
def ok(self, name: str, detail: str = "") -> None:
|
|
36
|
+
click.echo(f"ok {name}" + (f": {sanitize(detail)}" if detail else ""))
|
|
37
|
+
|
|
38
|
+
def fail(self, name: str, detail: str, fix: str) -> None:
|
|
39
|
+
self.failed = True
|
|
40
|
+
click.echo(f"FAIL {name}: {sanitize(detail)}")
|
|
41
|
+
click.echo(f" fix: {fix}")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _select(state: AppState, report: _Report) -> tuple[Environment, bool] | None:
|
|
45
|
+
try:
|
|
46
|
+
env, explicit = state.select()
|
|
47
|
+
except CliError as exc:
|
|
48
|
+
known = sorted(state.config().envs)
|
|
49
|
+
fix = f"{state.cli} env add <name> --url URL"
|
|
50
|
+
if known:
|
|
51
|
+
use = "local" if "local" in known else known[0]
|
|
52
|
+
fix = f"{state.cli} env use {use} (known: {', '.join(known)}), or {fix}"
|
|
53
|
+
report.fail("environment", exc.message.splitlines()[0], fix)
|
|
54
|
+
return None
|
|
55
|
+
report.ok("environment", f"{env.name} ({env.url})")
|
|
56
|
+
return env, explicit
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _check_url(state: AppState, env: Environment, report: _Report) -> bool:
|
|
60
|
+
try:
|
|
61
|
+
validate_base_url(env.url)
|
|
62
|
+
except UnsafePathError as exc:
|
|
63
|
+
report.fail("url", str(exc), f"{state.cli} env add {env.name} --url https://...")
|
|
64
|
+
return False
|
|
65
|
+
report.ok("url", "https or loopback")
|
|
66
|
+
return True
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _check_reachable(state: AppState, env: Environment, report: _Report) -> None:
|
|
70
|
+
try:
|
|
71
|
+
with state.client(env, None) as client:
|
|
72
|
+
response = client.request("GET", WHOAMI_PATH)
|
|
73
|
+
shown = "auth required" if response.status_code in AUTH_STATUSES else "ok"
|
|
74
|
+
report.ok(f"reachable ({shown})", f"server answered HTTP {response.status_code}")
|
|
75
|
+
except ApiError as exc:
|
|
76
|
+
report.fail("reachable", exc.message, "check the URL, your network and VPN")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _check_identity(state: AppState, env: Environment, explicit: bool, report: _Report) -> None:
|
|
80
|
+
wanted = state.tenant(env)
|
|
81
|
+
try:
|
|
82
|
+
token = state.token(env, explicit)
|
|
83
|
+
except CliError as exc:
|
|
84
|
+
var = token_env_var(state.cli)
|
|
85
|
+
if state.environ.get(var) and not explicit:
|
|
86
|
+
fix = (
|
|
87
|
+
f"pass --env {env.name} or set {env_var_name(state.cli)}={env.name} "
|
|
88
|
+
f"so {var} is used"
|
|
89
|
+
)
|
|
90
|
+
elif "chmod" in exc.message:
|
|
91
|
+
fix = exc.message[exc.message.index("run `") + 5 :].split("`")[0]
|
|
92
|
+
else:
|
|
93
|
+
fix = (
|
|
94
|
+
f"create a token at {env.url.rstrip('/')}/api-tokens/, then "
|
|
95
|
+
f"{login_hint(state.cli, env, wanted)} (or --token-stdin)"
|
|
96
|
+
)
|
|
97
|
+
report.fail("credentials", exc.message, fix)
|
|
98
|
+
return
|
|
99
|
+
var = token_env_var(state.cli)
|
|
100
|
+
report.ok(
|
|
101
|
+
"credentials",
|
|
102
|
+
f"token from {var}" if state.environ.get(var) else "present and bound to this origin",
|
|
103
|
+
)
|
|
104
|
+
try:
|
|
105
|
+
with state.client(env, token) as client:
|
|
106
|
+
who = fetch_whoami(client)
|
|
107
|
+
except ApiError as exc:
|
|
108
|
+
fix = (
|
|
109
|
+
"check the URL, your network and VPN"
|
|
110
|
+
if exc.status == 0
|
|
111
|
+
else login_hint(state.cli, env, wanted)
|
|
112
|
+
)
|
|
113
|
+
report.fail("whoami", exc.message, fix)
|
|
114
|
+
return
|
|
115
|
+
report.ok("whoami", str(who.get("email")))
|
|
116
|
+
if wanted is None:
|
|
117
|
+
pinned = who.get("tenant_id")
|
|
118
|
+
report.ok(
|
|
119
|
+
"tenant",
|
|
120
|
+
f"token tenant {describe_tenant(who.get('tenant_slug'), pinned)}"
|
|
121
|
+
if pinned
|
|
122
|
+
else "no tenant selected",
|
|
123
|
+
)
|
|
124
|
+
elif is_single_tenant(who):
|
|
125
|
+
report.ok("tenant", "single-tenant server; --tenant is ignored")
|
|
126
|
+
elif tenant_matches(wanted, who):
|
|
127
|
+
report.ok(
|
|
128
|
+
"tenant",
|
|
129
|
+
f"token is pinned to {describe_tenant(who.get('tenant_slug'), who.get('tenant_id'))}",
|
|
130
|
+
)
|
|
131
|
+
else:
|
|
132
|
+
report.fail(
|
|
133
|
+
"tenant",
|
|
134
|
+
f"token is pinned to {describe_tenant(who.get('tenant_slug'), who.get('tenant_id'))}, "
|
|
135
|
+
f"not {wanted}",
|
|
136
|
+
login_hint(state.cli, env, wanted),
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
@click.command("doctor", help="Check environment, connectivity, credentials and schema.")
|
|
141
|
+
@click.pass_context
|
|
142
|
+
def doctor(ctx: click.Context) -> None:
|
|
143
|
+
state = state_of(ctx)
|
|
144
|
+
report = _Report()
|
|
145
|
+
chosen = _select(state, report)
|
|
146
|
+
if chosen is not None:
|
|
147
|
+
env, explicit = chosen
|
|
148
|
+
if _check_url(state, env, report):
|
|
149
|
+
_check_reachable(state, env, report)
|
|
150
|
+
_check_identity(state, env, explicit, report)
|
|
151
|
+
report.ok(
|
|
152
|
+
"schema",
|
|
153
|
+
f"{state.schema_source} {state.schema_path} (version {schema_info(state.root)})"
|
|
154
|
+
+ (f"; live: {state.schema_note}" if state.schema_note else ""),
|
|
155
|
+
)
|
|
156
|
+
if report.failed:
|
|
157
|
+
ctx.exit(1)
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"""``env`` commands: manage named environments."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import click
|
|
6
|
+
|
|
7
|
+
from simple_module_remote.commands.runtime import AppState, CliError, state_of
|
|
8
|
+
from simple_module_remote.config.credentials import CredentialDeleteError
|
|
9
|
+
from simple_module_remote.config.environments import (
|
|
10
|
+
Config,
|
|
11
|
+
Environment,
|
|
12
|
+
save_config,
|
|
13
|
+
validate_env_name,
|
|
14
|
+
validate_tenant,
|
|
15
|
+
)
|
|
16
|
+
from simple_module_remote.http.safety import normalize_url, validate_base_url
|
|
17
|
+
from simple_module_remote.output.sanitize import sanitize
|
|
18
|
+
|
|
19
|
+
__all__ = ["env_group"]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _describe(env: Environment) -> str:
|
|
23
|
+
extras = []
|
|
24
|
+
if env.tenant:
|
|
25
|
+
extras.append(f"tenant={env.tenant}")
|
|
26
|
+
if env.protected:
|
|
27
|
+
extras.append("PROTECTED")
|
|
28
|
+
line = f"{env.name} {env.url}" + (f" [{', '.join(extras)}]" if extras else "")
|
|
29
|
+
return sanitize(line)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _known(state: AppState, config: Config, name: str) -> Environment:
|
|
33
|
+
found = config.envs.get(name)
|
|
34
|
+
if found is None:
|
|
35
|
+
raise CliError(f"unknown environment {name!r}: run `{state.cli} env list`")
|
|
36
|
+
return found
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@click.group("env", help="Manage named environments.")
|
|
40
|
+
def env_group() -> None:
|
|
41
|
+
pass
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@env_group.command("list", help="List environments; the current one is marked with *.")
|
|
45
|
+
@click.pass_context
|
|
46
|
+
def list_envs(ctx: click.Context) -> None:
|
|
47
|
+
config = state_of(ctx).config()
|
|
48
|
+
for name in sorted(config.envs):
|
|
49
|
+
marker = "*" if name == config.current else " "
|
|
50
|
+
click.echo(f"{marker} {_describe(config.envs[name])}")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@env_group.command("add", help="Add or replace an environment.")
|
|
54
|
+
@click.argument("name")
|
|
55
|
+
@click.option(
|
|
56
|
+
"--url",
|
|
57
|
+
default=None,
|
|
58
|
+
help="Base URL of the app, e.g. https://app.example.com (required for a new environment).",
|
|
59
|
+
)
|
|
60
|
+
@click.option("--tenant", default=None, help="Default tenant (kept when omitted).")
|
|
61
|
+
@click.option(
|
|
62
|
+
"--protected/--no-protected",
|
|
63
|
+
default=None,
|
|
64
|
+
help="Confirm before mutating calls (kept when omitted).",
|
|
65
|
+
)
|
|
66
|
+
@click.pass_context
|
|
67
|
+
def add_env(
|
|
68
|
+
ctx: click.Context, name: str, url: str | None, tenant: str | None, protected: bool | None
|
|
69
|
+
) -> None:
|
|
70
|
+
state = state_of(ctx)
|
|
71
|
+
with state.guard():
|
|
72
|
+
validate_env_name(name)
|
|
73
|
+
if url is not None:
|
|
74
|
+
url = normalize_url(validate_base_url(url))
|
|
75
|
+
if tenant:
|
|
76
|
+
validate_tenant(tenant)
|
|
77
|
+
config = state.config()
|
|
78
|
+
existing = config.envs.get(name)
|
|
79
|
+
url_given = url is not None
|
|
80
|
+
if url is None:
|
|
81
|
+
if existing is None:
|
|
82
|
+
raise CliError(f"--url is required to add the new environment {name!r}")
|
|
83
|
+
url = existing.url
|
|
84
|
+
changed = existing is not None and (
|
|
85
|
+
url != existing.url or (tenant is not None and tenant != existing.tenant)
|
|
86
|
+
)
|
|
87
|
+
# Only what was passed changes; the rest comes from the existing (or default) environment.
|
|
88
|
+
overrides = dict(config.overrides.get(name, {}))
|
|
89
|
+
if url_given or existing is None: # an inherited url stays inherited, not copied
|
|
90
|
+
overrides["url"] = url
|
|
91
|
+
if tenant is not None:
|
|
92
|
+
overrides["tenant"] = tenant
|
|
93
|
+
if protected is not None:
|
|
94
|
+
overrides["protected"] = protected
|
|
95
|
+
config.envs[name] = Environment(
|
|
96
|
+
name=name,
|
|
97
|
+
url=url,
|
|
98
|
+
tenant=tenant if tenant is not None else (existing.tenant if existing else None),
|
|
99
|
+
protected=protected
|
|
100
|
+
if protected is not None
|
|
101
|
+
else (existing.protected if existing else False),
|
|
102
|
+
)
|
|
103
|
+
config.overrides[name] = overrides
|
|
104
|
+
config.user_envs.add(name)
|
|
105
|
+
with state.guard():
|
|
106
|
+
save_config(state.cli, config)
|
|
107
|
+
click.echo(f"{'updated' if existing else 'added'} environment {name} ({sanitize(url)})")
|
|
108
|
+
with state.guard():
|
|
109
|
+
has_login = changed and bool(state.store().keys_for_env(name))
|
|
110
|
+
if has_login:
|
|
111
|
+
click.echo(
|
|
112
|
+
f"warning: the stored login for {name} was issued for the old url/tenant and may "
|
|
113
|
+
f"no longer apply; run `{state.cli} --env {name} login --token-stdin` again",
|
|
114
|
+
err=True,
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
@env_group.command("use", help="Make an environment the current one.")
|
|
119
|
+
@click.argument("name")
|
|
120
|
+
@click.pass_context
|
|
121
|
+
def use_env(ctx: click.Context, name: str) -> None:
|
|
122
|
+
state = state_of(ctx)
|
|
123
|
+
config = state.config()
|
|
124
|
+
_known(state, config, name)
|
|
125
|
+
config.current = name
|
|
126
|
+
with state.guard():
|
|
127
|
+
save_config(state.cli, config)
|
|
128
|
+
click.echo(f"current environment: {name}")
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
@env_group.command("remove", help="Remove an environment you added.")
|
|
132
|
+
@click.argument("name")
|
|
133
|
+
@click.pass_context
|
|
134
|
+
def remove_env(ctx: click.Context, name: str) -> None:
|
|
135
|
+
state = state_of(ctx)
|
|
136
|
+
config = state.config()
|
|
137
|
+
if name not in config.user_envs:
|
|
138
|
+
known = (
|
|
139
|
+
"is defined by the project defaults and cannot be removed"
|
|
140
|
+
if (name in config.envs)
|
|
141
|
+
else "does not exist"
|
|
142
|
+
)
|
|
143
|
+
raise CliError(f"environment {name!r} {known}")
|
|
144
|
+
was_current = config.current == name
|
|
145
|
+
# Tenants the config has seen (before this env is dropped): legacy keyring keys to try.
|
|
146
|
+
tenants = sorted(
|
|
147
|
+
{e.tenant for e in config.envs.values() if e.tenant}
|
|
148
|
+
| ({state.flag_tenant} if state.flag_tenant else set())
|
|
149
|
+
)
|
|
150
|
+
# Logins first: if one cannot be deleted the environment stays, so the removal can be retried.
|
|
151
|
+
with state.guard():
|
|
152
|
+
store = state.store()
|
|
153
|
+
try:
|
|
154
|
+
removed = store.delete_env(name, tenants)
|
|
155
|
+
except CredentialDeleteError as exc:
|
|
156
|
+
for key in exc.removed:
|
|
157
|
+
click.echo(f"removed stored login {key}")
|
|
158
|
+
raise CliError(
|
|
159
|
+
f"{exc}; environment {name!r} was kept: fix the credential store and run "
|
|
160
|
+
f"`{state.cli} env remove {name}` again"
|
|
161
|
+
) from None
|
|
162
|
+
config.user_envs.discard(name)
|
|
163
|
+
config.overrides.pop(name, None)
|
|
164
|
+
config.envs.pop(name, None)
|
|
165
|
+
if was_current:
|
|
166
|
+
config.current = None
|
|
167
|
+
with state.guard():
|
|
168
|
+
save_config(state.cli, config)
|
|
169
|
+
reset = name in state.config().envs # a project default of the same name remains
|
|
170
|
+
if reset:
|
|
171
|
+
click.echo(f"reset environment {name} to the project default")
|
|
172
|
+
else:
|
|
173
|
+
click.echo(f"removed environment {name}")
|
|
174
|
+
if not store.using_fallback:
|
|
175
|
+
click.echo(
|
|
176
|
+
"note: the OS keyring cannot be listed, so a login for a tenant this CLI never "
|
|
177
|
+
f"recorded may remain: `{state.cli} --env {name} --tenant T logout` removes one",
|
|
178
|
+
err=True,
|
|
179
|
+
)
|
|
180
|
+
if was_current:
|
|
181
|
+
click.echo("no environment is selected now: run `env use <name>`", err=True)
|
|
182
|
+
for key in removed:
|
|
183
|
+
click.echo(f"removed stored login {key}")
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
@env_group.command("show", help="Show one environment (default: the current one).")
|
|
187
|
+
@click.argument("name", required=False)
|
|
188
|
+
@click.pass_context
|
|
189
|
+
def show_env(ctx: click.Context, name: str | None) -> None:
|
|
190
|
+
state = state_of(ctx)
|
|
191
|
+
if name is None:
|
|
192
|
+
env, _ = state.select()
|
|
193
|
+
else:
|
|
194
|
+
env = _known(state, state.config(), name)
|
|
195
|
+
click.echo(f"name: {sanitize(env.name)}")
|
|
196
|
+
click.echo(f"url: {sanitize(env.url)}")
|
|
197
|
+
click.echo(f"tenant: {sanitize(env.tenant or '-')}")
|
|
198
|
+
click.echo(f"protected: {'yes' if env.protected else 'no'}")
|