secondkey 0.2.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.
secondkey/proxy.py ADDED
@@ -0,0 +1,244 @@
1
+ """A Postgres wire-protocol proxy that puts the gate in front of a database.
2
+
3
+ Point an agent's DATABASE_URL at the proxy instead of the database. Every
4
+ query, whether from psql, a script the agent wrote, an ORM or a migration
5
+ tool, is classified and checked against the policy:
6
+
7
+ * allowed queries are forwarded untouched;
8
+ * held or denied queries are swapped for a statement that makes the server
9
+ itself raise an error carrying SecondKey's message. Because the server
10
+ produces the error, transaction state stays correct for every client;
11
+ * once a human approves, the next identical query gets a snapshot and runs.
12
+
13
+ The proxy speaks plain text to clients (run it on localhost) and can use TLS
14
+ to the upstream database (--upstream-ssl, Python 3.11+).
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import asyncio
20
+ import os
21
+ import ssl
22
+ import struct
23
+ import sys
24
+ from dataclasses import dataclass, field
25
+ from typing import Any
26
+
27
+ from . import gate
28
+ from .classify import Action
29
+ from .policy import Policy, load_policy
30
+ from .sql import classify_sql
31
+
32
+ SSL_REQUEST = 80877103
33
+ GSSENC_REQUEST = 80877104
34
+ CANCEL_REQUEST = 80877102
35
+ PROTECTABLE = ("sql.drop", "sql.truncate", "sql.delete", "sql.update", "sql.alter")
36
+
37
+
38
+ @dataclass
39
+ class ProxyConfig:
40
+ listen_host: str = "127.0.0.1"
41
+ listen_port: int = 6543
42
+ upstream: str = "127.0.0.1:5432" # host:port or a unix socket path
43
+ upstream_ssl: bool = False
44
+ wait: float = 0.0
45
+ cwd: str = field(default_factory=os.getcwd)
46
+ snapshot_dsn: str | None = None # overrides how pg_dump connects
47
+
48
+ def upstream_parts(self) -> tuple[str | None, str | None, str | None]:
49
+ """(host, port, unix_path)"""
50
+ if self.upstream.startswith("/"):
51
+ d, name = os.path.split(self.upstream)
52
+ port = name.rsplit(".", 1)[-1] if name.startswith(".s.PGSQL.") else None
53
+ return d, port, self.upstream
54
+ host, _, port = self.upstream.rpartition(":")
55
+ return (host or "127.0.0.1"), (port or "5432"), None
56
+
57
+
58
+ def classify_query(sql: str, conn: dict[str, str]) -> list[Action]:
59
+ out = []
60
+ for st in classify_sql(sql):
61
+ provider = "postgres" if st.tables and st.category in PROTECTABLE else None
62
+ out.append(Action(st.category, st.text[:120], provider,
63
+ {"conn": conn, "tables": st.tables, "sql": st.text, "where": st.where, "kind": st.category}))
64
+ return out or [Action("sql.read", "empty query")]
65
+
66
+
67
+ def _quote_lit(s: str) -> str:
68
+ return "'" + s.replace("'", "''") + "'"
69
+
70
+
71
+ def raise_statement(message: str) -> str:
72
+ msg = message.replace("$sk$", "$ sk $")
73
+ return f"DO $sk$ BEGIN RAISE EXCEPTION USING MESSAGE = {_quote_lit(msg)}, ERRCODE = '42501'; END $sk$"
74
+
75
+
76
+ def parse_error_statement(short: str) -> str:
77
+ # Extended protocol: the error must happen at Parse time, so reference a relation whose
78
+ # name is the message. Postgres reports: relation "<message>" does not exist.
79
+ ident = short[:63].replace('"', "'")
80
+ return f'SELECT * FROM "{ident}"'
81
+
82
+
83
+ async def _read_msg(r: asyncio.StreamReader) -> tuple[bytes, bytes]:
84
+ head = await r.readexactly(5)
85
+ length = struct.unpack("!I", head[1:])[0]
86
+ return head[:1], await r.readexactly(length - 4)
87
+
88
+
89
+ def _msg(typ: bytes, body: bytes) -> bytes:
90
+ return typ + struct.pack("!I", len(body) + 4) + body
91
+
92
+
93
+ class Session:
94
+ def __init__(self, cfg: ProxyConfig, policy: Policy, params: dict[str, str]):
95
+ self.cfg, self.policy, self.params = cfg, policy, params
96
+ host, port, _ = cfg.upstream_parts()
97
+ db = params.get("database") or params.get("user") or "postgres"
98
+ if cfg.snapshot_dsn:
99
+ self.conn = {"dbname": cfg.snapshot_dsn}
100
+ else:
101
+ self.conn = {"dbname": db, "host": host or "", "port": port or "", "user": params.get("user", "")}
102
+ self.conn = {k: v for k, v in self.conn.items() if v}
103
+ self.db = db
104
+ self.skip_until_sync = False
105
+
106
+ def decide(self, sql: str) -> tuple[bool, str, str]:
107
+ """Return (allowed, long message, short message). Runs in a worker thread."""
108
+ actions = classify_query(sql, self.conn)
109
+ decision = self.policy.evaluate(actions)
110
+ if decision.decision == "allow" and not decision.snapshot_actions:
111
+ return True, "", ""
112
+ result = gate.evaluate(source="pg-proxy", tool="SQL",
113
+ tool_input={"command": sql, "database": self.db, "user": self.params.get("user", ""),
114
+ "conn": self.conn},
115
+ cwd=f"{self.cfg.cwd}", policy=self.policy, wait=self.cfg.wait, native_ask=False)
116
+ if result.outcome == "allow":
117
+ return True, result.message, ""
118
+ if result.outcome == "held" and result.request is not None:
119
+ rid = result.request.id
120
+ impact = ("; ".join(result.request.impact[:3]) + ". ") if result.request.impact else ""
121
+ return (False, f"SecondKey held this query for human approval (request {rid}). {impact}"
122
+ f"Ask a human to run `secondkey approve {rid}`, then run the same query again.",
123
+ f"secondkey: held {rid}, run: secondkey approve {rid}")
124
+ return False, result.message, "secondkey: blocked by policy, see: secondkey log"
125
+
126
+
127
+ async def _open_upstream(cfg: ProxyConfig) -> tuple[asyncio.StreamReader, asyncio.StreamWriter]:
128
+ host, port, unix = cfg.upstream_parts()
129
+ if unix:
130
+ r, w = await asyncio.open_unix_connection(unix)
131
+ else:
132
+ r, w = await asyncio.open_connection(host, int(port or 5432))
133
+ if cfg.upstream_ssl:
134
+ if not hasattr(w, "start_tls"):
135
+ raise RuntimeError("--upstream-ssl needs Python 3.11+")
136
+ w.write(struct.pack("!II", 8, SSL_REQUEST))
137
+ await w.drain()
138
+ if await r.readexactly(1) != b"S":
139
+ raise RuntimeError("upstream refused TLS")
140
+ await w.start_tls(ssl.create_default_context(), server_hostname=host)
141
+ return r, w
142
+
143
+
144
+ async def _pump(src: asyncio.StreamReader, dst: asyncio.StreamWriter) -> None:
145
+ try:
146
+ while True:
147
+ data = await src.read(65536)
148
+ if not data:
149
+ break
150
+ dst.write(data)
151
+ await dst.drain()
152
+ except (ConnectionError, asyncio.IncompleteReadError):
153
+ pass
154
+ finally:
155
+ try:
156
+ dst.close()
157
+ except Exception:
158
+ pass
159
+
160
+
161
+ async def handle_client(cfg: ProxyConfig, policy: Policy, cr: asyncio.StreamReader, cw: asyncio.StreamWriter) -> None:
162
+ uw: asyncio.StreamWriter | None = None
163
+ try:
164
+ while True:
165
+ length = struct.unpack("!I", await cr.readexactly(4))[0]
166
+ body = await cr.readexactly(length - 4)
167
+ code = struct.unpack("!I", body[:4])[0]
168
+ if code in (SSL_REQUEST, GSSENC_REQUEST):
169
+ cw.write(b"N") # plain text to the client; keep the proxy on localhost
170
+ await cw.drain()
171
+ continue
172
+ break
173
+ startup = struct.pack("!I", length) + body
174
+ ur, uw = await _open_upstream(cfg)
175
+ uw.write(startup)
176
+ await uw.drain()
177
+ if code == CANCEL_REQUEST:
178
+ return
179
+ parts = body[4:].split(b"\x00")
180
+ params = {parts[i].decode(): parts[i + 1].decode() for i in range(0, len(parts) - 1, 2) if parts[i]}
181
+ session = Session(cfg, policy, params)
182
+ server_to_client = asyncio.create_task(_pump(ur, cw))
183
+ try:
184
+ while True:
185
+ typ, payload = await _read_msg(cr)
186
+ if typ == b"Q":
187
+ sql = payload[:-1].decode(errors="replace")
188
+ allowed, long_msg, _ = await asyncio.to_thread(session.decide, sql)
189
+ if not allowed:
190
+ payload = raise_statement(long_msg).encode() + b"\x00"
191
+ elif typ == b"P":
192
+ name_end = payload.index(b"\x00")
193
+ q_end = payload.index(b"\x00", name_end + 1)
194
+ sql = payload[name_end + 1:q_end].decode(errors="replace")
195
+ allowed, _, short = await asyncio.to_thread(session.decide, sql)
196
+ if not allowed:
197
+ payload = payload[:name_end + 1] + parse_error_statement(short).encode() + b"\x00" + struct.pack("!H", 0)
198
+ elif typ == b"X":
199
+ uw.write(_msg(typ, payload))
200
+ await uw.drain()
201
+ break
202
+ uw.write(_msg(typ, payload))
203
+ await uw.drain()
204
+ except (asyncio.IncompleteReadError, ConnectionError):
205
+ pass
206
+ finally:
207
+ server_to_client.cancel()
208
+ except (asyncio.IncompleteReadError, ConnectionError, OSError, RuntimeError) as e:
209
+ print(f"secondkey proxy: connection error: {e}", file=sys.stderr)
210
+ finally:
211
+ for w in (cw, uw):
212
+ if w is not None:
213
+ try:
214
+ w.close()
215
+ except Exception:
216
+ pass
217
+
218
+
219
+ async def serve(cfg: ProxyConfig, ready: asyncio.Event | None = None) -> None:
220
+ policy = load_policy(cfg.cwd)
221
+ server = await asyncio.start_server(lambda r, w: handle_client(cfg, policy, r, w), cfg.listen_host, cfg.listen_port)
222
+ if ready:
223
+ ready.set()
224
+ async with server:
225
+ await server.serve_forever()
226
+
227
+
228
+ def run_proxy(cfg: ProxyConfig) -> int:
229
+ host, port, unix = cfg.upstream_parts()
230
+ print(f"secondkey proxy listening on {cfg.listen_host}:{cfg.listen_port} -> {unix or f'{host}:{port}'}"
231
+ f"{' (TLS)' if cfg.upstream_ssl else ''}", file=sys.stderr)
232
+ print(f"point the agent at it, e.g. DATABASE_URL=postgresql://USER:PASS@{cfg.listen_host}:{cfg.listen_port}/DBNAME",
233
+ file=sys.stderr)
234
+ try:
235
+ asyncio.run(serve(cfg))
236
+ except KeyboardInterrupt:
237
+ return 0
238
+ return 0
239
+
240
+
241
+ def config_from_args(a: Any) -> ProxyConfig:
242
+ lh, _, lp = a.listen.rpartition(":")
243
+ return ProxyConfig(listen_host=lh or "127.0.0.1", listen_port=int(lp), upstream=a.upstream, upstream_ssl=a.upstream_ssl,
244
+ wait=a.wait, cwd=a.cwd, snapshot_dsn=a.snapshot_dsn)
@@ -0,0 +1,155 @@
1
+ """Snapshot providers and the helpers that drive them."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import shutil
7
+ import time
8
+ from pathlib import Path
9
+
10
+ from ..classify import Action
11
+ from ..policy import Policy
12
+ from ..store import Snapshot, Store
13
+ from ..util import home, new_id, now, snapshot_root
14
+ from .base import NothingToProtect, Provider, RestoreError, SnapshotUnavailable
15
+ from .aws import AWSProvider
16
+ from .docker import DockerProvider
17
+ from .files import FilesProvider
18
+ from .git import GitProvider
19
+ from .k8s import K8sProvider
20
+ from .mysql import MySQLProvider
21
+ from .postgres import PostgresProvider
22
+ from .terraform import TerraformProvider
23
+
24
+ PROVIDERS: dict[str, Provider] = {p.name: p for p in (FilesProvider(), GitProvider(), PostgresProvider(), MySQLProvider(),
25
+ K8sProvider(), TerraformProvider(), AWSProvider(), DockerProvider())}
26
+
27
+ __all__ = ["PROVIDERS", "Provider", "RestoreError", "SnapshotUnavailable", "NothingToProtect", "plan", "prune", "dir_size", "take_all", "restore"]
28
+
29
+
30
+ def plan(actions: list[Action], policy: Policy) -> tuple[list[str], list[str]]:
31
+ """Return (impact lines, problems) for the actions that will be snapshotted."""
32
+ impact, problems = [], []
33
+ for a in actions:
34
+ prov = PROVIDERS.get(a.provider or "")
35
+ if not prov:
36
+ problems.append(f"{a.summary}: no automatic snapshot for {a.category}")
37
+ continue
38
+ try:
39
+ impact.extend(prov.plan(a, policy))
40
+ except SnapshotUnavailable as e:
41
+ problems.append(f"{a.summary}: {e}")
42
+ except Exception as e: # never let a planning bug block the decision flow
43
+ problems.append(f"{a.summary}: couldn't check ({e.__class__.__name__}: {e})")
44
+ return impact, problems
45
+
46
+
47
+ def take_all(actions: list[Action], request_id: str | None, policy: Policy,
48
+ store: Store) -> tuple[list[Snapshot], list[str], list[str]]:
49
+ """Snapshot every protectable action.
50
+
51
+ Returns (snapshots, skipped, failures). *skipped* are actions with no
52
+ provider or nothing to protect; *failures* are snapshots that should have
53
+ worked but didn't.
54
+ """
55
+ snaps, skipped, failures = [], [], []
56
+ for a in actions:
57
+ prov = PROVIDERS.get(a.provider or "")
58
+ if not prov:
59
+ skipped.append(f"{a.summary}: no automatic snapshot for {a.category}")
60
+ continue
61
+ sid = new_id("snap")
62
+ dest = snapshot_root() / sid
63
+ dest.mkdir(parents=True)
64
+ try:
65
+ label, meta = prov.take(a, dest, policy)
66
+ except NothingToProtect as e:
67
+ shutil.rmtree(dest, ignore_errors=True)
68
+ skipped.append(f"{a.summary}: {e}")
69
+ continue
70
+ except Exception as e:
71
+ shutil.rmtree(dest, ignore_errors=True)
72
+ failures.append(f"{a.summary}: {e}")
73
+ continue
74
+ meta["disk_bytes"] = dir_size(dest)
75
+ snap = Snapshot(sid, now(), request_id, prov.name, label, str(dest), {**meta, "action": a.to_dict()})
76
+ store.add_snapshot(snap)
77
+ snaps.append(snap)
78
+ if snaps:
79
+ maybe_auto_prune(store, policy)
80
+ return snaps, skipped, failures
81
+
82
+
83
+ def dir_size(path: str | Path) -> int:
84
+ total = 0
85
+ for root, _dirs, files in os.walk(path):
86
+ for f in files:
87
+ try:
88
+ total += os.lstat(os.path.join(root, f)).st_size
89
+ except OSError:
90
+ pass
91
+ return total
92
+
93
+
94
+ def prune(store: Store, policy: Policy, older_than_days: float | None = None, max_bytes: int | None = None,
95
+ dry_run: bool = False) -> list[tuple[Snapshot, str, int]]:
96
+ """Delete old snapshots. Returns (snapshot, reason, bytes) for each one removed.
97
+
98
+ Never removes the newest snapshot, so the last action can always be undone.
99
+ """
100
+ days = policy.retention_days if older_than_days is None else older_than_days
101
+ cap = policy.max_total_bytes if max_bytes is None else max_bytes
102
+ snaps = store.live_snapshots()
103
+ if not snaps:
104
+ return []
105
+ newest = snaps[-1].id
106
+ sized = [(s, s.meta.get("disk_bytes") if os.path.isdir(s.path) and "disk_bytes" in s.meta else
107
+ (dir_size(s.path) if os.path.isdir(s.path) else 0)) for s in snaps]
108
+ doomed: list[tuple[Snapshot, str, int]] = []
109
+ cutoff = now() - days * 86400 if days and days > 0 else None
110
+ keep = []
111
+ for s, size in sized:
112
+ if cutoff is not None and s.created < cutoff and s.id != newest:
113
+ doomed.append((s, f"older than {days:g} days", size))
114
+ else:
115
+ keep.append((s, size))
116
+ total = sum(sz for _, sz in keep)
117
+ if cap and cap > 0:
118
+ for s, size in keep:
119
+ if total <= cap or s.id == newest:
120
+ break
121
+ doomed.append((s, "over the total snapshot size limit", size))
122
+ total -= size
123
+ if not dry_run:
124
+ for s, _reason, _size in doomed:
125
+ try:
126
+ PROVIDERS[s.provider].cleanup(s)
127
+ except Exception: # cleanup is best effort
128
+ pass
129
+ shutil.rmtree(s.path, ignore_errors=True)
130
+ store.set_snapshot_status(s.id, "pruned")
131
+ return doomed
132
+
133
+
134
+ def maybe_auto_prune(store: Store, policy: Policy) -> None:
135
+ """Prune at most once a day, piggy-backing on normal use."""
136
+ marker = home() / ".last_prune"
137
+ try:
138
+ if marker.exists() and time.time() - marker.stat().st_mtime < 86400:
139
+ return
140
+ marker.touch()
141
+ removed = prune(store, policy)
142
+ if removed:
143
+ from .. import audit
144
+ audit.record("prune", snapshots=[s.id for s, _, _ in removed], auto=True,
145
+ bytes=sum(b for _, _, b in removed))
146
+ except Exception: # never let housekeeping break the gate
147
+ pass
148
+
149
+
150
+ def describe(snap: Snapshot, mode: str | None = None) -> list[str]:
151
+ return PROVIDERS[snap.provider].describe_restore(snap, mode)
152
+
153
+
154
+ def restore(snap: Snapshot, mode: str | None = None, force: bool = False) -> list[str]:
155
+ return PROVIDERS[snap.provider].restore(snap, mode, force)
@@ -0,0 +1,109 @@
1
+ """AWS snapshots: EBS volumes, RDS instances and S3 prefixes, via the AWS CLI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from ..classify import Action
11
+ from ..policy import Policy
12
+ from ..store import Snapshot
13
+ from ..util import CommandError, human_size, run
14
+ from .base import Provider, RestoreError, SnapshotUnavailable
15
+
16
+
17
+ def _aws(target: dict[str, Any], *args: str, timeout: float = 120) -> str:
18
+ argv = ["aws", *args]
19
+ for key in ("region", "profile"):
20
+ if target.get(key):
21
+ argv += [f"--{key}", target[key]]
22
+ try:
23
+ return run(argv, timeout=timeout).stdout
24
+ except CommandError as e:
25
+ raise SnapshotUnavailable(f"aws {' '.join(args[:2])} failed: {e.stderr.strip()[:300]}") from e
26
+
27
+
28
+ def _s3_size(target: dict[str, Any]) -> tuple[int, int]:
29
+ out = _aws(target, "s3", "ls", target["uri"], "--recursive", "--summarize", timeout=600)
30
+ n = re.search(r"Total Objects:\s*(\d+)", out)
31
+ b = re.search(r"Total Size:\s*(\d+)", out)
32
+ return (int(n.group(1)) if n else 0), (int(b.group(1)) if b else 0)
33
+
34
+
35
+ class AWSProvider(Provider):
36
+ name = "aws"
37
+
38
+ def plan(self, action: Action, policy: Policy) -> list[str]:
39
+ t = action.target
40
+ if t["kind"] == "ebs":
41
+ v = json.loads(_aws(t, "ec2", "describe-volumes", "--volume-ids", t["volume_id"], "--output", "json"))["Volumes"][0]
42
+ return [f"EBS {t['volume_id']}: {v['Size']} GiB {v['VolumeType']} in {v['AvailabilityZone']} (an EBS snapshot is taken first)"]
43
+ if t["kind"] == "rds":
44
+ d = json.loads(_aws(t, "rds", "describe-db-instances", "--db-instance-identifier", t["instance"], "--output", "json"))["DBInstances"][0]
45
+ return [f"RDS {t['instance']}: {d['Engine']} {d['DBInstanceClass']}, {d['AllocatedStorage']} GiB "
46
+ "(a manual DB snapshot is taken first; this can take several minutes)"]
47
+ n, size = _s3_size(t)
48
+ if size > policy.max_file_snapshot_bytes:
49
+ raise SnapshotUnavailable(f"{human_size(size)} in {t['uri']} is over the {human_size(policy.max_file_snapshot_bytes)} file snapshot limit")
50
+ return [f"{t['uri']}: {n:,} objects, {human_size(size)} (downloaded locally first)"]
51
+
52
+ def take(self, action: Action, dest: Path, policy: Policy) -> tuple[str, dict[str, Any]]:
53
+ t, sid = action.target, dest.name
54
+ if t["kind"] == "ebs":
55
+ v = json.loads(_aws(t, "ec2", "describe-volumes", "--volume-ids", t["volume_id"], "--output", "json"))["Volumes"][0]
56
+ snap = json.loads(_aws(t, "ec2", "create-snapshot", "--volume-id", t["volume_id"], "--description",
57
+ f"secondkey {sid} before delete-volume", "--output", "json"))
58
+ return f"EBS snapshot {snap['SnapshotId']} of {t['volume_id']}", {
59
+ **t, "snapshot_id": snap["SnapshotId"], "az": v["AvailabilityZone"], "volume_type": v["VolumeType"], "size": v["Size"]}
60
+ if t["kind"] == "rds":
61
+ ident = f"secondkey-{sid.replace('_', '-')}"
62
+ _aws(t, "rds", "create-db-snapshot", "--db-instance-identifier", t["instance"], "--db-snapshot-identifier", ident,
63
+ "--output", "json")
64
+ _aws(t, "rds", "wait", "db-snapshot-available", "--db-snapshot-identifier", ident, timeout=840)
65
+ return f"RDS snapshot {ident} of {t['instance']}", {**t, "db_snapshot": ident}
66
+ n, size = _s3_size(t)
67
+ if size > policy.max_file_snapshot_bytes:
68
+ raise SnapshotUnavailable("S3 prefix is over the file snapshot limit")
69
+ local = dest / "s3"
70
+ local.mkdir()
71
+ if t.get("recursive"):
72
+ _aws(t, "s3", "sync", t["uri"], str(local), "--only-show-errors", timeout=3600)
73
+ else:
74
+ _aws(t, "s3", "cp", t["uri"], str(local / Path(t["uri"]).name), "--only-show-errors", timeout=3600)
75
+ return f"{t['uri']} ({n:,} objects, {human_size(size)})", {**t, "objects": n, "bytes": size}
76
+
77
+ def describe_restore(self, snap: Snapshot, mode: str | None = None) -> list[str]:
78
+ m = snap.meta
79
+ if m["kind"] == "ebs":
80
+ return [f"create a new {m['size']} GiB {m['volume_type']} volume from {m['snapshot_id']} in {m['az']}",
81
+ "it gets a new volume id; attach it to the instance yourself"]
82
+ if m["kind"] == "rds":
83
+ return [f"restore DB instance {m['instance']} from snapshot {m['db_snapshot']} (takes several minutes)",
84
+ "instance class and networking use defaults unless you change them afterwards"]
85
+ return ([f"recreate bucket {m['uri'].split('/')[2]}"] if m.get("bucket_delete") else []) + \
86
+ [f"upload {m['objects']:,} saved objects back to {m['uri']}"]
87
+
88
+ def restore(self, snap: Snapshot, mode: str | None = None, force: bool = False) -> list[str]:
89
+ m = snap.meta
90
+ try:
91
+ if m["kind"] == "ebs":
92
+ v = json.loads(_aws(m, "ec2", "create-volume", "--snapshot-id", m["snapshot_id"], "--availability-zone", m["az"],
93
+ "--volume-type", m["volume_type"], "--output", "json"))
94
+ return [f"new volume {v['VolumeId']} created from {m['snapshot_id']} in {m['az']}; attach it to the instance"]
95
+ if m["kind"] == "rds":
96
+ _aws(m, "rds", "restore-db-instance-from-db-snapshot", "--db-instance-identifier", m["instance"],
97
+ "--db-snapshot-identifier", m["db_snapshot"], "--output", "json")
98
+ return [f"RDS instance {m['instance']} is being restored from {m['db_snapshot']} (check the console for status)"]
99
+ local = Path(snap.path) / "s3"
100
+ if m.get("bucket_delete"):
101
+ bucket = "s3://" + m["uri"].split("/")[2]
102
+ run(["aws", "s3", "mb", bucket, *(["--region", m["region"]] if m.get("region") else [])], check=False)
103
+ if m.get("recursive"):
104
+ _aws(m, "s3", "sync", str(local), m["uri"], "--only-show-errors", timeout=3600)
105
+ else:
106
+ _aws(m, "s3", "cp", str(next(local.iterdir())), m["uri"], "--only-show-errors", timeout=3600)
107
+ return [f"{m['objects']:,} objects uploaded back to {m['uri']}"]
108
+ except SnapshotUnavailable as e:
109
+ raise RestoreError(str(e)) from e
@@ -0,0 +1,48 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+ from typing import Any
5
+
6
+ from ..classify import Action
7
+ from ..policy import Policy
8
+ from ..store import Snapshot
9
+
10
+
11
+ class SnapshotUnavailable(RuntimeError):
12
+ """The action can't be protected by a snapshot (reason in message)."""
13
+
14
+
15
+ class NothingToProtect(SnapshotUnavailable):
16
+ """Nothing exists that the action could destroy (e.g. DROP TABLE IF EXISTS on a missing table)."""
17
+
18
+
19
+ class RestoreError(RuntimeError):
20
+ pass
21
+
22
+
23
+ class Provider:
24
+ name = "base"
25
+ #: whether `secondkey undo` can put things back automatically
26
+ restorable = True
27
+
28
+ def plan(self, action: Action, policy: Policy) -> list[str]:
29
+ """Check a snapshot is possible and describe the blast radius.
30
+
31
+ Returns human-readable impact lines. Raises SnapshotUnavailable.
32
+ """
33
+ return []
34
+
35
+ def take(self, action: Action, dest: Path, policy: Policy) -> tuple[str, dict[str, Any]]:
36
+ """Write the restore point into ``dest``. Returns (label, meta)."""
37
+ raise NotImplementedError
38
+
39
+ def describe_restore(self, snap: Snapshot, mode: str | None = None) -> list[str]:
40
+ return [f"restore {snap.label}"]
41
+
42
+ def restore(self, snap: Snapshot, mode: str | None = None, force: bool = False) -> list[str]:
43
+ """Put things back. Returns lines describing what was done."""
44
+ raise NotImplementedError
45
+
46
+ def cleanup(self, snap: Snapshot) -> None:
47
+ """Release anything held outside the snapshot folder (e.g. git refs) when pruning."""
48
+ return None
@@ -0,0 +1,70 @@
1
+ """Docker volume snapshots: tar the volume contents through a throwaway container."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ from ..classify import Action
9
+ from ..policy import Policy
10
+ from ..store import Snapshot
11
+ from ..util import CommandError, run
12
+ from .base import NothingToProtect, Provider, RestoreError, SnapshotUnavailable
13
+
14
+
15
+ def _image(policy: Policy | None) -> str:
16
+ return str((policy.snapshots.get("docker_image") if policy else None) or "alpine:3")
17
+
18
+
19
+ def _volumes(action: Action) -> list[str]:
20
+ t = action.target
21
+ if t.get("dangling"):
22
+ try:
23
+ return run(["docker", "volume", "ls", "-q", "-f", "dangling=true"], timeout=60).stdout.split()
24
+ except CommandError as e:
25
+ raise SnapshotUnavailable(f"docker volume ls failed: {e.stderr.strip()[:200]}") from e
26
+ return list(t.get("volumes") or [])
27
+
28
+
29
+ def _exists(vol: str) -> bool:
30
+ return run(["docker", "volume", "inspect", vol], check=False, timeout=30).returncode == 0
31
+
32
+
33
+ class DockerProvider(Provider):
34
+ name = "docker"
35
+
36
+ def plan(self, action: Action, policy: Policy) -> list[str]:
37
+ vols = [v for v in _volumes(action) if _exists(v)]
38
+ if not vols:
39
+ raise NothingToProtect("no matching volumes")
40
+ return [f"{len(vols)} volume{'s' if len(vols) != 1 else ''} will be archived: " + ", ".join(vols[:6])]
41
+
42
+ def take(self, action: Action, dest: Path, policy: Policy) -> tuple[str, dict[str, Any]]:
43
+ vols = [v for v in _volumes(action) if _exists(v)]
44
+ if not vols:
45
+ raise NothingToProtect("no matching volumes")
46
+ image = _image(policy)
47
+ for v in vols:
48
+ try:
49
+ run(["docker", "run", "--rm", "-v", f"{v}:/from:ro", "-v", f"{dest}:/to", image,
50
+ "tar", "czf", f"/to/{v}.tgz", "-C", "/from", "."], timeout=3600)
51
+ except CommandError as e:
52
+ raise SnapshotUnavailable(f"couldn't archive volume {v}: {e.stderr.strip()[:200]}") from e
53
+ return f"docker volumes {', '.join(vols[:4])}{' ...' if len(vols) > 4 else ''}", {"volumes": vols, "image": image}
54
+
55
+ def describe_restore(self, snap: Snapshot, mode: str | None = None) -> list[str]:
56
+ return [f"recreate volume {v} and unpack its saved contents" for v in snap.meta["volumes"]]
57
+
58
+ def restore(self, snap: Snapshot, mode: str | None = None, force: bool = False) -> list[str]:
59
+ out = []
60
+ for v in snap.meta["volumes"]:
61
+ if _exists(v) and not force:
62
+ raise RestoreError(f"volume {v} exists again; use --force to unpack over it")
63
+ try:
64
+ run(["docker", "volume", "create", v], timeout=60)
65
+ run(["docker", "run", "--rm", "-v", f"{v}:/to", "-v", f"{snap.path}:/from:ro", snap.meta["image"],
66
+ "tar", "xzf", f"/from/{v}.tgz", "-C", "/to"], timeout=3600)
67
+ except CommandError as e:
68
+ raise RestoreError(f"couldn't restore volume {v}: {e.stderr.strip()[:300]}") from e
69
+ out.append(f"volume {v} restored")
70
+ return out