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
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Implementation of `keychain-cli delete` (US5, T055)."""
|
|
2
|
+
# pylint: disable=missing-function-docstring
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import argparse
|
|
7
|
+
|
|
8
|
+
from keychain_cli.errors import NotFoundError, RefusedError
|
|
9
|
+
from keychain_cli.keychain import NotFound, SecretStore
|
|
10
|
+
from keychain_cli.names import validate_namespace, validate_variable
|
|
11
|
+
from keychain_cli.prompt import Prompter
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def run_delete(args: argparse.Namespace, store: SecretStore, prompts: Prompter) -> int:
|
|
15
|
+
"""Run `keychain-cli delete`."""
|
|
16
|
+
ns = validate_namespace(args.namespace)
|
|
17
|
+
|
|
18
|
+
if args.variable:
|
|
19
|
+
var = validate_variable(args.variable)
|
|
20
|
+
try:
|
|
21
|
+
store.delete_variable(ns, var)
|
|
22
|
+
except NotFound:
|
|
23
|
+
raise NotFoundError(
|
|
24
|
+
f"variable '{var}' not found in namespace '{ns.display}'",
|
|
25
|
+
f"Run `keychain-cli list {ns.display}` to see existing variables",
|
|
26
|
+
) from None
|
|
27
|
+
return 0
|
|
28
|
+
|
|
29
|
+
try:
|
|
30
|
+
variables = store.list_variables(ns)
|
|
31
|
+
except NotFound:
|
|
32
|
+
raise NotFoundError(
|
|
33
|
+
f"namespace '{ns.display}' not found",
|
|
34
|
+
"Run `keychain-cli list` to see existing namespaces",
|
|
35
|
+
) from None
|
|
36
|
+
|
|
37
|
+
count = len(variables)
|
|
38
|
+
if not args.force:
|
|
39
|
+
if not prompts.is_interactive():
|
|
40
|
+
raise RefusedError(
|
|
41
|
+
f"refusing to delete namespace '{ns.display}' non-interactively without --force",
|
|
42
|
+
"Pass --force to confirm deletion in automated scripts",
|
|
43
|
+
)
|
|
44
|
+
msg = (
|
|
45
|
+
f"Delete namespace {ns.display} and its {count} variables? "
|
|
46
|
+
"Type the namespace name to confirm:"
|
|
47
|
+
)
|
|
48
|
+
if not prompts.confirm_exact(msg, ns):
|
|
49
|
+
raise RefusedError(
|
|
50
|
+
f"deletion of namespace '{ns.display}' canceled",
|
|
51
|
+
"Type the exact namespace name to confirm deletion",
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
store.delete_namespace(ns)
|
|
55
|
+
return 0
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Implementation of `keychain-cli import` (US3, T046)."""
|
|
2
|
+
# pylint: disable=missing-function-docstring
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import argparse
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from keychain_cli.envfile import parse_env_file
|
|
10
|
+
from keychain_cli.errors import InvalidInputError
|
|
11
|
+
from keychain_cli.keychain import SecretStore
|
|
12
|
+
from keychain_cli.names import validate_namespace
|
|
13
|
+
from keychain_cli.output import StoreReport, err, print_report
|
|
14
|
+
from keychain_cli.prompt import Prompter
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def run_import(args: argparse.Namespace, store: SecretStore, prompts: Prompter) -> int:
|
|
18
|
+
"""Run `keychain-cli import`."""
|
|
19
|
+
ns = validate_namespace(args.namespace)
|
|
20
|
+
file_path = Path(args.file)
|
|
21
|
+
|
|
22
|
+
parsed = parse_env_file(file_path)
|
|
23
|
+
|
|
24
|
+
if not parsed.entries and parsed.malformed:
|
|
25
|
+
raise InvalidInputError(
|
|
26
|
+
"every line was malformed",
|
|
27
|
+
"Provide a file with at least one valid KEY=value entry",
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
for m in parsed.malformed:
|
|
31
|
+
if m.name is None:
|
|
32
|
+
err(f"warning: line {m.line}: malformed entry")
|
|
33
|
+
else:
|
|
34
|
+
err(f"warning: line {m.line} ({m.name}): malformed entry")
|
|
35
|
+
|
|
36
|
+
report = StoreReport(
|
|
37
|
+
malformed=parsed.malformed,
|
|
38
|
+
duplicates=parsed.duplicates,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
existing = [e for e in parsed.entries if store.exists(ns, e.name)]
|
|
42
|
+
new_entries = [e for e in parsed.entries if not store.exists(ns, e.name)]
|
|
43
|
+
|
|
44
|
+
overwrite = False
|
|
45
|
+
if existing:
|
|
46
|
+
if args.force:
|
|
47
|
+
overwrite = True
|
|
48
|
+
elif prompts.is_interactive():
|
|
49
|
+
names_str = ", ".join(e.name for e in existing)
|
|
50
|
+
msg = f"{len(existing)} variables already exist: {names_str}. Overwrite all?"
|
|
51
|
+
overwrite = prompts.confirm(msg, default=False)
|
|
52
|
+
else:
|
|
53
|
+
overwrite = False
|
|
54
|
+
|
|
55
|
+
try:
|
|
56
|
+
for entry in new_entries:
|
|
57
|
+
store.add(ns, entry.name, entry.value)
|
|
58
|
+
report.stored.append(entry.name)
|
|
59
|
+
|
|
60
|
+
if overwrite:
|
|
61
|
+
for entry in existing:
|
|
62
|
+
store.update(ns, entry.name, entry.value)
|
|
63
|
+
report.overwritten.append(entry.name)
|
|
64
|
+
else:
|
|
65
|
+
for entry in existing:
|
|
66
|
+
report.skipped.append(entry.name)
|
|
67
|
+
except KeyboardInterrupt:
|
|
68
|
+
print_report(report)
|
|
69
|
+
raise
|
|
70
|
+
|
|
71
|
+
print_report(report)
|
|
72
|
+
return 0 if not report.skipped else 4
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Implementation of `keychain-cli init` (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.commands.set_ import store_single_value
|
|
11
|
+
from keychain_cli.errors import InvalidInputError
|
|
12
|
+
from keychain_cli.keychain import SecretStore
|
|
13
|
+
from keychain_cli.manifest import load_manifest
|
|
14
|
+
from keychain_cli.names import Namespace
|
|
15
|
+
from keychain_cli.output import StoreReport, err, print_report
|
|
16
|
+
from keychain_cli.prompt import Prompter
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def run_init(
|
|
20
|
+
args: argparse.Namespace,
|
|
21
|
+
store: SecretStore,
|
|
22
|
+
prompts: Prompter,
|
|
23
|
+
resolve_ns_fn: Callable[[str | None], Namespace],
|
|
24
|
+
) -> int:
|
|
25
|
+
"""Run `keychain-cli init`."""
|
|
26
|
+
manifest = load_manifest(Path.cwd())
|
|
27
|
+
ns: Namespace = resolve_ns_fn(args.namespace)
|
|
28
|
+
|
|
29
|
+
missing = [v for v in manifest.variables if not store.exists(ns, v)]
|
|
30
|
+
|
|
31
|
+
if not missing:
|
|
32
|
+
err(f"namespace {ns.display} is complete")
|
|
33
|
+
return 0
|
|
34
|
+
|
|
35
|
+
if not prompts.is_interactive():
|
|
36
|
+
raise InvalidInputError(
|
|
37
|
+
f"cannot prompt for missing variables non-interactively: {', '.join(missing)}",
|
|
38
|
+
"Run interactively to be prompted, or store values with `keychain-cli set`",
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
report = StoreReport()
|
|
42
|
+
try:
|
|
43
|
+
for var in missing:
|
|
44
|
+
value = prompts.read_secret(f"Value for {ns.display}/{var}:")
|
|
45
|
+
if not value.data and not prompts.confirm(
|
|
46
|
+
f"Store an empty value for {var}?", default=False
|
|
47
|
+
):
|
|
48
|
+
report.skipped.append(var)
|
|
49
|
+
continue
|
|
50
|
+
store_single_value(
|
|
51
|
+
ns,
|
|
52
|
+
var,
|
|
53
|
+
value,
|
|
54
|
+
store,
|
|
55
|
+
prompts,
|
|
56
|
+
report,
|
|
57
|
+
force=False,
|
|
58
|
+
interactive=True,
|
|
59
|
+
)
|
|
60
|
+
except KeyboardInterrupt:
|
|
61
|
+
print_report(report)
|
|
62
|
+
raise
|
|
63
|
+
|
|
64
|
+
print_report(report)
|
|
65
|
+
return 0 if not report.skipped else 4
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Implementation of `keychain-cli list` (US4, T051)."""
|
|
2
|
+
# pylint: disable=missing-function-docstring
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import argparse
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
|
|
9
|
+
from keychain_cli.errors import NotFoundError, UsageError
|
|
10
|
+
from keychain_cli.keychain import NotFound, SecretStore
|
|
11
|
+
from keychain_cli.names import Namespace, validate_namespace
|
|
12
|
+
from keychain_cli.output import emit_names
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def run_list(
|
|
16
|
+
args: argparse.Namespace,
|
|
17
|
+
store: SecretStore,
|
|
18
|
+
resolve_ns_fn: Callable[[str | None], Namespace] | None = None,
|
|
19
|
+
) -> int:
|
|
20
|
+
"""Run `keychain-cli list`."""
|
|
21
|
+
if getattr(args, "all", False):
|
|
22
|
+
if args.namespace:
|
|
23
|
+
raise UsageError(
|
|
24
|
+
"--all does not accept a namespace argument",
|
|
25
|
+
"Use `keychain-cli list --all` to list namespaces, or "
|
|
26
|
+
"`keychain-cli list [NAMESPACE]` to list variables",
|
|
27
|
+
)
|
|
28
|
+
namespaces = store.list_namespaces()
|
|
29
|
+
emit_names([ns.display for ns in namespaces], args.json)
|
|
30
|
+
return 0
|
|
31
|
+
|
|
32
|
+
target_ns: Namespace | None = None
|
|
33
|
+
if args.namespace:
|
|
34
|
+
target_ns = validate_namespace(args.namespace)
|
|
35
|
+
elif resolve_ns_fn is not None:
|
|
36
|
+
try:
|
|
37
|
+
target_ns = resolve_ns_fn(None)
|
|
38
|
+
except UsageError:
|
|
39
|
+
target_ns = None
|
|
40
|
+
|
|
41
|
+
if target_ns is not None:
|
|
42
|
+
try:
|
|
43
|
+
variables = store.list_variables(target_ns)
|
|
44
|
+
except NotFound:
|
|
45
|
+
raise NotFoundError(
|
|
46
|
+
f"namespace '{target_ns.display}' not found",
|
|
47
|
+
"Check the namespace name or run `keychain-cli list` to see existing namespaces",
|
|
48
|
+
) from None
|
|
49
|
+
emit_names(variables, args.json)
|
|
50
|
+
return 0
|
|
51
|
+
|
|
52
|
+
namespaces = store.list_namespaces()
|
|
53
|
+
emit_names([ns.display for ns in namespaces], args.json)
|
|
54
|
+
return 0
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Implementation of `keychain-cli run` (US2, T038)."""
|
|
2
|
+
# pylint: disable=missing-function-docstring
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import argparse
|
|
7
|
+
import os
|
|
8
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from keychain_cli.errors import CommandNotFoundError, NotFoundError, UsageError
|
|
12
|
+
from keychain_cli.keychain import NotFound, SecretStore
|
|
13
|
+
from keychain_cli.names import Namespace
|
|
14
|
+
|
|
15
|
+
ExecFn = Callable[[str, Sequence[str], Mapping[str, str]], Any]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def run_run(
|
|
19
|
+
args: argparse.Namespace,
|
|
20
|
+
command_tail: list[str],
|
|
21
|
+
store: SecretStore,
|
|
22
|
+
exec_fn: ExecFn,
|
|
23
|
+
resolve_ns_fn: Callable[[str | None], Namespace],
|
|
24
|
+
) -> int:
|
|
25
|
+
"""Run `keychain-cli run`."""
|
|
26
|
+
if not command_tail:
|
|
27
|
+
raise UsageError(
|
|
28
|
+
"no command specified after `--`",
|
|
29
|
+
"Use: keychain-cli run [NAMESPACE] -- COMMAND [ARG ...]",
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
ns = resolve_ns_fn(args.namespace)
|
|
33
|
+
try:
|
|
34
|
+
values = store.get_all(ns)
|
|
35
|
+
except NotFound:
|
|
36
|
+
raise NotFoundError(
|
|
37
|
+
f"namespace '{ns.display}' not found",
|
|
38
|
+
"Run 'keychain-cli init' to configure this project, "
|
|
39
|
+
"or 'keychain-cli set' to store variables",
|
|
40
|
+
) from None
|
|
41
|
+
|
|
42
|
+
env = {**os.environ, **{name: v.data.decode("utf-8") for name, v in values.items()}}
|
|
43
|
+
|
|
44
|
+
try:
|
|
45
|
+
exec_fn(command_tail[0], command_tail, env)
|
|
46
|
+
except (FileNotFoundError, PermissionError) as err:
|
|
47
|
+
raise CommandNotFoundError(
|
|
48
|
+
f"cannot execute '{command_tail[0]}': {err.strerror}",
|
|
49
|
+
"Check that the command exists, is on PATH, and is executable",
|
|
50
|
+
) from None
|
|
51
|
+
|
|
52
|
+
return 0
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""Implementation of `keychain-cli set` (US1, T033)."""
|
|
2
|
+
# pylint: disable=missing-function-docstring
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import argparse
|
|
7
|
+
|
|
8
|
+
from keychain_cli.errors import InvalidInputError
|
|
9
|
+
from keychain_cli.keychain import AlreadyExists, SecretStore
|
|
10
|
+
from keychain_cli.names import Namespace, validate_namespace, validate_variable
|
|
11
|
+
from keychain_cli.output import StoreReport, print_report
|
|
12
|
+
from keychain_cli.prompt import Prompter
|
|
13
|
+
from keychain_cli.secret import SecretValue
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def store_single_value(
|
|
17
|
+
ns: Namespace,
|
|
18
|
+
var: str,
|
|
19
|
+
value: SecretValue,
|
|
20
|
+
store: SecretStore,
|
|
21
|
+
prompts: Prompter,
|
|
22
|
+
report: StoreReport,
|
|
23
|
+
*,
|
|
24
|
+
force: bool,
|
|
25
|
+
interactive: bool,
|
|
26
|
+
) -> None:
|
|
27
|
+
"""Store or update a single variable, updating the report."""
|
|
28
|
+
try:
|
|
29
|
+
store.add(ns, var, value)
|
|
30
|
+
report.stored.append(var)
|
|
31
|
+
except AlreadyExists:
|
|
32
|
+
if (
|
|
33
|
+
force
|
|
34
|
+
or interactive
|
|
35
|
+
and prompts.confirm(f"{var} already exists in {ns.display}. Overwrite?", default=False)
|
|
36
|
+
):
|
|
37
|
+
store.update(ns, var, value)
|
|
38
|
+
report.overwritten.append(var)
|
|
39
|
+
else:
|
|
40
|
+
report.skipped.append(var)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def run_set(args: argparse.Namespace, store: SecretStore, prompts: Prompter) -> int:
|
|
44
|
+
"""Run `keychain-cli set`."""
|
|
45
|
+
ns = validate_namespace(args.namespace)
|
|
46
|
+
|
|
47
|
+
variables: list[str] = list(args.variables)
|
|
48
|
+
seen: set[str] = set()
|
|
49
|
+
for var in variables:
|
|
50
|
+
validate_variable(var)
|
|
51
|
+
if var in seen:
|
|
52
|
+
raise InvalidInputError(
|
|
53
|
+
f"duplicate variable '{var}' in invocation",
|
|
54
|
+
"Name each variable once per invocation",
|
|
55
|
+
)
|
|
56
|
+
seen.add(var)
|
|
57
|
+
|
|
58
|
+
report = StoreReport()
|
|
59
|
+
is_interactive = prompts.is_interactive()
|
|
60
|
+
use_stdin = bool(args.stdin or not is_interactive)
|
|
61
|
+
|
|
62
|
+
if use_stdin:
|
|
63
|
+
if len(variables) != 1:
|
|
64
|
+
raise InvalidInputError(
|
|
65
|
+
"standard input mode takes exactly one variable",
|
|
66
|
+
"Name exactly one variable when piping input or using --stdin",
|
|
67
|
+
)
|
|
68
|
+
var = variables[0]
|
|
69
|
+
value = prompts.read_secret_from_stdin()
|
|
70
|
+
store_single_value(
|
|
71
|
+
ns,
|
|
72
|
+
var,
|
|
73
|
+
value,
|
|
74
|
+
store,
|
|
75
|
+
prompts,
|
|
76
|
+
report,
|
|
77
|
+
force=bool(args.force),
|
|
78
|
+
interactive=is_interactive,
|
|
79
|
+
)
|
|
80
|
+
print_report(report)
|
|
81
|
+
return 0 if not report.skipped else 4
|
|
82
|
+
|
|
83
|
+
# Interactive mode
|
|
84
|
+
try:
|
|
85
|
+
for var in variables:
|
|
86
|
+
value = prompts.read_secret(f"Value for {ns.display}/{var}:")
|
|
87
|
+
if not value.data and not prompts.confirm(
|
|
88
|
+
f"Store an empty value for {var}?", default=False
|
|
89
|
+
):
|
|
90
|
+
report.skipped.append(var)
|
|
91
|
+
continue
|
|
92
|
+
store_single_value(
|
|
93
|
+
ns,
|
|
94
|
+
var,
|
|
95
|
+
value,
|
|
96
|
+
store,
|
|
97
|
+
prompts,
|
|
98
|
+
report,
|
|
99
|
+
force=bool(args.force),
|
|
100
|
+
interactive=True,
|
|
101
|
+
)
|
|
102
|
+
except KeyboardInterrupt:
|
|
103
|
+
print_report(report)
|
|
104
|
+
raise
|
|
105
|
+
|
|
106
|
+
print_report(report)
|
|
107
|
+
return 0 if not report.skipped else 4
|
keychain_cli/envfile.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""Parser for `.env` files per research R-008 (US3, T045)."""
|
|
2
|
+
# pylint: disable=missing-function-docstring
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from keychain_cli.errors import InvalidInputError, NotFoundError
|
|
10
|
+
from keychain_cli.names import VARIABLE_PATTERN
|
|
11
|
+
from keychain_cli.output import DuplicateKey, MalformedLine
|
|
12
|
+
from keychain_cli.secret import SecretValue
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class EnvFileEntry:
|
|
17
|
+
"""One successfully parsed variable assignment."""
|
|
18
|
+
|
|
19
|
+
line: int
|
|
20
|
+
name: str
|
|
21
|
+
value: SecretValue
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class EnvFileParse:
|
|
26
|
+
"""The complete result of parsing a `.env` file."""
|
|
27
|
+
|
|
28
|
+
entries: list[EnvFileEntry] = field(default_factory=list)
|
|
29
|
+
malformed: list[MalformedLine] = field(default_factory=list)
|
|
30
|
+
duplicates: list[DuplicateKey] = field(default_factory=list)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _parse_double_quoted(s: str) -> str:
|
|
34
|
+
"""Parse and unescape a double-quoted string body. Raises ValueError if unterminated."""
|
|
35
|
+
result: list[str] = []
|
|
36
|
+
i = 0
|
|
37
|
+
n = len(s)
|
|
38
|
+
while i < n:
|
|
39
|
+
c = s[i]
|
|
40
|
+
if c == '"':
|
|
41
|
+
# Closing quote found! Remainder must be whitespace or comment.
|
|
42
|
+
rem = s[i + 1 :].strip()
|
|
43
|
+
if rem and not rem.startswith("#"):
|
|
44
|
+
raise ValueError("unexpected content after closing quote")
|
|
45
|
+
return "".join(result)
|
|
46
|
+
if c == "\\":
|
|
47
|
+
if i + 1 >= n:
|
|
48
|
+
raise ValueError("unterminated escape")
|
|
49
|
+
nxt = s[i + 1]
|
|
50
|
+
if nxt == "n":
|
|
51
|
+
result.append("\n")
|
|
52
|
+
elif nxt == "t":
|
|
53
|
+
result.append("\t")
|
|
54
|
+
elif nxt == '"':
|
|
55
|
+
result.append('"')
|
|
56
|
+
elif nxt == "\\":
|
|
57
|
+
result.append("\\")
|
|
58
|
+
else:
|
|
59
|
+
result.append("\\" + nxt)
|
|
60
|
+
i += 2
|
|
61
|
+
continue
|
|
62
|
+
result.append(c)
|
|
63
|
+
i += 1
|
|
64
|
+
raise ValueError("unterminated double quote")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _parse_single_quoted(s: str) -> str:
|
|
68
|
+
"""Parse a single-quoted string body. Raises ValueError if unterminated."""
|
|
69
|
+
close_idx = s.find("'")
|
|
70
|
+
if close_idx == -1:
|
|
71
|
+
raise ValueError("unterminated single quote")
|
|
72
|
+
rem = s[close_idx + 1 :].strip()
|
|
73
|
+
if rem and not rem.startswith("#"):
|
|
74
|
+
raise ValueError("unexpected content after closing quote")
|
|
75
|
+
return s[:close_idx]
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _parse_unquoted(s: str) -> str:
|
|
79
|
+
"""Strip trailing ` #` comments and surrounding whitespace from unquoted value."""
|
|
80
|
+
# Trailing comment must be preceded by space
|
|
81
|
+
# Look for ' #'
|
|
82
|
+
comment_idx = s.find(" #")
|
|
83
|
+
if comment_idx != -1:
|
|
84
|
+
s = s[:comment_idx]
|
|
85
|
+
return s.strip()
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def parse_env_file(path: Path) -> EnvFileParse:
|
|
89
|
+
"""Parse a `.env` file at the given path."""
|
|
90
|
+
if not path.exists():
|
|
91
|
+
raise NotFoundError(f"file '{path}' not found", "Check the path and retry")
|
|
92
|
+
if not path.is_file():
|
|
93
|
+
raise InvalidInputError(
|
|
94
|
+
f"'{path}' is not a regular file",
|
|
95
|
+
"Provide a path to a regular file",
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
try:
|
|
99
|
+
raw_bytes = path.read_bytes()
|
|
100
|
+
except (PermissionError, OSError) as err:
|
|
101
|
+
raise InvalidInputError(
|
|
102
|
+
f"cannot read '{path}': {err.strerror}",
|
|
103
|
+
"Make sure the file exists and is readable",
|
|
104
|
+
) from None
|
|
105
|
+
|
|
106
|
+
try:
|
|
107
|
+
text = raw_bytes.decode("utf-8")
|
|
108
|
+
except UnicodeDecodeError as err:
|
|
109
|
+
# Determine the line where decode failed
|
|
110
|
+
line_no = raw_bytes[: err.start].count(b"\n") + 1
|
|
111
|
+
raise InvalidInputError(
|
|
112
|
+
f"file '{path}' contains invalid UTF-8 at line {line_no}",
|
|
113
|
+
"Ensure the file is encoded in valid UTF-8",
|
|
114
|
+
) from None
|
|
115
|
+
|
|
116
|
+
lines = text.splitlines()
|
|
117
|
+
entries_by_name: dict[str, EnvFileEntry] = {}
|
|
118
|
+
first_lines: dict[str, int] = {}
|
|
119
|
+
duplicates_list: list[DuplicateKey] = []
|
|
120
|
+
malformed: list[MalformedLine] = []
|
|
121
|
+
|
|
122
|
+
for line_no, raw_line in enumerate(lines, start=1):
|
|
123
|
+
line = raw_line.strip()
|
|
124
|
+
if not line or line.startswith("#"):
|
|
125
|
+
continue
|
|
126
|
+
|
|
127
|
+
if line.startswith("export "):
|
|
128
|
+
line = line[len("export ") :].strip()
|
|
129
|
+
|
|
130
|
+
if "=" not in line:
|
|
131
|
+
malformed.append(MalformedLine(line=line_no, name=None))
|
|
132
|
+
continue
|
|
133
|
+
|
|
134
|
+
key_part, _, val_part = line.partition("=")
|
|
135
|
+
key = key_part.strip()
|
|
136
|
+
|
|
137
|
+
if not VARIABLE_PATTERN.match(key):
|
|
138
|
+
malformed.append(MalformedLine(line=line_no, name=None))
|
|
139
|
+
continue
|
|
140
|
+
|
|
141
|
+
val_part = val_part.lstrip()
|
|
142
|
+
try:
|
|
143
|
+
if val_part.startswith('"'):
|
|
144
|
+
parsed_val = _parse_double_quoted(val_part[1:])
|
|
145
|
+
elif val_part.startswith("'"):
|
|
146
|
+
parsed_val = _parse_single_quoted(val_part[1:])
|
|
147
|
+
else:
|
|
148
|
+
parsed_val = _parse_unquoted(val_part)
|
|
149
|
+
except ValueError:
|
|
150
|
+
malformed.append(MalformedLine(line=line_no, name=key))
|
|
151
|
+
continue
|
|
152
|
+
|
|
153
|
+
entry = EnvFileEntry(
|
|
154
|
+
line=line_no,
|
|
155
|
+
name=key,
|
|
156
|
+
value=SecretValue.from_text(parsed_val),
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
if key in entries_by_name:
|
|
160
|
+
dup = DuplicateKey(
|
|
161
|
+
name=key,
|
|
162
|
+
first_line=first_lines[key],
|
|
163
|
+
last_line=line_no,
|
|
164
|
+
)
|
|
165
|
+
duplicates_list.append(dup)
|
|
166
|
+
else:
|
|
167
|
+
first_lines[key] = line_no
|
|
168
|
+
|
|
169
|
+
entries_by_name[key] = entry
|
|
170
|
+
|
|
171
|
+
return EnvFileParse(
|
|
172
|
+
entries=sorted(entries_by_name.values(), key=lambda e: e.name),
|
|
173
|
+
malformed=malformed,
|
|
174
|
+
duplicates=duplicates_list,
|
|
175
|
+
)
|
keychain_cli/errors.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""User-facing errors and the exit-code table.
|
|
2
|
+
|
|
3
|
+
Every exception here carries only strings. Constructors reject anything that is not ``str``
|
|
4
|
+
so a secret value, or its length, can never ride on an exception into an error message
|
|
5
|
+
(constitution Principle II; spec FR-037, FR-038). Exit codes are the contract in
|
|
6
|
+
``specs/001-keychain-secret-manager/contracts/cli.md``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
# Non-error results that still use a distinct exit status.
|
|
12
|
+
EXIT_CHECK_MISSING = 10
|
|
13
|
+
EXIT_INTERRUPTED = 130
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _require_text(value: object, what: str) -> str:
|
|
17
|
+
# Exact type on purpose: a str subclass could override __str__ to reveal a value.
|
|
18
|
+
if type(value) is not str: # pylint: disable=unidiomatic-typecheck
|
|
19
|
+
msg = f"{what} must be a plain str, not {type(value).__name__}"
|
|
20
|
+
raise TypeError(msg)
|
|
21
|
+
return value
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class KeychainCliError(Exception):
|
|
25
|
+
"""Base class. Exit code 1 means an unexpected internal error."""
|
|
26
|
+
|
|
27
|
+
exit_code = 1
|
|
28
|
+
|
|
29
|
+
def __init__(self, message: str, next_step: str) -> None:
|
|
30
|
+
self.message = _require_text(message, "message")
|
|
31
|
+
self.next_step = _require_text(next_step, "next_step")
|
|
32
|
+
super().__init__(self.message)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class UsageError(KeychainCliError):
|
|
36
|
+
"""Bad arguments, missing ``--``, or an out-of-range option."""
|
|
37
|
+
|
|
38
|
+
exit_code = 2
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class NotFoundError(KeychainCliError):
|
|
42
|
+
"""Namespace, variable, file, or manifest does not exist."""
|
|
43
|
+
|
|
44
|
+
exit_code = 3
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class RefusedError(KeychainCliError):
|
|
48
|
+
"""The developer declined, or consent could not be asked for non-interactively."""
|
|
49
|
+
|
|
50
|
+
exit_code = 4
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class KeychainError(KeychainCliError):
|
|
54
|
+
"""The Keychain refused or failed. Carries the OS status and OS message only."""
|
|
55
|
+
|
|
56
|
+
exit_code = 5
|
|
57
|
+
|
|
58
|
+
def __init__(self, os_status: int, os_message: str) -> None:
|
|
59
|
+
if type(os_status) is not int: # pylint: disable=unidiomatic-typecheck
|
|
60
|
+
msg = "os_status must be an int"
|
|
61
|
+
raise TypeError(msg)
|
|
62
|
+
self.os_status = os_status
|
|
63
|
+
self.os_message = _require_text(os_message, "os_message")
|
|
64
|
+
super().__init__(
|
|
65
|
+
f"Keychain operation failed: {self.os_message} (status {self.os_status})",
|
|
66
|
+
"Make sure your login keychain is unlocked and you approved any macOS prompt, "
|
|
67
|
+
"then retry",
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class UnsupportedPlatformError(KeychainCliError):
|
|
72
|
+
"""Not macOS, or too old a macOS or Python."""
|
|
73
|
+
|
|
74
|
+
exit_code = 6
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class InvalidInputError(KeychainCliError):
|
|
78
|
+
"""Bad name, malformed manifest, empty or ambiguous stdin value, unreadable file."""
|
|
79
|
+
|
|
80
|
+
exit_code = 7
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class CommandNotFoundError(KeychainCliError):
|
|
84
|
+
"""``run``: the target command does not exist or is not executable."""
|
|
85
|
+
|
|
86
|
+
exit_code = 8
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class ClipboardError(KeychainCliError):
|
|
90
|
+
"""``copy``: clipboard write failed or clearing could not be scheduled."""
|
|
91
|
+
|
|
92
|
+
exit_code = 9
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def format_error(error: KeychainCliError) -> str:
|
|
96
|
+
"""Render one error line: what failed, then what to do next."""
|
|
97
|
+
return f"keychain-cli: {error.message}. {error.next_step}"
|