keyexec 0.1.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.
keyexec/keychain.py ADDED
@@ -0,0 +1,153 @@
1
+ """The macOS login Keychain, one generic password per entry under the service `keyexec`.
2
+
3
+ Written against the Security framework rather than through keyring, which can neither list a service's items nor update one in place: it deletes and re-adds, which resets the item's access list and so the user's "Always Allow".
4
+ """
5
+
6
+ import ctypes
7
+ import sys
8
+ from collections.abc import Generator
9
+ from contextlib import contextmanager
10
+ from ctypes import c_bool, c_char_p, c_int32, c_long, c_uint32, c_void_p
11
+ from ctypes.util import find_library
12
+
13
+ from keyexec.errors import StoreError
14
+
15
+ # Imported only on macOS (store.backend); the assert is what lets ty and pyright check the framework calls below.
16
+ assert sys.platform == "darwin"
17
+
18
+ SERVICE = "keyexec"
19
+ MAX_VALUE_BYTES: int | None = None
20
+ ERR_SEC_ITEM_NOT_FOUND = -25300
21
+ UTF8 = 0x08000100
22
+
23
+ _security = ctypes.CDLL(find_library("Security"))
24
+ _cf = ctypes.CDLL(find_library("CoreFoundation"))
25
+
26
+ _cf.CFDictionaryCreate.argtypes = (c_void_p, c_void_p, c_void_p, c_long, c_void_p, c_void_p)
27
+ _cf.CFDictionaryCreate.restype = c_void_p
28
+ _cf.CFDictionaryGetValue.argtypes = (c_void_p, c_void_p)
29
+ _cf.CFDictionaryGetValue.restype = c_void_p
30
+ _cf.CFStringCreateWithCString.argtypes = (c_void_p, c_char_p, c_uint32)
31
+ _cf.CFStringCreateWithCString.restype = c_void_p
32
+ _cf.CFStringGetCString.argtypes = (c_void_p, c_char_p, c_long, c_uint32)
33
+ _cf.CFStringGetCString.restype = c_bool
34
+ _cf.CFDataCreate.argtypes = (c_void_p, c_char_p, c_long)
35
+ _cf.CFDataCreate.restype = c_void_p
36
+ _cf.CFDataGetBytePtr.argtypes = (c_void_p,)
37
+ _cf.CFDataGetBytePtr.restype = c_void_p
38
+ _cf.CFDataGetLength.argtypes = (c_void_p,)
39
+ _cf.CFDataGetLength.restype = c_long
40
+ _cf.CFArrayGetCount.argtypes = (c_void_p,)
41
+ _cf.CFArrayGetCount.restype = c_long
42
+ _cf.CFArrayGetValueAtIndex.argtypes = (c_void_p, c_long)
43
+ _cf.CFArrayGetValueAtIndex.restype = c_void_p
44
+ _cf.CFRelease.argtypes = (c_void_p,)
45
+ _cf.CFRelease.restype = None
46
+ for _call in ("SecItemCopyMatching", "SecItemAdd", "SecItemUpdate"):
47
+ getattr(_security, _call).argtypes = (c_void_p, c_void_p)
48
+ getattr(_security, _call).restype = c_int32
49
+ _security.SecItemDelete.argtypes = (c_void_p,)
50
+ _security.SecItemDelete.restype = c_int32
51
+
52
+
53
+ def _constant(library: ctypes.CDLL, name: str) -> c_void_p:
54
+ return c_void_p.in_dll(library, name)
55
+
56
+
57
+ @contextmanager
58
+ def _owned(*objects: int | None) -> Generator[None, None, None]:
59
+ try:
60
+ yield
61
+ finally:
62
+ for obj in objects:
63
+ if obj:
64
+ _cf.CFRelease(obj)
65
+
66
+
67
+ def _string(text: str) -> int:
68
+ return _cf.CFStringCreateWithCString(None, text.encode("utf-8"), UTF8)
69
+
70
+
71
+ def _query(*pairs: tuple[str, c_void_p | int]) -> int:
72
+ keys = (c_void_p * len(pairs))(*(_constant(_security, key) for key, _ in pairs))
73
+ values = (c_void_p * len(pairs))(*(value for _, value in pairs))
74
+ callbacks = (ctypes.addressof(c_void_p.in_dll(_cf, name)) for name in ("kCFTypeDictionaryKeyCallBacks", "kCFTypeDictionaryValueCallBacks"))
75
+ return _cf.CFDictionaryCreate(None, keys, values, len(pairs), *callbacks)
76
+
77
+
78
+ def _item(name: str | None, *extra: tuple[str, c_void_p | int]) -> tuple[int, list[int]]:
79
+ service = _string(SERVICE)
80
+ created = [service]
81
+ pairs: list[tuple[str, c_void_p | int]] = [("kSecClass", _constant(_security, "kSecClassGenericPassword")), ("kSecAttrService", service)]
82
+ if name is not None:
83
+ account = _string(name)
84
+ created.append(account)
85
+ pairs.append(("kSecAttrAccount", account))
86
+ query = _query(*pairs, *extra)
87
+ return query, created
88
+
89
+
90
+ def _check(status: int, operation: str) -> None:
91
+ if status != 0:
92
+ raise StoreError(f"macOS Keychain {operation} failed with OSStatus {status}")
93
+
94
+
95
+ def get(name: str) -> str | None:
96
+ query, created = _item(name, ("kSecReturnData", _constant(_cf, "kCFBooleanTrue")), ("kSecMatchLimit", _constant(_security, "kSecMatchLimitOne")))
97
+ data = c_void_p()
98
+ with _owned(query, *created):
99
+ status = _security.SecItemCopyMatching(query, ctypes.byref(data))
100
+ if status == ERR_SEC_ITEM_NOT_FOUND:
101
+ return None
102
+ _check(status, "read")
103
+ with _owned(data.value):
104
+ blob = ctypes.string_at(_cf.CFDataGetBytePtr(data), _cf.CFDataGetLength(data))
105
+ try:
106
+ return blob.decode("utf-8")
107
+ except UnicodeDecodeError:
108
+ # `from None`: the decode error quotes the offending bytes, which are part of the value.
109
+ raise StoreError(f"entry {name!r} does not hold UTF-8 text, so keyexec did not write it") from None
110
+
111
+
112
+ def put(name: str, value: str) -> None:
113
+ blob = value.encode("utf-8")
114
+ data = _cf.CFDataCreate(None, blob, len(blob))
115
+ query, created = _item(name)
116
+ changes = _query(("kSecValueData", data))
117
+ with _owned(query, changes, data, *created):
118
+ # Update in place so the item keeps its access list; add only when there is nothing to update.
119
+ status = _security.SecItemUpdate(query, changes)
120
+ if status == ERR_SEC_ITEM_NOT_FOUND:
121
+ addition, more = _item(name, ("kSecValueData", data))
122
+ with _owned(addition, *more):
123
+ status = _security.SecItemAdd(addition, None)
124
+ _check(status, "write")
125
+
126
+
127
+ def delete(name: str) -> bool:
128
+ query, created = _item(name)
129
+ with _owned(query, *created):
130
+ status = _security.SecItemDelete(query)
131
+ if status == ERR_SEC_ITEM_NOT_FOUND:
132
+ return False
133
+ _check(status, "delete")
134
+ return True
135
+
136
+
137
+ def names() -> list[str]:
138
+ query, created = _item(None, ("kSecReturnAttributes", _constant(_cf, "kCFBooleanTrue")), ("kSecMatchLimit", _constant(_security, "kSecMatchLimitAll")))
139
+ found = c_void_p()
140
+ with _owned(query, *created):
141
+ status = _security.SecItemCopyMatching(query, ctypes.byref(found))
142
+ if status == ERR_SEC_ITEM_NOT_FOUND:
143
+ return []
144
+ _check(status, "list")
145
+ account_key = _constant(_security, "kSecAttrAccount")
146
+ buffer = ctypes.create_string_buffer(256)
147
+ accounts = []
148
+ with _owned(found.value):
149
+ for i in range(_cf.CFArrayGetCount(found)):
150
+ account = _cf.CFDictionaryGetValue(_cf.CFArrayGetValueAtIndex(found, i), account_key)
151
+ if account and _cf.CFStringGetCString(account, buffer, len(buffer), UTF8):
152
+ accounts.append(buffer.value.decode("utf-8"))
153
+ return sorted(accounts)
keyexec/migrate.py ADDED
@@ -0,0 +1,366 @@
1
+ import json
2
+ import os
3
+ import re
4
+ import shlex
5
+ import shutil
6
+ import tempfile
7
+ from collections import defaultdict
8
+ from dataclasses import asdict, dataclass, field
9
+ from datetime import datetime
10
+ from enum import StrEnum
11
+ from pathlib import Path
12
+
13
+ from keyexec import store
14
+ from keyexec.config import JSONObject, Scope, ServerRef, Transport, digest, is_http, is_keyexec, iter_servers, read_config, transport_of
15
+ from keyexec.errors import ConfigError, ErrorCode, UsageError
16
+ from keyexec.inject import HEADER_NAME_RE
17
+
18
+ # Scored against the MCP Registry's isSecret labels by scripts/measure_migrate.py; docs/design.md has the numbers and the alternatives that were refused.
19
+ SECRET_NAME_RE = re.compile(r"(token|secret|password|passwd|credentials?|key)$|(^|[_-])(pat|pass|pwd)$|passphrase$|^(proxy-)?authorization$", re.IGNORECASE)
20
+ NOT_SECRET_NAME_RE = re.compile(r"pub(lic)?[_-]?key$|(^|[_-])key[_-]?id$|^idempotency[_-]key$", re.IGNORECASE)
21
+ CREDENTIAL_URL_RE = re.compile(r"^[a-z][a-z0-9+.-]*://[^/\s:@]*:[^/\s@]+@", re.IGNORECASE)
22
+ # The same, found anywhere: an argument usually wraps the URL (`--url=postgres://u:p@h`, `jdbc:postgresql://u:p@h`).
23
+ CREDENTIAL_URL_IN_TEXT_RE = re.compile(r"(?<![a-z0-9+.-])[a-z][a-z0-9+.-]*://[^/\s:@]*:[^/\s@]+@", re.IGNORECASE)
24
+ # Formats the vendors document for their tokens, so a match is a secret whatever the variable is called. AWS's AKIA key id is left out: it identifies a key, it is not one.
25
+ TOKEN_VALUE_RE = re.compile(
26
+ r"\b(gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,}|glpat-[A-Za-z0-9_-]{20,}|sk-[A-Za-z0-9_-]{20,}|[sr]k_(live|test)_[A-Za-z0-9]{20,}|xox[abprs]-[A-Za-z0-9-]{10,}|xapp-[A-Za-z0-9-]{10,}|AIza[A-Za-z0-9_-]{35}|eyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+)"
27
+ )
28
+ AUTH_SCHEME_RE = re.compile(r"(Bearer|Basic|Token)\s+(\S+)", re.IGNORECASE)
29
+ # The helper runs through sh or cmd.exe and doctor re-splits it with shlex; these characters stay special inside double quotes in one of them, so they are refused, not quoted. A single backslash is literal in all three, which is what lets a Windows path through.
30
+ SHELL_UNSAFE_RE = re.compile(r'["$`!%]|\\\\')
31
+ PLACEHOLDER = "<keyexec>"
32
+ ORIGINAL_ARGS = "<original command and args>"
33
+
34
+
35
+ class Kind(StrEnum):
36
+ ENV = "env"
37
+ HEADER = "header"
38
+
39
+
40
+ class Status(StrEnum):
41
+ MIGRATE = "migrate"
42
+ SKIPPED = "skipped"
43
+
44
+
45
+ class SkipReason(StrEnum):
46
+ HELPER_SET = "headersHelper already set"
47
+ ALREADY_WRAPPED = "already wrapped by keyexec"
48
+ NEEDS_QUOTING = "header name needs shell quoting"
49
+ INVALID_HEADER = "not a valid HTTP header name"
50
+ TOO_LONG = "value too long for the credential store"
51
+ NO_COMMAND = "no command to wrap"
52
+
53
+
54
+ @dataclass(frozen=True, slots=True, kw_only=True)
55
+ class Item:
56
+ scope: Scope
57
+ project: str | None
58
+ server: str
59
+ kind: Kind
60
+ key: str
61
+ entry: str
62
+ value_length: int
63
+ reason: SkipReason | None = None
64
+ template: str | None = None
65
+ value: str = field(default="", repr=False)
66
+
67
+ @property
68
+ def status(self) -> Status:
69
+ return Status.SKIPPED if self.reason else Status.MIGRATE
70
+
71
+ def to_dict(self) -> JSONObject:
72
+ data = asdict(self)
73
+ del data["value"]
74
+ return {**data, "status": self.status}
75
+
76
+
77
+ @dataclass(frozen=True, slots=True, kw_only=True)
78
+ class Preview:
79
+ """A migrated server's new shape, holding no value and not the original args, which can carry secrets of their own."""
80
+
81
+ scope: Scope
82
+ project: str | None
83
+ server: str
84
+ kind: Kind
85
+ transport: Transport
86
+ launch: str
87
+ kept_keys: tuple[str, ...]
88
+
89
+ def to_dict(self) -> JSONObject:
90
+ where = {"scope": self.scope, "project": self.project, "server": self.server}
91
+ if self.kind is Kind.ENV:
92
+ return {**where, "transport": self.transport, "launch": f"{self.launch} {ORIGINAL_ARGS}", "env_keys": list(self.kept_keys)}
93
+ return {**where, "transport": self.transport, "headersHelper": self.launch, "header_keys": list(self.kept_keys)}
94
+
95
+
96
+ @dataclass(frozen=True, slots=True, kw_only=True)
97
+ class Plan:
98
+ config: Path
99
+ config_digest: str
100
+ keyexec: str | None
101
+ items: tuple[Item, ...]
102
+ servers: tuple[Preview, ...]
103
+ warnings: tuple[str, ...]
104
+
105
+ def migrating(self) -> list[Item]:
106
+ return [i for i in self.items if i.status is Status.MIGRATE]
107
+
108
+ def to_dict(self) -> JSONObject:
109
+ return {
110
+ "ok": True,
111
+ "config": str(self.config),
112
+ "keyexec": self.keyexec,
113
+ "applied": False,
114
+ "items": [i.to_dict() for i in self.items],
115
+ "servers": [s.to_dict() for s in self.servers],
116
+ "warnings": list(self.warnings),
117
+ }
118
+
119
+
120
+ @dataclass(frozen=True, slots=True, kw_only=True)
121
+ class Applied:
122
+ plan: Plan
123
+ backup: Path
124
+
125
+ @property
126
+ def stored(self) -> list[str]:
127
+ return list(dict.fromkeys(i.entry for i in self.plan.migrating()))
128
+
129
+ @property
130
+ def warnings(self) -> list[str]:
131
+ return [*self.plan.warnings, backup_warning(self.backup)]
132
+
133
+ @property
134
+ def next_steps(self) -> list[str]:
135
+ return ["restart Claude Code", "run `keyexec doctor`", f"delete {self.backup}"]
136
+
137
+ def to_dict(self) -> JSONObject:
138
+ return {
139
+ **self.plan.to_dict(),
140
+ "applied": True,
141
+ "backup": str(self.backup),
142
+ "stored": self.stored,
143
+ "warnings": self.warnings,
144
+ "next_steps": self.next_steps,
145
+ }
146
+
147
+
148
+ def backup_warning(backup: Path | str) -> str:
149
+ return f"{backup} still holds plaintext tokens; delete it once Claude Code works with the migrated config"
150
+
151
+
152
+ def entry_names(server: str, keys: list[str]) -> dict[str, str]:
153
+ # Env vars usually open with words the server name already has (`github` and `GITHUB_TOKEN`, `reddit-ads` and `REDDIT_ADS_TOKEN`), so they are dropped: `github-token`, `reddit-ads-token`.
154
+ # Not when two keys of one server would then collide: `jira-confluence` keeps `jira_` and `confluence_`, which are what tell its two tokens apart.
155
+ words = set(re.split(r"[^a-z0-9]+", server.lower()))
156
+
157
+ def trimmed(key: str) -> str:
158
+ key = key.lower()
159
+ while (split := re.fullmatch(r"([a-z0-9]+)[_-](.+)", key)) and split[1] in words:
160
+ key = split[2]
161
+ return key
162
+
163
+ def slug(name: str) -> str:
164
+ prefix, key = (re.sub(r"[^a-z0-9._-]", "-", part.lower()) for part in (server, name))
165
+ # A long server name is cut, never the key: cutting the key would give every key of that server the same entry.
166
+ prefix = prefix[: max(0, 63 - len(key))].rstrip("._-")
167
+ return f"{prefix}-{key}".lstrip("._-")[:64] if prefix else key.lstrip("._-")[:64]
168
+
169
+ short = {key: trimmed(key) for key in keys}
170
+ chosen = short if len(set(short.values())) == len(short) else {key: key.lower() for key in keys}
171
+ return {key: slug(name) for key, name in chosen.items()}
172
+
173
+
174
+ def _candidates(server: JSONObject) -> tuple[Kind, dict[str, str]]:
175
+ kind = Kind.HEADER if is_http(server) else Kind.ENV
176
+ block = server.get("headers" if kind is Kind.HEADER else "env")
177
+ if not isinstance(block, dict):
178
+ return kind, {}
179
+ # A `${VAR}` value names a variable set elsewhere; there is no token here to move.
180
+ return kind, {k: v for k, v in block.items() if isinstance(v, str) and v and "${" not in v and is_secret(k, v)}
181
+
182
+
183
+ def is_secret(key: str, value: str) -> bool:
184
+ if CREDENTIAL_URL_RE.match(value) or TOKEN_VALUE_RE.search(value):
185
+ return True
186
+ return bool(SECRET_NAME_RE.search(key)) and not NOT_SECRET_NAME_RE.search(key)
187
+
188
+
189
+ def plaintext_keys(data: JSONObject) -> list[tuple[ServerRef, str]]:
190
+ return [(ref, key) for ref in iter_servers(data) for key in _candidates(ref.server)[1]]
191
+
192
+
193
+ def _token_in_args(server: JSONObject) -> bool:
194
+ args = server.get("args")
195
+ return isinstance(args, list) and any(isinstance(a, str) and (TOKEN_VALUE_RE.search(a) or CREDENTIAL_URL_IN_TEXT_RE.search(a)) for a in args)
196
+
197
+
198
+ def _skip_reason(server: JSONObject, kind: Kind, key: str, secret: str) -> SkipReason | None:
199
+ if not store.fits(secret):
200
+ return SkipReason.TOO_LONG
201
+ if kind is Kind.HEADER and "headersHelper" in server:
202
+ return SkipReason.HELPER_SET
203
+ if kind is Kind.ENV and not (isinstance(server.get("command"), str) and isinstance(server.get("args", []), list)):
204
+ return SkipReason.NO_COMMAND
205
+ if kind is Kind.ENV and is_keyexec(server.get("command")):
206
+ return SkipReason.ALREADY_WRAPPED
207
+ if kind is Kind.HEADER and SHELL_UNSAFE_RE.search(key):
208
+ return SkipReason.NEEDS_QUOTING
209
+ # `headers` would split `a=b` at its first `=` and send header `a`, so a key it cannot take is skipped here, not mangled at launch.
210
+ if kind is Kind.HEADER and not HEADER_NAME_RE.fullmatch(key):
211
+ return SkipReason.INVALID_HEADER
212
+ return None
213
+
214
+
215
+ def _item(ref: ServerRef, kind: Kind, key: str, value: str, entry: str) -> Item:
216
+ template, secret = None, value
217
+ if kind is Kind.HEADER:
218
+ scheme = AUTH_SCHEME_RE.fullmatch(value)
219
+ template = f"{scheme[1]} {{{entry}}}" if scheme else f"{{{entry}}}"
220
+ secret = scheme[2] if scheme else value
221
+ return Item(
222
+ scope=ref.scope,
223
+ project=ref.project,
224
+ server=ref.name,
225
+ kind=kind,
226
+ key=key,
227
+ entry=entry,
228
+ value_length=len(secret),
229
+ reason=_skip_reason(ref.server, kind, key, secret),
230
+ template=template,
231
+ value=secret,
232
+ )
233
+
234
+
235
+ def _rewrite(server: JSONObject, items: list[Item], keyexec: str) -> JSONObject:
236
+ new = dict(server)
237
+ keys = {i.key for i in items}
238
+ if items[0].kind is Kind.ENV:
239
+ mappings = [arg for i in items for arg in ("--env", f"{i.key}={i.entry}")]
240
+ new["command"] = keyexec
241
+ new["args"] = ["run", *mappings, "--", server["command"], *server.get("args", [])]
242
+ block = "env"
243
+ else:
244
+ new["headersHelper"] = " ".join([f'"{keyexec}"', "headers", *(f'--header "{i.key}={i.template}"' for i in items)])
245
+ block = "headers"
246
+ remaining = {k: v for k, v in server[block].items() if k not in keys}
247
+ if remaining:
248
+ new[block] = remaining
249
+ else:
250
+ del new[block]
251
+ return new
252
+
253
+
254
+ def _preview(ref: ServerRef, items: list[Item], keyexec: str) -> Preview:
255
+ new = _rewrite(ref.server, items, keyexec)
256
+ kind = items[0].kind
257
+ if kind is Kind.ENV:
258
+ args = new["args"]
259
+ launch = shlex.join([new["command"], *args[: args.index("--") + 1]])
260
+ else:
261
+ launch = new["headersHelper"]
262
+ kept = new.get("env" if kind is Kind.ENV else "headers", {})
263
+ return Preview(
264
+ scope=ref.scope, project=ref.project, server=ref.name, kind=kind, transport=transport_of(ref.server), launch=launch, kept_keys=tuple(sorted(kept))
265
+ )
266
+
267
+
268
+ def _clashes(items: list[Item]) -> list[str]:
269
+ # One entry may serve several servers when they carry the same token; only differing values would overwrite each other.
270
+ values: defaultdict[str, set[str]] = defaultdict(set)
271
+ for item in items:
272
+ values[item.entry].add(item.value)
273
+ return sorted(entry for entry, seen in values.items() if len(seen) > 1)
274
+
275
+
276
+ def build_plan(path: Path, keyexec: str | None) -> Plan:
277
+ raw, data = read_config(path)
278
+ items: list[Item] = []
279
+ servers: list[Preview] = []
280
+ warnings: list[str] = []
281
+ if keyexec is None:
282
+ warnings.append("keyexec executable not found on PATH; --apply will refuse until it is installed")
283
+ elif SHELL_UNSAFE_RE.search(keyexec):
284
+ raise ConfigError(f"keyexec path {keyexec!r} contains characters that cannot be quoted safely for Claude Code's shell")
285
+ for ref in iter_servers(data):
286
+ kind, candidates = _candidates(ref.server)
287
+ names = entry_names(ref.name, list(candidates))
288
+ server_items = [_item(ref, kind, key, value, names[key]) for key, value in candidates.items()]
289
+ items.extend(server_items)
290
+ warnings.extend(f"server {ref.name!r} {i.kind} {i.key!r} skipped: {i.reason}" for i in server_items if i.status is Status.SKIPPED)
291
+ if _token_in_args(ref.server):
292
+ warnings.append(f"server {ref.name!r} passes what looks like a token in its args; keyexec moves env and headers only, so move it to env by hand")
293
+ if migrating := [i for i in server_items if i.status is Status.MIGRATE]:
294
+ servers.append(_preview(ref, migrating, keyexec or PLACEHOLDER))
295
+ if clashes := _clashes([i for i in items if i.status is Status.MIGRATE]):
296
+ raise ConfigError(f"different secrets map to the same entry name: {', '.join(clashes)}")
297
+ return Plan(config=path, config_digest=digest(raw), keyexec=keyexec, items=tuple(items), servers=tuple(servers), warnings=tuple(warnings))
298
+
299
+
300
+ def _unchanged(plan: Plan) -> bytes:
301
+ raw, _ = read_config(plan.config)
302
+ if digest(raw) != plan.config_digest:
303
+ raise ConfigError(f"{plan.config} changed since the plan was made (Claude Code may have written it); run migrate again", ErrorCode.CONFIG_CHANGED)
304
+ return raw
305
+
306
+
307
+ def _write_backup(path: Path, raw: bytes) -> Path:
308
+ backup = path.with_name(f"{path.name}.keyexec-backup-{datetime.now().astimezone():%Y%m%dT%H%M%S}")
309
+ try:
310
+ # The backup holds every token in plaintext: owner-only on POSIX (a umask can only narrow 0600); Windows ignores the mode and applies the folder's ACL.
311
+ fd = os.open(backup, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0), 0o600)
312
+ with os.fdopen(fd, "wb") as handle:
313
+ handle.write(raw)
314
+ except OSError as exc:
315
+ raise ConfigError(f"could not write backup {backup}: {exc}") from exc
316
+ return backup
317
+
318
+
319
+ def _replace_atomic(plan: Plan, text: str) -> None:
320
+ path = plan.config
321
+ fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp")
322
+ try:
323
+ with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle:
324
+ handle.write(text)
325
+ handle.flush()
326
+ os.fsync(handle.fileno())
327
+ shutil.copymode(path, tmp)
328
+ # Checked again as late as possible: Claude Code rewrites this file while it runs, and whatever it wrote since the plan would be lost.
329
+ _unchanged(plan)
330
+ Path(tmp).replace(path)
331
+ except OSError as exc:
332
+ raise ConfigError(f"could not write {path}: {exc}") from exc
333
+ finally:
334
+ Path(tmp).unlink(missing_ok=True)
335
+
336
+
337
+ def apply_plan(plan: Plan, force: bool = False) -> Applied:
338
+ todo = plan.migrating()
339
+ if not todo:
340
+ raise UsageError("the plan has nothing to migrate", ErrorCode.NOTHING_TO_MIGRATE)
341
+ if not plan.keyexec or not Path(plan.keyexec).is_file():
342
+ raise ConfigError("cannot find the keyexec executable to point the servers at; install it with `uv tool install` first", ErrorCode.KEYEXEC_NOT_FOUND)
343
+ conflicts = sorted({i.entry for i in todo if store.get_secret(i.entry) not in (None, i.value)})
344
+ if conflicts and not force:
345
+ raise UsageError(f"entries already hold a different value: {', '.join(conflicts)} (use --force to overwrite)", ErrorCode.ENTRY_EXISTS)
346
+ raw = _unchanged(plan)
347
+ for item in todo:
348
+ store.set_secret(item.entry, item.value)
349
+
350
+ data = json.loads(raw)
351
+ by_server: defaultdict[tuple[Scope, str | None, str], list[Item]] = defaultdict(list)
352
+ for item in todo:
353
+ by_server[item.scope, item.project, item.server].append(item)
354
+ for (scope, project, name), items in by_server.items():
355
+ # The digest matched the plan, so this path holds the object iter_servers walked.
356
+ block = data["mcpServers"] if scope is Scope.USER else data["projects"][project]["mcpServers"]
357
+ block[name] = _rewrite(block[name], items, plan.keyexec)
358
+
359
+ backup = _write_backup(plan.config, raw)
360
+ try:
361
+ _replace_atomic(plan, json.dumps(data, indent=2, ensure_ascii=False))
362
+ except ConfigError:
363
+ # The config is untouched, so the backup only duplicates it, plaintext tokens included: left behind, it would be a copy nobody was told about.
364
+ backup.unlink(missing_ok=True)
365
+ raise
366
+ return Applied(plan=plan, backup=backup)
keyexec/store.py ADDED
@@ -0,0 +1,86 @@
1
+ import re
2
+ import sys
3
+ from functools import cache
4
+ from typing import Protocol
5
+
6
+ from keyexec.errors import ErrorCode, MissingSecretError, StoreError, UsageError
7
+
8
+ NAME_RE = re.compile(r"^[a-z0-9][a-z0-9._-]{0,63}$")
9
+
10
+
11
+ class Backend(Protocol):
12
+ MAX_VALUE_BYTES: int | None
13
+
14
+ def get(self, name: str) -> str | None: ...
15
+ def put(self, name: str, value: str) -> None: ...
16
+ def delete(self, name: str) -> bool: ...
17
+ def names(self) -> list[str]: ...
18
+
19
+
20
+ @cache
21
+ def backend() -> Backend:
22
+ if sys.platform == "win32":
23
+ from keyexec import wincred
24
+
25
+ return wincred
26
+ if sys.platform == "darwin":
27
+ from keyexec import keychain
28
+
29
+ return keychain
30
+ raise StoreError(f"no supported credential store on {sys.platform}: keyexec uses Windows Credential Manager or the macOS Keychain")
31
+
32
+
33
+ def validate_name(name: str) -> str:
34
+ if not NAME_RE.fullmatch(name):
35
+ # The name is not echoed: a token pasted where an entry name belongs would otherwise land in the MCP server's log.
36
+ raise UsageError(f"invalid entry name ({len(name)} characters): entry names match {NAME_RE.pattern}", ErrorCode.INVALID_NAME)
37
+ return name
38
+
39
+
40
+ def fits(value: str) -> bool:
41
+ limit = backend().MAX_VALUE_BYTES
42
+ return limit is None or len(value.encode("utf-8")) <= limit
43
+
44
+
45
+ def validate_value(value: str) -> str:
46
+ if not value:
47
+ raise UsageError("refusing to store an empty value", ErrorCode.EMPTY_VALUE)
48
+ if not fits(value):
49
+ raise UsageError(
50
+ f"the value is {len(value.encode('utf-8'))} bytes; the credential store holds at most {backend().MAX_VALUE_BYTES}", ErrorCode.VALUE_TOO_LONG
51
+ )
52
+ return value
53
+
54
+
55
+ def get_secret(name: str) -> str | None:
56
+ return backend().get(validate_name(name))
57
+
58
+
59
+ def list_names() -> list[str]:
60
+ return backend().names()
61
+
62
+
63
+ def set_secret(name: str, value: str) -> None:
64
+ backend().put(validate_name(name), validate_value(value))
65
+
66
+
67
+ def delete_secret(name: str) -> None:
68
+ if not backend().delete(validate_name(name)):
69
+ raise MissingSecretError(f"no entry named {name!r}")
70
+
71
+
72
+ def resolve(names: list[str]) -> tuple[dict[str, str], list[str]]:
73
+ """Every name is looked up before any is used, so a caller refuses as a whole rather than start a server with half its secrets; an empty value counts as missing."""
74
+ found: dict[str, str] = {}
75
+ missing: list[str] = []
76
+ for name in dict.fromkeys(names):
77
+ value = get_secret(name)
78
+ if value:
79
+ found[name] = value
80
+ else:
81
+ missing.append(name)
82
+ return found, missing
83
+
84
+
85
+ def missing_hint(names: list[str]) -> str:
86
+ return f"{', '.join(names)} (store them with `keyexec set <entry>`)"