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/__init__.py +3 -0
- secondkey/__main__.py +3 -0
- secondkey/audit.py +98 -0
- secondkey/classify.py +616 -0
- secondkey/cli.py +651 -0
- secondkey/default_policy.yaml +85 -0
- secondkey/gate.py +192 -0
- secondkey/hooks/__init__.py +0 -0
- secondkey/hooks/claude_code.py +67 -0
- secondkey/hooks/cursor.py +77 -0
- secondkey/notify.py +36 -0
- secondkey/policy.py +165 -0
- secondkey/proxy.py +244 -0
- secondkey/snapshots/__init__.py +155 -0
- secondkey/snapshots/aws.py +109 -0
- secondkey/snapshots/base.py +48 -0
- secondkey/snapshots/docker.py +70 -0
- secondkey/snapshots/files.py +108 -0
- secondkey/snapshots/git.py +216 -0
- secondkey/snapshots/k8s.py +97 -0
- secondkey/snapshots/mysql.py +104 -0
- secondkey/snapshots/postgres.py +388 -0
- secondkey/snapshots/terraform.py +74 -0
- secondkey/sql.py +142 -0
- secondkey/store.py +211 -0
- secondkey/util.py +108 -0
- secondkey-0.2.0.dist-info/METADATA +208 -0
- secondkey-0.2.0.dist-info/RECORD +32 -0
- secondkey-0.2.0.dist-info/WHEEL +5 -0
- secondkey-0.2.0.dist-info/entry_points.txt +2 -0
- secondkey-0.2.0.dist-info/licenses/LICENSE +202 -0
- secondkey-0.2.0.dist-info/top_level.txt +1 -0
secondkey/store.py
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
"""SQLite-backed state: approval requests and snapshots."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import sqlite3
|
|
7
|
+
from contextlib import contextmanager
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from typing import Any, Iterator
|
|
10
|
+
|
|
11
|
+
from .util import home, new_id, now
|
|
12
|
+
|
|
13
|
+
SCHEMA = """
|
|
14
|
+
CREATE TABLE IF NOT EXISTS requests (
|
|
15
|
+
id TEXT PRIMARY KEY,
|
|
16
|
+
created REAL NOT NULL,
|
|
17
|
+
updated REAL NOT NULL,
|
|
18
|
+
status TEXT NOT NULL, -- pending | approved | denied | executed | expired | failed
|
|
19
|
+
source TEXT NOT NULL, -- claude-code | exec | ...
|
|
20
|
+
cwd TEXT NOT NULL,
|
|
21
|
+
tool TEXT NOT NULL,
|
|
22
|
+
command TEXT NOT NULL,
|
|
23
|
+
fingerprint TEXT NOT NULL,
|
|
24
|
+
actions TEXT NOT NULL, -- JSON list of actions that need protecting
|
|
25
|
+
reason TEXT,
|
|
26
|
+
impact TEXT, -- JSON list of human-readable impact lines
|
|
27
|
+
decided_by TEXT,
|
|
28
|
+
decided_at REAL,
|
|
29
|
+
expires REAL,
|
|
30
|
+
skip_snapshot INTEGER DEFAULT 0,
|
|
31
|
+
snapshot_ids TEXT DEFAULT '[]'
|
|
32
|
+
);
|
|
33
|
+
CREATE INDEX IF NOT EXISTS requests_fp ON requests(fingerprint, status);
|
|
34
|
+
CREATE TABLE IF NOT EXISTS snapshots (
|
|
35
|
+
id TEXT PRIMARY KEY,
|
|
36
|
+
created REAL NOT NULL,
|
|
37
|
+
request_id TEXT,
|
|
38
|
+
provider TEXT NOT NULL,
|
|
39
|
+
label TEXT NOT NULL,
|
|
40
|
+
path TEXT NOT NULL,
|
|
41
|
+
meta TEXT NOT NULL,
|
|
42
|
+
status TEXT NOT NULL DEFAULT 'ok', -- ok | restored | failed
|
|
43
|
+
restored_at REAL,
|
|
44
|
+
restored_by TEXT
|
|
45
|
+
);
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass
|
|
50
|
+
class Request:
|
|
51
|
+
id: str
|
|
52
|
+
created: float
|
|
53
|
+
updated: float
|
|
54
|
+
status: str
|
|
55
|
+
source: str
|
|
56
|
+
cwd: str
|
|
57
|
+
tool: str
|
|
58
|
+
command: str
|
|
59
|
+
fingerprint: str
|
|
60
|
+
actions: list[dict[str, Any]]
|
|
61
|
+
reason: str | None = None
|
|
62
|
+
impact: list[str] = field(default_factory=list)
|
|
63
|
+
decided_by: str | None = None
|
|
64
|
+
decided_at: float | None = None
|
|
65
|
+
expires: float | None = None
|
|
66
|
+
skip_snapshot: bool = False
|
|
67
|
+
snapshot_ids: list[str] = field(default_factory=list)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@dataclass
|
|
71
|
+
class Snapshot:
|
|
72
|
+
id: str
|
|
73
|
+
created: float
|
|
74
|
+
request_id: str | None
|
|
75
|
+
provider: str
|
|
76
|
+
label: str
|
|
77
|
+
path: str
|
|
78
|
+
meta: dict[str, Any]
|
|
79
|
+
status: str = "ok"
|
|
80
|
+
restored_at: float | None = None
|
|
81
|
+
restored_by: str | None = None
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class Store:
|
|
85
|
+
def __init__(self, path: str | None = None):
|
|
86
|
+
self.path = path or str(home() / "state.db")
|
|
87
|
+
self.db = sqlite3.connect(self.path, timeout=30, isolation_level=None)
|
|
88
|
+
self.db.row_factory = sqlite3.Row
|
|
89
|
+
self.db.execute("PRAGMA journal_mode=WAL")
|
|
90
|
+
self.db.executescript(SCHEMA)
|
|
91
|
+
|
|
92
|
+
@contextmanager
|
|
93
|
+
def tx(self) -> Iterator[sqlite3.Connection]:
|
|
94
|
+
self.db.execute("BEGIN IMMEDIATE")
|
|
95
|
+
try:
|
|
96
|
+
yield self.db
|
|
97
|
+
self.db.execute("COMMIT")
|
|
98
|
+
except BaseException:
|
|
99
|
+
self.db.execute("ROLLBACK")
|
|
100
|
+
raise
|
|
101
|
+
|
|
102
|
+
# ----------------------------------------------------------- requests
|
|
103
|
+
@staticmethod
|
|
104
|
+
def _req(row: sqlite3.Row) -> Request:
|
|
105
|
+
d = dict(row)
|
|
106
|
+
d["actions"] = json.loads(d["actions"])
|
|
107
|
+
d["impact"] = json.loads(d["impact"] or "[]")
|
|
108
|
+
d["snapshot_ids"] = json.loads(d["snapshot_ids"] or "[]")
|
|
109
|
+
d["skip_snapshot"] = bool(d["skip_snapshot"])
|
|
110
|
+
return Request(**d)
|
|
111
|
+
|
|
112
|
+
def expire_old(self) -> None:
|
|
113
|
+
t = now()
|
|
114
|
+
self.db.execute("UPDATE requests SET status='expired', updated=? WHERE status='approved' AND expires IS NOT NULL AND expires < ?", (t, t))
|
|
115
|
+
self.db.execute("UPDATE requests SET status='expired', updated=? WHERE status='pending' AND created < ?", (t, t - 24 * 3600))
|
|
116
|
+
|
|
117
|
+
def create_request(self, *, source: str, cwd: str, tool: str, command: str, fingerprint: str,
|
|
118
|
+
actions: list[dict[str, Any]], reason: str, impact: list[str]) -> tuple[Request, bool]:
|
|
119
|
+
"""Create a pending request, or return the existing pending one for the same call."""
|
|
120
|
+
with self.tx() as db:
|
|
121
|
+
row = db.execute("SELECT * FROM requests WHERE fingerprint=? AND status='pending' ORDER BY created DESC LIMIT 1",
|
|
122
|
+
(fingerprint,)).fetchone()
|
|
123
|
+
if row:
|
|
124
|
+
return self._req(row), False
|
|
125
|
+
rid, t = new_id("req"), now()
|
|
126
|
+
db.execute("INSERT INTO requests (id, created, updated, status, source, cwd, tool, command, fingerprint, actions, reason, impact)"
|
|
127
|
+
" VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",
|
|
128
|
+
(rid, t, t, "pending", source, cwd, tool, command, fingerprint, json.dumps(actions), reason, json.dumps(impact)))
|
|
129
|
+
return self.get_request(rid), True
|
|
130
|
+
|
|
131
|
+
def get_request(self, rid: str) -> Request | None:
|
|
132
|
+
row = self.db.execute("SELECT * FROM requests WHERE id=?", (rid,)).fetchone()
|
|
133
|
+
return self._req(row) if row else None
|
|
134
|
+
|
|
135
|
+
def list_requests(self, status: str | None = None, limit: int = 50) -> list[Request]:
|
|
136
|
+
self.expire_old()
|
|
137
|
+
if status:
|
|
138
|
+
rows = self.db.execute("SELECT * FROM requests WHERE status=? ORDER BY created DESC LIMIT ?", (status, limit))
|
|
139
|
+
else:
|
|
140
|
+
rows = self.db.execute("SELECT * FROM requests ORDER BY created DESC LIMIT ?", (limit,))
|
|
141
|
+
return [self._req(r) for r in rows]
|
|
142
|
+
|
|
143
|
+
def decide(self, rid: str, approve: bool, by: str, ttl: float, skip_snapshot: bool = False) -> Request:
|
|
144
|
+
with self.tx() as db:
|
|
145
|
+
row = db.execute("SELECT * FROM requests WHERE id=?", (rid,)).fetchone()
|
|
146
|
+
if not row:
|
|
147
|
+
raise KeyError(rid)
|
|
148
|
+
if row["status"] != "pending":
|
|
149
|
+
raise ValueError(f"{rid} is already {row['status']}")
|
|
150
|
+
t = now()
|
|
151
|
+
db.execute("UPDATE requests SET status=?, decided_by=?, decided_at=?, updated=?, expires=?, skip_snapshot=? WHERE id=?",
|
|
152
|
+
("approved" if approve else "denied", by, t, t, t + ttl if approve else None, int(skip_snapshot), rid))
|
|
153
|
+
return self.get_request(rid)
|
|
154
|
+
|
|
155
|
+
def recent_denial(self, fingerprint: str, within: float) -> Request | None:
|
|
156
|
+
row = self.db.execute("SELECT * FROM requests WHERE fingerprint=? AND status='denied' AND decided_at >= ?"
|
|
157
|
+
" ORDER BY decided_at DESC LIMIT 1", (fingerprint, now() - within)).fetchone()
|
|
158
|
+
return self._req(row) if row else None
|
|
159
|
+
|
|
160
|
+
def claim_grant(self, fingerprint: str) -> Request | None:
|
|
161
|
+
"""Atomically take a valid approval for this exact call, if one exists."""
|
|
162
|
+
self.expire_old()
|
|
163
|
+
with self.tx() as db:
|
|
164
|
+
row = db.execute("SELECT * FROM requests WHERE fingerprint=? AND status='approved' AND (expires IS NULL OR expires >= ?)"
|
|
165
|
+
" ORDER BY decided_at DESC LIMIT 1", (fingerprint, now())).fetchone()
|
|
166
|
+
if not row:
|
|
167
|
+
return None
|
|
168
|
+
db.execute("UPDATE requests SET status='executing', updated=? WHERE id=?", (now(), row["id"]))
|
|
169
|
+
return self.get_request(row["id"])
|
|
170
|
+
|
|
171
|
+
def finish(self, rid: str, status: str, snapshot_ids: list[str] | None = None, reason: str | None = None) -> None:
|
|
172
|
+
fields, vals = ["status=?", "updated=?"], [status, now()]
|
|
173
|
+
if snapshot_ids is not None:
|
|
174
|
+
fields.append("snapshot_ids=?")
|
|
175
|
+
vals.append(json.dumps(snapshot_ids))
|
|
176
|
+
if reason is not None:
|
|
177
|
+
fields.append("reason=?")
|
|
178
|
+
vals.append(reason)
|
|
179
|
+
self.db.execute(f"UPDATE requests SET {', '.join(fields)} WHERE id=?", (*vals, rid))
|
|
180
|
+
|
|
181
|
+
# ----------------------------------------------------------- snapshots
|
|
182
|
+
def add_snapshot(self, s: Snapshot) -> None:
|
|
183
|
+
self.db.execute("INSERT INTO snapshots (id, created, request_id, provider, label, path, meta, status) VALUES (?,?,?,?,?,?,?,?)",
|
|
184
|
+
(s.id, s.created, s.request_id, s.provider, s.label, s.path, json.dumps(s.meta), s.status))
|
|
185
|
+
|
|
186
|
+
@staticmethod
|
|
187
|
+
def _snap(row: sqlite3.Row) -> Snapshot:
|
|
188
|
+
d = dict(row)
|
|
189
|
+
d["meta"] = json.loads(d["meta"])
|
|
190
|
+
return Snapshot(**d)
|
|
191
|
+
|
|
192
|
+
def get_snapshot(self, sid: str) -> Snapshot | None:
|
|
193
|
+
row = self.db.execute("SELECT * FROM snapshots WHERE id=?", (sid,)).fetchone()
|
|
194
|
+
return self._snap(row) if row else None
|
|
195
|
+
|
|
196
|
+
def snapshots_for(self, rid: str) -> list[Snapshot]:
|
|
197
|
+
return [self._snap(r) for r in self.db.execute("SELECT * FROM snapshots WHERE request_id=? ORDER BY created", (rid,))]
|
|
198
|
+
|
|
199
|
+
def list_snapshots(self, limit: int = 50) -> list[Snapshot]:
|
|
200
|
+
return [self._snap(r) for r in self.db.execute("SELECT * FROM snapshots ORDER BY created DESC LIMIT ?", (limit,))]
|
|
201
|
+
|
|
202
|
+
def set_snapshot_status(self, sid: str, status: str) -> None:
|
|
203
|
+
self.db.execute("UPDATE snapshots SET status=? WHERE id=?", (status, sid))
|
|
204
|
+
|
|
205
|
+
def live_snapshots(self) -> list[Snapshot]:
|
|
206
|
+
"""Snapshots whose files still exist on disk, oldest first."""
|
|
207
|
+
return [self._snap(r) for r in self.db.execute(
|
|
208
|
+
"SELECT * FROM snapshots WHERE status IN ('ok', 'restored', 'unused') ORDER BY created")]
|
|
209
|
+
|
|
210
|
+
def mark_restored(self, sid: str, by: str) -> None:
|
|
211
|
+
self.db.execute("UPDATE snapshots SET status='restored', restored_at=?, restored_by=? WHERE id=?", (now(), by, sid))
|
secondkey/util.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""Small shared helpers: state directory, ids, subprocess wrapper."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import getpass
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import secrets
|
|
9
|
+
import shutil
|
|
10
|
+
import subprocess
|
|
11
|
+
import time
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Mapping, Sequence
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def home() -> Path:
|
|
17
|
+
"""Directory holding SecondKey state (database, audit log, snapshots)."""
|
|
18
|
+
p = Path(os.environ.get("SECONDKEY_HOME") or Path.home() / ".secondkey")
|
|
19
|
+
if not p.exists():
|
|
20
|
+
p.mkdir(parents=True, exist_ok=True)
|
|
21
|
+
try:
|
|
22
|
+
if os.name != "nt" and p.stat().st_mode & 0o077:
|
|
23
|
+
p.chmod(0o700) # snapshots hold real data: owner only
|
|
24
|
+
except OSError:
|
|
25
|
+
pass
|
|
26
|
+
return p
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def snapshot_root() -> Path:
|
|
30
|
+
p = home() / "snapshots"
|
|
31
|
+
p.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
32
|
+
return p
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def new_id(prefix: str) -> str:
|
|
36
|
+
return f"{prefix}_{secrets.token_hex(3)}"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def now() -> float:
|
|
40
|
+
return time.time()
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def whoami() -> str:
|
|
44
|
+
for var in ("SECONDKEY_USER", "USER", "USERNAME"):
|
|
45
|
+
if os.environ.get(var):
|
|
46
|
+
return os.environ[var]
|
|
47
|
+
try:
|
|
48
|
+
return getpass.getuser()
|
|
49
|
+
except Exception: # pragma: no cover - platform specific
|
|
50
|
+
return "unknown"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
TOOL_HINTS = {
|
|
54
|
+
"pg_dump": "install the PostgreSQL client tools (same major version as your server or newer), e.g. `brew install libpq` or `apt install postgresql-client-16`",
|
|
55
|
+
"pg_restore": "install the PostgreSQL client tools (they include pg_restore)",
|
|
56
|
+
"psql": "install the PostgreSQL client tools (they include psql)",
|
|
57
|
+
"mysqldump": "install the MySQL client tools, e.g. `brew install mysql-client` or `apt install mysql-client`",
|
|
58
|
+
"mysql": "install the MySQL client tools",
|
|
59
|
+
"kubectl": "install kubectl and make sure your kubeconfig points at the cluster",
|
|
60
|
+
"terraform": "install Terraform (or use `tofu`)",
|
|
61
|
+
"aws": "install the AWS CLI v2 and configure credentials",
|
|
62
|
+
"docker": "install Docker and make sure the daemon is running",
|
|
63
|
+
"neonctl": "install the Neon CLI: `npm i -g neonctl` and run `neonctl auth`",
|
|
64
|
+
"git": "install git",
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class CommandError(RuntimeError):
|
|
69
|
+
def __init__(self, argv: Sequence[str], code: int, stderr: str):
|
|
70
|
+
self.argv, self.code, self.stderr = list(argv), code, stderr
|
|
71
|
+
super().__init__(f"{argv[0]} exited {code}: {stderr.strip()[:400]}")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def run(argv: Sequence[str], cwd: str | None = None, env: Mapping[str, str] | None = None,
|
|
75
|
+
input: str | None = None, timeout: float = 600, check: bool = True) -> subprocess.CompletedProcess:
|
|
76
|
+
"""Run a command without a shell. Raises CommandError on failure when check=True."""
|
|
77
|
+
if shutil.which(argv[0]) is None and not os.path.isabs(argv[0]):
|
|
78
|
+
hint = TOOL_HINTS.get(os.path.basename(argv[0]))
|
|
79
|
+
raise CommandError(argv, 127, f"{argv[0]} not found on PATH" + (f"; {hint}" if hint else ""))
|
|
80
|
+
proc = subprocess.run(list(argv), cwd=cwd, env=dict(env) if env is not None else None, input=input,
|
|
81
|
+
capture_output=True, text=True, timeout=timeout)
|
|
82
|
+
if check and proc.returncode != 0:
|
|
83
|
+
raise CommandError(argv, proc.returncode, proc.stderr or proc.stdout)
|
|
84
|
+
return proc
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def human_size(n: int) -> str:
|
|
88
|
+
size = float(n)
|
|
89
|
+
for unit in ("B", "KB", "MB", "GB"):
|
|
90
|
+
if size < 1024 or unit == "GB":
|
|
91
|
+
return f"{size:.0f} {unit}" if unit == "B" else f"{size:.1f} {unit}"
|
|
92
|
+
size /= 1024
|
|
93
|
+
return f"{n} B" # pragma: no cover
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
_REDACT = [
|
|
97
|
+
(re.compile(r"(\b[a-z][a-z0-9+.-]*://[^:/@\s]+:)([^@\s]+)(@)", re.I), r"\1***\3"), # scheme://user:pass@
|
|
98
|
+
(re.compile(r"(\s-p)(?!\s)(\S+)"), r"\1***"), # mysql -pSECRET
|
|
99
|
+
(re.compile(r"(--password[= ])(\S+)", re.I), r"\1***"),
|
|
100
|
+
(re.compile(r"\b([A-Z0-9_]*(?:PASSWORD|PASSWD|SECRET|TOKEN|API_KEY)[A-Z0-9_]*=)(\S+)"), r"\1***"),
|
|
101
|
+
]
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def redact(text: str) -> str:
|
|
105
|
+
"""Mask credentials before a command is stored, logged or sent to Slack."""
|
|
106
|
+
for rx, rep in _REDACT:
|
|
107
|
+
text = rx.sub(rep, text)
|
|
108
|
+
return text
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: secondkey
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: The second key for every AI agent action: approve, snapshot and undo destructive commands.
|
|
5
|
+
Author: Abhishek
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/Abhishek-dev18/SecondKey
|
|
8
|
+
Keywords: ai-agents,claude-code,mcp,safety,change-control,undo,devops
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Classifier: Topic :: Security
|
|
13
|
+
Classifier: Topic :: System :: Systems Administration
|
|
14
|
+
Requires-Python: >=3.9
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
Requires-Dist: PyYAML>=6.0
|
|
18
|
+
Provides-Extra: dev
|
|
19
|
+
Requires-Dist: pytest>=7; extra == "dev"
|
|
20
|
+
Requires-Dist: pg8000>=1.30; extra == "dev"
|
|
21
|
+
Dynamic: license-file
|
|
22
|
+
|
|
23
|
+
<p align="center">
|
|
24
|
+
<img src="assets/logo-wordmark.svg" alt="SecondKey" width="260">
|
|
25
|
+
</p>
|
|
26
|
+
|
|
27
|
+
<p align="center"><b>Agents hold the first key. You hold the second.</b></p>
|
|
28
|
+
|
|
29
|
+
SecondKey is a change-control gate for AI agents. It sits between Claude Code (or any agent that runs shell commands) and your infrastructure:
|
|
30
|
+
|
|
31
|
+
- **Safe commands pass straight through.** Reads, tests and plans run with no delay.
|
|
32
|
+
- **Destructive commands stop at the gate.** `DROP TABLE`, `DELETE`, `rm -rf`, `git push --force`, `terraform destroy`, `kubectl delete` and more are held until a human approves.
|
|
33
|
+
- **A restore point is taken right before an approved command runs.** If the approval was a mistake, `secondkey undo` puts things back.
|
|
34
|
+
- **Secrets are never read.** `.env`, cloud credentials, SSH keys and `curl | sh` are denied by policy.
|
|
35
|
+
- **Everything is logged** in a hash-chained audit log, so tampering is detectable.
|
|
36
|
+
|
|
37
|
+
> Status: v0.2, early. Works with Claude Code and Cursor (hooks), any Postgres client via the proxy, and anything else via `secondkey exec`.
|
|
38
|
+
|
|
39
|
+
## Install
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
pipx install git+https://github.com/Abhishek-dev18/SecondKey
|
|
43
|
+
cd your-project
|
|
44
|
+
secondkey init # writes .secondkey/policy.yaml and adds the Claude Code hook
|
|
45
|
+
secondkey doctor # checks hooks, tools and state
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
`init --agent cursor` adds the Cursor hooks (repeat `--agent` for both). `init --scope user` installs for every project instead. Try it end to end with [docs/try-it-with-claude-code.md](docs/try-it-with-claude-code.md). Requires Python 3.9+. For Postgres snapshots, `psql`, `pg_dump` and `pg_restore` must be on your PATH (same major version as your server or newer).
|
|
49
|
+
|
|
50
|
+
## What it looks like
|
|
51
|
+
|
|
52
|
+
The agent tries something destructive:
|
|
53
|
+
|
|
54
|
+
```
|
|
55
|
+
psql $PROD_DB -c "DROP TABLE users CASCADE;"
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Claude Code is told:
|
|
59
|
+
|
|
60
|
+
```
|
|
61
|
+
SecondKey held this command for human approval (request req_880c0e).
|
|
62
|
+
Why: sql.drop → ask. Impact: users: 5,000 rows.
|
|
63
|
+
A restore point will be taken right before it runs, so it can be undone.
|
|
64
|
+
Ask the user to review it and run `secondkey approve req_880c0e` ...
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
You look and decide:
|
|
68
|
+
|
|
69
|
+
```console
|
|
70
|
+
$ secondkey pending
|
|
71
|
+
req_880c0e pending 12s ago claude-code /home/riya/shop
|
|
72
|
+
psql $PROD_DB -c "DROP TABLE users CASCADE;"
|
|
73
|
+
why: sql.drop → ask
|
|
74
|
+
impact: users: 5,000 rows
|
|
75
|
+
|
|
76
|
+
$ secondkey approve req_880c0e
|
|
77
|
+
approved req_880c0e by riya. The agent can now retry the exact same command (valid 15 min).
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
The agent retries, SecondKey dumps `users` (plus the foreign keys on other tables that `CASCADE` will remove), and the command runs. If that was a mistake:
|
|
81
|
+
|
|
82
|
+
```console
|
|
83
|
+
$ secondkey undo req_880c0e
|
|
84
|
+
snap_453a77 postgres users (5,000 rows)
|
|
85
|
+
will: users: recreate the table with 5,000 rows, indexes and constraints
|
|
86
|
+
will: re-add foreign key orders_user_id_fkey on orders if it's missing
|
|
87
|
+
will: re-add foreign key carts_user_id_fkey on carts if it's missing
|
|
88
|
+
Restore? [y/N] y
|
|
89
|
+
✓ tables recreated from the snapshot: users
|
|
90
|
+
✓ foreign key orders_user_id_fkey on orders re-added
|
|
91
|
+
✓ foreign key carts_user_id_fkey on carts re-added
|
|
92
|
+
✓ verified users: 5,000 rows
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
## Commands
|
|
96
|
+
|
|
97
|
+
| Command | What it does |
|
|
98
|
+
|---|---|
|
|
99
|
+
| `secondkey init` | Write a policy and install the Claude Code `PreToolUse` hook (merges with your existing settings) |
|
|
100
|
+
| `secondkey check "<cmd>"` | Show how a command is classified and what the policy decides, with its impact. Runs nothing |
|
|
101
|
+
| `secondkey pending` | List held commands (`--all` for history) |
|
|
102
|
+
| `secondkey approve <req>` | Turn the second key. Valid once, for the exact same command, for 15 minutes |
|
|
103
|
+
| `secondkey deny <req>` | Reject. The agent is told not to retry |
|
|
104
|
+
| `secondkey snapshots` | List restore points |
|
|
105
|
+
| `secondkey undo <snap or req>` | Restore. Shows what it will do and asks first (`--yes`, `--dry-run`, `--mode`) |
|
|
106
|
+
| `secondkey log` | Audit log. `--verify` checks the hash chain |
|
|
107
|
+
| `secondkey policy` | Show the effective policy |
|
|
108
|
+
| `secondkey exec -- <cmd>` | Run a command through the gate, for agents without hook support. Waits up to 5 min for approval |
|
|
109
|
+
| `secondkey proxy --upstream host:5432` | Postgres proxy: gates every query from scripts, ORMs and migrations, not just shell commands |
|
|
110
|
+
| `secondkey prune` | Delete old restore points (also runs automatically once a day; the newest is always kept) |
|
|
111
|
+
| `secondkey doctor` | Check hooks, tools, policy, audit chain and snapshot storage |
|
|
112
|
+
|
|
113
|
+
## How it works
|
|
114
|
+
|
|
115
|
+
```
|
|
116
|
+
agent proposes a command
|
|
117
|
+
→ classify shell/SQL/tool call → actions like sql.drop, git.force_push, secrets.read
|
|
118
|
+
→ policy first matching rule: allow / ask / deny (a && b gets the strictest)
|
|
119
|
+
→ deny blocked, agent told not to work around it
|
|
120
|
+
→ allow runs (some rules, like single-file rm, take a quiet snapshot first)
|
|
121
|
+
→ ask held as a request; Slack ping if configured
|
|
122
|
+
human approves → agent retries → snapshot → runs
|
|
123
|
+
→ audit every decision appended to a hash-chained log
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
SecondKey never widens what Claude Code allows on its own: for allowed commands it returns no decision, so Claude Code's normal permission rules still apply. If SecondKey itself errors, the hook answers `ask` (Claude Code) or `deny` (Cursor) rather than crashing, because a crashing hook would let the command run.
|
|
127
|
+
|
|
128
|
+
**The agent can't hold the second key.** A built-in guard, which no policy can turn off, denies an agent that tries to run `secondkey approve`/`deny`/`undo`/`prune`, touch `~/.secondkey/`, or change `.secondkey/policy.yaml`, `.claude/settings*.json` or `.cursor/hooks.json`. Commands are stored and logged with passwords and tokens masked, and the state directory is private to your user.
|
|
129
|
+
|
|
130
|
+
### What can be undone
|
|
131
|
+
|
|
132
|
+
| Target | Snapshot | Undo |
|
|
133
|
+
|---|---|---|
|
|
134
|
+
| **Postgres** `DROP`, `TRUNCATE`, `DELETE`, `UPDATE`, `ALTER` via `psql` | `pg_dump` of the affected tables, row counts, foreign keys on other tables that point at them | Dropped tables are recreated with indexes, constraints and sequences, and foreign keys are re-added. For tables that still exist, saved rows are put back by primary key and rows written since are kept (`--mode exact` removes them). Verified inside the transaction; if anything fails, nothing changes |
|
|
135
|
+
| **Files** `rm`, `rm -rf` | tar.gz of the paths | Put back; refuses to overwrite paths that exist again unless `--force` |
|
|
136
|
+
| **Git** force push, delete remote branch, `reset --hard`, `checkout -- .`, `clean`, `branch -D`, stash drop | Commits pinned under `refs/secondkey/…`, uncommitted changes saved with `git stash create`, untracked files archived | Force-push the old commit back, reset and re-apply changes, recreate branches, restore files. Your current changes are saved first |
|
|
137
|
+
| **Migrations** `prisma migrate reset`, `alembic downgrade`, `rails db:drop`, `manage.py flush` and more | Whole-database `pg_dump` when a Postgres `DATABASE_URL` is set | The whole database restored in one transaction |
|
|
138
|
+
| **Neon** (any of the above, `postgres_strategy: neon`) | Just the timestamp: no copy, works for any size | `neon branches restore <branch> ^self@<time>`; the current state is kept as a branch |
|
|
139
|
+
| **MySQL / MariaDB** `mysql -e "DROP/DELETE/…"` | `mysqldump` of the affected tables | Replayed, row counts verified |
|
|
140
|
+
| **AWS** `ec2 delete-volume`, `rds delete-db-instance`, `s3 rm/rb` | EBS snapshot, RDS manual snapshot, or S3 objects downloaded | New volume from the snapshot, instance restored, objects uploaded back |
|
|
141
|
+
| **Docker** `volume rm`, `volume prune`, `system prune --volumes` | Volume contents tarred through a throwaway container | Volume recreated and unpacked |
|
|
142
|
+
| **Kubernetes** `kubectl delete` | `kubectl get -o yaml`, cleaned of server fields | `kubectl apply`. Data in deleted volumes is not restored |
|
|
143
|
+
| **Terraform** `destroy`, `apply`, `state rm/mv` | `terraform state pull` and the config's git commit | State surgery: state pushed back. Destroy: explains how to recreate from the saved config. Cloud resources can't be un-destroyed, and SecondKey won't pretend otherwise |
|
|
144
|
+
|
|
145
|
+
**Cannot be undone, so they're denied or held without a snapshot:** emails, payments and webhooks; `DROP DATABASE`; cloud deletes (`aws … delete`, `terminate-instances`); `docker system prune`; anything that reads secrets.
|
|
146
|
+
|
|
147
|
+
Blast radius is shown before you approve: row counts per table, and for `DELETE`/`UPDATE … WHERE` how many rows match (estimated in a read-only transaction).
|
|
148
|
+
|
|
149
|
+
## Policy
|
|
150
|
+
|
|
151
|
+
`secondkey init` writes `.secondkey/policy.yaml`. Rules are checked top to bottom and the first match wins:
|
|
152
|
+
|
|
153
|
+
```yaml
|
|
154
|
+
rules:
|
|
155
|
+
- match: ["secrets.*", "shell.pipe_to_shell", "sql.drop_database"]
|
|
156
|
+
action: deny
|
|
157
|
+
- match: ["sql.drop", "sql.delete", "sql.truncate", "git.force_push", "tf.destroy", "k8s.delete"]
|
|
158
|
+
action: ask # snapshot: true is the default for ask
|
|
159
|
+
- match: ["fs.delete"] # rm of single files
|
|
160
|
+
action: allow
|
|
161
|
+
snapshot: true # run, but keep a restore point
|
|
162
|
+
default: allow
|
|
163
|
+
|
|
164
|
+
approval:
|
|
165
|
+
via: secondkey # or "agent": snapshot, then let Claude Code's own prompt ask you
|
|
166
|
+
wait_seconds: 0 # how long the hook waits for an approval before replying "held"
|
|
167
|
+
ttl_minutes: 15
|
|
168
|
+
require_snapshot: true
|
|
169
|
+
|
|
170
|
+
notify:
|
|
171
|
+
slack_webhook: "${SECONDKEY_SLACK_WEBHOOK}"
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
Run `secondkey check "<command>"` to see the category of any command. Policy lookup order: `$SECONDKEY_POLICY`, `.secondkey/policy.yaml` in the project (searching upward to the git root), `~/.secondkey/policy.yaml`, then the built-in default.
|
|
175
|
+
|
|
176
|
+
State (approvals, snapshots, audit log) lives in `~/.secondkey/` (override with `SECONDKEY_HOME`).
|
|
177
|
+
|
|
178
|
+
## Known limits (v0.2)
|
|
179
|
+
|
|
180
|
+
- Hooks see the commands an agent runs. For Postgres, run `secondkey proxy` so scripts and ORMs are gated too. Other databases and APIs called from agent-written code aren't covered, so give agents scoped credentials.
|
|
181
|
+
- An agent could still write a script that edits SecondKey's files directly; the guard covers tool calls and shell commands, not arbitrary code. Running agents as a separate OS user closes this.
|
|
182
|
+
- MCP tools are gated by name; their effects can't be snapshotted automatically.
|
|
183
|
+
- Approvals happen in the CLI, or Slack (notification only for now; buttons come with the hosted version).
|
|
184
|
+
- Snapshots are local. Dumps over `postgres_max_dump_mb` (2 GB) and file snapshots over 500 MB are refused and reported as unprotected; use the Neon strategy for big Postgres databases.
|
|
185
|
+
- Tested on Linux. macOS should work; Windows is untested.
|
|
186
|
+
|
|
187
|
+
More recipes: [docs/policy-cookbook.md](docs/policy-cookbook.md).
|
|
188
|
+
|
|
189
|
+
## Development
|
|
190
|
+
|
|
191
|
+
```bash
|
|
192
|
+
pip install -e ".[dev]"
|
|
193
|
+
pytest -q # unit + git + files + stubbed k8s/terraform/aws/docker/mysql
|
|
194
|
+
SECONDKEY_TEST_PG='postgresql://postgres:postgres@localhost:5432/postgres' pytest -q # + real Postgres and the proxy
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
Releases: push a tag like `v0.2.0` and `.github/workflows/release.yml` publishes to PyPI (needs a one-time trusted-publisher setup on pypi.org, described in the workflow file). Licensed under Apache-2.0.
|
|
198
|
+
|
|
199
|
+
## This repo
|
|
200
|
+
|
|
201
|
+
| Path | What it is |
|
|
202
|
+
|---|---|
|
|
203
|
+
| `src/secondkey/` | The CLI (`classify.py`, `policy.py`, `gate.py`, `snapshots/`, `hooks/`, `proxy.py`) |
|
|
204
|
+
| `docs/` | Policy cookbook and a 5-minute Claude Code walkthrough |
|
|
205
|
+
| `tests/` | Test suite |
|
|
206
|
+
| `index.html`, `assets/` | Landing page (live demo of the gate) and logo files |
|
|
207
|
+
|
|
208
|
+
The landing page is a single static file. Enable GitHub Pages for the `main` branch to publish it.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
secondkey/__init__.py,sha256=Hgbii8QVZCqgAjI2cn9f7KEOWudT7oX9sKVU0LDWx2s,82
|
|
2
|
+
secondkey/__main__.py,sha256=k1ocEWawweo1qCJWNFAAvyxz3tcY13dzvCenHszij30,48
|
|
3
|
+
secondkey/audit.py,sha256=3MZLGR_ZFuHuIaKPBI9oE9cy80xif1hcYXifV5sC1mE,2943
|
|
4
|
+
secondkey/classify.py,sha256=f7Kxvkd9_Eavb4ktBddxo9Uahuf2Un1KlMhgzM-rDYw,30767
|
|
5
|
+
secondkey/cli.py,sha256=DZodZqIV9z_XN-3e9oJ_nlR2f3FP7fls5Q11OzCKaV0,28094
|
|
6
|
+
secondkey/default_policy.yaml,sha256=dRD4EnAAh_J3C1FpamZhXSiJHUMgdZq7kAqvFBK60OM,3667
|
|
7
|
+
secondkey/gate.py,sha256=PE2-A7HDrapDFUCiE4Ug9w72B9-fxPD6yw0ISxRq1C8,9441
|
|
8
|
+
secondkey/notify.py,sha256=ALSSlm_dN-lk9f878b0nXfSrbWPrvU-r0Dgu24CZWFM,1396
|
|
9
|
+
secondkey/policy.py,sha256=dI_I9_KvPSN5CwhxVabKMdyv_YlIJvDeekIWPXLeZSw,5657
|
|
10
|
+
secondkey/proxy.py,sha256=sN36ER25eqtuUpkZdygZz4dHjd6p4b6D89zEHUSEmeo,10142
|
|
11
|
+
secondkey/sql.py,sha256=GvZVlsVoeed7qIvQS_nnoQbstyHttuHMXTQ7yTa9Iw0,5221
|
|
12
|
+
secondkey/store.py,sha256=_guYD5WSDh7XD8syGeT22kNcLrwyv4_P_C8BnJcVC5E,8976
|
|
13
|
+
secondkey/util.py,sha256=eYWDR_SdOwX8HKz0Sn7m-kURn6BMbtZBeRBMELby-2o,4045
|
|
14
|
+
secondkey/hooks/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
15
|
+
secondkey/hooks/claude_code.py,sha256=-jxVNX0vrRbhRWA8lCJvUUl6lHbfMbsWdDDoM2eVDMc,2588
|
|
16
|
+
secondkey/hooks/cursor.py,sha256=OJl66J0uCl871joH0Jfbx_DQYpHAbzO-aD25FlrCt6s,3302
|
|
17
|
+
secondkey/snapshots/__init__.py,sha256=4ZagXf47cNmuICbnFsDQDQ4cfpkxuHkWO7VIcx2qCes,6070
|
|
18
|
+
secondkey/snapshots/aws.py,sha256=lXnFafjla3SXYWnebxGohBGFfDlJXGZ_GwJmMj0TmqU,6329
|
|
19
|
+
secondkey/snapshots/base.py,sha256=YL7bU9fXRbsZQGTRkiOgiHBFo6zoqBaWeoxLiI-yAFQ,1549
|
|
20
|
+
secondkey/snapshots/docker.py,sha256=Sj2AYKDJ0hVb3vSecwHjbVDYihY-DEvG6JhrgCjpPsI,3107
|
|
21
|
+
secondkey/snapshots/files.py,sha256=7KhjIx_sSlsENp56SZTnwUJPAnU_SlzKr3ZRgFTpn4k,4571
|
|
22
|
+
secondkey/snapshots/git.py,sha256=oUQZy4Uf-rAuDeXrwHDU8yGXE4e34KMPp_getRN7rTg,10552
|
|
23
|
+
secondkey/snapshots/k8s.py,sha256=WpikUepv57C7gJ6qesQJtJ4wMpMaywHNbBfQdK3PI88,4230
|
|
24
|
+
secondkey/snapshots/mysql.py,sha256=BzekTzCHx1i04iIyCXD17UI4c6bMzIuBGEgH5rSw9fs,4773
|
|
25
|
+
secondkey/snapshots/postgres.py,sha256=wmrsPigyQx0rrPGba8ej-wdFULtYgWupweRuUNZ5gcI,20537
|
|
26
|
+
secondkey/snapshots/terraform.py,sha256=UtUHtfXgrbmK7GIk-HAAbsJrdixT2ecm50ww0rKP0u0,3589
|
|
27
|
+
secondkey-0.2.0.dist-info/licenses/LICENSE,sha256=WNHhf_5RCaeuKWyq_K39vmp9F28LxKsB4SpomwSZ2L0,11357
|
|
28
|
+
secondkey-0.2.0.dist-info/METADATA,sha256=Og41BoDT9Pwtu6qm0Ifw3W_V0XOOwjZ1HppLABwstKA,12196
|
|
29
|
+
secondkey-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
30
|
+
secondkey-0.2.0.dist-info/entry_points.txt,sha256=k2qTwSjpJNUZkTbg-b2FI_C_OPEwBSzvu88tJ49rDZI,49
|
|
31
|
+
secondkey-0.2.0.dist-info/top_level.txt,sha256=_FSFP3Jys3MCV472UVF5_25F-TP2DdLSGAc1FbkTFF4,10
|
|
32
|
+
secondkey-0.2.0.dist-info/RECORD,,
|