knuckles-cli 0.2.0__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.
- knuckles_cli/__init__.py +3 -0
- knuckles_cli/__main__.py +7 -0
- knuckles_cli/api.py +252 -0
- knuckles_cli/cli.py +684 -0
- knuckles_cli/config.py +201 -0
- knuckles_cli/doctor.py +250 -0
- knuckles_cli/envfile.py +103 -0
- knuckles_cli/errors.py +43 -0
- knuckles_cli/ops.py +451 -0
- knuckles_cli/providers.py +365 -0
- knuckles_cli/py.typed +0 -0
- knuckles_cli-0.2.0.dist-info/METADATA +140 -0
- knuckles_cli-0.2.0.dist-info/RECORD +17 -0
- knuckles_cli-0.2.0.dist-info/WHEEL +5 -0
- knuckles_cli-0.2.0.dist-info/entry_points.txt +2 -0
- knuckles_cli-0.2.0.dist-info/licenses/LICENSE +21 -0
- knuckles_cli-0.2.0.dist-info/top_level.txt +1 -0
knuckles_cli/config.py
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
"""Operator profiles: which Knuckles server, and which admin token.
|
|
2
|
+
|
|
3
|
+
Profiles live in a JSON file (default
|
|
4
|
+
``$XDG_CONFIG_HOME/knuckles/config.json``, overridable with
|
|
5
|
+
``KNUCKLES_CONFIG``) written with mode 0600 because it holds the admin
|
|
6
|
+
token. ``KNUCKLES_URL`` and ``KNUCKLES_ADMIN_TOKEN`` override the
|
|
7
|
+
stored profile, so CI and agents can run with env vars and no file.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import TYPE_CHECKING, Any
|
|
17
|
+
from urllib.parse import urlsplit
|
|
18
|
+
|
|
19
|
+
from knuckles_cli.errors import INVALID_INPUT, NOT_LOGGED_IN, CliError
|
|
20
|
+
|
|
21
|
+
if TYPE_CHECKING:
|
|
22
|
+
from collections.abc import Mapping
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class Profile:
|
|
27
|
+
"""One configured Knuckles server.
|
|
28
|
+
|
|
29
|
+
Attributes:
|
|
30
|
+
url: Knuckles base URL, no trailing slash.
|
|
31
|
+
admin_token: Operator admin token, or ``None`` for public-only
|
|
32
|
+
use (e.g. ``doctor`` against the discovery endpoints).
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
url: str
|
|
36
|
+
admin_token: str | None
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def normalize_url(url: str) -> str:
|
|
40
|
+
"""Validate a Knuckles base URL and strip any trailing slash.
|
|
41
|
+
|
|
42
|
+
The URL must match the server's ``KNUCKLES_BASE_URL`` exactly (it
|
|
43
|
+
is the JWT ``iss``), so the trailing slash is normalized away here.
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
url: The URL as typed.
|
|
47
|
+
|
|
48
|
+
Returns:
|
|
49
|
+
The URL without a trailing slash.
|
|
50
|
+
|
|
51
|
+
Raises:
|
|
52
|
+
CliError: If the URL is not absolute http(s).
|
|
53
|
+
"""
|
|
54
|
+
parts = urlsplit(url.strip())
|
|
55
|
+
if parts.scheme not in ("http", "https") or not parts.netloc:
|
|
56
|
+
raise CliError(INVALID_INPUT, f"Not an http(s) URL: {url!r}")
|
|
57
|
+
return url.strip().rstrip("/")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def config_path(env: Mapping[str, str] | None = None) -> Path:
|
|
61
|
+
"""Return where the profile file lives.
|
|
62
|
+
|
|
63
|
+
Args:
|
|
64
|
+
env: Environment to read; defaults to ``os.environ``.
|
|
65
|
+
|
|
66
|
+
Returns:
|
|
67
|
+
``KNUCKLES_CONFIG`` if set, else
|
|
68
|
+
``$XDG_CONFIG_HOME/knuckles/config.json`` (``~/.config`` when
|
|
69
|
+
XDG is unset).
|
|
70
|
+
"""
|
|
71
|
+
env = os.environ if env is None else env
|
|
72
|
+
override = env.get("KNUCKLES_CONFIG")
|
|
73
|
+
if override:
|
|
74
|
+
return Path(override)
|
|
75
|
+
base = env.get("XDG_CONFIG_HOME") or str(Path.home() / ".config")
|
|
76
|
+
return Path(base) / "knuckles" / "config.json"
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _read_raw(path: Path) -> dict[str, Any]:
|
|
80
|
+
"""Read the config file as a dict, tolerating its absence.
|
|
81
|
+
|
|
82
|
+
Args:
|
|
83
|
+
path: Config file path.
|
|
84
|
+
|
|
85
|
+
Returns:
|
|
86
|
+
The parsed object, or ``{}`` when the file does not exist.
|
|
87
|
+
|
|
88
|
+
Raises:
|
|
89
|
+
CliError: If the file exists but is not a JSON object.
|
|
90
|
+
"""
|
|
91
|
+
if not path.exists():
|
|
92
|
+
return {}
|
|
93
|
+
try:
|
|
94
|
+
raw = json.loads(path.read_text())
|
|
95
|
+
except json.JSONDecodeError as exc:
|
|
96
|
+
raise CliError(INVALID_INPUT, f"{path} is not valid JSON: {exc}") from exc
|
|
97
|
+
if not isinstance(raw, dict):
|
|
98
|
+
raise CliError(INVALID_INPUT, f"{path} must contain a JSON object.")
|
|
99
|
+
return raw
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _write_raw(path: Path, raw: dict[str, Any]) -> None:
|
|
103
|
+
"""Write the config file owner-only (0600).
|
|
104
|
+
|
|
105
|
+
Args:
|
|
106
|
+
path: Config file path.
|
|
107
|
+
raw: Object to serialize.
|
|
108
|
+
"""
|
|
109
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
110
|
+
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
111
|
+
with os.fdopen(fd, "w") as handle:
|
|
112
|
+
json.dump(raw, handle, indent=2)
|
|
113
|
+
handle.write("\n")
|
|
114
|
+
os.chmod(path, 0o600)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def load_profiles(path: Path) -> dict[str, Profile]:
|
|
118
|
+
"""Load every stored profile.
|
|
119
|
+
|
|
120
|
+
Args:
|
|
121
|
+
path: Config file path.
|
|
122
|
+
|
|
123
|
+
Returns:
|
|
124
|
+
Mapping of profile name to :class:`Profile`.
|
|
125
|
+
|
|
126
|
+
Raises:
|
|
127
|
+
CliError: If the file is malformed.
|
|
128
|
+
"""
|
|
129
|
+
profiles = _read_raw(path).get("profiles", {})
|
|
130
|
+
if not isinstance(profiles, dict):
|
|
131
|
+
raise CliError(INVALID_INPUT, f"{path}: 'profiles' must be an object.")
|
|
132
|
+
result: dict[str, Profile] = {}
|
|
133
|
+
for name, value in profiles.items():
|
|
134
|
+
if not isinstance(value, dict) or not isinstance(value.get("url"), str):
|
|
135
|
+
raise CliError(INVALID_INPUT, f"{path}: profile {name!r} has no url.")
|
|
136
|
+
token = value.get("admin_token")
|
|
137
|
+
result[name] = Profile(
|
|
138
|
+
url=value["url"], admin_token=token if isinstance(token, str) else None
|
|
139
|
+
)
|
|
140
|
+
return result
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def save_profile(path: Path, name: str, profile: Profile) -> None:
|
|
144
|
+
"""Create or replace one profile, keeping the others.
|
|
145
|
+
|
|
146
|
+
Args:
|
|
147
|
+
path: Config file path.
|
|
148
|
+
name: Profile name.
|
|
149
|
+
profile: Values to store.
|
|
150
|
+
"""
|
|
151
|
+
raw = _read_raw(path)
|
|
152
|
+
profiles = raw.setdefault("profiles", {})
|
|
153
|
+
profiles[name] = {"url": profile.url, "admin_token": profile.admin_token}
|
|
154
|
+
_write_raw(path, raw)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def remove_profile(path: Path, name: str) -> bool:
|
|
158
|
+
"""Delete one profile.
|
|
159
|
+
|
|
160
|
+
Args:
|
|
161
|
+
path: Config file path.
|
|
162
|
+
name: Profile name.
|
|
163
|
+
|
|
164
|
+
Returns:
|
|
165
|
+
``True`` if the profile existed.
|
|
166
|
+
"""
|
|
167
|
+
raw = _read_raw(path)
|
|
168
|
+
profiles = raw.get("profiles", {})
|
|
169
|
+
if name not in profiles:
|
|
170
|
+
return False
|
|
171
|
+
del profiles[name]
|
|
172
|
+
_write_raw(path, raw)
|
|
173
|
+
return True
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def resolve_profile(*, path: Path, name: str, env: Mapping[str, str]) -> Profile:
|
|
177
|
+
"""Work out which server and token a command should use.
|
|
178
|
+
|
|
179
|
+
Args:
|
|
180
|
+
path: Config file path.
|
|
181
|
+
name: Profile name to load.
|
|
182
|
+
env: Environment whose ``KNUCKLES_URL`` / ``KNUCKLES_ADMIN_TOKEN``
|
|
183
|
+
override the stored profile.
|
|
184
|
+
|
|
185
|
+
Returns:
|
|
186
|
+
The effective :class:`Profile`.
|
|
187
|
+
|
|
188
|
+
Raises:
|
|
189
|
+
CliError: ``NOT_LOGGED_IN`` when neither a stored profile nor
|
|
190
|
+
``KNUCKLES_URL`` names a server.
|
|
191
|
+
"""
|
|
192
|
+
stored = load_profiles(path).get(name)
|
|
193
|
+
url = env.get("KNUCKLES_URL") or (stored.url if stored else None)
|
|
194
|
+
if not url:
|
|
195
|
+
raise CliError(
|
|
196
|
+
NOT_LOGGED_IN,
|
|
197
|
+
f"No Knuckles server configured for profile {name!r}. Run "
|
|
198
|
+
"`knuckles login --url https://auth.example.com` or set KNUCKLES_URL.",
|
|
199
|
+
)
|
|
200
|
+
token = env.get("KNUCKLES_ADMIN_TOKEN") or (stored.admin_token if stored else None)
|
|
201
|
+
return Profile(url=normalize_url(url), admin_token=token)
|
knuckles_cli/doctor.py
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
"""Setup checks behind ``knuckles doctor``.
|
|
2
|
+
|
|
3
|
+
Server checks use only the public discovery endpoints; tenant checks
|
|
4
|
+
read the redacted admin row, so encrypted values are seen only as
|
|
5
|
+
``*_configured`` booleans (Decision #025).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from dataclasses import asdict, dataclass
|
|
11
|
+
from typing import TYPE_CHECKING, Any, Literal
|
|
12
|
+
from urllib.parse import urlsplit
|
|
13
|
+
|
|
14
|
+
from knuckles_cli.errors import CliError
|
|
15
|
+
from knuckles_cli.providers import (
|
|
16
|
+
CONFIG_GROUPS,
|
|
17
|
+
ConfigGroup,
|
|
18
|
+
is_local_host,
|
|
19
|
+
passkey_config,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
if TYPE_CHECKING:
|
|
23
|
+
from collections.abc import Mapping
|
|
24
|
+
|
|
25
|
+
from knuckles_cli.api import KnucklesAPI
|
|
26
|
+
|
|
27
|
+
Status = Literal["ok", "warn", "fail"]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class Check:
|
|
32
|
+
"""One doctor finding.
|
|
33
|
+
|
|
34
|
+
Attributes:
|
|
35
|
+
name: Short check name, prefixed with the client id for
|
|
36
|
+
tenant checks.
|
|
37
|
+
status: ``ok``, ``warn`` or ``fail``.
|
|
38
|
+
detail: What was found and, for problems, what to do.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
name: str
|
|
42
|
+
status: Status
|
|
43
|
+
detail: str
|
|
44
|
+
|
|
45
|
+
def to_dict(self) -> dict[str, str]:
|
|
46
|
+
"""Render as a JSON-safe dict.
|
|
47
|
+
|
|
48
|
+
Returns:
|
|
49
|
+
``{"name", "status", "detail"}``.
|
|
50
|
+
"""
|
|
51
|
+
return asdict(self)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _is_secure(url: str) -> bool:
|
|
55
|
+
"""Whether a URL is https or a local-development host.
|
|
56
|
+
|
|
57
|
+
Args:
|
|
58
|
+
url: Absolute URL or origin.
|
|
59
|
+
|
|
60
|
+
Returns:
|
|
61
|
+
``True`` if tokens sent to it are not exposed in transit.
|
|
62
|
+
"""
|
|
63
|
+
parts = urlsplit(url)
|
|
64
|
+
return parts.scheme == "https" or is_local_host(parts.hostname or "")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def check_server(api: KnucklesAPI) -> list[Check]:
|
|
68
|
+
"""Check a deployment's public surface.
|
|
69
|
+
|
|
70
|
+
Args:
|
|
71
|
+
api: Client for the deployment.
|
|
72
|
+
|
|
73
|
+
Returns:
|
|
74
|
+
Health, issuer, JWKS and HTTPS checks — or a single failing
|
|
75
|
+
``reachable`` check when the server cannot be reached.
|
|
76
|
+
"""
|
|
77
|
+
try:
|
|
78
|
+
health_status, health = api.get_public("/health")
|
|
79
|
+
except CliError as exc:
|
|
80
|
+
return [Check("reachable", "fail", exc.message)]
|
|
81
|
+
|
|
82
|
+
checks: list[Check] = []
|
|
83
|
+
if (
|
|
84
|
+
health_status == 200
|
|
85
|
+
and isinstance(health, dict)
|
|
86
|
+
and health.get("status") == "ok"
|
|
87
|
+
):
|
|
88
|
+
checks.append(Check("health", "ok", "Server and database are up."))
|
|
89
|
+
else:
|
|
90
|
+
checks.append(
|
|
91
|
+
Check("health", "fail", f"/health returned HTTP {health_status}: {health}")
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
_, discovery = api.get_public("/.well-known/openid-configuration")
|
|
95
|
+
issuer = discovery.get("issuer") if isinstance(discovery, dict) else None
|
|
96
|
+
if issuer == api.base_url:
|
|
97
|
+
checks.append(Check("issuer", "ok", f"Tokens are issued by {issuer}."))
|
|
98
|
+
else:
|
|
99
|
+
checks.append(
|
|
100
|
+
Check(
|
|
101
|
+
"issuer",
|
|
102
|
+
"fail",
|
|
103
|
+
f"Server reports issuer {issuer!r} but you connected to "
|
|
104
|
+
f"{api.base_url!r}. Set KNUCKLES_BASE_URL on the server to the "
|
|
105
|
+
"exact URL apps use (no trailing slash) or every token fails "
|
|
106
|
+
"issuer verification.",
|
|
107
|
+
)
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
_, jwks = api.get_public("/.well-known/jwks.json")
|
|
111
|
+
keys = jwks.get("keys") if isinstance(jwks, dict) else None
|
|
112
|
+
if (
|
|
113
|
+
isinstance(keys, list)
|
|
114
|
+
and keys
|
|
115
|
+
and all(isinstance(k, dict) and k.get("kid") for k in keys)
|
|
116
|
+
):
|
|
117
|
+
checks.append(Check("jwks", "ok", f"{len(keys)} signing key(s) published."))
|
|
118
|
+
else:
|
|
119
|
+
checks.append(
|
|
120
|
+
Check("jwks", "fail", "JWKS has no usable keys; apps cannot verify tokens.")
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
if urlsplit(api.base_url).scheme == "https":
|
|
124
|
+
checks.append(Check("https", "ok", "Served over HTTPS."))
|
|
125
|
+
elif _is_secure(api.base_url):
|
|
126
|
+
checks.append(Check("https", "ok", "Local development host."))
|
|
127
|
+
else:
|
|
128
|
+
checks.append(
|
|
129
|
+
Check("https", "warn", "Plain HTTP exposes tokens in transit; use HTTPS.")
|
|
130
|
+
)
|
|
131
|
+
return checks
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _is_set(row: Mapping[str, Any], group: ConfigGroup, column: str) -> bool:
|
|
135
|
+
"""Whether one tenant-config column has a value.
|
|
136
|
+
|
|
137
|
+
Args:
|
|
138
|
+
row: Redacted app-client row.
|
|
139
|
+
group: The column's group.
|
|
140
|
+
column: Column name.
|
|
141
|
+
|
|
142
|
+
Returns:
|
|
143
|
+
``True`` when the column is populated.
|
|
144
|
+
"""
|
|
145
|
+
if column in group.secret_columns:
|
|
146
|
+
return bool(row.get(f"{column}_configured"))
|
|
147
|
+
return bool(row.get(column))
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _check_origins(prefix: str, origins: list[str]) -> Check:
|
|
151
|
+
"""Check a tenant's allowed origins.
|
|
152
|
+
|
|
153
|
+
Args:
|
|
154
|
+
prefix: Check-name prefix (the client id).
|
|
155
|
+
origins: The tenant's ``allowed_origins``.
|
|
156
|
+
|
|
157
|
+
Returns:
|
|
158
|
+
The origins check.
|
|
159
|
+
"""
|
|
160
|
+
name = f"{prefix}: origins"
|
|
161
|
+
if not origins:
|
|
162
|
+
return Check(
|
|
163
|
+
name,
|
|
164
|
+
"fail",
|
|
165
|
+
"No allowed origins: every redirect_url will be rejected. Add one "
|
|
166
|
+
"with `knuckles apps set-origins`.",
|
|
167
|
+
)
|
|
168
|
+
insecure = [o for o in origins if not _is_secure(o)]
|
|
169
|
+
if insecure:
|
|
170
|
+
return Check(name, "warn", f"Not HTTPS: {', '.join(insecure)}.")
|
|
171
|
+
return Check(name, "ok", ", ".join(origins))
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _check_passkey_fit(prefix: str, row: Mapping[str, Any]) -> Check:
|
|
175
|
+
"""Check a fully configured passkey group for internal consistency.
|
|
176
|
+
|
|
177
|
+
Args:
|
|
178
|
+
prefix: Check-name prefix (the client id).
|
|
179
|
+
row: Redacted app-client row.
|
|
180
|
+
|
|
181
|
+
Returns:
|
|
182
|
+
The passkey check.
|
|
183
|
+
"""
|
|
184
|
+
name = f"{prefix}: passkey"
|
|
185
|
+
origin = str(row["webauthn_origin"])
|
|
186
|
+
try:
|
|
187
|
+
passkey_config(
|
|
188
|
+
origin=origin,
|
|
189
|
+
rp_id=str(row["webauthn_rp_id"]),
|
|
190
|
+
rp_name=str(row["webauthn_rp_name"]),
|
|
191
|
+
)
|
|
192
|
+
except CliError as exc:
|
|
193
|
+
return Check(name, "fail", exc.message)
|
|
194
|
+
allowed = [o.rstrip("/").lower() for o in row.get("allowed_origins") or []]
|
|
195
|
+
if origin.rstrip("/").lower() not in allowed:
|
|
196
|
+
return Check(
|
|
197
|
+
name,
|
|
198
|
+
"warn",
|
|
199
|
+
f"Passkey origin {origin} is not one of the allowed origins.",
|
|
200
|
+
)
|
|
201
|
+
return Check(name, "ok", f"rp_id {row['webauthn_rp_id']} for {origin}.")
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def check_app(row: Mapping[str, Any]) -> list[Check]:
|
|
205
|
+
"""Check one tenant's configuration.
|
|
206
|
+
|
|
207
|
+
Args:
|
|
208
|
+
row: Redacted app-client row from the admin API.
|
|
209
|
+
|
|
210
|
+
Returns:
|
|
211
|
+
An origins check plus one check per config group.
|
|
212
|
+
"""
|
|
213
|
+
prefix = str(row.get("client_id"))
|
|
214
|
+
checks = [_check_origins(prefix, list(row.get("allowed_origins") or []))]
|
|
215
|
+
for group in CONFIG_GROUPS.values():
|
|
216
|
+
name = f"{prefix}: {group.name}"
|
|
217
|
+
missing = [c for c in group.columns if not _is_set(row, group, c)]
|
|
218
|
+
if len(missing) == len(group.columns):
|
|
219
|
+
checks.append(
|
|
220
|
+
Check(
|
|
221
|
+
name,
|
|
222
|
+
"warn",
|
|
223
|
+
"Not configured. Uses the operator env vars while "
|
|
224
|
+
"KNUCKLES_ALLOW_ENV_TENANT_FALLBACK is on; otherwise this "
|
|
225
|
+
f"sign-in method is off. Set it with `knuckles providers "
|
|
226
|
+
f"{group.name} {prefix}`.",
|
|
227
|
+
)
|
|
228
|
+
)
|
|
229
|
+
elif missing and group.atomic:
|
|
230
|
+
checks.append(
|
|
231
|
+
Check(
|
|
232
|
+
name,
|
|
233
|
+
"fail",
|
|
234
|
+
f"Partially configured (missing {', '.join(missing)}): sign-in "
|
|
235
|
+
"fails with TENANT_CONFIG_INCOMPLETE.",
|
|
236
|
+
)
|
|
237
|
+
)
|
|
238
|
+
elif missing:
|
|
239
|
+
checks.append(
|
|
240
|
+
Check(
|
|
241
|
+
name,
|
|
242
|
+
"warn",
|
|
243
|
+
f"{', '.join(missing)} not set; inherited from operator env vars.",
|
|
244
|
+
)
|
|
245
|
+
)
|
|
246
|
+
elif group.name == "passkey":
|
|
247
|
+
checks.append(_check_passkey_fit(prefix, row))
|
|
248
|
+
else:
|
|
249
|
+
checks.append(Check(name, "ok", "Configured."))
|
|
250
|
+
return checks
|
knuckles_cli/envfile.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Write Knuckles credentials into a consuming app's ``.env`` file."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
from typing import TYPE_CHECKING
|
|
8
|
+
|
|
9
|
+
from knuckles_cli.errors import ENV_FILE_CONFLICT, CliError
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from collections.abc import Mapping
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
_ASSIGNMENT_RE = re.compile(r"^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _unquote(value: str) -> str:
|
|
19
|
+
"""Strip one layer of matching quotes from a dotenv value.
|
|
20
|
+
|
|
21
|
+
Args:
|
|
22
|
+
value: Raw right-hand side.
|
|
23
|
+
|
|
24
|
+
Returns:
|
|
25
|
+
The unquoted value.
|
|
26
|
+
"""
|
|
27
|
+
value = value.strip()
|
|
28
|
+
if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
|
|
29
|
+
return value[1:-1]
|
|
30
|
+
return value
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def check_env(
|
|
34
|
+
path: Path, values: Mapping[str, str | None], *, force: bool = False
|
|
35
|
+
) -> None:
|
|
36
|
+
"""Fail if writing ``values`` would clobber different existing ones.
|
|
37
|
+
|
|
38
|
+
Callers run this before an irreversible step (creating a tenant,
|
|
39
|
+
rotating a secret) so a conflict is caught while nothing has
|
|
40
|
+
changed yet.
|
|
41
|
+
|
|
42
|
+
Args:
|
|
43
|
+
path: The ``.env`` file.
|
|
44
|
+
values: Keys and values about to be written. A ``None`` value
|
|
45
|
+
stands for one not known yet (a secret about to be minted),
|
|
46
|
+
which conflicts with any existing non-empty value.
|
|
47
|
+
force: Skip the check.
|
|
48
|
+
|
|
49
|
+
Raises:
|
|
50
|
+
CliError: ``ENV_FILE_CONFLICT`` naming the clashing keys.
|
|
51
|
+
"""
|
|
52
|
+
if force or not path.exists():
|
|
53
|
+
return
|
|
54
|
+
clashes = []
|
|
55
|
+
for line in path.read_text().splitlines():
|
|
56
|
+
match = _ASSIGNMENT_RE.match(line)
|
|
57
|
+
if not match:
|
|
58
|
+
continue
|
|
59
|
+
key, raw = match.groups()
|
|
60
|
+
existing = _unquote(raw)
|
|
61
|
+
if key in values and existing and existing != values[key]:
|
|
62
|
+
clashes.append(key)
|
|
63
|
+
if clashes:
|
|
64
|
+
raise CliError(
|
|
65
|
+
ENV_FILE_CONFLICT,
|
|
66
|
+
f"{path} already sets {', '.join(clashes)} to a different value. "
|
|
67
|
+
"Re-run with --force to overwrite.",
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def write_env(path: Path, values: dict[str, str], *, force: bool = False) -> None:
|
|
72
|
+
"""Set keys in a ``.env`` file, preserving every other line.
|
|
73
|
+
|
|
74
|
+
Existing assignments are replaced in place; new keys are appended
|
|
75
|
+
in the order given. A newly created file is mode 0600.
|
|
76
|
+
|
|
77
|
+
Args:
|
|
78
|
+
path: The ``.env`` file.
|
|
79
|
+
values: Keys and values to set.
|
|
80
|
+
force: Overwrite keys that already hold a different value.
|
|
81
|
+
|
|
82
|
+
Raises:
|
|
83
|
+
CliError: ``ENV_FILE_CONFLICT`` if a key holds a different
|
|
84
|
+
value and ``force`` is false.
|
|
85
|
+
"""
|
|
86
|
+
check_env(path, values, force=force)
|
|
87
|
+
lines = path.read_text().splitlines() if path.exists() else []
|
|
88
|
+
remaining = dict(values)
|
|
89
|
+
output: list[str] = []
|
|
90
|
+
for line in lines:
|
|
91
|
+
match = _ASSIGNMENT_RE.match(line)
|
|
92
|
+
if match and match.group(1) in remaining:
|
|
93
|
+
key = match.group(1)
|
|
94
|
+
output.append(f"{key}={remaining.pop(key)}")
|
|
95
|
+
else:
|
|
96
|
+
output.append(line)
|
|
97
|
+
output.extend(f"{key}={value}" for key, value in remaining.items())
|
|
98
|
+
|
|
99
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
100
|
+
# The mode only applies on creation: an existing file keeps its own.
|
|
101
|
+
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
102
|
+
with os.fdopen(fd, "w") as handle:
|
|
103
|
+
handle.write("\n".join(output) + "\n")
|
knuckles_cli/errors.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""The CLI's single error type.
|
|
2
|
+
|
|
3
|
+
Every failure the CLI reports — a Knuckles API error passed through
|
|
4
|
+
verbatim, a network failure, or a local validation problem — is a
|
|
5
|
+
:class:`CliError` carrying a machine-readable ``code``. ``--json``
|
|
6
|
+
output renders it as the same ``{"error": {"code", "message"}}``
|
|
7
|
+
envelope the Knuckles API uses, so agents parse one shape everywhere.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
# Local (non-server) error codes.
|
|
13
|
+
NOT_LOGGED_IN = "NOT_LOGGED_IN"
|
|
14
|
+
NETWORK_ERROR = "NETWORK_ERROR"
|
|
15
|
+
INVALID_INPUT = "INVALID_INPUT"
|
|
16
|
+
ADMIN_API_DISABLED = "ADMIN_API_DISABLED"
|
|
17
|
+
ENV_FILE_CONFLICT = "ENV_FILE_CONFLICT"
|
|
18
|
+
HTTP_ERROR = "HTTP_ERROR"
|
|
19
|
+
EMAIL_DOMAIN_UNVERIFIED = "EMAIL_DOMAIN_UNVERIFIED"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class CliError(Exception):
|
|
23
|
+
"""A reportable CLI failure.
|
|
24
|
+
|
|
25
|
+
Attributes:
|
|
26
|
+
code: Machine-readable error code (a Knuckles API code or one
|
|
27
|
+
of the local constants in this module).
|
|
28
|
+
message: Human-readable explanation, safe to print.
|
|
29
|
+
status_code: HTTP status when the error came from Knuckles.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
def __init__(self, code: str, message: str, *, status_code: int | None = None):
|
|
33
|
+
"""Initialize the error.
|
|
34
|
+
|
|
35
|
+
Args:
|
|
36
|
+
code: Machine-readable error code.
|
|
37
|
+
message: Human-readable explanation.
|
|
38
|
+
status_code: Optional HTTP status from the server.
|
|
39
|
+
"""
|
|
40
|
+
super().__init__(f"{code}: {message}")
|
|
41
|
+
self.code = code
|
|
42
|
+
self.message = message
|
|
43
|
+
self.status_code = status_code
|