rotato 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.
- rotato/__init__.py +0 -0
- rotato/bws.py +71 -0
- rotato/cli.py +165 -0
- rotato/cli_test.py +96 -0
- rotato/consumer/__init__.py +7 -0
- rotato/consumer/config.py +94 -0
- rotato/consumer/config_test.py +58 -0
- rotato/consumer/fetch.py +15 -0
- rotato/consumer/gitcredential.py +54 -0
- rotato/consumer/gitcredential_test.py +33 -0
- rotato/consumer/github.py +46 -0
- rotato/consumer/github_test.py +91 -0
- rotato/consumer/install.py +155 -0
- rotato/consumer/install_test.py +110 -0
- rotato/core.py +46 -0
- rotato/core_test.py +57 -0
- rotato/rotators/__init__.py +7 -0
- rotato/rotators/gitlab_pat.py +36 -0
- rotato/rotators/gitlab_pat_test.py +50 -0
- rotato-0.1.0.dist-info/METADATA +81 -0
- rotato-0.1.0.dist-info/RECORD +25 -0
- rotato-0.1.0.dist-info/WHEEL +5 -0
- rotato-0.1.0.dist-info/entry_points.txt +2 -0
- rotato-0.1.0.dist-info/licenses/LICENSE +21 -0
- rotato-0.1.0.dist-info/top_level.txt +1 -0
rotato/__init__.py
ADDED
|
File without changes
|
rotato/bws.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""Thin wrapper over the Bitwarden Secrets Manager SDK.
|
|
2
|
+
|
|
3
|
+
Isolated here so the rest of rotato depends only on get_value / set_value.
|
|
4
|
+
Validated against bitwarden-sdk 2.1.0 (see the pin in pyproject); re-check the
|
|
5
|
+
method signatures if you bump it.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import dataclasses
|
|
9
|
+
import os
|
|
10
|
+
|
|
11
|
+
import bitwarden_sdk
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclasses.dataclass
|
|
15
|
+
class Secret:
|
|
16
|
+
id: str
|
|
17
|
+
key: str
|
|
18
|
+
value: str
|
|
19
|
+
note: str
|
|
20
|
+
organization_id: str
|
|
21
|
+
project_id: str | None
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class BwsClient:
|
|
25
|
+
"""Reads/writes a single secret's value in Bitwarden Secrets Manager."""
|
|
26
|
+
|
|
27
|
+
def __init__(self, access_token: str | None = None):
|
|
28
|
+
self._client = bitwarden_sdk.BitwardenClient(
|
|
29
|
+
bitwarden_sdk.client_settings_from_dict(
|
|
30
|
+
{
|
|
31
|
+
"apiUrl": os.environ.get(
|
|
32
|
+
"BWS_API_URL", "https://api.bitwarden.com"
|
|
33
|
+
),
|
|
34
|
+
"identityUrl": os.environ.get(
|
|
35
|
+
"BWS_IDENTITY_URL", "https://identity.bitwarden.com"
|
|
36
|
+
),
|
|
37
|
+
"deviceType": bitwarden_sdk.DeviceType.SDK,
|
|
38
|
+
"userAgent": "rotato",
|
|
39
|
+
}
|
|
40
|
+
)
|
|
41
|
+
)
|
|
42
|
+
token = access_token or os.environ["BWS_ACCESS_TOKEN"]
|
|
43
|
+
self._client.auth().login_access_token(token)
|
|
44
|
+
|
|
45
|
+
def get(self, secret_id: str) -> Secret:
|
|
46
|
+
data = self._client.secrets().get(secret_id).data
|
|
47
|
+
# ids come back as UUID objects; coerce to str so they serialize
|
|
48
|
+
# cleanly when passed back to update().
|
|
49
|
+
return Secret(
|
|
50
|
+
id=str(data.id),
|
|
51
|
+
key=data.key,
|
|
52
|
+
value=data.value,
|
|
53
|
+
note=data.note or "",
|
|
54
|
+
organization_id=str(data.organization_id),
|
|
55
|
+
project_id=str(data.project_id) if data.project_id else None,
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
def get_value(self, secret_id: str) -> str:
|
|
59
|
+
return self.get(secret_id).value
|
|
60
|
+
|
|
61
|
+
def set_value(self, secret_id: str, value: str) -> None:
|
|
62
|
+
# update() replaces the whole secret, so preserve everything but value.
|
|
63
|
+
s = self.get(secret_id)
|
|
64
|
+
self._client.secrets().update(
|
|
65
|
+
id=s.id,
|
|
66
|
+
key=s.key,
|
|
67
|
+
value=value,
|
|
68
|
+
note=s.note,
|
|
69
|
+
organization_id=s.organization_id,
|
|
70
|
+
project_ids=[s.project_id] if s.project_id else None,
|
|
71
|
+
)
|
rotato/cli.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""rotato CLI.
|
|
2
|
+
|
|
3
|
+
One entry point (the `rotato` console script) with two surfaces:
|
|
4
|
+
|
|
5
|
+
server rotato run <name> run a named rotator (Cloud Run job)
|
|
6
|
+
consumer rotato install ... bootstrap this machine
|
|
7
|
+
rotato fetch <name|uuid> print a secret's value, read-only
|
|
8
|
+
rotato github-token <...> mint a GitHub App installation token
|
|
9
|
+
rotato git-credential <...> git credential helper
|
|
10
|
+
|
|
11
|
+
Backward-compatible: a bare `rotato <name>` (or the ROTATOR env var) with no
|
|
12
|
+
recognized subcommand still runs a rotator, so the container ENTRYPOINT keeps
|
|
13
|
+
working unchanged.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import argparse
|
|
17
|
+
import os
|
|
18
|
+
import sys
|
|
19
|
+
|
|
20
|
+
from rotato import bws, rotators
|
|
21
|
+
from rotato.consumer import fetch, gitcredential, github, install
|
|
22
|
+
|
|
23
|
+
_SUBCOMMANDS = {"run", "fetch", "github-token", "git-credential", "install"}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _run_rotator(name: str) -> int:
|
|
27
|
+
if not name:
|
|
28
|
+
print(
|
|
29
|
+
"usage: rotato run <rotator-name> (or set ROTATOR)",
|
|
30
|
+
file=sys.stderr,
|
|
31
|
+
)
|
|
32
|
+
return 2
|
|
33
|
+
run = rotators.REGISTRY.get(name)
|
|
34
|
+
if run is None:
|
|
35
|
+
print(f"unknown rotator: {name}", file=sys.stderr)
|
|
36
|
+
return 2
|
|
37
|
+
# Let failures propagate: the traceback (incl. any RotationError break-glass
|
|
38
|
+
# value) goes to stderr -> Cloud Logging, and the non-zero exit trips the
|
|
39
|
+
# failure alert.
|
|
40
|
+
run(bws.BwsClient())
|
|
41
|
+
return 0
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _cmd_run(args) -> int:
|
|
45
|
+
return _run_rotator(args.name or os.environ.get("ROTATOR", ""))
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _cmd_fetch(args) -> int:
|
|
49
|
+
print(fetch.fetch_value(args.secret))
|
|
50
|
+
return 0
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _cmd_github_token(args) -> int:
|
|
54
|
+
print(
|
|
55
|
+
github.mint_token(
|
|
56
|
+
args.secret, args.app_id, args.installation_id, args.api
|
|
57
|
+
)
|
|
58
|
+
)
|
|
59
|
+
return 0
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _cmd_git_credential(args) -> int:
|
|
63
|
+
sys.stdout.write(
|
|
64
|
+
gitcredential.emit_credential(
|
|
65
|
+
args.secret,
|
|
66
|
+
args.operation,
|
|
67
|
+
is_github=args.github,
|
|
68
|
+
app_id=args.app_id,
|
|
69
|
+
installation_id=args.installation_id,
|
|
70
|
+
api=args.api,
|
|
71
|
+
)
|
|
72
|
+
)
|
|
73
|
+
return 0
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _cmd_install(args) -> int:
|
|
77
|
+
if args.github:
|
|
78
|
+
if not args.app_id or not args.installation_id:
|
|
79
|
+
print(
|
|
80
|
+
"error: --app-id and --installation-id are required "
|
|
81
|
+
"with --github",
|
|
82
|
+
file=sys.stderr,
|
|
83
|
+
)
|
|
84
|
+
return 2
|
|
85
|
+
elif not args.user:
|
|
86
|
+
print("error: --user <git-user> is required", file=sys.stderr)
|
|
87
|
+
return 2
|
|
88
|
+
return install.run(
|
|
89
|
+
install.InstallArgs(
|
|
90
|
+
secret_id=args.secret,
|
|
91
|
+
mode="github" if args.github else "token",
|
|
92
|
+
host=args.host or "",
|
|
93
|
+
user=args.user or "",
|
|
94
|
+
app_id=args.app_id or "",
|
|
95
|
+
installation_id=args.installation_id or "",
|
|
96
|
+
name=args.name or "",
|
|
97
|
+
git_file=args.file or "",
|
|
98
|
+
dry_run=args.dry_run,
|
|
99
|
+
)
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
104
|
+
parser = argparse.ArgumentParser(prog="rotato")
|
|
105
|
+
sub = parser.add_subparsers(dest="command")
|
|
106
|
+
|
|
107
|
+
p_run = sub.add_parser("run", help="run a named rotator (server-side)")
|
|
108
|
+
p_run.add_argument("name", nargs="?", help="rotator name (or set ROTATOR)")
|
|
109
|
+
p_run.set_defaults(func=_cmd_run)
|
|
110
|
+
|
|
111
|
+
p_fetch = sub.add_parser("fetch", help="print a secret's value, read-only")
|
|
112
|
+
p_fetch.add_argument("secret", help="secret name or uuid")
|
|
113
|
+
p_fetch.set_defaults(func=_cmd_fetch)
|
|
114
|
+
|
|
115
|
+
p_gh = sub.add_parser(
|
|
116
|
+
"github-token", help="mint a GitHub App installation token"
|
|
117
|
+
)
|
|
118
|
+
p_gh.add_argument("secret", help="PEM secret name or uuid")
|
|
119
|
+
p_gh.add_argument("--app-id", required=True, help="App ID or Client ID")
|
|
120
|
+
p_gh.add_argument("--installation-id", required=True)
|
|
121
|
+
p_gh.add_argument("--api", default=github.DEFAULT_API)
|
|
122
|
+
p_gh.set_defaults(func=_cmd_github_token)
|
|
123
|
+
|
|
124
|
+
p_gc = sub.add_parser("git-credential", help="git credential helper")
|
|
125
|
+
p_gc.add_argument("secret", help="secret name or uuid")
|
|
126
|
+
p_gc.add_argument(
|
|
127
|
+
"operation", nargs="?", default="", help="get|store|erase"
|
|
128
|
+
)
|
|
129
|
+
p_gc.add_argument("--github", action="store_true", help="GitHub App mode")
|
|
130
|
+
p_gc.add_argument("--app-id", default="")
|
|
131
|
+
p_gc.add_argument("--installation-id", default="")
|
|
132
|
+
p_gc.add_argument("--api", default=github.DEFAULT_API)
|
|
133
|
+
p_gc.set_defaults(func=_cmd_git_credential)
|
|
134
|
+
|
|
135
|
+
p_in = sub.add_parser("install", help="one-time per-machine consumer setup")
|
|
136
|
+
p_in.add_argument("secret", help="secret uuid to install")
|
|
137
|
+
p_in.add_argument("--github", action="store_true", help="GitHub App mode")
|
|
138
|
+
p_in.add_argument("--host", help="git host (default gitlab/github.com)")
|
|
139
|
+
p_in.add_argument("--user", help="git username (required, token mode)")
|
|
140
|
+
p_in.add_argument("--app-id", help="App/Client ID (required --github)")
|
|
141
|
+
p_in.add_argument(
|
|
142
|
+
"--installation-id", help="installation ID (required --github)"
|
|
143
|
+
)
|
|
144
|
+
p_in.add_argument("--name", help="name to record (default: BWS key)")
|
|
145
|
+
p_in.add_argument("--file", help="git config file (default: --global)")
|
|
146
|
+
p_in.add_argument("--dry-run", action="store_true")
|
|
147
|
+
p_in.set_defaults(func=_cmd_install)
|
|
148
|
+
|
|
149
|
+
return parser
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def main(argv=None) -> int:
|
|
153
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
154
|
+
|
|
155
|
+
# Legacy: bare `rotato <name>` (or ROTATOR env) still runs a rotator, so the
|
|
156
|
+
# container ENTRYPOINT ["rotato"] keeps working. Only fall through when the
|
|
157
|
+
# first token is neither a known subcommand nor an option.
|
|
158
|
+
legacy = not argv or (
|
|
159
|
+
argv[0] not in _SUBCOMMANDS and not argv[0].startswith("-")
|
|
160
|
+
)
|
|
161
|
+
if legacy:
|
|
162
|
+
return _run_rotator(argv[0] if argv else os.environ.get("ROTATOR", ""))
|
|
163
|
+
|
|
164
|
+
args = _build_parser().parse_args(argv)
|
|
165
|
+
return args.func(args)
|
rotato/cli_test.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""Tests for the rotato CLI dispatcher."""
|
|
2
|
+
|
|
3
|
+
import rotato.cli as cli
|
|
4
|
+
|
|
5
|
+
# --- legacy server-side path (container ENTRYPOINT ["rotato"]) ---
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def test_unknown_rotator_returns_2(capsys):
|
|
9
|
+
assert cli.main(["definitely-not-a-rotator"]) == 2
|
|
10
|
+
assert "unknown rotator" in capsys.readouterr().err
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def test_no_name_returns_2(monkeypatch):
|
|
14
|
+
monkeypatch.delenv("ROTATOR", raising=False)
|
|
15
|
+
assert cli.main([]) == 2
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def test_run_subcommand_unknown_rotator_returns_2(capsys):
|
|
19
|
+
assert cli.main(["run", "nope"]) == 2
|
|
20
|
+
assert "unknown rotator" in capsys.readouterr().err
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _stub_registry(monkeypatch):
|
|
24
|
+
"""Register a fake rotator and a fake client; return the call recorder."""
|
|
25
|
+
seen = {}
|
|
26
|
+
monkeypatch.setattr(
|
|
27
|
+
cli.rotators,
|
|
28
|
+
"REGISTRY",
|
|
29
|
+
{"myrot": lambda store: seen.update(store=store)},
|
|
30
|
+
)
|
|
31
|
+
monkeypatch.setattr(cli.bws, "BwsClient", lambda: "FAKE_CLIENT")
|
|
32
|
+
return seen
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def test_legacy_bare_name_dispatches_to_rotator(monkeypatch):
|
|
36
|
+
seen = _stub_registry(monkeypatch)
|
|
37
|
+
assert cli.main(["myrot"]) == 0
|
|
38
|
+
assert seen["store"] == "FAKE_CLIENT"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def test_run_subcommand_dispatches_to_rotator(monkeypatch):
|
|
42
|
+
seen = _stub_registry(monkeypatch)
|
|
43
|
+
assert cli.main(["run", "myrot"]) == 0
|
|
44
|
+
assert seen["store"] == "FAKE_CLIENT"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def test_rotator_env_fallback(monkeypatch):
|
|
48
|
+
seen = _stub_registry(monkeypatch)
|
|
49
|
+
monkeypatch.setenv("ROTATOR", "myrot")
|
|
50
|
+
assert cli.main([]) == 0
|
|
51
|
+
assert seen["store"] == "FAKE_CLIENT"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
# --- consumer subcommands ---
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def test_fetch_prints_value(monkeypatch, capsys):
|
|
58
|
+
monkeypatch.setattr(cli.fetch, "fetch_value", lambda s: "SECRETVALUE")
|
|
59
|
+
assert cli.main(["fetch", "gitlab-pat"]) == 0
|
|
60
|
+
assert capsys.readouterr().out.strip() == "SECRETVALUE"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def test_git_credential_get_emits_password(monkeypatch, capsys):
|
|
64
|
+
monkeypatch.setattr(cli.gitcredential.fetch, "fetch_value", lambda s: "PAT")
|
|
65
|
+
assert cli.main(["git-credential", "gitlab-pat", "get"]) == 0
|
|
66
|
+
assert capsys.readouterr().out == "password=PAT\n"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def test_github_token_prints_minted_token(monkeypatch, capsys):
|
|
70
|
+
monkeypatch.setattr(
|
|
71
|
+
cli.github, "mint_token", lambda s, a, i, api: "ghs_tok"
|
|
72
|
+
)
|
|
73
|
+
rc = cli.main(
|
|
74
|
+
["github-token", "pem", "--app-id", "1", "--installation-id", "2"]
|
|
75
|
+
)
|
|
76
|
+
assert rc == 0
|
|
77
|
+
assert capsys.readouterr().out.strip() == "ghs_tok"
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def test_install_requires_user_in_token_mode(capsys):
|
|
81
|
+
assert cli.main(["install", "some-uuid"]) == 2
|
|
82
|
+
assert "--user" in capsys.readouterr().err
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def test_install_github_requires_app_id(capsys):
|
|
86
|
+
assert cli.main(["install", "pem", "--github"]) == 2
|
|
87
|
+
assert "--app-id" in capsys.readouterr().err
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def test_install_dry_run(monkeypatch, capsys, tmp_path):
|
|
91
|
+
monkeypatch.setenv("ROTATO_CONFIG_DIR", str(tmp_path))
|
|
92
|
+
rc = cli.main(["install", "some-uuid", "--user", "alice", "--dry-run"])
|
|
93
|
+
assert rc == 0
|
|
94
|
+
out = capsys.readouterr().out
|
|
95
|
+
assert "dry run" in out
|
|
96
|
+
assert "alice" in out
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""Consumer-side commands: bootstrap a machine and fetch credentials.
|
|
2
|
+
|
|
3
|
+
These back the `rotato install / fetch / github-token / git-credential`
|
|
4
|
+
subcommands run on laptops and VMs (as opposed to the server-side rotators).
|
|
5
|
+
Everything reads this machine's read-only BWS token and the name -> uuid map
|
|
6
|
+
under ~/.config/rotato/; nothing here needs a repo checkout.
|
|
7
|
+
"""
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""Consumer-side paths and the local name -> uuid registry.
|
|
2
|
+
|
|
3
|
+
State lives under ~/.config/rotato/ (override the whole dir with
|
|
4
|
+
ROTATO_CONFIG_DIR, or a single file with ROTATO_TOKEN_FILE /
|
|
5
|
+
ROTATO_SECRETS_FILE) — never in a repo checkout:
|
|
6
|
+
|
|
7
|
+
token this machine's read-only BWS access token (chmod 600)
|
|
8
|
+
secrets.json a JSON object mapping friendly name -> secret uuid, so a secret
|
|
9
|
+
can be addressed by name instead of a uuid
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import pathlib
|
|
15
|
+
import re
|
|
16
|
+
|
|
17
|
+
# Bitwarden secret ids are UUIDs; anything else is treated as a friendly name.
|
|
18
|
+
_UUID_RE = re.compile(
|
|
19
|
+
r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",
|
|
20
|
+
re.IGNORECASE,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def config_dir() -> pathlib.Path:
|
|
25
|
+
override = os.environ.get("ROTATO_CONFIG_DIR")
|
|
26
|
+
if override:
|
|
27
|
+
return pathlib.Path(override)
|
|
28
|
+
return pathlib.Path.home() / ".config" / "rotato"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def token_file() -> pathlib.Path:
|
|
32
|
+
override = os.environ.get("ROTATO_TOKEN_FILE")
|
|
33
|
+
return pathlib.Path(override) if override else config_dir() / "token"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def secrets_file() -> pathlib.Path:
|
|
37
|
+
override = os.environ.get("ROTATO_SECRETS_FILE")
|
|
38
|
+
if override:
|
|
39
|
+
return pathlib.Path(override)
|
|
40
|
+
return config_dir() / "secrets.json"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def read_token() -> str:
|
|
44
|
+
"""This machine's read-only BWS access token; raises if missing/empty."""
|
|
45
|
+
path = token_file()
|
|
46
|
+
try:
|
|
47
|
+
token = path.read_text(encoding="utf-8").strip()
|
|
48
|
+
except OSError as exc:
|
|
49
|
+
raise SystemExit(f"rotato: cannot read token file: {path}") from exc
|
|
50
|
+
if not token:
|
|
51
|
+
raise SystemExit(f"rotato: token file is empty: {path}")
|
|
52
|
+
return token
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def load_secrets() -> dict[str, str]:
|
|
56
|
+
"""The name -> uuid map; an empty dict if absent or unparseable."""
|
|
57
|
+
try:
|
|
58
|
+
data = json.loads(secrets_file().read_text(encoding="utf-8"))
|
|
59
|
+
except (OSError, json.JSONDecodeError):
|
|
60
|
+
return {}
|
|
61
|
+
return data if isinstance(data, dict) else {}
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def record_secret(name: str, uuid: str) -> None:
|
|
65
|
+
"""Record name -> uuid, replacing any existing entry for that name.
|
|
66
|
+
|
|
67
|
+
Writes via a temp file in the same dir so the swap is atomic.
|
|
68
|
+
"""
|
|
69
|
+
path = secrets_file()
|
|
70
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
71
|
+
secrets = load_secrets()
|
|
72
|
+
secrets[name] = uuid
|
|
73
|
+
tmp = path.with_name(path.name + ".tmp")
|
|
74
|
+
tmp.write_text(
|
|
75
|
+
json.dumps(secrets, indent=2, sort_keys=True) + "\n", encoding="utf-8"
|
|
76
|
+
)
|
|
77
|
+
tmp.replace(path)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def resolve(name_or_uuid: str) -> str:
|
|
81
|
+
"""Map a friendly name to its uuid; pass a uuid through unchanged.
|
|
82
|
+
|
|
83
|
+
A recorded name wins over the uuid shape, so a name that happens to look
|
|
84
|
+
like a uuid still resolves to its mapped value.
|
|
85
|
+
"""
|
|
86
|
+
secrets = load_secrets()
|
|
87
|
+
if name_or_uuid in secrets:
|
|
88
|
+
return secrets[name_or_uuid]
|
|
89
|
+
if _UUID_RE.match(name_or_uuid):
|
|
90
|
+
return name_or_uuid
|
|
91
|
+
raise SystemExit(
|
|
92
|
+
f"rotato: unknown secret name {name_or_uuid!r}; "
|
|
93
|
+
f"not found in {secrets_file()}"
|
|
94
|
+
)
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Tests for consumer paths and the name -> uuid registry."""
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
import rotato.consumer.config as config
|
|
6
|
+
|
|
7
|
+
_UUID = "12345678-1234-1234-1234-123456789abc"
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@pytest.fixture(autouse=True)
|
|
11
|
+
def _isolate(tmp_path, monkeypatch):
|
|
12
|
+
monkeypatch.setenv("ROTATO_CONFIG_DIR", str(tmp_path))
|
|
13
|
+
monkeypatch.delenv("ROTATO_TOKEN_FILE", raising=False)
|
|
14
|
+
monkeypatch.delenv("ROTATO_SECRETS_FILE", raising=False)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def test_resolve_passes_uuid_through():
|
|
18
|
+
assert config.resolve(_UUID) == _UUID
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def test_resolve_maps_name_to_uuid():
|
|
22
|
+
config.record_secret("gitlab-pat", _UUID)
|
|
23
|
+
assert config.resolve("gitlab-pat") == _UUID
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def test_resolve_unknown_name_exits():
|
|
27
|
+
with pytest.raises(SystemExit):
|
|
28
|
+
config.resolve("no-such-name")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def test_resolve_recorded_name_wins_over_uuid_shape():
|
|
32
|
+
# a recorded name that happens to look like a uuid still maps to its value.
|
|
33
|
+
uuid_shaped_name = "00000000-0000-0000-0000-000000000000"
|
|
34
|
+
config.record_secret(uuid_shaped_name, _UUID)
|
|
35
|
+
assert config.resolve(uuid_shaped_name) == _UUID
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def test_record_secret_roundtrip_and_dedupe():
|
|
39
|
+
config.record_secret("a", _UUID)
|
|
40
|
+
config.record_secret("a", "other-uuid") # same name replaces
|
|
41
|
+
config.record_secret("b", _UUID)
|
|
42
|
+
assert config.load_secrets() == {"a": "other-uuid", "b": _UUID}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def test_load_secrets_missing_file_is_empty():
|
|
46
|
+
assert config.load_secrets() == {}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def test_read_token_strips_and_reads(tmp_path, monkeypatch):
|
|
50
|
+
token = tmp_path / "token"
|
|
51
|
+
token.write_text(" sekret\n")
|
|
52
|
+
monkeypatch.setenv("ROTATO_TOKEN_FILE", str(token))
|
|
53
|
+
assert config.read_token() == "sekret"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def test_read_token_missing_exits():
|
|
57
|
+
with pytest.raises(SystemExit):
|
|
58
|
+
config.read_token()
|
rotato/consumer/fetch.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""`rotato fetch <name|uuid>` — print a secret's current value, read-only.
|
|
2
|
+
|
|
3
|
+
The primitive every consumer builds on (git via `rotato git-credential`,
|
|
4
|
+
anything else — env vars, app config, systemd units — by calling this directly).
|
|
5
|
+
Authenticates with this machine's read-only BWS token and resolves a friendly
|
|
6
|
+
name to its uuid via secrets.json.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from rotato import bws
|
|
10
|
+
from rotato.consumer import config
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def fetch_value(name_or_uuid: str) -> str:
|
|
14
|
+
secret_id = config.resolve(name_or_uuid)
|
|
15
|
+
return bws.BwsClient(access_token=config.read_token()).get_value(secret_id)
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""`rotato git-credential` — a git credential helper.
|
|
2
|
+
|
|
3
|
+
Git invokes a helper as `<helper> get|store|erase`, reading key=value context
|
|
4
|
+
on stdin and, on `get`, expecting `username=`/`password=` back on stdout. This
|
|
5
|
+
is a thin adapter over fetch / github-token; store and erase are no-ops (nothing
|
|
6
|
+
lives on disk). `install` wires it into git config for you, e.g.:
|
|
7
|
+
|
|
8
|
+
[credential "https://gitlab.com"]
|
|
9
|
+
username = <user>
|
|
10
|
+
helper = "!rotato git-credential <name|uuid>"
|
|
11
|
+
[credential "https://github.com"]
|
|
12
|
+
helper = "!rotato git-credential --github
|
|
13
|
+
--app-id .. --installation-id .. <pem>"
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from rotato.consumer import fetch, github
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def emit_credential(
|
|
20
|
+
name_or_uuid: str,
|
|
21
|
+
operation: str,
|
|
22
|
+
*,
|
|
23
|
+
is_github: bool = False,
|
|
24
|
+
app_id: str = "",
|
|
25
|
+
installation_id: str = "",
|
|
26
|
+
api: str = github.DEFAULT_API,
|
|
27
|
+
) -> str:
|
|
28
|
+
"""Return the git-credential response for `operation` (empty unless get)."""
|
|
29
|
+
# git only needs a value on `get`; nothing to persist or clear otherwise.
|
|
30
|
+
if operation != "get":
|
|
31
|
+
return ""
|
|
32
|
+
|
|
33
|
+
if is_github:
|
|
34
|
+
# Installation tokens require the username x-access-token.
|
|
35
|
+
token = _protocol_safe(
|
|
36
|
+
github.mint_token(name_or_uuid, app_id, installation_id, api)
|
|
37
|
+
)
|
|
38
|
+
return f"username=x-access-token\npassword={token}\n"
|
|
39
|
+
return f"password={_protocol_safe(fetch.fetch_value(name_or_uuid))}\n"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _protocol_safe(value: str) -> str:
|
|
43
|
+
"""Reject a value that would corrupt git's line-oriented credential wire.
|
|
44
|
+
|
|
45
|
+
A newline/carriage-return/NUL in the emitted password lets the rest of the
|
|
46
|
+
value be reparsed by git as attribute lines — so refuse rather than leak a
|
|
47
|
+
truncated or attacker-shaped credential.
|
|
48
|
+
"""
|
|
49
|
+
if any(c in value for c in ("\n", "\r", "\0")):
|
|
50
|
+
raise SystemExit(
|
|
51
|
+
"rotato: secret value contains a control character; refusing to "
|
|
52
|
+
"emit it as a git credential"
|
|
53
|
+
)
|
|
54
|
+
return value
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Tests for the git credential-helper adapter."""
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
import rotato.consumer.gitcredential as gc
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def test_get_token_mode_emits_password(monkeypatch):
|
|
9
|
+
monkeypatch.setattr(gc.fetch, "fetch_value", lambda s: "PAT123")
|
|
10
|
+
out = gc.emit_credential("gitlab-pat", "get")
|
|
11
|
+
assert out == "password=PAT123\n"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def test_github_mode_emits_username_and_password(monkeypatch):
|
|
15
|
+
monkeypatch.setattr(gc.github, "mint_token", lambda s, a, i, api: "ghs_tok")
|
|
16
|
+
out = gc.emit_credential(
|
|
17
|
+
"pem", "get", is_github=True, app_id="1", installation_id="2"
|
|
18
|
+
)
|
|
19
|
+
assert out == "username=x-access-token\npassword=ghs_tok\n"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def test_store_and_erase_are_noops(monkeypatch):
|
|
23
|
+
monkeypatch.setattr(gc.fetch, "fetch_value", lambda s: "unused")
|
|
24
|
+
assert gc.emit_credential("gitlab-pat", "store") == ""
|
|
25
|
+
assert gc.emit_credential("gitlab-pat", "erase") == ""
|
|
26
|
+
assert gc.emit_credential("gitlab-pat", "") == ""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def test_value_with_newline_is_rejected(monkeypatch):
|
|
30
|
+
# a newline in the value would corrupt git's line-oriented protocol.
|
|
31
|
+
monkeypatch.setattr(gc.fetch, "fetch_value", lambda s: "abc\nhost=evil")
|
|
32
|
+
with pytest.raises(SystemExit):
|
|
33
|
+
gc.emit_credential("gitlab-pat", "get")
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""`rotato github-token` — mint a short-lived GitHub App installation token.
|
|
2
|
+
|
|
3
|
+
The stored secret is the App private key (PEM), not a usable credential. We
|
|
4
|
+
fetch it, sign a short-lived RS256 JWT, and exchange it for an installation
|
|
5
|
+
access token (~1h). The PEM stays in memory; only the minted token is returned.
|
|
6
|
+
|
|
7
|
+
Deps: pyjwt[crypto] (RS256 signing) + httpx2 (already a rotato dependency).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import time
|
|
11
|
+
|
|
12
|
+
import httpx2
|
|
13
|
+
import jwt
|
|
14
|
+
|
|
15
|
+
from rotato.consumer import fetch
|
|
16
|
+
|
|
17
|
+
DEFAULT_API = "https://api.github.com"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def mint_token(
|
|
21
|
+
pem_name_or_uuid: str,
|
|
22
|
+
app_id: str,
|
|
23
|
+
installation_id: str,
|
|
24
|
+
api: str = DEFAULT_API,
|
|
25
|
+
) -> str:
|
|
26
|
+
pem = fetch.fetch_value(pem_name_or_uuid)
|
|
27
|
+
|
|
28
|
+
# iat backdated 60s for clock skew, exp +9min (GitHub caps app JWTs at 10).
|
|
29
|
+
# iss is the App ID or Client ID; GitHub accepts either as a string.
|
|
30
|
+
now = int(time.time())
|
|
31
|
+
token = jwt.encode(
|
|
32
|
+
{"iat": now - 60, "exp": now + 540, "iss": app_id},
|
|
33
|
+
pem,
|
|
34
|
+
algorithm="RS256",
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
resp = httpx2.post(
|
|
38
|
+
f"{api}/app/installations/{installation_id}/access_tokens",
|
|
39
|
+
headers={
|
|
40
|
+
"Authorization": f"Bearer {token}",
|
|
41
|
+
"Accept": "application/vnd.github+json",
|
|
42
|
+
"X-GitHub-Api-Version": "2022-11-28",
|
|
43
|
+
},
|
|
44
|
+
)
|
|
45
|
+
resp.raise_for_status()
|
|
46
|
+
return resp.json()["token"]
|