datadouble 0.0.3__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.
- datadouble/__init__.py +10 -0
- datadouble/announce.py +380 -0
- datadouble/anonymize.py +165 -0
- datadouble/api.py +1159 -0
- datadouble/boundary.py +47 -0
- datadouble/catalog.py +677 -0
- datadouble/channels.py +62 -0
- datadouble/ci.py +1357 -0
- datadouble/cli.py +940 -0
- datadouble/closure.py +712 -0
- datadouble/engine.py +435 -0
- datadouble/files.py +78 -0
- datadouble/images.py +265 -0
- datadouble/jailer.py +403 -0
- datadouble/names.py +114 -0
- datadouble/notify.py +262 -0
- datadouble/objects.py +195 -0
- datadouble/outcome.py +27 -0
- datadouble/pii.py +109 -0
- datadouble/planner.py +1492 -0
- datadouble/programs.py +68 -0
- datadouble/promote.py +190 -0
- datadouble/prune.py +258 -0
- datadouble/py.typed +0 -0
- datadouble/redaction.py +131 -0
- datadouble/registry.py +128 -0
- datadouble/replicate.py +562 -0
- datadouble/resolve.py +201 -0
- datadouble/run.py +1075 -0
- datadouble/runtime.py +154 -0
- datadouble/secrets.py +57 -0
- datadouble/settings.py +81 -0
- datadouble/signing.py +98 -0
- datadouble/spec.py +1590 -0
- datadouble/staging.py +346 -0
- datadouble/storage.py +222 -0
- datadouble/strict.py +498 -0
- datadouble/subset.py +406 -0
- datadouble/verify.py +171 -0
- datadouble/versions.py +25 -0
- datadouble-0.0.3.dist-info/METADATA +36 -0
- datadouble-0.0.3.dist-info/RECORD +45 -0
- datadouble-0.0.3.dist-info/WHEEL +4 -0
- datadouble-0.0.3.dist-info/entry_points.txt +12 -0
- datadouble-0.0.3.dist-info/licenses/LICENSE +21 -0
datadouble/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# Copyright (c) 2026- Tight Line LLC
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""Realistic, safe copies of production data for development and testing."""
|
|
5
|
+
|
|
6
|
+
from importlib.metadata import version
|
|
7
|
+
|
|
8
|
+
__version__: str = version("datadouble")
|
|
9
|
+
|
|
10
|
+
__all__ = ["__version__"]
|
datadouble/announce.py
ADDED
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
# Copyright (c) 2026- Tight Line LLC
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""``announce``: telling consumers where their copies are.
|
|
5
|
+
|
|
6
|
+
Announcing never writes data; ``replicate`` has already made the copies. Each
|
|
7
|
+
announcement carries the copy's labels (spec, group, engine, engine version,
|
|
8
|
+
owner) and provenance (generation, build time), and where to reach it: a
|
|
9
|
+
volume, or connection parameters. A copy's credentials go only to
|
|
10
|
+
secret-capable targets.
|
|
11
|
+
|
|
12
|
+
Announce adapters register under ``datadouble.announcers``; the entry point
|
|
13
|
+
names a callable that takes the adapter's settings and returns an
|
|
14
|
+
:class:`Announcer`. ``dotenv`` and ``ci-outputs`` live here.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import re
|
|
20
|
+
from collections.abc import Callable, Mapping
|
|
21
|
+
from enum import StrEnum
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import TYPE_CHECKING, Protocol
|
|
24
|
+
|
|
25
|
+
from pydantic import BaseModel, ConfigDict, JsonValue
|
|
26
|
+
|
|
27
|
+
from datadouble.replicate import Copy, record_announced
|
|
28
|
+
from datadouble.secrets import SecretError
|
|
29
|
+
from datadouble.settings import SettingsError, parse_settings
|
|
30
|
+
from datadouble.spec import Spec
|
|
31
|
+
from datadouble.staging import StagingError
|
|
32
|
+
|
|
33
|
+
if TYPE_CHECKING:
|
|
34
|
+
from datadouble.registry import Registry
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class AnnounceError(Exception):
|
|
38
|
+
"""An announcement that could not be written, or withdrawn."""
|
|
39
|
+
|
|
40
|
+
def __init__(self, message: str, written: tuple[str, ...] = ()) -> None:
|
|
41
|
+
"""``written`` is what the adapter wrote before it failed, so it is recorded."""
|
|
42
|
+
super().__init__(message)
|
|
43
|
+
self.written = written
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class Announced(BaseModel):
|
|
47
|
+
"""One copy, as announced: labels, provenance and location."""
|
|
48
|
+
|
|
49
|
+
model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
|
|
50
|
+
|
|
51
|
+
copy_id: str
|
|
52
|
+
kind: str
|
|
53
|
+
labels: dict[str, str]
|
|
54
|
+
location: dict[str, JsonValue]
|
|
55
|
+
secrets: dict[str, str] = {}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def describe(copy: Copy) -> Announced:
|
|
59
|
+
"""What consumers are told about a copy."""
|
|
60
|
+
spec, group, line = copy.prefix.split("/")
|
|
61
|
+
engine, _, version = line.rpartition("-")
|
|
62
|
+
labels = {
|
|
63
|
+
"spec": spec,
|
|
64
|
+
"group": group,
|
|
65
|
+
"engine": engine,
|
|
66
|
+
"engine-version": version,
|
|
67
|
+
"generation": str(copy.generation),
|
|
68
|
+
"built-at": copy.built_at.isoformat(),
|
|
69
|
+
"mode": str(copy.mode),
|
|
70
|
+
}
|
|
71
|
+
if copy.owner:
|
|
72
|
+
labels["owner"] = copy.owner
|
|
73
|
+
return Announced(
|
|
74
|
+
copy_id=copy.id,
|
|
75
|
+
kind=str(copy.kind),
|
|
76
|
+
labels=labels,
|
|
77
|
+
# The copy of the group's files, beside the database's (decision 149).
|
|
78
|
+
location={
|
|
79
|
+
**copy.location,
|
|
80
|
+
**{f"files_{key}": value for key, value in (copy.files or {}).items()},
|
|
81
|
+
},
|
|
82
|
+
secrets=copy.secrets,
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class Announcer(Protocol):
|
|
87
|
+
"""Writes where copies can be reached to one kind of target."""
|
|
88
|
+
|
|
89
|
+
def announce(self, copies: tuple[Announced, ...]) -> tuple[str, ...]:
|
|
90
|
+
"""Announce copies; return what was written, for the response."""
|
|
91
|
+
...
|
|
92
|
+
|
|
93
|
+
def withdraw(self, copy_ids: tuple[str, ...], announced: tuple[str, ...], /) -> tuple[str, ...]:
|
|
94
|
+
"""Remove announcements of released copies; return what was removed.
|
|
95
|
+
|
|
96
|
+
``announced`` is every target this ``announce`` entry reported for these
|
|
97
|
+
copies, as the registry recorded it, so an adapter removes what it wrote
|
|
98
|
+
where it wrote it. An adapter attempts every target, then raises one
|
|
99
|
+
:class:`AnnounceError` naming each one it left behind.
|
|
100
|
+
"""
|
|
101
|
+
...
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
type AnnouncerFactory = Callable[[Mapping[str, JsonValue]], Announcer]
|
|
105
|
+
|
|
106
|
+
_NAME = re.compile(r"[^A-Z0-9]+")
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _variable(*parts: str) -> str:
|
|
110
|
+
return _NAME.sub("_", "_".join(parts).upper()).strip("_")
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _flatten(copy: Announced, *, secrets: bool) -> dict[str, str]:
|
|
114
|
+
values: dict[str, str] = {"COPY_ID": copy.copy_id, "KIND": copy.kind}
|
|
115
|
+
values.update({_variable(k): v for k, v in copy.labels.items()})
|
|
116
|
+
values.update(
|
|
117
|
+
{_variable(k): v if isinstance(v, str) else json.dumps(v) for k, v in copy.location.items()}
|
|
118
|
+
)
|
|
119
|
+
if secrets:
|
|
120
|
+
values.update({_variable(k): v for k, v in copy.secrets.items()})
|
|
121
|
+
return values
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _quote(value: str) -> str:
|
|
125
|
+
return "'" + value.replace("'", "'\\''") + "'" if re.search(r"[^\w@%+=:,./-]", value) else value
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class DotenvSettings(BaseModel):
|
|
129
|
+
"""Settings for the ``dotenv`` announce adapter."""
|
|
130
|
+
|
|
131
|
+
model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
|
|
132
|
+
|
|
133
|
+
path: Path
|
|
134
|
+
prefix: str = "DATADOUBLE"
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class DotenvAnnouncer:
|
|
138
|
+
"""A dotenv file, readable only by its owner, for local and simple CI use.
|
|
139
|
+
|
|
140
|
+
The first copy's values are unnumbered (``DATADOUBLE_PATH``); every copy also
|
|
141
|
+
appears numbered (``DATADOUBLE_1_PATH``). Credentials are included.
|
|
142
|
+
"""
|
|
143
|
+
|
|
144
|
+
def __init__(self, settings: DotenvSettings) -> None:
|
|
145
|
+
"""Write to ``settings.path``."""
|
|
146
|
+
self.settings = settings
|
|
147
|
+
|
|
148
|
+
def announce(self, copies: tuple[Announced, ...]) -> tuple[str, ...]:
|
|
149
|
+
"""Write the file, replacing what was there."""
|
|
150
|
+
lines: list[str] = []
|
|
151
|
+
prefix = self.settings.prefix
|
|
152
|
+
for number, copy in enumerate(copies, start=1):
|
|
153
|
+
values = _flatten(copy, secrets=True)
|
|
154
|
+
if number == 1:
|
|
155
|
+
lines.extend(f"{prefix}_{k}={_quote(v)}" for k, v in values.items())
|
|
156
|
+
lines.extend(f"{prefix}_{number}_{k}={_quote(v)}" for k, v in values.items())
|
|
157
|
+
path = self.settings.path
|
|
158
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
159
|
+
descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
160
|
+
with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
|
|
161
|
+
handle.write("".join(f"{line}\n" for line in lines))
|
|
162
|
+
return (f"dotenv:{path}",)
|
|
163
|
+
|
|
164
|
+
def withdraw(
|
|
165
|
+
self, copy_ids: tuple[str, ...], _announced: tuple[str, ...], /
|
|
166
|
+
) -> tuple[str, ...]:
|
|
167
|
+
"""Remove the file if it announced any of the released copies."""
|
|
168
|
+
path = self.settings.path
|
|
169
|
+
try:
|
|
170
|
+
if not path.is_file():
|
|
171
|
+
return ()
|
|
172
|
+
text = path.read_text(encoding="utf-8")
|
|
173
|
+
if not any(f"_COPY_ID={copy_id}\n" in text for copy_id in copy_ids):
|
|
174
|
+
return ()
|
|
175
|
+
path.unlink()
|
|
176
|
+
except OSError as error:
|
|
177
|
+
message = f"left behind: dotenv:{path} ({error.strerror})"
|
|
178
|
+
raise AnnounceError(message) from None
|
|
179
|
+
return (f"dotenv:{path}",)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
class CiSystem(StrEnum):
|
|
183
|
+
"""Where ``ci-outputs`` writes."""
|
|
184
|
+
|
|
185
|
+
AUTO = "auto"
|
|
186
|
+
GITHUB = "github"
|
|
187
|
+
GITLAB = "gitlab"
|
|
188
|
+
FILE = "file"
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
class CiOutputsSettings(BaseModel):
|
|
192
|
+
"""Settings for the ``ci-outputs`` announce adapter."""
|
|
193
|
+
|
|
194
|
+
model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
|
|
195
|
+
|
|
196
|
+
system: CiSystem = CiSystem.AUTO
|
|
197
|
+
path: Path | None = None
|
|
198
|
+
"""For ``gitlab`` (a dotenv report) and ``file`` (JSON); ignored for ``github``."""
|
|
199
|
+
prefix: str = "DATADOUBLE"
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
class CiOutputsAnnouncer:
|
|
203
|
+
"""Job outputs of the running CI system. Never includes credentials.
|
|
204
|
+
|
|
205
|
+
GitHub Actions gets step outputs through ``GITHUB_OUTPUT``; GitLab CI a
|
|
206
|
+
dotenv report (declare it under ``artifacts: reports: dotenv``); anything
|
|
207
|
+
else a JSON file.
|
|
208
|
+
"""
|
|
209
|
+
|
|
210
|
+
def __init__(self, settings: CiOutputsSettings, environ: Mapping[str, str]) -> None:
|
|
211
|
+
"""Choose the target from ``settings`` and the environment."""
|
|
212
|
+
self.settings = settings
|
|
213
|
+
self.environ = environ
|
|
214
|
+
|
|
215
|
+
def _system(self) -> CiSystem:
|
|
216
|
+
if self.settings.system is not CiSystem.AUTO:
|
|
217
|
+
return self.settings.system
|
|
218
|
+
if self.environ.get("GITHUB_OUTPUT"):
|
|
219
|
+
return CiSystem.GITHUB
|
|
220
|
+
if self.environ.get("GITLAB_CI"):
|
|
221
|
+
return CiSystem.GITLAB
|
|
222
|
+
return CiSystem.FILE
|
|
223
|
+
|
|
224
|
+
def _path(self, system: CiSystem) -> Path:
|
|
225
|
+
if system is CiSystem.GITHUB:
|
|
226
|
+
return Path(self.environ.get("GITHUB_OUTPUT", ""))
|
|
227
|
+
if self.settings.path is None:
|
|
228
|
+
message = f"ci-outputs for {system} needs a `path`"
|
|
229
|
+
raise AnnounceError(message)
|
|
230
|
+
return self.settings.path
|
|
231
|
+
|
|
232
|
+
def announce(self, copies: tuple[Announced, ...]) -> tuple[str, ...]:
|
|
233
|
+
"""Write the outputs."""
|
|
234
|
+
system = self._system()
|
|
235
|
+
path = self._path(system)
|
|
236
|
+
if system is CiSystem.FILE:
|
|
237
|
+
data = [
|
|
238
|
+
copy.model_copy(update={"secrets": {}}).model_dump(mode="json") for copy in copies
|
|
239
|
+
]
|
|
240
|
+
path.write_text(json.dumps({"copies": data}, indent=2) + "\n", encoding="utf-8")
|
|
241
|
+
return (f"file:{path}",)
|
|
242
|
+
prefix = self.settings.prefix
|
|
243
|
+
lines: list[str] = []
|
|
244
|
+
for number, copy in enumerate(copies, start=1):
|
|
245
|
+
values = _flatten(copy, secrets=False)
|
|
246
|
+
if number == 1:
|
|
247
|
+
lines.extend(f"{prefix}_{k}={v}" for k, v in values.items())
|
|
248
|
+
lines.extend(f"{prefix}_{number}_{k}={v}" for k, v in values.items())
|
|
249
|
+
mode = "a" if system is CiSystem.GITHUB else "w"
|
|
250
|
+
with path.open(mode, encoding="utf-8") as handle:
|
|
251
|
+
handle.write("".join(f"{line}\n" for line in lines))
|
|
252
|
+
return (f"{system}:{path}",)
|
|
253
|
+
|
|
254
|
+
def withdraw(
|
|
255
|
+
self, _copy_ids: tuple[str, ...], _announced: tuple[str, ...], /
|
|
256
|
+
) -> tuple[str, ...]:
|
|
257
|
+
"""Job outputs end with the job; there is nothing to remove."""
|
|
258
|
+
return ()
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def dotenv_announcer(settings: Mapping[str, JsonValue]) -> Announcer:
|
|
262
|
+
"""The ``dotenv`` entry point."""
|
|
263
|
+
return DotenvAnnouncer(parse_settings(DotenvSettings, settings, "dotenv announce"))
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def ci_outputs_announcer(settings: Mapping[str, JsonValue]) -> Announcer:
|
|
267
|
+
"""The ``ci-outputs`` entry point."""
|
|
268
|
+
return CiOutputsAnnouncer(
|
|
269
|
+
parse_settings(CiOutputsSettings, settings, "ci-outputs announce"), os.environ
|
|
270
|
+
)
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
_WITHDRAW_FAILURES = (AnnounceError, SecretError, SettingsError, OSError, ValueError)
|
|
274
|
+
"""What one entry's withdrawal may fail with without stopping the others'."""
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _entries(spec: Spec) -> list[tuple[str, str, Mapping[str, JsonValue]]]:
|
|
278
|
+
"""Each ``announce`` entry's key, adapter name and settings.
|
|
279
|
+
|
|
280
|
+
The key is the adapter's name, ``name#2`` for the second entry of the same adapter,
|
|
281
|
+
and so on: positional per adapter, so reordering same-adapter entries changes it.
|
|
282
|
+
"""
|
|
283
|
+
found: list[tuple[str, str, Mapping[str, JsonValue]]] = []
|
|
284
|
+
seen: dict[str, int] = {}
|
|
285
|
+
for entry in spec.announce:
|
|
286
|
+
for name, settings in entry.items():
|
|
287
|
+
seen[name] = seen.get(name, 0) + 1
|
|
288
|
+
found.append((name if seen[name] == 1 else f"{name}#{seen[name]}", name, settings))
|
|
289
|
+
return found
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _announcer(registry: "Registry", name: str, settings: Mapping[str, JsonValue]) -> Announcer:
|
|
293
|
+
factory = registry.announcers.get(name)
|
|
294
|
+
if factory is None:
|
|
295
|
+
message = f"no announce adapter named {name!r} is installed"
|
|
296
|
+
raise AnnounceError(message)
|
|
297
|
+
return factory(settings)
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _announcers(spec: Spec, registry: "Registry") -> list[tuple[str, Announcer]]:
|
|
301
|
+
"""Each ``announce`` entry's adapter, by its key."""
|
|
302
|
+
return [(key, _announcer(registry, name, settings)) for key, name, settings in _entries(spec)]
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def announce(spec: Spec, registry: "Registry", copies: tuple[Copy, ...]) -> tuple[str, ...]:
|
|
306
|
+
"""Announce copies (with their credentials, for the targets allowed them) everywhere."""
|
|
307
|
+
ready = tuple(copy for copy in copies if copy.state == "ready")
|
|
308
|
+
if not ready:
|
|
309
|
+
return ()
|
|
310
|
+
described = tuple(describe(copy) for copy in ready)
|
|
311
|
+
written: dict[str, tuple[str, ...]] = {}
|
|
312
|
+
try:
|
|
313
|
+
for key, announcer in _announcers(spec, registry):
|
|
314
|
+
try:
|
|
315
|
+
written[key] = announcer.announce(described)
|
|
316
|
+
except AnnounceError as error:
|
|
317
|
+
if error.written:
|
|
318
|
+
written[key] = error.written
|
|
319
|
+
raise
|
|
320
|
+
except BaseException as error:
|
|
321
|
+
# What was written before the failure is recorded, so release finds it; a
|
|
322
|
+
# failure to record is reported with the original error, not instead of it.
|
|
323
|
+
if written:
|
|
324
|
+
try:
|
|
325
|
+
record_announced(spec, ready, written)
|
|
326
|
+
except (StagingError, OSError, ValueError) as recording:
|
|
327
|
+
error.add_note(f"recording what was announced failed too: {recording}")
|
|
328
|
+
raise
|
|
329
|
+
targets = tuple(target for entry in written.values() for target in entry)
|
|
330
|
+
if written:
|
|
331
|
+
try:
|
|
332
|
+
record_announced(spec, ready, written)
|
|
333
|
+
except (StagingError, OSError, ValueError) as error:
|
|
334
|
+
message = (
|
|
335
|
+
f"announced, but not recorded, so release will not withdraw: {', '.join(targets)}"
|
|
336
|
+
f" ({error})"
|
|
337
|
+
)
|
|
338
|
+
raise AnnounceError(message) from error
|
|
339
|
+
return targets
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def withdraw(spec: Spec, registry: "Registry", copies: tuple[Copy, ...]) -> tuple[str, ...]:
|
|
343
|
+
"""Remove announcements of released copies everywhere, where they were announced."""
|
|
344
|
+
if not copies:
|
|
345
|
+
return ()
|
|
346
|
+
copy_ids = tuple(copy.id for copy in copies)
|
|
347
|
+
recorded: dict[str, tuple[str, ...]] = {}
|
|
348
|
+
for copy in copies:
|
|
349
|
+
for key, targets in copy.announced.items():
|
|
350
|
+
recorded[key] = tuple(dict.fromkeys((*recorded.get(key, ()), *targets)))
|
|
351
|
+
removed: list[str] = []
|
|
352
|
+
failures: list[str] = []
|
|
353
|
+
entries = _entries(spec)
|
|
354
|
+
for key, name, settings in entries:
|
|
355
|
+
announced = recorded.get(key, ())
|
|
356
|
+
# Each entry is made and withdrawn on its own: the copies are already gone from
|
|
357
|
+
# the registry, so one failing entry must not keep the others from running.
|
|
358
|
+
# An adapter's own AnnounceError from withdraw names what it left behind; any
|
|
359
|
+
# other failure (making the adapter, an OSError) gets the recorded targets added.
|
|
360
|
+
try:
|
|
361
|
+
announcer = _announcer(registry, name, settings)
|
|
362
|
+
except _WITHDRAW_FAILURES as error:
|
|
363
|
+
failures.append(f"{key}: {error} (recorded: {', '.join(announced) or 'nothing'})")
|
|
364
|
+
continue
|
|
365
|
+
try:
|
|
366
|
+
removed.extend(announcer.withdraw(copy_ids, announced))
|
|
367
|
+
except AnnounceError as error:
|
|
368
|
+
failures.append(f"{key}: {error}")
|
|
369
|
+
except _WITHDRAW_FAILURES as error:
|
|
370
|
+
failures.append(f"{key}: {error} (recorded: {', '.join(announced) or 'nothing'})")
|
|
371
|
+
current = {key for key, _, _ in entries}
|
|
372
|
+
failures.extend(
|
|
373
|
+
f"recorded by an announce entry no longer in the spec: {key}: {', '.join(targets)}"
|
|
374
|
+
for key, targets in recorded.items()
|
|
375
|
+
if key not in current and targets
|
|
376
|
+
)
|
|
377
|
+
if failures:
|
|
378
|
+
message = "announcements left behind; remove them by hand: " + "; ".join(failures)
|
|
379
|
+
raise AnnounceError(message)
|
|
380
|
+
return tuple(removed)
|
datadouble/anonymize.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
# Copyright (c) 2026- Tight Line LLC
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""Replacement values for the strategies that work value by value.
|
|
5
|
+
|
|
6
|
+
Faker, hash and format-preserving rules map each distinct original value to a
|
|
7
|
+
replacement here, in the Datadouble process; the engine adapter then applies
|
|
8
|
+
the mapping in one native update per table. Every replacement is keyed by the
|
|
9
|
+
run's anonymization key, so the same input gets the same output in every
|
|
10
|
+
table and every image group of a build, and nothing about the original can be
|
|
11
|
+
recovered without the key.
|
|
12
|
+
|
|
13
|
+
Generated emails, URLs, phone numbers and IP addresses use reserved example
|
|
14
|
+
domains and documentation ranges, so the PII scan does not mistake them for
|
|
15
|
+
real data.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import hashlib
|
|
19
|
+
import hmac
|
|
20
|
+
import secrets
|
|
21
|
+
from collections.abc import Callable, Iterable
|
|
22
|
+
from typing import assert_never
|
|
23
|
+
|
|
24
|
+
from faker import Faker
|
|
25
|
+
|
|
26
|
+
from datadouble.catalog import ColumnKind
|
|
27
|
+
from datadouble.pii import detect
|
|
28
|
+
from datadouble.spec import FakerKind, FakerRule, FormatPreservingRule, HashRule
|
|
29
|
+
|
|
30
|
+
_MAX_ATTEMPTS = 100
|
|
31
|
+
_INT32_MAX = 2**31 - 1
|
|
32
|
+
_LUHN_CARRY = 9
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class AnonymizeError(Exception):
|
|
36
|
+
"""Replacement values that cannot be generated as the rules require."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
type ValueRule = FakerRule | HashRule | FormatPreservingRule
|
|
40
|
+
"""Rules whose replacements are computed here, value by value."""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def new_key() -> bytes:
|
|
44
|
+
"""A random anonymization key, for runs whose spec does not supply one."""
|
|
45
|
+
return secrets.token_bytes(32)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class Anonymizer:
|
|
49
|
+
"""Computes replacements under one anonymization key."""
|
|
50
|
+
|
|
51
|
+
def __init__(self, key: bytes, locale: str = "en_US") -> None:
|
|
52
|
+
"""Use ``key`` for every replacement; ``locale`` picks Faker's data."""
|
|
53
|
+
self._key = key
|
|
54
|
+
self._faker = Faker(locale)
|
|
55
|
+
|
|
56
|
+
def _digest(self, *parts: str) -> bytes:
|
|
57
|
+
message = "\x1f".join(parts).encode()
|
|
58
|
+
return hmac.new(self._key, message, hashlib.sha256).digest()
|
|
59
|
+
|
|
60
|
+
def _seed(self, *parts: str) -> int:
|
|
61
|
+
return int.from_bytes(self._digest(*parts)[:8], "big")
|
|
62
|
+
|
|
63
|
+
def fake(self, kind: FakerKind, value: str, attempt: int = 0) -> str:
|
|
64
|
+
"""A fake value of ``kind`` for ``value``; ``attempt`` varies it on collisions."""
|
|
65
|
+
fake = self._faker
|
|
66
|
+
fake.seed_instance(self._seed("faker", kind, str(attempt), value))
|
|
67
|
+
generators: dict[FakerKind, Callable[[], str]] = {
|
|
68
|
+
FakerKind.FIRST_NAME: fake.first_name,
|
|
69
|
+
FakerKind.LAST_NAME: fake.last_name,
|
|
70
|
+
FakerKind.NAME: fake.name,
|
|
71
|
+
FakerKind.EMAIL: lambda: f"{fake.user_name()}@{fake.safe_domain_name()}",
|
|
72
|
+
FakerKind.USER_NAME: fake.user_name,
|
|
73
|
+
FakerKind.PHONE_NUMBER: lambda: (
|
|
74
|
+
f"+1-{fake.random_int(200, 999)}-555-01{fake.random_int(0, 99):02d}"
|
|
75
|
+
),
|
|
76
|
+
FakerKind.STREET_ADDRESS: fake.street_address,
|
|
77
|
+
FakerKind.CITY: fake.city,
|
|
78
|
+
FakerKind.POSTCODE: fake.postcode,
|
|
79
|
+
FakerKind.COMPANY: fake.company,
|
|
80
|
+
FakerKind.IPV4: lambda: f"192.0.2.{fake.random_int(1, 254)}",
|
|
81
|
+
FakerKind.URL: lambda: f"https://{fake.safe_domain_name()}/{fake.slug()}",
|
|
82
|
+
FakerKind.TEXT: lambda: fake.sentence(nb_words=8),
|
|
83
|
+
FakerKind.DATE_OF_BIRTH: lambda: fake.date_of_birth(
|
|
84
|
+
minimum_age=18, maximum_age=90
|
|
85
|
+
).isoformat(),
|
|
86
|
+
}
|
|
87
|
+
return generators[kind]()
|
|
88
|
+
|
|
89
|
+
def hash(self, value: str, length: int, kind: ColumnKind, attempt: int = 0) -> str:
|
|
90
|
+
"""A keyed hash of ``value``: hex text, or a non-negative 32-bit integer."""
|
|
91
|
+
digest = self._digest("hash", str(attempt), value)
|
|
92
|
+
if kind is ColumnKind.INTEGER:
|
|
93
|
+
return str(int.from_bytes(digest, "big") % _INT32_MAX)
|
|
94
|
+
return digest.hex()[:length]
|
|
95
|
+
|
|
96
|
+
def preserve_format(self, value: str, *, luhn: bool, attempt: int = 0) -> str:
|
|
97
|
+
"""Replace digits with digits and letters with letters of the same case."""
|
|
98
|
+
stream = self._digest("format", str(attempt), value)
|
|
99
|
+
while len(stream) < len(value):
|
|
100
|
+
stream += hashlib.sha256(stream).digest()
|
|
101
|
+
out: list[str] = []
|
|
102
|
+
for char, byte in zip(value, stream, strict=False):
|
|
103
|
+
if char.isascii() and char.isdigit():
|
|
104
|
+
out.append(str(byte % 10))
|
|
105
|
+
elif char.isascii() and char.isalpha():
|
|
106
|
+
base = ord("a") if char.islower() else ord("A")
|
|
107
|
+
out.append(chr(base + byte % 26))
|
|
108
|
+
else:
|
|
109
|
+
out.append(char)
|
|
110
|
+
result = "".join(out)
|
|
111
|
+
return _with_luhn_check(result) if luhn else result
|
|
112
|
+
|
|
113
|
+
def replacement(self, rule: ValueRule, kind: ColumnKind, value: str, attempt: int) -> str:
|
|
114
|
+
"""The replacement ``rule`` gives ``value`` on a given attempt."""
|
|
115
|
+
match rule:
|
|
116
|
+
case FakerRule():
|
|
117
|
+
return self.fake(rule.faker, value, attempt)
|
|
118
|
+
case HashRule():
|
|
119
|
+
return self.hash(value, rule.hash.length, kind, attempt)
|
|
120
|
+
case FormatPreservingRule():
|
|
121
|
+
luhn = rule.format_preserving.luhn
|
|
122
|
+
return self.preserve_format(value, luhn=luhn, attempt=attempt)
|
|
123
|
+
case _:
|
|
124
|
+
assert_never(rule)
|
|
125
|
+
|
|
126
|
+
def mapping(
|
|
127
|
+
self, rule: ValueRule, kind: ColumnKind, values: Iterable[str], *, unique: bool
|
|
128
|
+
) -> dict[str, str]:
|
|
129
|
+
"""Replacements for distinct ``values``; with ``unique``, no two share one."""
|
|
130
|
+
result: dict[str, str] = {}
|
|
131
|
+
taken: set[str] = set()
|
|
132
|
+
for value in sorted(set(values)):
|
|
133
|
+
for attempt in range(_MAX_ATTEMPTS):
|
|
134
|
+
replacement = self.replacement(rule, kind, value, attempt)
|
|
135
|
+
# A hash is meant to look like nothing; hex text can still hold a
|
|
136
|
+
# digit run the PII scan reads as a card number, so try again.
|
|
137
|
+
if isinstance(rule, HashRule) and detect(replacement):
|
|
138
|
+
continue
|
|
139
|
+
if not unique or replacement not in taken:
|
|
140
|
+
break
|
|
141
|
+
else:
|
|
142
|
+
message = (
|
|
143
|
+
f"could not find a unique replacement after {_MAX_ATTEMPTS} attempts; "
|
|
144
|
+
"the rule produces too few distinct values for this column"
|
|
145
|
+
)
|
|
146
|
+
raise AnonymizeError(message)
|
|
147
|
+
taken.add(replacement)
|
|
148
|
+
result[value] = replacement
|
|
149
|
+
return result
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _with_luhn_check(digits_and_more: str) -> str:
|
|
153
|
+
"""Set the last digit so the digits pass the Luhn check, as card numbers do."""
|
|
154
|
+
positions = [i for i, c in enumerate(digits_and_more) if c.isascii() and c.isdigit()]
|
|
155
|
+
if not positions:
|
|
156
|
+
return digits_and_more
|
|
157
|
+
digits = [int(digits_and_more[i]) for i in positions[:-1]]
|
|
158
|
+
total = 0
|
|
159
|
+
for index, digit in enumerate(reversed(digits)):
|
|
160
|
+
doubled = digit * 2 if index % 2 == 0 else digit
|
|
161
|
+
total += doubled - _LUHN_CARRY if doubled > _LUHN_CARRY else doubled
|
|
162
|
+
check = (10 - total % 10) % 10
|
|
163
|
+
chars = list(digits_and_more)
|
|
164
|
+
chars[positions[-1]] = str(check)
|
|
165
|
+
return "".join(chars)
|