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/manifest.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""Manifest loader and validator for `.keychain-cli.toml` (US6, T061)."""
|
|
2
|
+
# pylint: disable=missing-function-docstring
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import tomllib
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from keychain_cli.errors import InvalidInputError, NotFoundError
|
|
11
|
+
from keychain_cli.names import Namespace, validate_namespace, validate_variable
|
|
12
|
+
|
|
13
|
+
MANIFEST_NAME = ".keychain-cli.toml"
|
|
14
|
+
ALLOWED_KEYS = {"namespace", "variables"}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class Manifest:
|
|
19
|
+
"""The contents of a `.keychain-cli.toml` file."""
|
|
20
|
+
|
|
21
|
+
namespace: Namespace
|
|
22
|
+
variables: list[str]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def load_manifest(directory: Path) -> Manifest:
|
|
26
|
+
"""Load and validate `.keychain-cli.toml` from the specified directory."""
|
|
27
|
+
manifest_path = directory / MANIFEST_NAME
|
|
28
|
+
if not manifest_path.exists():
|
|
29
|
+
raise NotFoundError(
|
|
30
|
+
f"manifest '{MANIFEST_NAME}' not found in {directory}",
|
|
31
|
+
f"Create a {MANIFEST_NAME} file in the project directory, "
|
|
32
|
+
"or name the namespace explicitly",
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
try:
|
|
36
|
+
raw_text = manifest_path.read_text(encoding="utf-8")
|
|
37
|
+
except (PermissionError, OSError) as err:
|
|
38
|
+
raise InvalidInputError(
|
|
39
|
+
f"cannot read '{MANIFEST_NAME}': {err.strerror}",
|
|
40
|
+
f"Make sure {MANIFEST_NAME} is readable",
|
|
41
|
+
) from None
|
|
42
|
+
|
|
43
|
+
try:
|
|
44
|
+
data = tomllib.loads(raw_text)
|
|
45
|
+
except tomllib.TOMLDecodeError as err:
|
|
46
|
+
raise InvalidInputError(
|
|
47
|
+
f"TOML parse error in '{MANIFEST_NAME}': {err}",
|
|
48
|
+
f"Fix the syntax error in {MANIFEST_NAME}",
|
|
49
|
+
) from None
|
|
50
|
+
|
|
51
|
+
for key, val in data.items():
|
|
52
|
+
if isinstance(val, dict):
|
|
53
|
+
raise InvalidInputError(
|
|
54
|
+
f"tables or nested sections are not allowed in '{MANIFEST_NAME}'",
|
|
55
|
+
"Define 'namespace' and 'variables' at the top level only",
|
|
56
|
+
)
|
|
57
|
+
if key not in ALLOWED_KEYS:
|
|
58
|
+
raise InvalidInputError(
|
|
59
|
+
f"unknown key '{key}' in '{MANIFEST_NAME}'",
|
|
60
|
+
f"Allowed keys are {', '.join(sorted(ALLOWED_KEYS))}",
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
if "namespace" not in data:
|
|
64
|
+
raise InvalidInputError(
|
|
65
|
+
f"missing required key 'namespace' in '{MANIFEST_NAME}'",
|
|
66
|
+
"Specify a namespace string in the manifest",
|
|
67
|
+
)
|
|
68
|
+
if not isinstance(data["namespace"], str):
|
|
69
|
+
raise InvalidInputError(
|
|
70
|
+
f"'namespace' must be a string in '{MANIFEST_NAME}'",
|
|
71
|
+
"Specify the namespace as a quoted string",
|
|
72
|
+
)
|
|
73
|
+
namespace = validate_namespace(data["namespace"])
|
|
74
|
+
|
|
75
|
+
if "variables" not in data:
|
|
76
|
+
raise InvalidInputError(
|
|
77
|
+
f"missing required key 'variables' in '{MANIFEST_NAME}'",
|
|
78
|
+
"Specify an array of variable names in the manifest",
|
|
79
|
+
)
|
|
80
|
+
if not isinstance(data["variables"], list):
|
|
81
|
+
raise InvalidInputError(
|
|
82
|
+
f"'variables' must be an array of strings in '{MANIFEST_NAME}'",
|
|
83
|
+
"Specify variables as a list of strings",
|
|
84
|
+
)
|
|
85
|
+
if not data["variables"]:
|
|
86
|
+
raise InvalidInputError(
|
|
87
|
+
f"variables list cannot be empty in '{MANIFEST_NAME}'",
|
|
88
|
+
"List at least one variable name that the project requires",
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
variables: list[str] = []
|
|
92
|
+
seen: set[str] = set()
|
|
93
|
+
for var in data["variables"]:
|
|
94
|
+
if not isinstance(var, str):
|
|
95
|
+
raise InvalidInputError(
|
|
96
|
+
f"each variable must be a string in '{MANIFEST_NAME}'",
|
|
97
|
+
"Ensure every variable in the list is a quoted string",
|
|
98
|
+
)
|
|
99
|
+
validate_variable(var)
|
|
100
|
+
if var in seen:
|
|
101
|
+
raise InvalidInputError(
|
|
102
|
+
f"duplicate variable '{var}' in '{MANIFEST_NAME}'",
|
|
103
|
+
"Remove the duplicate variable name from the list",
|
|
104
|
+
)
|
|
105
|
+
seen.add(var)
|
|
106
|
+
variables.append(var)
|
|
107
|
+
|
|
108
|
+
return Manifest(namespace=namespace, variables=variables)
|
keychain_cli/names.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Namespace and variable name rules (spec FR-007, FR-007a, FR-007b).
|
|
2
|
+
|
|
3
|
+
Namespaces are matched case-insensitively: ``key`` is the lowercase form used for every
|
|
4
|
+
lookup, ``display`` is the casing the developer typed. Variable names are environment
|
|
5
|
+
variable names and stay case-sensitive.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
|
|
13
|
+
from keychain_cli.errors import InvalidInputError
|
|
14
|
+
|
|
15
|
+
NAMESPACE_FORM = (
|
|
16
|
+
"1 to 64 characters: ASCII letters, digits, '-', '_', or '.', starting with a letter or digit"
|
|
17
|
+
)
|
|
18
|
+
VARIABLE_FORM = (
|
|
19
|
+
"a valid environment variable name: letters, digits, or '_', not starting with a digit"
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
_NAMESPACE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
|
|
23
|
+
_VARIABLE_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
|
|
24
|
+
VARIABLE_PATTERN = _VARIABLE_RE
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class Namespace:
|
|
29
|
+
"""A validated namespace name.
|
|
30
|
+
|
|
31
|
+
``key`` is used for every lookup and comparison; ``display`` is shown to the developer.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
key: str
|
|
35
|
+
display: str
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def validate_namespace(display: str) -> Namespace:
|
|
39
|
+
"""Validate a namespace name and derive its lowercase key."""
|
|
40
|
+
if not _NAMESPACE_RE.match(display):
|
|
41
|
+
raise InvalidInputError(
|
|
42
|
+
f"invalid namespace name {display!r}",
|
|
43
|
+
f"Use {NAMESPACE_FORM}",
|
|
44
|
+
)
|
|
45
|
+
return Namespace(key=display.lower(), display=display)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def validate_variable(name: str) -> str:
|
|
49
|
+
"""Validate an environment variable name. Returns it unchanged."""
|
|
50
|
+
if not _VARIABLE_RE.match(name):
|
|
51
|
+
raise InvalidInputError(
|
|
52
|
+
f"invalid variable name {name!r}",
|
|
53
|
+
f"Use {VARIABLE_FORM}",
|
|
54
|
+
)
|
|
55
|
+
return name
|
keychain_cli/output.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Output helpers and the report types that are safe to print.
|
|
2
|
+
|
|
3
|
+
Results go to stdout, diagnostics to stderr (FR-042). Every type in this module holds names,
|
|
4
|
+
counts, and line numbers only; none can carry a secret value.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import sys
|
|
11
|
+
from collections.abc import Sequence
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def out(line: str) -> None:
|
|
16
|
+
"""Write one result line to stdout."""
|
|
17
|
+
sys.stdout.write(line + "\n")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def err(line: str) -> None:
|
|
21
|
+
"""Write one diagnostic line to stderr."""
|
|
22
|
+
sys.stderr.write(line + "\n")
|
|
23
|
+
sys.stderr.flush()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def emit_names(names: Sequence[str], json_mode: bool) -> None: # noqa: FBT001 - CLI flag
|
|
27
|
+
"""Print names one per line, or as a compact JSON array when ``json_mode`` is set."""
|
|
28
|
+
if json_mode:
|
|
29
|
+
out(json.dumps(list(names), separators=(",", ":")))
|
|
30
|
+
return
|
|
31
|
+
for name in names:
|
|
32
|
+
out(name)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True)
|
|
36
|
+
class MalformedLine:
|
|
37
|
+
"""A ``.env`` line that could not be parsed. Never carries the line's content."""
|
|
38
|
+
|
|
39
|
+
line: int
|
|
40
|
+
name: str | None = None
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class DuplicateKey:
|
|
45
|
+
"""A key defined more than once in a ``.env`` file; the last definition wins."""
|
|
46
|
+
|
|
47
|
+
name: str
|
|
48
|
+
first_line: int
|
|
49
|
+
last_line: int
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass
|
|
53
|
+
class StoreReport:
|
|
54
|
+
"""What a ``set``, ``import``, or ``init`` did, by variable name only."""
|
|
55
|
+
|
|
56
|
+
stored: list[str] = field(default_factory=list)
|
|
57
|
+
skipped: list[str] = field(default_factory=list)
|
|
58
|
+
overwritten: list[str] = field(default_factory=list)
|
|
59
|
+
malformed: list[MalformedLine] = field(default_factory=list)
|
|
60
|
+
duplicates: list[DuplicateKey] = field(default_factory=list)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def print_report(report: StoreReport) -> None:
|
|
64
|
+
"""Render a ``StoreReport`` to stderr, omitting empty categories."""
|
|
65
|
+
for label, names in (
|
|
66
|
+
("stored", report.stored),
|
|
67
|
+
("overwritten", report.overwritten),
|
|
68
|
+
("skipped", report.skipped),
|
|
69
|
+
):
|
|
70
|
+
if names:
|
|
71
|
+
err(f"{label}: {', '.join(names)}")
|
|
72
|
+
if report.malformed:
|
|
73
|
+
err(
|
|
74
|
+
f"malformed: {len(report.malformed)} line(s): "
|
|
75
|
+
+ ", ".join(_describe(m) for m in report.malformed)
|
|
76
|
+
)
|
|
77
|
+
for dup in report.duplicates:
|
|
78
|
+
err(f"duplicate key {dup.name} (lines {dup.first_line}, {dup.last_line}): last value used")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _describe(malformed: MalformedLine) -> str:
|
|
82
|
+
if malformed.name is None:
|
|
83
|
+
return f"line {malformed.line}"
|
|
84
|
+
return f"line {malformed.line} ({malformed.name})"
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Refuse to run anywhere but a supported macOS and Python (spec FR-044; constitution III)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import platform
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
from keychain_cli.errors import UnsupportedPlatformError
|
|
9
|
+
|
|
10
|
+
MIN_MACOS_MAJOR = 13
|
|
11
|
+
MIN_PYTHON = (3, 11)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _macos_major() -> int:
|
|
15
|
+
release = platform.mac_ver()[0]
|
|
16
|
+
head = release.split(".", 1)[0]
|
|
17
|
+
return int(head) if head.isdigit() else 0
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def ensure_supported() -> None:
|
|
21
|
+
"""Raise ``UnsupportedPlatformError`` unless this is macOS 13+ on Python 3.11+."""
|
|
22
|
+
if sys.platform != "darwin":
|
|
23
|
+
raise UnsupportedPlatformError(
|
|
24
|
+
f"unsupported platform {sys.platform!r}; keychain-cli requires macOS",
|
|
25
|
+
"Run it on a Mac. There is deliberately no fallback storage on other systems",
|
|
26
|
+
)
|
|
27
|
+
major = _macos_major()
|
|
28
|
+
if major < MIN_MACOS_MAJOR:
|
|
29
|
+
raise UnsupportedPlatformError(
|
|
30
|
+
f"unsupported macOS version {platform.mac_ver()[0] or 'unknown'}; "
|
|
31
|
+
f"keychain-cli requires macOS {MIN_MACOS_MAJOR} or later",
|
|
32
|
+
"Upgrade macOS to a supported version",
|
|
33
|
+
)
|
|
34
|
+
if sys.version_info < MIN_PYTHON:
|
|
35
|
+
found = ".".join(str(part) for part in sys.version_info[:3])
|
|
36
|
+
wanted = ".".join(str(part) for part in MIN_PYTHON)
|
|
37
|
+
raise UnsupportedPlatformError(
|
|
38
|
+
f"unsupported Python {found}; keychain-cli requires Python {wanted} or later",
|
|
39
|
+
"Reinstall with a newer interpreter, for example: uv tool install keychain-cli",
|
|
40
|
+
)
|
keychain_cli/prompt.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Interactive input: hidden secret prompts, confirmations, and the stdin value path.
|
|
2
|
+
|
|
3
|
+
Everything that touches the terminal lives here so commands can be tested with a fake
|
|
4
|
+
(constitution VI). Secret entry never echoes (FR-003). The stdin path takes exactly one
|
|
5
|
+
value per invocation and strips exactly one trailing newline (FR-004a).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import getpass
|
|
11
|
+
import sys
|
|
12
|
+
from collections.abc import Callable
|
|
13
|
+
from typing import BinaryIO, Protocol
|
|
14
|
+
|
|
15
|
+
from keychain_cli.errors import InvalidInputError
|
|
16
|
+
from keychain_cli.names import Namespace
|
|
17
|
+
from keychain_cli.secret import SecretValue
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Prompter(Protocol):
|
|
21
|
+
"""The seam commands use for all terminal interaction."""
|
|
22
|
+
|
|
23
|
+
def is_interactive(self) -> bool:
|
|
24
|
+
"""True when a person is at a terminal and can answer prompts."""
|
|
25
|
+
...
|
|
26
|
+
|
|
27
|
+
def read_secret(self, prompt: str) -> SecretValue:
|
|
28
|
+
"""Read a secret with echo suppressed."""
|
|
29
|
+
...
|
|
30
|
+
|
|
31
|
+
def confirm(self, question: str, *, default: bool = False) -> bool:
|
|
32
|
+
"""Ask a yes/no question; an empty answer returns ``default``."""
|
|
33
|
+
...
|
|
34
|
+
|
|
35
|
+
def confirm_exact(self, question: str, expected: Namespace) -> bool:
|
|
36
|
+
"""Ask the developer to retype a namespace name."""
|
|
37
|
+
...
|
|
38
|
+
|
|
39
|
+
def read_secret_from_stdin(self) -> SecretValue:
|
|
40
|
+
"""Read one value from standard input."""
|
|
41
|
+
...
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def strip_one_newline(data: bytes) -> bytes:
|
|
45
|
+
"""Remove exactly one trailing newline (``\\n`` or ``\\r\\n``) if present."""
|
|
46
|
+
if data.endswith(b"\r\n"):
|
|
47
|
+
return data[:-2]
|
|
48
|
+
if data.endswith(b"\n"):
|
|
49
|
+
return data[:-1]
|
|
50
|
+
return data
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class TtyPrompter:
|
|
54
|
+
"""Production prompter. Talks to ``/dev/tty`` and ``getpass``."""
|
|
55
|
+
|
|
56
|
+
def __init__(
|
|
57
|
+
self,
|
|
58
|
+
*,
|
|
59
|
+
stdin: BinaryIO | None = None,
|
|
60
|
+
tty_readline: Callable[[], str] | None = None,
|
|
61
|
+
getpass_fn: Callable[[str], str] | None = None,
|
|
62
|
+
) -> None:
|
|
63
|
+
self._stdin = stdin
|
|
64
|
+
self._tty_readline = tty_readline or _read_line_from_tty
|
|
65
|
+
self._getpass = getpass_fn or _getpass_to_stderr
|
|
66
|
+
|
|
67
|
+
def is_interactive(self) -> bool:
|
|
68
|
+
return sys.stdin.isatty()
|
|
69
|
+
|
|
70
|
+
def read_secret(self, prompt: str) -> SecretValue:
|
|
71
|
+
return SecretValue.from_text(self._getpass(prompt))
|
|
72
|
+
|
|
73
|
+
def confirm(self, question: str, *, default: bool = False) -> bool:
|
|
74
|
+
sys.stderr.write(f"{question} [{'Y/n' if default else 'y/N'}] ")
|
|
75
|
+
sys.stderr.flush()
|
|
76
|
+
answer = self._tty_readline().strip().lower()
|
|
77
|
+
if not answer:
|
|
78
|
+
return default
|
|
79
|
+
return answer in {"y", "yes"}
|
|
80
|
+
|
|
81
|
+
def confirm_exact(self, question: str, expected: Namespace) -> bool:
|
|
82
|
+
sys.stderr.write(f"{question} ")
|
|
83
|
+
sys.stderr.flush()
|
|
84
|
+
answer = self._tty_readline().strip()
|
|
85
|
+
return answer in {expected.display, expected.key}
|
|
86
|
+
|
|
87
|
+
def read_secret_from_stdin(self) -> SecretValue:
|
|
88
|
+
stream = self._stdin or sys.stdin.buffer
|
|
89
|
+
data = strip_one_newline(stream.read())
|
|
90
|
+
if not data:
|
|
91
|
+
raise InvalidInputError(
|
|
92
|
+
"no value was supplied on standard input",
|
|
93
|
+
"Pipe exactly one value, or run interactively to be prompted",
|
|
94
|
+
)
|
|
95
|
+
return SecretValue(data)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _read_line_from_tty() -> str:
|
|
99
|
+
with open("/dev/tty", encoding="utf-8") as tty: # noqa: PTH123 - device, not a path
|
|
100
|
+
return tty.readline()
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _getpass_to_stderr(prompt: str) -> str:
|
|
104
|
+
return getpass.getpass(prompt, stream=sys.stderr)
|
keychain_cli/secret.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""The one type allowed to hold a secret while it is in process memory.
|
|
2
|
+
|
|
3
|
+
``SecretValue`` cannot be formatted, printed, or JSON-encoded into a string that contains
|
|
4
|
+
the value. ``repr`` and ``str`` are redacted, and ``format`` raises so an f-string cannot
|
|
5
|
+
leak it by accident. Code that needs the bytes asks for ``.data`` explicitly, which is easy
|
|
6
|
+
to audit with a search.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import final
|
|
12
|
+
|
|
13
|
+
REDACTED = "SecretValue(<redacted>)"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@final
|
|
17
|
+
class SecretValue:
|
|
18
|
+
"""Immutable wrapper around the raw bytes of one secret."""
|
|
19
|
+
|
|
20
|
+
__slots__ = ("_data",)
|
|
21
|
+
|
|
22
|
+
def __init__(self, data: bytes) -> None:
|
|
23
|
+
# Exact type on purpose: no bytes subclass with a custom repr may hold a secret.
|
|
24
|
+
if type(data) is not bytes: # pylint: disable=unidiomatic-typecheck
|
|
25
|
+
msg = f"SecretValue takes bytes, not {type(data).__name__}"
|
|
26
|
+
raise TypeError(msg)
|
|
27
|
+
self._data = data
|
|
28
|
+
|
|
29
|
+
@classmethod
|
|
30
|
+
def from_text(cls, text: str) -> SecretValue:
|
|
31
|
+
"""Wrap a str, encoding it as UTF-8."""
|
|
32
|
+
return cls(text.encode("utf-8"))
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
def data(self) -> bytes:
|
|
36
|
+
"""The raw bytes. The only way to read the value."""
|
|
37
|
+
return self._data
|
|
38
|
+
|
|
39
|
+
def __eq__(self, other: object) -> bool:
|
|
40
|
+
if not isinstance(other, SecretValue):
|
|
41
|
+
return NotImplemented
|
|
42
|
+
return self._data == other._data
|
|
43
|
+
|
|
44
|
+
def __hash__(self) -> int:
|
|
45
|
+
return hash(self._data)
|
|
46
|
+
|
|
47
|
+
def __repr__(self) -> str:
|
|
48
|
+
return REDACTED
|
|
49
|
+
|
|
50
|
+
def __str__(self) -> str:
|
|
51
|
+
return REDACTED
|
|
52
|
+
|
|
53
|
+
def __format__(self, format_spec: str) -> str: # pylint: disable=invalid-format-returned
|
|
54
|
+
# Raising here is the point: f"{secret}" must fail rather than leak.
|
|
55
|
+
msg = "SecretValue cannot be formatted into a string"
|
|
56
|
+
raise TypeError(msg)
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: keychain-cli
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Security-focused CLI for storing and retrieving secrets in macOS Keychain
|
|
5
|
+
Keywords: macos,keychain,secrets,secret-management,environment-variables,dotenv,cli
|
|
6
|
+
Author: CivicActions
|
|
7
|
+
License-Expression: AGPL-3.0-or-later
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Classifier: Development Status :: 4 - Beta
|
|
10
|
+
Classifier: Environment :: MacOS X
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Intended Audience :: System Administrators
|
|
13
|
+
Classifier: Operating System :: MacOS :: MacOS X
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
19
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
20
|
+
Classifier: Topic :: Security
|
|
21
|
+
Classifier: Topic :: Software Development :: Build Tools
|
|
22
|
+
Classifier: Topic :: Utilities
|
|
23
|
+
Requires-Python: >=3.11
|
|
24
|
+
Project-URL: Homepage, https://github.com/CivicActions/keychain-cli
|
|
25
|
+
Project-URL: Repository, https://github.com/CivicActions/keychain-cli
|
|
26
|
+
Project-URL: Changelog, https://github.com/CivicActions/keychain-cli/blob/main/CHANGELOG.md
|
|
27
|
+
Project-URL: Issues, https://github.com/CivicActions/keychain-cli/issues
|
|
28
|
+
Project-URL: Security, https://github.com/CivicActions/keychain-cli/blob/main/SECURITY.md
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
|
|
31
|
+
# keychain-cli
|
|
32
|
+
|
|
33
|
+
Store project secrets in the macOS Keychain and hand them to one command's environment,
|
|
34
|
+
instead of keeping a plaintext `.env` file.
|
|
35
|
+
|
|
36
|
+
## What it is
|
|
37
|
+
|
|
38
|
+
A small Python command-line tool for macOS. Each project gets a *namespace* in your login
|
|
39
|
+
Keychain holding named environment variables. You store values at a hidden prompt, then run
|
|
40
|
+
your development command through the tool, which places the variables in that command's
|
|
41
|
+
environment and nowhere else. Your shell is never modified. Nothing is written to disk.
|
|
42
|
+
|
|
43
|
+
Requires macOS 13 or later and Python 3.11 or later. There is no fallback storage on other
|
|
44
|
+
platforms; the tool exits with code 6.
|
|
45
|
+
|
|
46
|
+
## Install
|
|
47
|
+
|
|
48
|
+
From PyPI:
|
|
49
|
+
|
|
50
|
+
```sh
|
|
51
|
+
uv tool install keychain-cli
|
|
52
|
+
keychain-cli --version
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Or from the git repository:
|
|
56
|
+
|
|
57
|
+
```sh
|
|
58
|
+
uv tool install git+https://github.com/civicactions/keychain-cli
|
|
59
|
+
keychain-cli --version
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
To uninstall:
|
|
63
|
+
|
|
64
|
+
```sh
|
|
65
|
+
uv tool uninstall keychain-cli
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## First secret in 60 seconds
|
|
69
|
+
|
|
70
|
+
1. Store secrets in a project namespace:
|
|
71
|
+
|
|
72
|
+
```sh
|
|
73
|
+
keychain-cli set my-project API_TOKEN DB_PASSWORD
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
You are prompted for each value without terminal echo:
|
|
77
|
+
|
|
78
|
+
```text
|
|
79
|
+
Value for my-project/API_TOKEN:
|
|
80
|
+
Value for my-project/DB_PASSWORD:
|
|
81
|
+
stored: API_TOKEN, DB_PASSWORD
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
2. Run your command with secrets injected:
|
|
85
|
+
|
|
86
|
+
```sh
|
|
87
|
+
keychain-cli run my-project -- npm run dev
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
The command starts with `API_TOKEN` and `DB_PASSWORD` available in its environment.
|
|
91
|
+
When the process finishes, no secrets remain in your shell session.
|
|
92
|
+
|
|
93
|
+
## Team setup with a manifest
|
|
94
|
+
|
|
95
|
+
Projects can commit a `.keychain-cli.toml` manifest in the project root directory to declare
|
|
96
|
+
the namespace and required environment variable names (names only, never values):
|
|
97
|
+
|
|
98
|
+
```toml
|
|
99
|
+
# .keychain-cli.toml
|
|
100
|
+
namespace = "my-project"
|
|
101
|
+
variables = [
|
|
102
|
+
"API_TOKEN",
|
|
103
|
+
"DB_PASSWORD",
|
|
104
|
+
]
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
### Onboarding and drift detection
|
|
108
|
+
|
|
109
|
+
1. Check for missing variables without storing anything:
|
|
110
|
+
|
|
111
|
+
```sh
|
|
112
|
+
keychain-cli check
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
Exits `0` if all variables are present, or `10` if any are missing (listing the missing names).
|
|
116
|
+
|
|
117
|
+
2. Initialize missing secrets:
|
|
118
|
+
|
|
119
|
+
```sh
|
|
120
|
+
keychain-cli init
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Prompts only for declared variables not yet in your Keychain. Existing values are never touched.
|
|
124
|
+
|
|
125
|
+
3. Run without typing the namespace:
|
|
126
|
+
|
|
127
|
+
```sh
|
|
128
|
+
keychain-cli run -- npm run dev
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
The tool infers `my-project` from `.keychain-cli.toml` in the current directory.
|
|
132
|
+
|
|
133
|
+
## Commands
|
|
134
|
+
|
|
135
|
+
| Command | Summary |
|
|
136
|
+
|---|---|
|
|
137
|
+
| `set <namespace> <VAR>...` | Store one or more secrets via hidden prompt or standard input |
|
|
138
|
+
| `list [<namespace>]` | List namespaces, or variable names in a namespace |
|
|
139
|
+
| `run [<namespace>] -- <cmd>` | Run a command with secrets injected into its environment |
|
|
140
|
+
| `import <namespace> <file>` | Import an existing `.env` file into a namespace |
|
|
141
|
+
| `delete <namespace> [<VAR>]` | Remove a single variable or an entire namespace |
|
|
142
|
+
| `init [<namespace>]` | Prompt for missing secrets declared in `.keychain-cli.toml` |
|
|
143
|
+
| `check [<namespace>]` | Report which declared secrets are missing |
|
|
144
|
+
|
|
145
|
+
For full command documentation, options, and exit codes, run `keychain-cli <command> --help`
|
|
146
|
+
or see `specs/001-keychain-secret-manager/contracts/cli.md`.
|
|
147
|
+
|
|
148
|
+
## Exit codes
|
|
149
|
+
|
|
150
|
+
| Code | Meaning |
|
|
151
|
+
|---|---|
|
|
152
|
+
| 0 | Success |
|
|
153
|
+
| 1 | Unexpected internal error |
|
|
154
|
+
| 2 | Usage error: bad arguments, missing `--`, out-of-range option |
|
|
155
|
+
| 3 | Not found: namespace, variable, file, or manifest |
|
|
156
|
+
| 4 | Refused: overwrite or deletion declined, or non-interactive without `--force` |
|
|
157
|
+
| 5 | Keychain error: locked, denied, canceled, unavailable, or unexpected status |
|
|
158
|
+
| 6 | Unsupported platform or Python version |
|
|
159
|
+
| 7 | Invalid input: bad name, malformed manifest, empty or ambiguous stdin value |
|
|
160
|
+
| 8 | `run`: command not found or not executable |
|
|
161
|
+
| 9 | `copy`: clipboard write failed, or clearing could not be scheduled |
|
|
162
|
+
| 10 | `check`: one or more required variables are missing |
|
|
163
|
+
| 130 | Interrupted during `set`, `import`, or `init` |
|
|
164
|
+
|
|
165
|
+
## Occasional: pasting a value into a web console
|
|
166
|
+
|
|
167
|
+
For destinations that cannot read environment variables (such as a vendor web console),
|
|
168
|
+
a single secret can be copied to the system clipboard:
|
|
169
|
+
|
|
170
|
+
```sh
|
|
171
|
+
keychain-cli copy my-project API_TOKEN
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
**Security notice**:
|
|
175
|
+
- This is an occasional fallback, not the normal way to use secrets; prefer `keychain-cli run`.
|
|
176
|
+
- The clipboard is readable by every application running as your user. Clipboard managers,
|
|
177
|
+
history tools, and clipboard sync services (such as Universal Clipboard) can defeat automatic clearing.
|
|
178
|
+
- The secret is automatically cleared after 45 seconds (configurable with `--clear-after SECONDS`, 1–300)
|
|
179
|
+
only if the clipboard still contains the value.
|
|
180
|
+
- Governed by exception entry CLIP-001 in [SECURITY-EXCEPTIONS.md](https://github.com/CivicActions/keychain-cli/blob/main/SECURITY-EXCEPTIONS.md).
|
|
181
|
+
|
|
182
|
+
## Troubleshooting
|
|
183
|
+
|
|
184
|
+
**macOS asks me to allow keychain-cli to access an item.** Items in the login Keychain
|
|
185
|
+
trust the *application* that created them, and for this tool that application is the Python
|
|
186
|
+
interpreter. After `uv tool upgrade` switches to a different Python, or when you run from a
|
|
187
|
+
development checkout, macOS asks once per item. Click **Always Allow**. This is the
|
|
188
|
+
operating system protecting the item, not a defect.
|
|
189
|
+
|
|
190
|
+
**"Keychain operation failed ... interaction not allowed" over SSH.** The login Keychain is
|
|
191
|
+
locked and there is no screen on which macOS can show the unlock dialog. Unlock it at the
|
|
192
|
+
console, or run the command locally.
|
|
193
|
+
|
|
194
|
+
**Exit code 6.** You are not on macOS 13 or later, or Python is older than 3.11. Reinstall
|
|
195
|
+
with `uv tool install`, which brings its own supported interpreter.
|
|
196
|
+
|
|
197
|
+
## Security notes
|
|
198
|
+
|
|
199
|
+
- Secret values never appear in command-line arguments, shell history, log output, error
|
|
200
|
+
messages, temporary files, or exception text. The Keychain is driven directly through the
|
|
201
|
+
Security framework, not through the `security` command.
|
|
202
|
+
- Each developer's Keychain holds their own values. The tool never syncs or shares them.
|
|
203
|
+
- The threat model is in [docs/threat-model.md](https://github.com/CivicActions/keychain-cli/blob/main/docs/threat-model.md). Deliberate
|
|
204
|
+
exceptions to the rules above are listed in [SECURITY-EXCEPTIONS.md](https://github.com/CivicActions/keychain-cli/blob/main/SECURITY-EXCEPTIONS.md).
|
|
205
|
+
Report vulnerabilities as described in [SECURITY.md](https://github.com/CivicActions/keychain-cli/blob/main/SECURITY.md).
|
|
206
|
+
|
|
207
|
+
## Contributing
|
|
208
|
+
|
|
209
|
+
Commit messages and pull request titles follow [Conventional Commits](https://www.conventionalcommits.org/);
|
|
210
|
+
releases, version numbers, and the changelog are automated with Release Please. See
|
|
211
|
+
[CONTRIBUTING.md](https://github.com/CivicActions/keychain-cli/blob/main/CONTRIBUTING.md) before opening a pull request.
|