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,296 @@
|
|
|
1
|
+
"""Credentials bound to the server origin they were issued for."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
from collections.abc import Collection, Generator, Mapping
|
|
6
|
+
from contextlib import contextmanager
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import Protocol
|
|
9
|
+
|
|
10
|
+
import keyring
|
|
11
|
+
import keyring.backends.fail
|
|
12
|
+
import keyring.errors
|
|
13
|
+
|
|
14
|
+
from simple_module_remote.config._file_store import (
|
|
15
|
+
ORIGIN_FIELD,
|
|
16
|
+
PIN_FIELDS,
|
|
17
|
+
TOKEN_FIELD,
|
|
18
|
+
FileStore,
|
|
19
|
+
FileStoreError,
|
|
20
|
+
open_service_lock,
|
|
21
|
+
)
|
|
22
|
+
from simple_module_remote.config.environments import Environment
|
|
23
|
+
from simple_module_remote.config.paths import env_prefix
|
|
24
|
+
|
|
25
|
+
TOKEN_ENV_SUFFIX = "_TOKEN"
|
|
26
|
+
MASK = "***"
|
|
27
|
+
# Keyring backends cannot enumerate, so the keys stored are tracked under this name;
|
|
28
|
+
# environment names are [a-z0-9-], so it never collides with a credential key.
|
|
29
|
+
INDEX_KEY = "~index"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class CredentialError(Exception):
|
|
33
|
+
"""Raised for missing or unusable credentials; the message never contains a token."""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class CredentialDeleteError(CredentialError):
|
|
37
|
+
"""Some stored logins could not be deleted; ``removed`` were."""
|
|
38
|
+
|
|
39
|
+
def __init__(self, failed: list[str], removed: list[str]) -> None:
|
|
40
|
+
self.failed, self.removed = failed, removed
|
|
41
|
+
super().__init__(f"could not delete the stored login(s): {', '.join(failed)}")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class KeyringBackend(Protocol):
|
|
45
|
+
def get_password(self, service: str, username: str, /) -> str | None: ...
|
|
46
|
+
def set_password(self, service: str, username: str, password: str, /) -> None: ...
|
|
47
|
+
def delete_password(self, service: str, username: str, /) -> None: ...
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True, repr=False)
|
|
51
|
+
class StoredCredential:
|
|
52
|
+
token: str
|
|
53
|
+
origin: str
|
|
54
|
+
# The tenant the token was pinned to when it was stored (from whoami at login).
|
|
55
|
+
tenant_id: str | None = None
|
|
56
|
+
tenant_slug: str | None = None
|
|
57
|
+
|
|
58
|
+
def __repr__(self) -> str:
|
|
59
|
+
return f"StoredCredential(token={MASK!r}, origin={self.origin!r})"
|
|
60
|
+
|
|
61
|
+
def pins(self) -> dict[str, str]:
|
|
62
|
+
return {f: v for f in PIN_FIELDS if (v := getattr(self, f)) is not None}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def validate_token(token: str, *, source: str) -> str:
|
|
66
|
+
"""``token`` when it is printable ASCII without whitespace; never echoes the value."""
|
|
67
|
+
if not token or not all(0x21 <= ord(ch) <= 0x7E for ch in token):
|
|
68
|
+
raise CredentialError(
|
|
69
|
+
f"{source} is not a valid token: it must be printable ASCII with no spaces or "
|
|
70
|
+
"control characters"
|
|
71
|
+
)
|
|
72
|
+
return token
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def describe_tenant(slug: object, tenant_id: object) -> str:
|
|
76
|
+
"""``slug (id)`` for a tenant, or just the id when no slug is known."""
|
|
77
|
+
if slug and tenant_id:
|
|
78
|
+
return f"{slug} ({tenant_id})"
|
|
79
|
+
return str(slug or tenant_id or "none")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
SINGLE_TENANT_ID = "default" # what a single-tenant server reports as the tenant id
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def is_single_tenant(who: Mapping[str, object]) -> bool:
|
|
86
|
+
"""Whether whoami describes a single-tenant server (no real tenant to select)."""
|
|
87
|
+
return who.get("tenant_id") == SINGLE_TENANT_ID and not who.get("tenant_slug")
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def tenant_matches(wanted: str, who: Mapping[str, object]) -> bool:
|
|
91
|
+
"""Whether ``wanted`` (a slug or an id) names the tenant a token is pinned to."""
|
|
92
|
+
return wanted in (who.get("tenant_id"), who.get("tenant_slug"))
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def credential_key(env: str, tenant: str | None) -> str:
|
|
96
|
+
return f"{env}/{tenant}" if tenant else env
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _keyring_usable() -> bool:
|
|
100
|
+
backend = keyring.get_keyring()
|
|
101
|
+
if isinstance(backend, keyring.backends.fail.Keyring):
|
|
102
|
+
return False
|
|
103
|
+
return getattr(backend, "priority", 0) >= 1
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def pin_kwargs(data: Mapping[str, object]) -> dict[str, str | None]:
|
|
107
|
+
return {f: v if isinstance(v := data.get(f), str) else None for f in PIN_FIELDS}
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class CredentialStore:
|
|
111
|
+
def __init__(self, cli: str, *, backend: KeyringBackend | None = None) -> None:
|
|
112
|
+
self._service = cli
|
|
113
|
+
self._file: FileStore | None = None
|
|
114
|
+
self._lock_depth = 0
|
|
115
|
+
self._backend: KeyringBackend | None = None
|
|
116
|
+
if backend is None:
|
|
117
|
+
if _keyring_usable():
|
|
118
|
+
self._backend = keyring.get_keyring()
|
|
119
|
+
elif not isinstance(backend, keyring.backends.fail.Keyring):
|
|
120
|
+
self._backend = backend
|
|
121
|
+
|
|
122
|
+
@contextmanager
|
|
123
|
+
def _service_lock(self) -> Generator[None]:
|
|
124
|
+
"""Serialise keyring credential + index updates across processes (flock on a lock file).
|
|
125
|
+
|
|
126
|
+
Reentrant within this store. A no-op where ``fcntl`` is missing (Windows), where
|
|
127
|
+
concurrent logins can still lose an index entry; the file backend has its own lock.
|
|
128
|
+
"""
|
|
129
|
+
if self._lock_depth or self._backend is None:
|
|
130
|
+
self._lock_depth += 1
|
|
131
|
+
try:
|
|
132
|
+
yield
|
|
133
|
+
finally:
|
|
134
|
+
self._lock_depth -= 1
|
|
135
|
+
return
|
|
136
|
+
try:
|
|
137
|
+
fd = open_service_lock(self._service)
|
|
138
|
+
except FileStoreError as exc:
|
|
139
|
+
raise CredentialError(str(exc)) from None
|
|
140
|
+
self._lock_depth += 1
|
|
141
|
+
try:
|
|
142
|
+
yield
|
|
143
|
+
finally:
|
|
144
|
+
self._lock_depth -= 1
|
|
145
|
+
if fd is not None:
|
|
146
|
+
os.close(fd) # closing releases the lock
|
|
147
|
+
|
|
148
|
+
@property
|
|
149
|
+
def using_fallback(self) -> bool:
|
|
150
|
+
return self._backend is None
|
|
151
|
+
|
|
152
|
+
def _file_store(self) -> FileStore | None:
|
|
153
|
+
"""The fallback file store, built on first use (raises FileStoreError if unsupported)."""
|
|
154
|
+
if self._backend is not None:
|
|
155
|
+
return None
|
|
156
|
+
if self._file is None:
|
|
157
|
+
self._file = FileStore(self._service)
|
|
158
|
+
return self._file
|
|
159
|
+
|
|
160
|
+
def _require_backend(self) -> KeyringBackend:
|
|
161
|
+
if self._backend is None:
|
|
162
|
+
raise CredentialError("no credential backend is available")
|
|
163
|
+
return self._backend
|
|
164
|
+
|
|
165
|
+
def get(self, key: str) -> StoredCredential | None:
|
|
166
|
+
try:
|
|
167
|
+
if (file := self._file_store()) is not None:
|
|
168
|
+
found = file.get(key)
|
|
169
|
+
if not found:
|
|
170
|
+
return None
|
|
171
|
+
return StoredCredential(
|
|
172
|
+
found[TOKEN_FIELD], found[ORIGIN_FIELD], **pin_kwargs(found)
|
|
173
|
+
)
|
|
174
|
+
return self._keyring_get(key)
|
|
175
|
+
except FileStoreError as exc:
|
|
176
|
+
raise CredentialError(str(exc)) from None
|
|
177
|
+
except keyring.errors.KeyringError:
|
|
178
|
+
raise CredentialError("the OS keyring could not be read") from None
|
|
179
|
+
|
|
180
|
+
def _keyring_get(self, key: str) -> StoredCredential | None:
|
|
181
|
+
raw = self._require_backend().get_password(self._service, key)
|
|
182
|
+
if raw is None:
|
|
183
|
+
return None
|
|
184
|
+
try:
|
|
185
|
+
data = json.loads(raw)
|
|
186
|
+
token, origin = data[TOKEN_FIELD], data[ORIGIN_FIELD]
|
|
187
|
+
except (ValueError, KeyError, TypeError):
|
|
188
|
+
raise CredentialError(f"stored credential {key!r} is corrupt; log in again") from None
|
|
189
|
+
if not isinstance(token, str) or not isinstance(origin, str):
|
|
190
|
+
raise CredentialError(f"stored credential {key!r} is corrupt; log in again")
|
|
191
|
+
return StoredCredential(token=token, origin=origin, **pin_kwargs(data))
|
|
192
|
+
|
|
193
|
+
def _index(self) -> list[str]:
|
|
194
|
+
raw = self._require_backend().get_password(self._service, INDEX_KEY)
|
|
195
|
+
try:
|
|
196
|
+
data = json.loads(raw) if raw else []
|
|
197
|
+
except ValueError:
|
|
198
|
+
return []
|
|
199
|
+
return [k for k in data if isinstance(k, str)] if isinstance(data, list) else []
|
|
200
|
+
|
|
201
|
+
def _update_index(self, *, add: str | None = None, remove: str | None = None) -> None:
|
|
202
|
+
"""Change the key index. The keyring has no lock, so re-read right before writing and
|
|
203
|
+
merge: a concurrent writer's entry survives unless this call removes it."""
|
|
204
|
+
backend = self._require_backend()
|
|
205
|
+
keys = {k for k in self._index() if k != remove}
|
|
206
|
+
if add is not None:
|
|
207
|
+
keys.add(add)
|
|
208
|
+
if keys:
|
|
209
|
+
backend.set_password(self._service, INDEX_KEY, json.dumps(sorted(keys)))
|
|
210
|
+
elif backend.get_password(self._service, INDEX_KEY) is not None:
|
|
211
|
+
backend.delete_password(self._service, INDEX_KEY)
|
|
212
|
+
|
|
213
|
+
def put(self, key: str, cred: StoredCredential) -> None:
|
|
214
|
+
try:
|
|
215
|
+
if (file := self._file_store()) is not None:
|
|
216
|
+
file.put(key, cred.token, cred.origin, cred.pins())
|
|
217
|
+
else:
|
|
218
|
+
payload = json.dumps(
|
|
219
|
+
{TOKEN_FIELD: cred.token, ORIGIN_FIELD: cred.origin, **cred.pins()}
|
|
220
|
+
)
|
|
221
|
+
backend = self._require_backend()
|
|
222
|
+
with self._service_lock():
|
|
223
|
+
# Index first: a failed credential write leaves a harmless stale entry,
|
|
224
|
+
# never an orphaned credential nobody can enumerate.
|
|
225
|
+
self._update_index(add=key)
|
|
226
|
+
backend.set_password(self._service, key, payload)
|
|
227
|
+
except FileStoreError as exc:
|
|
228
|
+
raise CredentialError(str(exc)) from None
|
|
229
|
+
except keyring.errors.KeyringError:
|
|
230
|
+
raise CredentialError("the OS keyring could not be written") from None
|
|
231
|
+
|
|
232
|
+
def keys_for_env(self, env: str, tenants: Collection[str] = ()) -> list[str]:
|
|
233
|
+
"""The stored logins of ``env``: its own key and every ``env/<tenant>`` key.
|
|
234
|
+
|
|
235
|
+
A keyring cannot be listed, so its keys come from the index plus the legacy keys
|
|
236
|
+
``env`` and ``env/<tenant>`` for each of ``tenants`` (those the config has seen).
|
|
237
|
+
"""
|
|
238
|
+
try:
|
|
239
|
+
if (file := self._file_store()) is not None:
|
|
240
|
+
candidates = file.keys()
|
|
241
|
+
else:
|
|
242
|
+
backend = self._require_backend()
|
|
243
|
+
guesses = [env, *(f"{env}/{t}" for t in tenants), *self._index()]
|
|
244
|
+
candidates = [k for k in guesses if backend.get_password(self._service, k)]
|
|
245
|
+
except FileStoreError as exc:
|
|
246
|
+
raise CredentialError(str(exc)) from None
|
|
247
|
+
except keyring.errors.KeyringError:
|
|
248
|
+
raise CredentialError("the OS keyring could not be read") from None
|
|
249
|
+
return [k for k in dict.fromkeys(candidates) if k == env or k.startswith(env + "/")]
|
|
250
|
+
|
|
251
|
+
def delete_env(self, env: str, tenants: Collection[str] = ()) -> list[str]:
|
|
252
|
+
"""Delete every credential of ``env`` (``env`` and ``env/<tenant>``); the keys removed."""
|
|
253
|
+
removed: list[str] = []
|
|
254
|
+
failed: list[str] = []
|
|
255
|
+
with self._service_lock():
|
|
256
|
+
for key in self.keys_for_env(env, tenants):
|
|
257
|
+
try:
|
|
258
|
+
if self.delete(key):
|
|
259
|
+
removed.append(key)
|
|
260
|
+
except CredentialError:
|
|
261
|
+
failed.append(key)
|
|
262
|
+
if failed:
|
|
263
|
+
raise CredentialDeleteError(failed, removed)
|
|
264
|
+
return removed
|
|
265
|
+
|
|
266
|
+
def delete(self, key: str) -> bool:
|
|
267
|
+
try:
|
|
268
|
+
if (file := self._file_store()) is not None:
|
|
269
|
+
return file.delete(key)
|
|
270
|
+
backend = self._require_backend()
|
|
271
|
+
with self._service_lock():
|
|
272
|
+
if backend.get_password(self._service, key) is None:
|
|
273
|
+
self._update_index(remove=key) # a stale index entry
|
|
274
|
+
return False
|
|
275
|
+
try:
|
|
276
|
+
backend.delete_password(self._service, key)
|
|
277
|
+
except keyring.errors.PasswordDeleteError:
|
|
278
|
+
raise CredentialError(f"the OS keyring refused to delete {key!r}") from None
|
|
279
|
+
self._update_index(remove=key) # only after the deletion succeeded
|
|
280
|
+
return True
|
|
281
|
+
except FileStoreError as exc:
|
|
282
|
+
raise CredentialError(str(exc)) from None
|
|
283
|
+
except keyring.errors.KeyringError:
|
|
284
|
+
raise CredentialError("the OS keyring could not be updated") from None
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def token_env_var(cli: str) -> str:
|
|
288
|
+
"""The environment variable that supplies a token for *cli*."""
|
|
289
|
+
return env_prefix(cli) + TOKEN_ENV_SUFFIX
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def login_hint(cli: str, env: Environment, tenant: str | None) -> str:
|
|
293
|
+
"""The command that stores a token; root options (--env, --tenant) precede the subcommand."""
|
|
294
|
+
hint = f"{cli} --env {env.name}"
|
|
295
|
+
hint = f"{hint} --tenant {tenant}" if tenant else hint
|
|
296
|
+
return f"{hint} login --token"
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
"""Named environments: load, merge defaults, save, and pick one."""
|
|
2
|
+
|
|
3
|
+
import contextlib
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
import tomllib
|
|
7
|
+
from collections.abc import Mapping
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
import tomli_w
|
|
12
|
+
|
|
13
|
+
from simple_module_remote.config.paths import config_dir, env_url_var_name, env_var_name
|
|
14
|
+
from simple_module_remote.http.errors import UnsafePathError
|
|
15
|
+
from simple_module_remote.http.safety import normalize_origin, normalize_url, validate_base_url
|
|
16
|
+
from simple_module_remote.output.reasons import os_reason
|
|
17
|
+
|
|
18
|
+
CONFIG_FILENAME = "config.toml"
|
|
19
|
+
ENV_NAME_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,39}$")
|
|
20
|
+
MAX_TENANT_LEN = 128
|
|
21
|
+
ENV_TABLE = "env"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class ConfigError(Exception):
|
|
25
|
+
"""Raised for unusable configuration; the message is safe to show."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def validate_env_name(name: str) -> str:
|
|
29
|
+
if not ENV_NAME_RE.fullmatch(name):
|
|
30
|
+
raise ConfigError(
|
|
31
|
+
f"invalid environment name {name!r}: 1-40 lowercase letters, digits or '-', "
|
|
32
|
+
"starting with a letter or digit"
|
|
33
|
+
)
|
|
34
|
+
return name
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def validate_tenant(tenant: str) -> str:
|
|
38
|
+
"""A tenant slug or id: printable, no whitespace, bounded."""
|
|
39
|
+
if (
|
|
40
|
+
not tenant
|
|
41
|
+
or len(tenant) > MAX_TENANT_LEN
|
|
42
|
+
or not tenant.isprintable()
|
|
43
|
+
or any(ch.isspace() for ch in tenant)
|
|
44
|
+
):
|
|
45
|
+
raise ConfigError(
|
|
46
|
+
f"invalid tenant {tenant!r}: up to {MAX_TENANT_LEN} printable characters, no spaces"
|
|
47
|
+
)
|
|
48
|
+
return tenant
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class Environment:
|
|
53
|
+
name: str
|
|
54
|
+
url: str
|
|
55
|
+
tenant: str | None = None
|
|
56
|
+
protected: bool = False
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def origin(self) -> str:
|
|
60
|
+
return normalize_origin(self.url)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass
|
|
64
|
+
class Config:
|
|
65
|
+
current: str | None = None
|
|
66
|
+
envs: dict[str, Environment] = field(default_factory=dict)
|
|
67
|
+
# Names the user file defines or edited; only these are written back.
|
|
68
|
+
user_envs: set[str] = field(default_factory=set)
|
|
69
|
+
# The keys the user file sets per environment; defaults fill in the rest, so only
|
|
70
|
+
# what the user passed is written back.
|
|
71
|
+
overrides: dict[str, dict[str, object]] = field(default_factory=dict)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _read(path: Path | None) -> dict[str, object]:
|
|
75
|
+
if path is None or not path.is_file():
|
|
76
|
+
return {}
|
|
77
|
+
try:
|
|
78
|
+
return tomllib.loads(path.read_text(encoding="utf-8"))
|
|
79
|
+
except (tomllib.TOMLDecodeError, OSError) as exc:
|
|
80
|
+
raise ConfigError(f"cannot read config {path}: {exc}") from exc
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _env_tables(data: dict[str, object]) -> dict[str, dict[str, object]]:
|
|
84
|
+
raw = data.get(ENV_TABLE, {})
|
|
85
|
+
if not isinstance(raw, dict):
|
|
86
|
+
return {}
|
|
87
|
+
return {validate_env_name(str(k)): v for k, v in raw.items() if isinstance(v, dict)}
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _build(name: str, table: dict[str, object], base: Environment | None) -> Environment:
|
|
91
|
+
url = table.get("url", base.url if base else None)
|
|
92
|
+
if not isinstance(url, str) or not url:
|
|
93
|
+
raise ConfigError(f"environment {name!r} has no url")
|
|
94
|
+
tenant = table.get("tenant", base.tenant if base else None)
|
|
95
|
+
if tenant is not None and not isinstance(tenant, str):
|
|
96
|
+
raise ConfigError(f"environment {name!r}: 'tenant' must be a string")
|
|
97
|
+
protected = table.get("protected", base.protected if base else False)
|
|
98
|
+
if not isinstance(protected, bool):
|
|
99
|
+
raise ConfigError(f"environment {name!r}: 'protected' must be true or false")
|
|
100
|
+
try:
|
|
101
|
+
checked = validate_base_url(url) # the string as written, before normalising strips parts
|
|
102
|
+
except UnsafePathError as exc:
|
|
103
|
+
raise ConfigError(f"environment {name!r}: {exc}") from None
|
|
104
|
+
return Environment(name=name, url=normalize_url(checked), tenant=tenant, protected=protected)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def user_config_path(cli: str) -> Path:
|
|
108
|
+
return config_dir(cli) / CONFIG_FILENAME
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def load_config(cli: str, defaults_path: Path | None) -> Config:
|
|
112
|
+
defaults = _read(defaults_path)
|
|
113
|
+
user = _read(user_config_path(cli))
|
|
114
|
+
envs: dict[str, Environment] = {}
|
|
115
|
+
for name, table in _env_tables(defaults).items():
|
|
116
|
+
envs[name] = _build(name, table, None)
|
|
117
|
+
user_tables = _env_tables(user)
|
|
118
|
+
for name, table in user_tables.items():
|
|
119
|
+
envs[name] = _build(name, table, envs.get(name))
|
|
120
|
+
current = user.get("current", defaults.get("current"))
|
|
121
|
+
return Config(
|
|
122
|
+
current=current if isinstance(current, str) else None,
|
|
123
|
+
envs=envs,
|
|
124
|
+
user_envs=set(user_tables),
|
|
125
|
+
overrides={name: dict(table) for name, table in user_tables.items()},
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _user_table(config: Config, env: Environment) -> dict[str, object]:
|
|
130
|
+
if env.name in config.overrides:
|
|
131
|
+
return dict(config.overrides[env.name])
|
|
132
|
+
table: dict[str, object] = {"url": env.url, "protected": env.protected}
|
|
133
|
+
if env.tenant is not None:
|
|
134
|
+
table["tenant"] = env.tenant
|
|
135
|
+
return table
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def save_config(cli: str, config: Config) -> None:
|
|
139
|
+
path = user_config_path(cli)
|
|
140
|
+
tables = {
|
|
141
|
+
name: _user_table(config, env)
|
|
142
|
+
for name in sorted(config.user_envs)
|
|
143
|
+
if (env := config.envs.get(name)) is not None
|
|
144
|
+
}
|
|
145
|
+
data: dict[str, object] = {}
|
|
146
|
+
if config.current is not None:
|
|
147
|
+
data["current"] = config.current
|
|
148
|
+
if tables:
|
|
149
|
+
data[ENV_TABLE] = tables
|
|
150
|
+
tmp = path.with_name(f"{path.name}.{os.getpid()}.tmp")
|
|
151
|
+
try:
|
|
152
|
+
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
153
|
+
tmp.write_text(tomli_w.dumps(data), encoding="utf-8")
|
|
154
|
+
tmp.replace(path)
|
|
155
|
+
except OSError as exc:
|
|
156
|
+
raise ConfigError(f"cannot write config {path}: {os_reason(exc)}") from None
|
|
157
|
+
finally:
|
|
158
|
+
with contextlib.suppress(OSError):
|
|
159
|
+
tmp.unlink(missing_ok=True)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def select_env(
|
|
163
|
+
config: Config, flag: str | None, environ: Mapping[str, str], cli: str
|
|
164
|
+
) -> tuple[Environment, bool]:
|
|
165
|
+
var = env_var_name(cli)
|
|
166
|
+
from_var = environ.get(var) or None
|
|
167
|
+
name, explicit = flag or from_var, bool(flag or from_var)
|
|
168
|
+
if not name:
|
|
169
|
+
name = config.current
|
|
170
|
+
if not name:
|
|
171
|
+
raise ConfigError(f"no environment selected: run `{cli} env use <name>` or pass --env")
|
|
172
|
+
env = config.envs.get(name)
|
|
173
|
+
url = environ.get(env_url_var_name(cli))
|
|
174
|
+
if env is None and explicit and url:
|
|
175
|
+
# CI: the runner has no config file; the URL variable defines the named environment.
|
|
176
|
+
try:
|
|
177
|
+
return Environment(name=validate_env_name(name), url=validate_base_url(url)), True
|
|
178
|
+
except UnsafePathError as exc:
|
|
179
|
+
raise ConfigError(f"{env_url_var_name(cli)}: {exc}") from None
|
|
180
|
+
if env is None:
|
|
181
|
+
known = ", ".join(sorted(config.envs)) or "none"
|
|
182
|
+
raise ConfigError(
|
|
183
|
+
f"unknown environment {name!r} (known: {known}): run `{cli} env add {name} --url ...` "
|
|
184
|
+
f"or set {env_url_var_name(cli)} to define it for this run"
|
|
185
|
+
)
|
|
186
|
+
return env, explicit
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Where a CLI keeps its config, and how its env vars are named."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def _base(var: str, fallback: str) -> Path:
|
|
8
|
+
value = os.environ.get(var)
|
|
9
|
+
return Path(value) if value else Path.home() / fallback
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def config_dir(cli: str) -> Path:
|
|
13
|
+
return _base("XDG_CONFIG_HOME", ".config") / cli
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def cache_dir(cli: str) -> Path:
|
|
17
|
+
"""Where *cli* caches downloaded data (the live schema): never credentials."""
|
|
18
|
+
return _base("XDG_CACHE_HOME", ".cache") / cli
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def env_prefix(cli: str) -> str:
|
|
22
|
+
return cli.upper().replace("-", "_")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def env_var_name(cli: str) -> str:
|
|
26
|
+
"""The environment variable that selects the environment for *cli*."""
|
|
27
|
+
return f"{env_prefix(cli)}_ENV"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def env_url_var_name(cli: str) -> str:
|
|
31
|
+
"""The variable that gives the URL of an environment that is not configured (CI)."""
|
|
32
|
+
return f"{env_prefix(cli)}_URL"
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""Pick the credential a request uses: the environment variable or a stored login."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
from typing import NamedTuple
|
|
5
|
+
|
|
6
|
+
from simple_module_remote.config.credentials import (
|
|
7
|
+
CredentialError,
|
|
8
|
+
CredentialStore,
|
|
9
|
+
StoredCredential,
|
|
10
|
+
credential_key,
|
|
11
|
+
describe_tenant,
|
|
12
|
+
is_single_tenant,
|
|
13
|
+
login_hint,
|
|
14
|
+
tenant_matches,
|
|
15
|
+
token_env_var,
|
|
16
|
+
validate_token,
|
|
17
|
+
)
|
|
18
|
+
from simple_module_remote.config.environments import Environment
|
|
19
|
+
from simple_module_remote.config.paths import env_var_name
|
|
20
|
+
from simple_module_remote.http.safety import normalize_origin
|
|
21
|
+
|
|
22
|
+
__all__ = ["ResolvedToken", "find_credential", "resolve_credential", "resolve_token"]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ResolvedToken(NamedTuple):
|
|
26
|
+
token: str
|
|
27
|
+
# How to name the tenant in output: the slug when the stored login knows it.
|
|
28
|
+
tenant_label: str | None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def find_credential(
|
|
32
|
+
store: CredentialStore, env: Environment, tenant: str | None
|
|
33
|
+
) -> tuple[str, StoredCredential] | None:
|
|
34
|
+
"""The stored login for ``env``/``tenant``, as ``(key, credential)``.
|
|
35
|
+
|
|
36
|
+
A single-tenant server ignores ``--tenant``, so its login lives in the plain
|
|
37
|
+
environment slot and is found from there when the tenant slot is empty.
|
|
38
|
+
"""
|
|
39
|
+
key = credential_key(env.name, tenant)
|
|
40
|
+
cred = store.get(key)
|
|
41
|
+
if cred is not None:
|
|
42
|
+
return key, cred
|
|
43
|
+
if tenant:
|
|
44
|
+
plain = store.get(env.name)
|
|
45
|
+
if plain is not None and is_single_tenant(plain.pins()):
|
|
46
|
+
return env.name, plain
|
|
47
|
+
return None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def resolve_credential(
|
|
51
|
+
store: CredentialStore,
|
|
52
|
+
env: Environment,
|
|
53
|
+
tenant: str | None,
|
|
54
|
+
environ: Mapping[str, str],
|
|
55
|
+
cli: str,
|
|
56
|
+
explicit: bool,
|
|
57
|
+
) -> ResolvedToken:
|
|
58
|
+
var = token_env_var(cli)
|
|
59
|
+
from_env = environ.get(var)
|
|
60
|
+
if from_env:
|
|
61
|
+
if explicit:
|
|
62
|
+
return ResolvedToken(validate_token(from_env, source=var), tenant)
|
|
63
|
+
raise CredentialError(
|
|
64
|
+
f"{var} is set but not used: it is only honoured when the environment is chosen "
|
|
65
|
+
f"explicitly (pass --env or set {env_var_name(cli)})"
|
|
66
|
+
)
|
|
67
|
+
found = find_credential(store, env, tenant)
|
|
68
|
+
hint = login_hint(cli, env, tenant)
|
|
69
|
+
if found is None:
|
|
70
|
+
raise CredentialError(f"no stored credentials for {env.name!r}: run `{hint}`")
|
|
71
|
+
key, cred = found
|
|
72
|
+
if normalize_origin(cred.origin) != env.origin: # tolerates pre-normalisation logins
|
|
73
|
+
raise CredentialError(
|
|
74
|
+
f"the stored token for {env.name!r} was issued for {cred.origin}, "
|
|
75
|
+
f"but the environment now points at {env.origin}: run `{hint}`"
|
|
76
|
+
)
|
|
77
|
+
pinned = cred.pins()
|
|
78
|
+
single = is_single_tenant(pinned)
|
|
79
|
+
if tenant and cred.tenant_id is not None and not single and not tenant_matches(tenant, pinned):
|
|
80
|
+
raise CredentialError(
|
|
81
|
+
f"the stored token for {key!r} is pinned to tenant "
|
|
82
|
+
f"{describe_tenant(cred.tenant_slug, cred.tenant_id)}, not {tenant!r}: run `{hint}`"
|
|
83
|
+
)
|
|
84
|
+
label = None if single else (cred.tenant_slug or tenant)
|
|
85
|
+
return ResolvedToken(cred.token, label)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def resolve_token(
|
|
89
|
+
store: CredentialStore,
|
|
90
|
+
env: Environment,
|
|
91
|
+
tenant: str | None,
|
|
92
|
+
environ: Mapping[str, str],
|
|
93
|
+
cli: str,
|
|
94
|
+
explicit: bool,
|
|
95
|
+
) -> str:
|
|
96
|
+
return resolve_credential(store, env, tenant, environ, cli, explicit).token
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""curated area of the remote CLI engine."""
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""generate area of the remote CLI engine."""
|