keychain-cli 0.1.1__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.
- keychain_cli/__init__.py +4 -0
- keychain_cli/__main__.py +8 -0
- keychain_cli/_clipclear.py +40 -0
- keychain_cli/cli.py +455 -0
- keychain_cli/clipboard.py +68 -0
- keychain_cli/commands/__init__.py +5 -0
- keychain_cli/commands/check.py +34 -0
- keychain_cli/commands/copy.py +53 -0
- keychain_cli/commands/delete.py +55 -0
- keychain_cli/commands/import_.py +72 -0
- keychain_cli/commands/init.py +65 -0
- keychain_cli/commands/list_.py +54 -0
- keychain_cli/commands/run.py +52 -0
- keychain_cli/commands/set_.py +107 -0
- keychain_cli/envfile.py +175 -0
- keychain_cli/errors.py +97 -0
- keychain_cli/keychain/__init__.py +78 -0
- keychain_cli/keychain/_cf.py +186 -0
- keychain_cli/keychain/_sec.py +131 -0
- keychain_cli/keychain/store.py +239 -0
- keychain_cli/manifest.py +108 -0
- keychain_cli/names.py +55 -0
- keychain_cli/output.py +84 -0
- keychain_cli/platform_check.py +40 -0
- keychain_cli/prompt.py +104 -0
- keychain_cli/secret.py +56 -0
- keychain_cli-0.1.1.dist-info/METADATA +211 -0
- keychain_cli-0.1.1.dist-info/RECORD +31 -0
- keychain_cli-0.1.1.dist-info/WHEEL +4 -0
- keychain_cli-0.1.1.dist-info/entry_points.txt +3 -0
- keychain_cli-0.1.1.dist-info/licenses/LICENSE +661 -0
keychain_cli/__init__.py
ADDED
keychain_cli/__main__.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Detached clipboard clearing helper (US7, T071).
|
|
2
|
+
|
|
3
|
+
Runs detached in its own session, sleeps for the specified seconds, and clears
|
|
4
|
+
the clipboard only if its contents still match the expected SHA-256 digest.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
import subprocess
|
|
11
|
+
import sys
|
|
12
|
+
import time
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def main() -> int:
|
|
16
|
+
"""Read digest and interval from stdin, sleep, and clear if unmodified."""
|
|
17
|
+
try:
|
|
18
|
+
raw_digest = sys.stdin.readline().strip()
|
|
19
|
+
raw_seconds = sys.stdin.readline().strip()
|
|
20
|
+
if not raw_digest or not raw_seconds:
|
|
21
|
+
return 0
|
|
22
|
+
seconds = float(raw_seconds)
|
|
23
|
+
except (ValueError, OSError):
|
|
24
|
+
return 0
|
|
25
|
+
|
|
26
|
+
time.sleep(seconds)
|
|
27
|
+
|
|
28
|
+
try:
|
|
29
|
+
current = subprocess.check_output(["/usr/bin/pbpaste"]) # noqa: S603
|
|
30
|
+
if hashlib.sha256(current).hexdigest() == raw_digest:
|
|
31
|
+
proc = subprocess.Popen(["/usr/bin/pbcopy"], stdin=subprocess.PIPE) # noqa: S603
|
|
32
|
+
proc.communicate(b"")
|
|
33
|
+
except Exception: # noqa: BLE001
|
|
34
|
+
pass
|
|
35
|
+
|
|
36
|
+
return 0
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
if __name__ == "__main__":
|
|
40
|
+
sys.exit(main())
|
keychain_cli/cli.py
ADDED
|
@@ -0,0 +1,455 @@
|
|
|
1
|
+
"""Entry point: platform guard, ``--`` split, argument parsing, dispatch, exit codes.
|
|
2
|
+
|
|
3
|
+
Commands are registered here but, in this build, every one reports "not implemented" with
|
|
4
|
+
exit 1. The storage layer beneath them is complete and tested.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import os
|
|
11
|
+
import sys
|
|
12
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from keychain_cli import __version__
|
|
18
|
+
from keychain_cli.errors import (
|
|
19
|
+
EXIT_INTERRUPTED,
|
|
20
|
+
InvalidInputError,
|
|
21
|
+
KeychainCliError,
|
|
22
|
+
NotFoundError,
|
|
23
|
+
UsageError,
|
|
24
|
+
format_error,
|
|
25
|
+
)
|
|
26
|
+
from keychain_cli.keychain import SecretStore
|
|
27
|
+
from keychain_cli.names import Namespace, validate_namespace
|
|
28
|
+
from keychain_cli.output import err
|
|
29
|
+
from keychain_cli.platform_check import ensure_supported
|
|
30
|
+
from keychain_cli.prompt import Prompter, TtyPrompter
|
|
31
|
+
|
|
32
|
+
TEST_KEYCHAIN_ENV = "KEYCHAIN_CLI_TEST_KEYCHAIN"
|
|
33
|
+
|
|
34
|
+
ExecFn = Callable[[str, Sequence[str], Mapping[str, str]], Any]
|
|
35
|
+
SpawnFn = Callable[..., Any]
|
|
36
|
+
StoreFactory = Callable[[], SecretStore]
|
|
37
|
+
|
|
38
|
+
COMMANDS = ("set", "list", "run", "import", "delete", "init", "check", "copy")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True)
|
|
42
|
+
class Services:
|
|
43
|
+
"""Side-effect seams injected into commands (constitution VI)."""
|
|
44
|
+
|
|
45
|
+
store_factory: StoreFactory
|
|
46
|
+
prompts: Prompter
|
|
47
|
+
exec_fn: ExecFn
|
|
48
|
+
spawn_fn: SpawnFn
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def split_command_tail(argv: Sequence[str]) -> tuple[list[str], list[str] | None]:
|
|
52
|
+
"""Split at the first literal ``--``. The tail is the command ``run`` will launch.
|
|
53
|
+
|
|
54
|
+
Done before argparse sees anything so that ``run -- cmd`` (namespace omitted) cannot be
|
|
55
|
+
misread as ``run cmd``. Returns ``(head, None)`` when there is no ``--``.
|
|
56
|
+
"""
|
|
57
|
+
args = list(argv)
|
|
58
|
+
if "--" not in args:
|
|
59
|
+
return args, None
|
|
60
|
+
index = args.index("--")
|
|
61
|
+
return args[:index], args[index + 1 :]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def resolve_namespace(explicit: str | None, *, allow_infer: bool) -> Namespace:
|
|
65
|
+
"""Turn the namespace argument into a ``Namespace``, with manifest inference."""
|
|
66
|
+
from keychain_cli.manifest import MANIFEST_NAME, load_manifest
|
|
67
|
+
|
|
68
|
+
if explicit is not None:
|
|
69
|
+
ns = validate_namespace(explicit)
|
|
70
|
+
# Check if manifest exists in cwd and declares a different namespace
|
|
71
|
+
try:
|
|
72
|
+
manifest = load_manifest(Path.cwd())
|
|
73
|
+
if manifest.namespace.key != ns.key:
|
|
74
|
+
err(
|
|
75
|
+
f"using namespace {ns.display} (manifest declares {manifest.namespace.display})"
|
|
76
|
+
)
|
|
77
|
+
except (NotFoundError, InvalidInputError):
|
|
78
|
+
pass
|
|
79
|
+
return ns
|
|
80
|
+
|
|
81
|
+
if allow_infer:
|
|
82
|
+
try:
|
|
83
|
+
manifest = load_manifest(Path.cwd())
|
|
84
|
+
err(f"using namespace {manifest.namespace.display} from {MANIFEST_NAME}")
|
|
85
|
+
return manifest.namespace
|
|
86
|
+
except NotFoundError:
|
|
87
|
+
raise UsageError(
|
|
88
|
+
"no namespace given",
|
|
89
|
+
"Name it as the first argument, or add a .keychain-cli.toml manifest to the "
|
|
90
|
+
"current directory",
|
|
91
|
+
) from None
|
|
92
|
+
|
|
93
|
+
raise UsageError(
|
|
94
|
+
"no namespace given",
|
|
95
|
+
"Name it explicitly; this command never infers a namespace from a manifest",
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def default_store_factory() -> SecretStore:
|
|
100
|
+
"""Open the Keychain store. Imported lazily so the platform check runs first."""
|
|
101
|
+
from keychain_cli.keychain.store import SecurityFrameworkStore, open_keychain
|
|
102
|
+
|
|
103
|
+
override = os.environ.get(TEST_KEYCHAIN_ENV)
|
|
104
|
+
if override:
|
|
105
|
+
err(f"using test keychain {override}")
|
|
106
|
+
return SecurityFrameworkStore(keychain=open_keychain(Path(override)))
|
|
107
|
+
return SecurityFrameworkStore()
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
111
|
+
parser = argparse.ArgumentParser(
|
|
112
|
+
prog="keychain-cli",
|
|
113
|
+
usage="%(prog)s [-h] [--version] COMMAND ...\n %(prog)s COMMAND -h",
|
|
114
|
+
description=(
|
|
115
|
+
"Store project secrets in the macOS Keychain and hand them to one command's "
|
|
116
|
+
"environment, instead of keeping a plaintext .env file."
|
|
117
|
+
),
|
|
118
|
+
)
|
|
119
|
+
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
120
|
+
subparsers = parser.add_subparsers(dest="command", metavar="COMMAND", required=True)
|
|
121
|
+
|
|
122
|
+
set_parser = subparsers.add_parser(
|
|
123
|
+
"set",
|
|
124
|
+
help="store one or more secrets in a namespace",
|
|
125
|
+
description=(
|
|
126
|
+
"Store secrets in a namespace via interactive prompts or standard input.\n\n"
|
|
127
|
+
"Example:\n"
|
|
128
|
+
" keychain-cli set client-a API_TOKEN DB_PASSWORD\n\n"
|
|
129
|
+
"Standard input rule:\n"
|
|
130
|
+
" With --stdin or when standard input is not a TTY, exactly one variable name\n"
|
|
131
|
+
" must be given, and the secret value is read from standard input.\n\n"
|
|
132
|
+
"Exit codes:\n"
|
|
133
|
+
" 0: All requested variables stored or overwritten\n"
|
|
134
|
+
" 4: At least one variable skipped or overwrite refused\n"
|
|
135
|
+
" 5: Keychain operation failed\n"
|
|
136
|
+
" 7: Invalid variable name, duplicate variable, or invalid stdin input\n"
|
|
137
|
+
" 130: Interrupted by user"
|
|
138
|
+
),
|
|
139
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
140
|
+
)
|
|
141
|
+
set_parser.add_argument("namespace", help="target namespace")
|
|
142
|
+
set_parser.add_argument("variables", nargs="+", help="variable name(s) to store")
|
|
143
|
+
set_parser.add_argument(
|
|
144
|
+
"--force",
|
|
145
|
+
action="store_true",
|
|
146
|
+
help="overwrite existing variables without confirmation",
|
|
147
|
+
)
|
|
148
|
+
set_parser.add_argument(
|
|
149
|
+
"--stdin",
|
|
150
|
+
action="store_true",
|
|
151
|
+
help="read value from standard input (exactly one variable)",
|
|
152
|
+
)
|
|
153
|
+
list_parser = subparsers.add_parser(
|
|
154
|
+
"list",
|
|
155
|
+
help="list namespaces, or the variable names in one",
|
|
156
|
+
description=(
|
|
157
|
+
"List namespaces, or the variable names in a namespace.\n\n"
|
|
158
|
+
"If no namespace is given and a .keychain-cli.toml manifest exists in the\n"
|
|
159
|
+
"current directory, that namespace's variables are listed.\n\n"
|
|
160
|
+
"Examples:\n"
|
|
161
|
+
" keychain-cli list\n"
|
|
162
|
+
" keychain-cli list client-a\n"
|
|
163
|
+
" keychain-cli list --all\n\n"
|
|
164
|
+
"Exit codes:\n"
|
|
165
|
+
" 0: Success\n"
|
|
166
|
+
" 2: Invalid arguments\n"
|
|
167
|
+
" 3: Namespace not found"
|
|
168
|
+
),
|
|
169
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
170
|
+
)
|
|
171
|
+
list_parser.add_argument("namespace", nargs="?", help="namespace to list variables for")
|
|
172
|
+
list_parser.add_argument(
|
|
173
|
+
"--all",
|
|
174
|
+
action="store_true",
|
|
175
|
+
help="list all namespaces, ignoring any current-directory manifest",
|
|
176
|
+
)
|
|
177
|
+
list_parser.add_argument(
|
|
178
|
+
"--json",
|
|
179
|
+
action="store_true",
|
|
180
|
+
help="emit names as a compact JSON array on stdout",
|
|
181
|
+
)
|
|
182
|
+
run = subparsers.add_parser(
|
|
183
|
+
"run",
|
|
184
|
+
help="run a command with a namespace's secrets in its environment",
|
|
185
|
+
usage="%(prog)s [NAMESPACE] -- COMMAND [ARG ...]",
|
|
186
|
+
description=(
|
|
187
|
+
"Run a command with secrets from a namespace injected into its environment.\n\n"
|
|
188
|
+
"If no namespace is given, the namespace is inferred from .keychain-cli.toml\n"
|
|
189
|
+
"in the current directory.\n\n"
|
|
190
|
+
"Example:\n"
|
|
191
|
+
" keychain-cli run client-a -- /usr/bin/env\n\n"
|
|
192
|
+
"The `--` separator is required to separate keychain-cli arguments from the command.\n"
|
|
193
|
+
"After launch, the exit status is the command's own exit status.\n\n"
|
|
194
|
+
"Exit codes (before launch):\n"
|
|
195
|
+
" 2: Missing `--` or invalid usage\n"
|
|
196
|
+
" 3: Namespace not found\n"
|
|
197
|
+
" 5: Keychain operation failed\n"
|
|
198
|
+
" 8: Command not found or not executable"
|
|
199
|
+
),
|
|
200
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
201
|
+
)
|
|
202
|
+
run.add_argument("namespace", nargs="?", help="namespace to load (or omit to use the manifest)")
|
|
203
|
+
import_parser = subparsers.add_parser(
|
|
204
|
+
"import",
|
|
205
|
+
help="import a .env file into a namespace",
|
|
206
|
+
description=(
|
|
207
|
+
"Import variables from a .env-style file into a namespace.\n\n"
|
|
208
|
+
"Example:\n"
|
|
209
|
+
" keychain-cli import client-a project.env\n\n"
|
|
210
|
+
"Parsing rules:\n"
|
|
211
|
+
" - Blank lines and lines starting with '#' are ignored\n"
|
|
212
|
+
" - Optional leading 'export '\n"
|
|
213
|
+
" - KEY=value syntax with single, double, or unquoted values\n"
|
|
214
|
+
" - Trailing unquoted comments starting with ' #' are stripped\n"
|
|
215
|
+
" - The source file is never modified\n\n"
|
|
216
|
+
"Exit codes:\n"
|
|
217
|
+
" 0: Every parsed entry stored or overwritten\n"
|
|
218
|
+
" 3: File not found\n"
|
|
219
|
+
" 4: Overwrite declined or skipped\n"
|
|
220
|
+
" 5: Keychain operation failed\n"
|
|
221
|
+
" 7: File unreadable, not regular, or every line malformed\n"
|
|
222
|
+
" 130: Interrupted by user"
|
|
223
|
+
),
|
|
224
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
225
|
+
)
|
|
226
|
+
import_parser.add_argument("namespace", help="target namespace")
|
|
227
|
+
import_parser.add_argument("file", help="path to .env file to import")
|
|
228
|
+
import_parser.add_argument(
|
|
229
|
+
"--force",
|
|
230
|
+
action="store_true",
|
|
231
|
+
help="overwrite existing variables without confirmation",
|
|
232
|
+
)
|
|
233
|
+
delete_parser = subparsers.add_parser(
|
|
234
|
+
"delete",
|
|
235
|
+
help="delete one variable or a whole namespace",
|
|
236
|
+
description=(
|
|
237
|
+
"Delete a single variable or an entire namespace.\n\n"
|
|
238
|
+
"Examples:\n"
|
|
239
|
+
" keychain-cli delete client-a API_TOKEN\n"
|
|
240
|
+
" keychain-cli delete client-a\n\n"
|
|
241
|
+
"Deleting an entire namespace requires interactive confirmation by typing\n"
|
|
242
|
+
"the namespace name, or passing --force.\n"
|
|
243
|
+
"The namespace is never inferred from a manifest for delete.\n\n"
|
|
244
|
+
"Exit codes:\n"
|
|
245
|
+
" 0: Deleted successfully\n"
|
|
246
|
+
" 2: Missing namespace or invalid arguments\n"
|
|
247
|
+
" 3: Variable or namespace not found\n"
|
|
248
|
+
" 4: Deletion declined or non-interactive without --force\n"
|
|
249
|
+
" 5: Keychain operation failed"
|
|
250
|
+
),
|
|
251
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
252
|
+
)
|
|
253
|
+
delete_parser.add_argument("namespace", help="target namespace (never inferred)")
|
|
254
|
+
delete_parser.add_argument("variable", nargs="?", help="optional variable name to delete")
|
|
255
|
+
delete_parser.add_argument(
|
|
256
|
+
"--force",
|
|
257
|
+
action="store_true",
|
|
258
|
+
help="delete whole namespace without confirmation",
|
|
259
|
+
)
|
|
260
|
+
init_parser = subparsers.add_parser(
|
|
261
|
+
"init",
|
|
262
|
+
help="store the variables a project manifest requires",
|
|
263
|
+
description=(
|
|
264
|
+
"Prompt for and store any variables declared in .keychain-cli.toml that\n"
|
|
265
|
+
"are not already present in the Keychain.\n\n"
|
|
266
|
+
"Examples:\n"
|
|
267
|
+
" keychain-cli init\n"
|
|
268
|
+
" keychain-cli init client-a\n\n"
|
|
269
|
+
"Exit codes:\n"
|
|
270
|
+
" 0: Complete; all declared variables are stored\n"
|
|
271
|
+
" 3: Manifest file not found\n"
|
|
272
|
+
" 5: Keychain operation failed\n"
|
|
273
|
+
" 7: Manifest malformed, or missing variables when run non-interactively\n"
|
|
274
|
+
" 130: Interrupted by user"
|
|
275
|
+
),
|
|
276
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
277
|
+
)
|
|
278
|
+
init_parser.add_argument("namespace", nargs="?", help="optional namespace override")
|
|
279
|
+
|
|
280
|
+
check_parser = subparsers.add_parser(
|
|
281
|
+
"check",
|
|
282
|
+
help="report which manifest variables are missing",
|
|
283
|
+
description=(
|
|
284
|
+
"Report which variables declared in .keychain-cli.toml are missing.\n\n"
|
|
285
|
+
"Examples:\n"
|
|
286
|
+
" keychain-cli check\n"
|
|
287
|
+
" keychain-cli check --json\n\n"
|
|
288
|
+
"Exit codes:\n"
|
|
289
|
+
" 0: All required variables are present\n"
|
|
290
|
+
" 3: Manifest file not found\n"
|
|
291
|
+
" 7: Manifest malformed\n"
|
|
292
|
+
" 10: One or more required variables are missing"
|
|
293
|
+
),
|
|
294
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
295
|
+
)
|
|
296
|
+
check_parser.add_argument("namespace", nargs="?", help="optional namespace override")
|
|
297
|
+
check_parser.add_argument(
|
|
298
|
+
"--json",
|
|
299
|
+
action="store_true",
|
|
300
|
+
help="emit missing variable names as a compact JSON array on stdout",
|
|
301
|
+
)
|
|
302
|
+
copy_parser = subparsers.add_parser(
|
|
303
|
+
"copy",
|
|
304
|
+
help="copy one secret to the clipboard (optional capability)",
|
|
305
|
+
description=(
|
|
306
|
+
"Copy a single secret to the system clipboard for pasting into applications\n"
|
|
307
|
+
"that cannot read environment variables.\n\n"
|
|
308
|
+
"Example:\n"
|
|
309
|
+
" keychain-cli copy client-a API_TOKEN\n\n"
|
|
310
|
+
"Security notice:\n"
|
|
311
|
+
" Not the normal way to use a secret; prefer `run`.\n"
|
|
312
|
+
" The clipboard is readable by every application running as you, and clipboard\n"
|
|
313
|
+
" managers or history tools can defeat automatic clearing.\n\n"
|
|
314
|
+
"Exit codes:\n"
|
|
315
|
+
" 0: Copied and clearing scheduled\n"
|
|
316
|
+
" 2: Clearing interval out of range or invalid arguments\n"
|
|
317
|
+
" 3: Variable or namespace not found\n"
|
|
318
|
+
" 5: Keychain operation failed\n"
|
|
319
|
+
" 9: Clipboard write failed or clearing helper could not be started"
|
|
320
|
+
),
|
|
321
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
322
|
+
)
|
|
323
|
+
copy_parser.add_argument("namespace", help="target namespace (never inferred)")
|
|
324
|
+
copy_parser.add_argument("variable", help="exact name of variable to copy")
|
|
325
|
+
copy_parser.add_argument(
|
|
326
|
+
"--clear-after",
|
|
327
|
+
type=int,
|
|
328
|
+
default=45,
|
|
329
|
+
help="seconds before clearing the clipboard (1-300, default 45)",
|
|
330
|
+
)
|
|
331
|
+
return parser
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _not_implemented(command: str) -> KeychainCliError:
|
|
335
|
+
return KeychainCliError(
|
|
336
|
+
f"the {command} command is not implemented in this build",
|
|
337
|
+
"This build contains the storage layer only; see CHANGELOG.md",
|
|
338
|
+
)
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def _dispatch(args: argparse.Namespace, _command_tail: list[str], services: Services) -> int:
|
|
342
|
+
store = services.store_factory()
|
|
343
|
+
if args.command == "set":
|
|
344
|
+
from keychain_cli.commands.set_ import run_set
|
|
345
|
+
|
|
346
|
+
return run_set(args, store, services.prompts)
|
|
347
|
+
if args.command == "run":
|
|
348
|
+
from keychain_cli.commands.run import run_run
|
|
349
|
+
|
|
350
|
+
return run_run(
|
|
351
|
+
args,
|
|
352
|
+
_command_tail,
|
|
353
|
+
store,
|
|
354
|
+
services.exec_fn,
|
|
355
|
+
resolve_ns_fn=lambda ns: resolve_namespace(ns, allow_infer=True),
|
|
356
|
+
)
|
|
357
|
+
if args.command == "import":
|
|
358
|
+
from keychain_cli.commands.import_ import run_import
|
|
359
|
+
|
|
360
|
+
return run_import(args, store, services.prompts)
|
|
361
|
+
if args.command == "list":
|
|
362
|
+
from keychain_cli.commands.list_ import run_list
|
|
363
|
+
|
|
364
|
+
return run_list(
|
|
365
|
+
args,
|
|
366
|
+
store,
|
|
367
|
+
resolve_ns_fn=lambda ns: resolve_namespace(ns, allow_infer=True),
|
|
368
|
+
)
|
|
369
|
+
if args.command == "delete":
|
|
370
|
+
from keychain_cli.commands.delete import run_delete
|
|
371
|
+
|
|
372
|
+
return run_delete(args, store, services.prompts)
|
|
373
|
+
if args.command == "init":
|
|
374
|
+
from keychain_cli.commands.init import run_init
|
|
375
|
+
|
|
376
|
+
return run_init(
|
|
377
|
+
args,
|
|
378
|
+
store,
|
|
379
|
+
services.prompts,
|
|
380
|
+
resolve_ns_fn=lambda ns: resolve_namespace(ns, allow_infer=True),
|
|
381
|
+
)
|
|
382
|
+
if args.command == "check":
|
|
383
|
+
from keychain_cli.commands.check import run_check
|
|
384
|
+
|
|
385
|
+
return run_check(
|
|
386
|
+
args,
|
|
387
|
+
store,
|
|
388
|
+
resolve_ns_fn=lambda ns: resolve_namespace(ns, allow_infer=True),
|
|
389
|
+
)
|
|
390
|
+
if args.command == "copy":
|
|
391
|
+
from keychain_cli.commands.copy import run_copy
|
|
392
|
+
|
|
393
|
+
return run_copy(args, store, services.spawn_fn)
|
|
394
|
+
raise _not_implemented(args.command)
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def _require_separator_for_run(head: list[str], command_tail: list[str] | None) -> list[str]:
|
|
398
|
+
"""``run`` must have ``--``; checked before argparse so the message explains the form."""
|
|
399
|
+
if head and head[0] == "run" and command_tail is None:
|
|
400
|
+
if "-h" in head or "--help" in head:
|
|
401
|
+
return []
|
|
402
|
+
raise UsageError(
|
|
403
|
+
"the run command needs `--` before the command to launch",
|
|
404
|
+
"Use: keychain-cli run [NAMESPACE] -- COMMAND [ARG ...]",
|
|
405
|
+
)
|
|
406
|
+
return command_tail or []
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def main(
|
|
410
|
+
argv: Sequence[str] | None = None,
|
|
411
|
+
*,
|
|
412
|
+
store_factory: StoreFactory | None = None,
|
|
413
|
+
prompts: Prompter | None = None,
|
|
414
|
+
exec_fn: ExecFn | None = None,
|
|
415
|
+
spawn_fn: SpawnFn | None = None,
|
|
416
|
+
) -> int:
|
|
417
|
+
"""Run the CLI and return its exit code. Never raises to the caller."""
|
|
418
|
+
services = Services(
|
|
419
|
+
store_factory=store_factory or default_store_factory,
|
|
420
|
+
prompts=prompts or TtyPrompter(),
|
|
421
|
+
exec_fn=exec_fn or _default_exec,
|
|
422
|
+
spawn_fn=spawn_fn or _default_spawn,
|
|
423
|
+
)
|
|
424
|
+
try:
|
|
425
|
+
ensure_supported()
|
|
426
|
+
head, command_tail = split_command_tail(sys.argv[1:] if argv is None else argv)
|
|
427
|
+
command_tail = _require_separator_for_run(head, command_tail)
|
|
428
|
+
args = build_parser().parse_args(head)
|
|
429
|
+
return _dispatch(args, command_tail, services)
|
|
430
|
+
except SystemExit as exit_request: # argparse --help/--version/usage errors
|
|
431
|
+
code = exit_request.code
|
|
432
|
+
return code if isinstance(code, int) else 2
|
|
433
|
+
except KeychainCliError as error:
|
|
434
|
+
err(format_error(error))
|
|
435
|
+
return error.exit_code
|
|
436
|
+
except KeyboardInterrupt:
|
|
437
|
+
err("keychain-cli: interrupted")
|
|
438
|
+
return EXIT_INTERRUPTED
|
|
439
|
+
except Exception as error: # noqa: BLE001 - last line of defence; never print a traceback
|
|
440
|
+
err(
|
|
441
|
+
f"keychain-cli: unexpected error ({type(error).__name__}). "
|
|
442
|
+
"Report the command you ran, without any secret values"
|
|
443
|
+
)
|
|
444
|
+
return 1
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def _default_exec(file: str, argv: Sequence[str], env: Mapping[str, str]) -> None:
|
|
448
|
+
"""Replace this process with ``argv``. Only ``run`` will call it; no shell is involved."""
|
|
449
|
+
os.execvpe(file, list(argv), dict(env)) # noqa: S606 - argv list, never a shell string
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def _default_spawn(*args: Any, **kwargs: Any) -> Any:
|
|
453
|
+
import subprocess # noqa: PLC0415 - lazy; only the clipboard path spawns processes
|
|
454
|
+
|
|
455
|
+
return subprocess.Popen(*args, **kwargs) # noqa: S603 - argv list, never a shell string
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Clipboard operations and clearing management (US7, T072).
|
|
2
|
+
|
|
3
|
+
Deliberate exposure channel governed by SECURITY-EXCEPTIONS.md entry CLIP-001.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
from collections.abc import Callable
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from keychain_cli.errors import ClipboardError
|
|
14
|
+
from keychain_cli.secret import SecretValue
|
|
15
|
+
|
|
16
|
+
DEFAULT_CLEAR_AFTER = 45
|
|
17
|
+
MIN_CLEAR_AFTER = 1
|
|
18
|
+
MAX_CLEAR_AFTER = 300
|
|
19
|
+
|
|
20
|
+
SpawnFn = Callable[..., Any]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def clear_now(spawn_fn: SpawnFn = subprocess.Popen) -> None:
|
|
24
|
+
"""Clear the clipboard immediately by piping empty input to pbcopy."""
|
|
25
|
+
try:
|
|
26
|
+
proc = spawn_fn(["/usr/bin/pbcopy"], stdin=subprocess.PIPE)
|
|
27
|
+
proc.communicate(b"")
|
|
28
|
+
except Exception: # noqa: BLE001
|
|
29
|
+
pass
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def copy_to_clipboard(value: SecretValue, spawn_fn: SpawnFn = subprocess.Popen) -> None:
|
|
33
|
+
"""Copy the secret value to the macOS clipboard via pbcopy."""
|
|
34
|
+
try:
|
|
35
|
+
proc = spawn_fn(["/usr/bin/pbcopy"], stdin=subprocess.PIPE)
|
|
36
|
+
proc.communicate(value.data)
|
|
37
|
+
if proc.returncode != 0:
|
|
38
|
+
raise ClipboardError(
|
|
39
|
+
"clipboard write failed",
|
|
40
|
+
"Ensure pbcopy is accessible and working in your session",
|
|
41
|
+
)
|
|
42
|
+
except ClipboardError:
|
|
43
|
+
raise
|
|
44
|
+
except Exception as err:
|
|
45
|
+
raise ClipboardError(
|
|
46
|
+
f"clipboard write failed: {err}",
|
|
47
|
+
"Ensure pbcopy is accessible and working in your session",
|
|
48
|
+
) from None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def schedule_clear(digest: str, seconds: int, spawn_fn: SpawnFn = subprocess.Popen) -> None:
|
|
52
|
+
"""Spawn the detached clearing helper to clear the clipboard after `seconds`."""
|
|
53
|
+
try:
|
|
54
|
+
proc = spawn_fn(
|
|
55
|
+
[sys.executable, "-m", "keychain_cli._clipclear"],
|
|
56
|
+
stdin=subprocess.PIPE,
|
|
57
|
+
stdout=subprocess.DEVNULL,
|
|
58
|
+
stderr=subprocess.DEVNULL,
|
|
59
|
+
start_new_session=True,
|
|
60
|
+
)
|
|
61
|
+
proc.stdin.write(f"{digest}\n{seconds}\n".encode())
|
|
62
|
+
proc.stdin.close()
|
|
63
|
+
except Exception as err:
|
|
64
|
+
clear_now(spawn_fn)
|
|
65
|
+
raise ClipboardError(
|
|
66
|
+
f"failed to schedule clipboard clearing: {err}",
|
|
67
|
+
"value was not left on the clipboard; retry or paste from another source",
|
|
68
|
+
) from None
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Implementation of `keychain-cli check` (US6, T062)."""
|
|
2
|
+
# pylint: disable=missing-function-docstring
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import argparse
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from keychain_cli.errors import EXIT_CHECK_MISSING
|
|
11
|
+
from keychain_cli.keychain import SecretStore
|
|
12
|
+
from keychain_cli.manifest import load_manifest
|
|
13
|
+
from keychain_cli.names import Namespace
|
|
14
|
+
from keychain_cli.output import emit_names
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def run_check(
|
|
18
|
+
args: argparse.Namespace,
|
|
19
|
+
store: SecretStore,
|
|
20
|
+
resolve_ns_fn: Callable[[str | None], Namespace],
|
|
21
|
+
) -> int:
|
|
22
|
+
"""Run `keychain-cli check`."""
|
|
23
|
+
manifest = load_manifest(Path.cwd())
|
|
24
|
+
ns: Namespace = resolve_ns_fn(args.namespace)
|
|
25
|
+
|
|
26
|
+
missing = [v for v in manifest.variables if not store.exists(ns, v)]
|
|
27
|
+
|
|
28
|
+
if missing:
|
|
29
|
+
emit_names(missing, args.json)
|
|
30
|
+
return EXIT_CHECK_MISSING
|
|
31
|
+
|
|
32
|
+
if args.json:
|
|
33
|
+
emit_names([], True)
|
|
34
|
+
return 0
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Implementation of `keychain-cli copy` (US7, T073)."""
|
|
2
|
+
# pylint: disable=missing-function-docstring
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import argparse
|
|
7
|
+
import hashlib
|
|
8
|
+
from collections.abc import Callable
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from keychain_cli.clipboard import (
|
|
12
|
+
MAX_CLEAR_AFTER,
|
|
13
|
+
MIN_CLEAR_AFTER,
|
|
14
|
+
copy_to_clipboard,
|
|
15
|
+
schedule_clear,
|
|
16
|
+
)
|
|
17
|
+
from keychain_cli.errors import NotFoundError, UsageError
|
|
18
|
+
from keychain_cli.keychain import NotFound, SecretStore
|
|
19
|
+
from keychain_cli.names import validate_namespace, validate_variable
|
|
20
|
+
from keychain_cli.output import err
|
|
21
|
+
|
|
22
|
+
SpawnFn = Callable[..., Any]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def run_copy(args: argparse.Namespace, store: SecretStore, spawn_fn: SpawnFn) -> int:
|
|
26
|
+
"""Run `keychain-cli copy`."""
|
|
27
|
+
clear_after = args.clear_after
|
|
28
|
+
if clear_after < MIN_CLEAR_AFTER or clear_after > MAX_CLEAR_AFTER:
|
|
29
|
+
raise UsageError(
|
|
30
|
+
f"--clear-after must be between {MIN_CLEAR_AFTER} and {MAX_CLEAR_AFTER} seconds, "
|
|
31
|
+
f"not {clear_after}",
|
|
32
|
+
f"Specify an integer between {MIN_CLEAR_AFTER} and {MAX_CLEAR_AFTER}",
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
ns = validate_namespace(args.namespace)
|
|
36
|
+
var = validate_variable(args.variable)
|
|
37
|
+
|
|
38
|
+
try:
|
|
39
|
+
secret = store.get(ns, var)
|
|
40
|
+
except NotFound:
|
|
41
|
+
raise NotFoundError(
|
|
42
|
+
f"variable '{var}' not found in namespace '{ns.display}'",
|
|
43
|
+
f"Run `keychain-cli list {ns.display}` to see existing variables",
|
|
44
|
+
) from None
|
|
45
|
+
|
|
46
|
+
copy_to_clipboard(secret, spawn_fn=spawn_fn)
|
|
47
|
+
digest = hashlib.sha256(secret.data).hexdigest()
|
|
48
|
+
schedule_clear(digest, clear_after, spawn_fn=spawn_fn)
|
|
49
|
+
|
|
50
|
+
err(f"copied {ns.display}/{var} to clipboard; it will be cleared in {clear_after} seconds.")
|
|
51
|
+
err("warning: clipboard managers, history tools, and clipboard sync may keep a copy.")
|
|
52
|
+
|
|
53
|
+
return 0
|