datadouble-vault 0.0.3__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.
@@ -0,0 +1,21 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ __pycache__/
5
+ *.py[cod]
6
+ .venv/
7
+ .env
8
+ .coverage
9
+ .coverage.*
10
+ coverage.xml
11
+ .reports/
12
+ .pytest_cache/
13
+ .mypy_cache/
14
+ .ruff_cache/
15
+ dist/
16
+ site/
17
+ .cache/
18
+
19
+ # The default work directory of `datadouble run`.
20
+ .datadouble/
21
+ node_modules/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026- Tight Line LLC
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.
@@ -0,0 +1,39 @@
1
+ Metadata-Version: 2.5
2
+ Name: datadouble-vault
3
+ Version: 0.0.3
4
+ Summary: Vault announce adapter for Datadouble
5
+ Project-URL: Homepage, https://datadouble.tightlinesoftware.com/
6
+ Project-URL: Source, https://github.com/datadouble/datadouble
7
+ Author: Tight Line LLC
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 2 - Pre-Alpha
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Classifier: Programming Language :: Python :: 3.13
13
+ Classifier: Programming Language :: Python :: 3.14
14
+ Classifier: Programming Language :: Python :: 3.15
15
+ Classifier: Topic :: Security
16
+ Classifier: Typing :: Typed
17
+ Requires-Python: >=3.13
18
+ Requires-Dist: datadouble
19
+ Description-Content-Type: text/markdown
20
+
21
+ # datadouble-vault
22
+
23
+ The Vault announce adapter for [Datadouble](https://datadouble.tightlinesoftware.com/):
24
+ one KV version 2 secret per copy, holding where the copy is and its
25
+ credentials. It works with HashiCorp Vault and OpenBao.
26
+
27
+ ```yaml
28
+ announce:
29
+ - vault:
30
+ address: https://vault.internal.example:8200
31
+ mount: secret # the KV v2 mount (default: secret)
32
+ path: datadouble/clones # entries go under <path>/<copy id>
33
+ ```
34
+
35
+ The token comes from `VAULT_TOKEN`; it never appears in the spec.
36
+
37
+ `mount` and `path` are inside Vault, not on the job's machine, so `ci init`
38
+ never mounts them into a job, even when they start with `/`
39
+ ([which settings become mounts](../../docs/ci-cd.md#which-settings-become-mounts)).
@@ -0,0 +1,19 @@
1
+ # datadouble-vault
2
+
3
+ The Vault announce adapter for [Datadouble](https://datadouble.tightlinesoftware.com/):
4
+ one KV version 2 secret per copy, holding where the copy is and its
5
+ credentials. It works with HashiCorp Vault and OpenBao.
6
+
7
+ ```yaml
8
+ announce:
9
+ - vault:
10
+ address: https://vault.internal.example:8200
11
+ mount: secret # the KV v2 mount (default: secret)
12
+ path: datadouble/clones # entries go under <path>/<copy id>
13
+ ```
14
+
15
+ The token comes from `VAULT_TOKEN`; it never appears in the spec.
16
+
17
+ `mount` and `path` are inside Vault, not on the job's machine, so `ci init`
18
+ never mounts them into a job, even when they start with `/`
19
+ ([which settings become mounts](../../docs/ci-cd.md#which-settings-become-mounts)).
@@ -0,0 +1,38 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ [project]
5
+ name = "datadouble-vault"
6
+ # All packages share one version until 1.0 (decision 38); scripts/make_tag.py
7
+ # sets it at release time.
8
+ version = "0.0.3"
9
+ description = "Vault announce adapter for Datadouble"
10
+ readme = "README.md"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Tight Line LLC" }]
14
+ requires-python = ">=3.13"
15
+ dependencies = ["datadouble"]
16
+ classifiers = [
17
+ "Development Status :: 2 - Pre-Alpha",
18
+ "Programming Language :: Python :: 3 :: Only",
19
+ "Programming Language :: Python :: 3.13",
20
+ "Programming Language :: Python :: 3.14",
21
+ "Programming Language :: Python :: 3.15",
22
+ "Topic :: Security",
23
+ "Typing :: Typed",
24
+ ]
25
+
26
+ [project.urls]
27
+ Homepage = "https://datadouble.tightlinesoftware.com/"
28
+ Source = "https://github.com/datadouble/datadouble"
29
+
30
+ [project.entry-points."datadouble.announcers"]
31
+ vault = "datadouble_vault:vault_announcer"
32
+
33
+ [build-system]
34
+ requires = ["hatchling>=1.33.0"]
35
+ build-backend = "hatchling.build"
36
+
37
+ [tool.hatch.build.targets.wheel]
38
+ packages = ["src/datadouble_vault"]
@@ -0,0 +1,130 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """The Vault announce adapter for Datadouble.
5
+
6
+ Spec settings::
7
+
8
+ announce:
9
+ - vault:
10
+ address: https://vault.internal.example:8200
11
+ mount: secret # a KV version 2 mount
12
+ path: datadouble/clones # entries go under <path>/<copy id>
13
+
14
+ Each copy gets one KV v2 secret with its labels, location and credentials.
15
+ Releasing a copy deletes the secret and its history. The token comes from
16
+ ``VAULT_TOKEN`` (and ``VAULT_NAMESPACE`` is honoured); it never appears in the
17
+ spec. Works with HashiCorp Vault and OpenBao.
18
+ """
19
+
20
+ import http.client
21
+ import json
22
+ import os
23
+ import urllib.error
24
+ import urllib.request
25
+ from collections.abc import Mapping
26
+ from urllib.parse import quote
27
+
28
+ from pydantic import BaseModel, ConfigDict, Field, JsonValue
29
+
30
+ from datadouble.announce import Announced, AnnounceError, Announcer
31
+ from datadouble.settings import parse_settings, remote
32
+
33
+ _TIMEOUT_SECONDS = 30
34
+
35
+
36
+ class VaultSettings(BaseModel):
37
+ """Settings for the ``vault`` announce adapter."""
38
+
39
+ model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
40
+
41
+ address: str = Field(pattern=r"^https?://")
42
+ mount: str = "secret"
43
+ path: str = "datadouble"
44
+
45
+
46
+ class VaultAnnouncer:
47
+ """One KV v2 secret per copy."""
48
+
49
+ def __init__(self, settings: VaultSettings, environ: Mapping[str, str]) -> None:
50
+ """Talk to ``settings.address`` with the token in ``environ``."""
51
+ self.settings = settings
52
+ token = environ.get("VAULT_TOKEN")
53
+ if not token:
54
+ message = "VAULT_TOKEN is not set"
55
+ raise AnnounceError(message)
56
+ self.headers = {"X-Vault-Token": token, "Content-Type": "application/json"}
57
+ if namespace := environ.get("VAULT_NAMESPACE"):
58
+ self.headers["X-Vault-Namespace"] = namespace
59
+
60
+ def _url(self, kind: str, copy_id: str) -> str:
61
+ path = "/".join(quote(part, safe="") for part in (*self.settings.path.split("/"), copy_id))
62
+ mount = quote(self.settings.mount, safe="")
63
+ return f"{self.settings.address.rstrip('/')}/v1/{mount}/{kind}/{path}"
64
+
65
+ def _request(self, method: str, url: str, body: bytes | None, action: str) -> None:
66
+ request = urllib.request.Request(url, data=body, method=method, headers=self.headers) # noqa: S310 - the address must be http(s), checked in settings
67
+ try:
68
+ with urllib.request.urlopen(request, timeout=_TIMEOUT_SECONDS): # noqa: S310 - as above
69
+ pass
70
+ except urllib.error.HTTPError as error:
71
+ message = f"{action} failed: Vault answered {error.code}"
72
+ raise AnnounceError(message) from None
73
+ except urllib.error.URLError as error:
74
+ message = f"{action} failed: {error.reason}"
75
+ raise AnnounceError(message) from None
76
+ except (OSError, http.client.HTTPException) as error:
77
+ message = f"{action} failed: {type(error).__name__}"
78
+ raise AnnounceError(message) from None
79
+
80
+ def announce(self, copies: tuple[Announced, ...]) -> tuple[str, ...]:
81
+ """Write one secret per copy."""
82
+ written: list[str] = []
83
+ for copy in copies:
84
+ data: dict[str, JsonValue] = {
85
+ "copy_id": copy.copy_id,
86
+ "kind": copy.kind,
87
+ **{f"label_{key.replace('-', '_')}": value for key, value in copy.labels.items()},
88
+ **copy.location,
89
+ **copy.secrets,
90
+ }
91
+ url = self._url("data", copy.copy_id)
92
+ try:
93
+ self._request(
94
+ "POST", url, json.dumps({"data": data}).encode(), f"writing {copy.copy_id}"
95
+ )
96
+ except AnnounceError as error:
97
+ raise AnnounceError(str(error), written=tuple(written)) from None
98
+ written.append(f"vault:{self.settings.mount}/{self.settings.path}/{copy.copy_id}")
99
+ return tuple(written)
100
+
101
+ def withdraw(
102
+ self, copy_ids: tuple[str, ...], _announced: tuple[str, ...], /
103
+ ) -> tuple[str, ...]:
104
+ """Delete each copy's secret and its versions, trying every one.
105
+
106
+ Then one :class:`AnnounceError` names each secret left behind.
107
+ """
108
+ removed: list[str] = []
109
+ failures: list[str] = []
110
+ for copy_id in copy_ids:
111
+ target = f"vault:{self.settings.mount}/{self.settings.path}/{copy_id}"
112
+ try:
113
+ self._request("DELETE", self._url("metadata", copy_id), None, f"deleting {copy_id}")
114
+ except AnnounceError as error:
115
+ failures.append(f"{target} ({error})")
116
+ else:
117
+ removed.append(target)
118
+ if failures:
119
+ message = "left behind: " + "; ".join(failures)
120
+ raise AnnounceError(message)
121
+ return tuple(removed)
122
+
123
+
124
+ @remote("mount", "path")
125
+ def vault_announcer(settings: Mapping[str, JsonValue]) -> Announcer:
126
+ """The entry point named in ``datadouble.announcers``.
127
+
128
+ ``mount`` and ``path`` are inside Vault, not on the job's machine.
129
+ """
130
+ return VaultAnnouncer(parse_settings(VaultSettings, settings, "vault announce"), os.environ)
File without changes
@@ -0,0 +1,170 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """The Vault announce adapter: against a stand-in server, and a real OpenBao."""
5
+
6
+ import datetime as dt
7
+ import http.client
8
+ import http.server
9
+ import json
10
+ import os
11
+ import threading
12
+ import urllib.error
13
+ import urllib.request
14
+ import uuid
15
+ from collections.abc import Generator
16
+ from typing import ClassVar
17
+
18
+ import pytest
19
+
20
+ from datadouble.announce import Announced, AnnounceError
21
+ from datadouble.registry import installed
22
+ from datadouble.settings import SettingsError, remote_keys
23
+ from datadouble_vault import VaultAnnouncer, VaultSettings, vault_announcer
24
+
25
+ COPY = Announced(
26
+ copy_id="abc123",
27
+ kind="instance",
28
+ labels={
29
+ "spec": "shop",
30
+ "engine-version": "18",
31
+ "built-at": dt.datetime(2026, 1, 1, tzinfo=dt.UTC).isoformat(),
32
+ },
33
+ location={"host": "db", "port": 5432},
34
+ secrets={"password": "s3cret"},
35
+ )
36
+
37
+
38
+ class _Recorder(http.server.BaseHTTPRequestHandler):
39
+ calls: ClassVar[list[tuple[str, str, dict[str, str], bytes]]] = []
40
+ status = 204
41
+ refused = ""
42
+
43
+ def _record(self) -> None:
44
+ length = int(self.headers.get("Content-Length", "0"))
45
+ body = self.rfile.read(length) if length else b""
46
+ type(self).calls.append((self.command, self.path, dict(self.headers), body))
47
+ refused = type(self).refused and self.path.endswith(type(self).refused)
48
+ self.send_response(403 if refused else type(self).status)
49
+ self.end_headers()
50
+
51
+ do_POST = _record # noqa: N815 - http.server's naming
52
+ do_DELETE = _record # noqa: N815 - http.server's naming
53
+
54
+ def log_message(self, format: str, *args: object) -> None: # noqa: A002 - http.server's name
55
+ return
56
+
57
+
58
+ @pytest.fixture
59
+ def server() -> Generator[str]:
60
+ _Recorder.calls = []
61
+ _Recorder.status = 204
62
+ _Recorder.refused = ""
63
+ httpd = http.server.HTTPServer(("127.0.0.1", 0), _Recorder)
64
+ thread = threading.Thread(target=httpd.serve_forever, daemon=True)
65
+ thread.start()
66
+ yield f"http://127.0.0.1:{httpd.server_address[1]}"
67
+ httpd.shutdown()
68
+
69
+
70
+ def test_announce_and_withdraw(server: str) -> None:
71
+ announcer = VaultAnnouncer(
72
+ VaultSettings(address=server, mount="kv", path="clones/shop"),
73
+ {"VAULT_TOKEN": "t", "VAULT_NAMESPACE": "team"},
74
+ )
75
+ assert announcer.announce((COPY,)) == ("vault:kv/clones/shop/abc123",)
76
+ assert announcer.withdraw(("abc123",), ()) == ("vault:kv/clones/shop/abc123",)
77
+ (post, delete) = _Recorder.calls
78
+ assert post[:2] == ("POST", "/v1/kv/data/clones/shop/abc123")
79
+ assert post[2]["X-Vault-Token"] == "t"
80
+ assert post[2]["X-Vault-Namespace"] == "team"
81
+ assert json.loads(post[3])["data"] == {
82
+ "copy_id": "abc123",
83
+ "kind": "instance",
84
+ "label_spec": "shop",
85
+ "label_engine_version": "18",
86
+ "label_built_at": "2026-01-01T00:00:00+00:00",
87
+ "host": "db",
88
+ "port": 5432,
89
+ "password": "s3cret",
90
+ }
91
+ assert delete[:2] == ("DELETE", "/v1/kv/metadata/clones/shop/abc123")
92
+
93
+
94
+ def test_failures(server: str) -> None:
95
+ _Recorder.status = 403
96
+ announcer = VaultAnnouncer(VaultSettings(address=server), {"VAULT_TOKEN": "t"})
97
+ with pytest.raises(AnnounceError, match="writing abc123 failed: Vault answered 403"):
98
+ announcer.announce((COPY,))
99
+ unreachable = VaultAnnouncer(VaultSettings(address="http://127.0.0.1:9"), {"VAULT_TOKEN": "t"})
100
+ with pytest.raises(AnnounceError, match="deleting abc123 failed"):
101
+ unreachable.withdraw(("abc123",), ())
102
+ with pytest.raises(AnnounceError, match="VAULT_TOKEN is not set"):
103
+ VaultAnnouncer(VaultSettings(address=server), {})
104
+ with pytest.raises(SettingsError, match="address"):
105
+ vault_announcer({"address": "ftp://x"})
106
+
107
+
108
+ def test_partial_failures(server: str) -> None:
109
+ announcer = VaultAnnouncer(VaultSettings(address=server), {"VAULT_TOKEN": "t"})
110
+ other = COPY.model_copy(update={"copy_id": "def456"})
111
+ _Recorder.refused = "/def456"
112
+ with pytest.raises(AnnounceError, match="writing def456 failed") as caught:
113
+ announcer.announce((COPY, other))
114
+ assert caught.value.written == ("vault:secret/datadouble/abc123",)
115
+ _Recorder.calls = []
116
+ with pytest.raises(AnnounceError) as failed:
117
+ announcer.withdraw(("def456", "abc123"), ())
118
+ assert str(failed.value) == (
119
+ "left behind: vault:secret/datadouble/def456 (deleting def456 failed: Vault answered 403)"
120
+ )
121
+ assert [call[0] for call in _Recorder.calls] == ["DELETE", "DELETE"]
122
+
123
+
124
+ @pytest.mark.parametrize(
125
+ "failure", [TimeoutError("timed out"), http.client.RemoteDisconnected("closed"),
126
+ http.client.BadStatusLine("x")],
127
+ ) # fmt: skip
128
+ def test_connection_failures_are_announce_errors(
129
+ failure: Exception, monkeypatch: pytest.MonkeyPatch
130
+ ) -> None:
131
+ def broken(*_args: object, **_kwargs: object) -> None:
132
+ raise failure
133
+
134
+ monkeypatch.setattr(urllib.request, "urlopen", broken)
135
+ announcer = VaultAnnouncer(VaultSettings(address="http://127.0.0.1:9"), {"VAULT_TOKEN": "t"})
136
+ name = type(failure).__name__
137
+ with pytest.raises(AnnounceError, match=f"deleting abc123 failed: {name}"):
138
+ announcer.withdraw(("abc123",), ())
139
+ with pytest.raises(AnnounceError, match=f"writing abc123 failed: {name}"):
140
+ announcer.announce((COPY,))
141
+
142
+
143
+ def test_installed(monkeypatch: pytest.MonkeyPatch) -> None:
144
+ monkeypatch.setenv("VAULT_TOKEN", "t")
145
+ assert "vault" in installed().announcers
146
+ # The mount and path are inside Vault, so `ci init` never mounts them.
147
+ assert installed().remote_settings().announcers["vault"] == (("mount",), ("path",))
148
+ assert remote_keys(vault_announcer) == (("mount",), ("path",))
149
+ assert isinstance(vault_announcer({"address": "http://x"}), VaultAnnouncer)
150
+
151
+
152
+ @pytest.mark.integration
153
+ def test_against_openbao() -> None:
154
+ address = os.environ.get("DATADOUBLE_TEST_VAULT_ADDR")
155
+ if not address:
156
+ pytest.skip("no Vault; run in the Compose default group")
157
+ token = os.environ["VAULT_TOKEN"]
158
+ copy = COPY.model_copy(update={"copy_id": uuid.uuid4().hex[:12]})
159
+ announcer = VaultAnnouncer(VaultSettings(address=address), os.environ)
160
+ announcer.announce((copy,))
161
+ request = urllib.request.Request( # noqa: S310 - the test server's address
162
+ f"{address}/v1/secret/data/datadouble/{copy.copy_id}", headers={"X-Vault-Token": token}
163
+ )
164
+ with urllib.request.urlopen(request) as response: # noqa: S310 - as above
165
+ stored = json.loads(response.read())["data"]["data"]
166
+ assert stored["password"] == COPY.secrets["password"]
167
+ announcer.withdraw((copy.copy_id,), ())
168
+ with pytest.raises(urllib.error.HTTPError) as caught:
169
+ urllib.request.urlopen(request) # noqa: S310 - as above
170
+ assert caught.value.code == 404