rotato 0.1.0__tar.gz

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-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Zhitao Gong
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
rotato-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,81 @@
1
+ Metadata-Version: 2.4
2
+ Name: rotato
3
+ Version: 0.1.0
4
+ Summary: Serverless secret/key rotation into Bitwarden Secrets Manager
5
+ Author-email: Zhitao Gong <zhitaao.gong@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/gongzhitaao/rotato
8
+ Project-URL: Repository, https://github.com/gongzhitaao/rotato
9
+ Project-URL: Issues, https://github.com/gongzhitaao/rotato/issues
10
+ Keywords: bitwarden,secrets,secret-rotation,credentials,cli,cloud-run
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: System Administrators
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Topic :: Security
21
+ Classifier: Topic :: System :: Systems Administration
22
+ Requires-Python: >=3.12
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: bitwarden-sdk>=2.1.0
26
+ Requires-Dist: httpx2>=2.10.0
27
+ Requires-Dist: pyjwt[crypto]>=2.8.0
28
+ Dynamic: license-file
29
+
30
+ # rotato
31
+
32
+ Serverless secret/key rotation into
33
+ [Bitwarden Secrets Manager](https://bitwarden.com/products/secrets-manager/).
34
+
35
+ A scheduled [Cloud Run job](https://cloud.google.com/run/docs/create-jobs)
36
+ rotates an expiring credential (e.g. a GitLab PAT) and writes the fresh value
37
+ back to Bitwarden. Every machine then fetches the *current* value on demand, so
38
+ the secret is never written to disk and rotations are transparent.
39
+
40
+ ## Install
41
+
42
+ ```bash
43
+ uv tool install rotato # or: pipx install rotato
44
+ ```
45
+
46
+ ## Consumer usage (laptop / VM)
47
+
48
+ Bootstrap a machine once — no repo checkout required:
49
+
50
+ ```bash
51
+ # GitLab PAT (or any Bitwarden token) as a git credential
52
+ rotato install <secret-uuid> --user <git-user>
53
+
54
+ # GitHub App mode: mint a short-lived installation token per git op
55
+ rotato install <pem-uuid> --github --app-id <id> --installation-id <id>
56
+ ```
57
+
58
+ `install` writes this machine's read-only Bitwarden token to
59
+ `~/.config/rotato/`, records a friendly `name -> uuid` map, and points git's
60
+ credential helper at `rotato`. After that:
61
+
62
+ ```bash
63
+ rotato fetch <name|uuid> # print a secret's current value, read-only
64
+ rotato github-token <name|uuid> --app-id <id> --installation-id <id>
65
+ git -C <a-repo> ls-remote # git now authenticates via Bitwarden
66
+ ```
67
+
68
+ ## Server side
69
+
70
+ The rotation job runs as `rotato run <rotator-name>` (also the container
71
+ entrypoint); `ROTATOR` selects the rotator. Deploying the Cloud Run job,
72
+ scheduler, and alerting is covered in the full documentation.
73
+
74
+ ## Documentation
75
+
76
+ Full design, invariants, deployment, and "add a rotator" guide:
77
+ [README.org](https://github.com/gongzhitaao/rotato/blob/main/README.org).
78
+
79
+ ## License
80
+
81
+ [MIT](https://github.com/gongzhitaao/rotato/blob/main/LICENSE).
rotato-0.1.0/README.md ADDED
@@ -0,0 +1,52 @@
1
+ # rotato
2
+
3
+ Serverless secret/key rotation into
4
+ [Bitwarden Secrets Manager](https://bitwarden.com/products/secrets-manager/).
5
+
6
+ A scheduled [Cloud Run job](https://cloud.google.com/run/docs/create-jobs)
7
+ rotates an expiring credential (e.g. a GitLab PAT) and writes the fresh value
8
+ back to Bitwarden. Every machine then fetches the *current* value on demand, so
9
+ the secret is never written to disk and rotations are transparent.
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ uv tool install rotato # or: pipx install rotato
15
+ ```
16
+
17
+ ## Consumer usage (laptop / VM)
18
+
19
+ Bootstrap a machine once — no repo checkout required:
20
+
21
+ ```bash
22
+ # GitLab PAT (or any Bitwarden token) as a git credential
23
+ rotato install <secret-uuid> --user <git-user>
24
+
25
+ # GitHub App mode: mint a short-lived installation token per git op
26
+ rotato install <pem-uuid> --github --app-id <id> --installation-id <id>
27
+ ```
28
+
29
+ `install` writes this machine's read-only Bitwarden token to
30
+ `~/.config/rotato/`, records a friendly `name -> uuid` map, and points git's
31
+ credential helper at `rotato`. After that:
32
+
33
+ ```bash
34
+ rotato fetch <name|uuid> # print a secret's current value, read-only
35
+ rotato github-token <name|uuid> --app-id <id> --installation-id <id>
36
+ git -C <a-repo> ls-remote # git now authenticates via Bitwarden
37
+ ```
38
+
39
+ ## Server side
40
+
41
+ The rotation job runs as `rotato run <rotator-name>` (also the container
42
+ entrypoint); `ROTATOR` selects the rotator. Deploying the Cloud Run job,
43
+ scheduler, and alerting is covered in the full documentation.
44
+
45
+ ## Documentation
46
+
47
+ Full design, invariants, deployment, and "add a rotator" guide:
48
+ [README.org](https://github.com/gongzhitaao/rotato/blob/main/README.org).
49
+
50
+ ## License
51
+
52
+ [MIT](https://github.com/gongzhitaao/rotato/blob/main/LICENSE).
@@ -0,0 +1,75 @@
1
+ [project]
2
+ name = "rotato"
3
+ version = "0.1.0"
4
+ description = "Serverless secret/key rotation into Bitwarden Secrets Manager"
5
+ readme = "README.md"
6
+ requires-python = ">=3.12"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ authors = [{ name = "Zhitao Gong", email = "zhitaao.gong@gmail.com" }]
10
+ keywords = [
11
+ "bitwarden",
12
+ "secrets",
13
+ "secret-rotation",
14
+ "credentials",
15
+ "cli",
16
+ "cloud-run",
17
+ ]
18
+ classifiers = [
19
+ "Development Status :: 4 - Beta",
20
+ "Environment :: Console",
21
+ "Intended Audience :: Developers",
22
+ "Intended Audience :: System Administrators",
23
+ "Operating System :: OS Independent",
24
+ "Programming Language :: Python :: 3",
25
+ "Programming Language :: Python :: 3.12",
26
+ "Programming Language :: Python :: 3.13",
27
+ "Programming Language :: Python :: 3.14",
28
+ "Topic :: Security",
29
+ "Topic :: System :: Systems Administration",
30
+ ]
31
+ dependencies = [
32
+ "bitwarden-sdk>=2.1.0",
33
+ "httpx2>=2.10.0",
34
+ "pyjwt[crypto]>=2.8.0",
35
+ ]
36
+
37
+ [project.urls]
38
+ Homepage = "https://github.com/gongzhitaao/rotato"
39
+ Repository = "https://github.com/gongzhitaao/rotato"
40
+ Issues = "https://github.com/gongzhitaao/rotato/issues"
41
+
42
+ [project.scripts]
43
+ rotato = "rotato.cli:main"
44
+
45
+ [build-system]
46
+ requires = ["setuptools>=77"]
47
+ build-backend = "setuptools.build_meta"
48
+
49
+ [tool.setuptools.packages.find]
50
+ where = ["src"]
51
+ include = ["rotato*"]
52
+
53
+ [dependency-groups]
54
+ dev = [
55
+ "pre-commit>=4.0.0",
56
+ "pylint>=4.0.6",
57
+ "pylint-google-style>=0.1.1",
58
+ "pytest>=9.1.1",
59
+ "ruff>=0.16.0",
60
+ ]
61
+
62
+ [tool.pytest.ini_options]
63
+ testpaths = ["src"]
64
+ python_files = ["*_test.py"]
65
+ addopts = "--import-mode=importlib"
66
+
67
+ [tool.ruff]
68
+ line-length = 80 # match Google's pylintrc max-line-length
69
+ target-version = "py312"
70
+ src = ["src"] # first-party root for import sorting
71
+
72
+ [tool.ruff.lint]
73
+ select = ["E", "F", "W", "I", "B", "UP"]
74
+
75
+ # pylint uses .pylintrc (Google's config, checked in at the repo root).
rotato-0.1.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
File without changes
@@ -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
+ )
@@ -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)
@@ -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
+ )