tortoise-graph 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.
- tortoise/__init__.py +45 -0
- tortoise/__main__.py +1865 -0
- tortoise/analyze.py +473 -0
- tortoise/api.py +303 -0
- tortoise/archived/search_legacy.py +31 -0
- tortoise/audit.py +236 -0
- tortoise/audit_events.py +284 -0
- tortoise/auth.py +107 -0
- tortoise/backup.py +155 -0
- tortoise/config.py +99 -0
- tortoise/connector_loader.py +74 -0
- tortoise/connectors/__init__.py +5 -0
- tortoise/connectors/github.py +432 -0
- tortoise/connectors/github_docs.py +146 -0
- tortoise/connectors/linear.py +199 -0
- tortoise/connectors/slack.py +222 -0
- tortoise/consistency.py +132 -0
- tortoise/crypto.py +52 -0
- tortoise/deployment.py +62 -0
- tortoise/domain_loader.py +142 -0
- tortoise/dream.py +153 -0
- tortoise/embedded_reaper.py +744 -0
- tortoise/embeddings.py +227 -0
- tortoise/ep.py +534 -0
- tortoise/exceptions.py +16 -0
- tortoise/extractor.py +945 -0
- tortoise/hosted_api.py +1982 -0
- tortoise/hosted_middleware.py +22 -0
- tortoise/idempotency.py +39 -0
- tortoise/ids.py +23 -0
- tortoise/indexer/github_indexer.py +129 -0
- tortoise/ingest.py +614 -0
- tortoise/log.py +29 -0
- tortoise/m0.py +50 -0
- tortoise/mcp_auth.py +337 -0
- tortoise/mcp_client.py +108 -0
- tortoise/mcp_server.py +1356 -0
- tortoise/memory_orchestrator.py +492 -0
- tortoise/memory_scope.py +15 -0
- tortoise/migrate_db.py +244 -0
- tortoise/migrate_kinds.py +141 -0
- tortoise/mining.py +338 -0
- tortoise/models.py +109 -0
- tortoise/monitoring.py +133 -0
- tortoise/navigation.py +216 -0
- tortoise/pack_registry.py +767 -0
- tortoise/pipeline_cli.py +197 -0
- tortoise/projection/__init__.py +913 -0
- tortoise/projection/edges.py +311 -0
- tortoise/projection/entities.py +521 -0
- tortoise/projection/grounding.py +95 -0
- tortoise/projection/propagation.py +114 -0
- tortoise/projection.py +37 -0
- tortoise/quadrature.py +90 -0
- tortoise/query_suggestions.py +194 -0
- tortoise/quota.py +163 -0
- tortoise/ranking.py +280 -0
- tortoise/render.py +108 -0
- tortoise/scripts/manifest.py +67 -0
- tortoise/sdk.py +4713 -0
- tortoise/search_engine.py +887 -0
- tortoise/security.py +268 -0
- tortoise/selfhost.py +157 -0
- tortoise/selfhost_api.py +201 -0
- tortoise/session_continuity.py +82 -0
- tortoise/session_indexer.py +569 -0
- tortoise/shared_state/__init__.py +20 -0
- tortoise/shared_state/concurrency.py +113 -0
- tortoise/shared_state/event_log.py +192 -0
- tortoise/shared_state/events.py +150 -0
- tortoise/shared_state/monitoring.py +87 -0
- tortoise/shared_state/recovery.py +126 -0
- tortoise/shared_state/tests/__init__.py +15 -0
- tortoise/shared_state/tests/test_concurrency.py +123 -0
- tortoise/shared_state/tests/test_events.py +145 -0
- tortoise/shared_state/tests/test_monitoring.py +54 -0
- tortoise/shared_state/tests/test_recovery.py +181 -0
- tortoise/source_credibility.py +306 -0
- tortoise/svbp.py +446 -0
- tortoise/taxonomy.py +71 -0
- tortoise/test_cross_ontology.py +180 -0
- tortoise/test_tortoise_client.py +206 -0
- tortoise/tool_registry.py +805 -0
- tortoise/tortoise_client.py +262 -0
- tortoise/verify_ontology.py +154 -0
- tortoise/version_vector.py +97 -0
- tortoise/weights.py +61 -0
- tortoise_graph-0.2.0.dist-info/METADATA +152 -0
- tortoise_graph-0.2.0.dist-info/RECORD +93 -0
- tortoise_graph-0.2.0.dist-info/WHEEL +5 -0
- tortoise_graph-0.2.0.dist-info/entry_points.txt +4 -0
- tortoise_graph-0.2.0.dist-info/licenses/LICENSE +95 -0
- tortoise_graph-0.2.0.dist-info/top_level.txt +1 -0
tortoise/audit_events.py
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
"""Audit event logger — three-tier persistence for control-plane operations.
|
|
2
|
+
|
|
3
|
+
Tier 1: Postgres INSERT via psycopg2 (sync, optional)
|
|
4
|
+
Tier 2: Local JSONL fallback file (~/.tortoise/audit_fallback.jsonl)
|
|
5
|
+
Tier 3: Replay — on next successful connection, replay fallback into Postgres
|
|
6
|
+
|
|
7
|
+
Postgres is optional. When TORTOISE_AUDIT_DSN is unset or psycopg2 is not
|
|
8
|
+
installed, audit operates in JSONL-only mode (Tier 2).
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import logging
|
|
14
|
+
import os
|
|
15
|
+
import threading
|
|
16
|
+
import time
|
|
17
|
+
from datetime import datetime, timezone
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
_logger = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
# Lazy import — psycopg2 is an optional dependency
|
|
23
|
+
try:
|
|
24
|
+
import psycopg2
|
|
25
|
+
import psycopg2.extras
|
|
26
|
+
_HAS_PSYCOPG2 = True
|
|
27
|
+
except ImportError:
|
|
28
|
+
psycopg2 = None # type: ignore
|
|
29
|
+
_HAS_PSYCOPG2 = False
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _now_iso() -> str:
|
|
33
|
+
return datetime.now(timezone.utc).isoformat()
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
_SCHEMA_DDL = """
|
|
37
|
+
CREATE TABLE IF NOT EXISTS audit_events (
|
|
38
|
+
id TEXT PRIMARY KEY,
|
|
39
|
+
team_id TEXT NOT NULL,
|
|
40
|
+
actor_user_id TEXT,
|
|
41
|
+
operation TEXT NOT NULL,
|
|
42
|
+
resource_type TEXT,
|
|
43
|
+
resource_id TEXT,
|
|
44
|
+
ip_address TEXT,
|
|
45
|
+
user_agent TEXT,
|
|
46
|
+
created_at TIMESTAMPTZ DEFAULT NOW()
|
|
47
|
+
);
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class AuditLogger:
|
|
52
|
+
"""Append-only audit event logger with optional Postgres backend.
|
|
53
|
+
|
|
54
|
+
Args:
|
|
55
|
+
dsn: Postgres connection string. If None, reads TORTOISE_AUDIT_DSN
|
|
56
|
+
from environment. If that is also unset, operates in JSONL-only
|
|
57
|
+
mode (no Postgres writes, no replay).
|
|
58
|
+
|
|
59
|
+
Thread-safe for single-process use. JSONL fallback uses a per-process
|
|
60
|
+
file (~/.tortoise/audit_fallback.jsonl).
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
def __init__(self, dsn: str | None = None):
|
|
64
|
+
self._dsn = dsn or os.environ.get("TORTOISE_AUDIT_DSN")
|
|
65
|
+
self._conn = None
|
|
66
|
+
self._fallback_dir = Path.home() / ".tortoise"
|
|
67
|
+
self._fallback_dir.mkdir(parents=True, exist_ok=True)
|
|
68
|
+
self._fallback_path = self._fallback_dir / "audit_fallback.jsonl"
|
|
69
|
+
self._replay_lock = threading.Lock()
|
|
70
|
+
self._replay_backoff = 1.0
|
|
71
|
+
|
|
72
|
+
# ── Public API ──────────────────────────────────────────────────
|
|
73
|
+
|
|
74
|
+
def append(
|
|
75
|
+
self,
|
|
76
|
+
team_id: str,
|
|
77
|
+
actor_user_id: str | None,
|
|
78
|
+
operation: str,
|
|
79
|
+
*,
|
|
80
|
+
resource_type: str | None = None,
|
|
81
|
+
resource_id: str | None = None,
|
|
82
|
+
ip_address: str | None = None,
|
|
83
|
+
user_agent: str | None = None,
|
|
84
|
+
) -> None:
|
|
85
|
+
"""Append an audit event.
|
|
86
|
+
|
|
87
|
+
Tries Postgres first. On failure, writes to JSONL fallback.
|
|
88
|
+
On any successful Postgres write, replays accumulated fallback entries.
|
|
89
|
+
"""
|
|
90
|
+
from tortoise.ids import ulid
|
|
91
|
+
|
|
92
|
+
event = {
|
|
93
|
+
"id": ulid(),
|
|
94
|
+
"team_id": team_id,
|
|
95
|
+
"actor_user_id": actor_user_id,
|
|
96
|
+
"operation": operation,
|
|
97
|
+
"resource_type": resource_type,
|
|
98
|
+
"resource_id": resource_id,
|
|
99
|
+
"ip_address": ip_address,
|
|
100
|
+
"user_agent": user_agent,
|
|
101
|
+
"created_at": _now_iso(),
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
pg_ok = self._try_pg_insert(event)
|
|
105
|
+
if not pg_ok:
|
|
106
|
+
self._write_fallback(event)
|
|
107
|
+
else:
|
|
108
|
+
# On successful Postgres write, attempt replay of any
|
|
109
|
+
# accumulated fallback entries from prior failures.
|
|
110
|
+
self._replay_fallback()
|
|
111
|
+
|
|
112
|
+
def close(self) -> None:
|
|
113
|
+
"""Close the Postgres connection if open."""
|
|
114
|
+
if self._conn is not None:
|
|
115
|
+
try:
|
|
116
|
+
self._conn.close()
|
|
117
|
+
except Exception:
|
|
118
|
+
pass
|
|
119
|
+
self._conn = None
|
|
120
|
+
|
|
121
|
+
# ── Internals ───────────────────────────────────────────────────
|
|
122
|
+
|
|
123
|
+
def _connect(self) -> bool:
|
|
124
|
+
"""Establish (or re-establish) Postgres connection.
|
|
125
|
+
|
|
126
|
+
Returns True on success, False on failure.
|
|
127
|
+
"""
|
|
128
|
+
if not self._dsn:
|
|
129
|
+
return False
|
|
130
|
+
if not self._dsn.startswith(("postgresql://", "postgres://")):
|
|
131
|
+
raise ValueError(
|
|
132
|
+
f"TORTOISE_AUDIT_DSN must start with postgresql:// or postgres://, got: {self._dsn[:20]}..."
|
|
133
|
+
)
|
|
134
|
+
if not _HAS_PSYCOPG2:
|
|
135
|
+
_logger.debug("psycopg2 not installed — audit in JSONL-only mode")
|
|
136
|
+
return False
|
|
137
|
+
|
|
138
|
+
try:
|
|
139
|
+
if self._conn is not None:
|
|
140
|
+
try:
|
|
141
|
+
self._conn.close()
|
|
142
|
+
except Exception:
|
|
143
|
+
pass
|
|
144
|
+
self._conn = psycopg2.connect(self._dsn)
|
|
145
|
+
self._conn.autocommit = True
|
|
146
|
+
self._ensure_schema()
|
|
147
|
+
self._replay_backoff = 1.0 # reset backoff on success
|
|
148
|
+
return True
|
|
149
|
+
except Exception as e:
|
|
150
|
+
_logger.warning("AuditLogger: Postgres connection failed: %s", e)
|
|
151
|
+
self._conn = None
|
|
152
|
+
return False
|
|
153
|
+
|
|
154
|
+
def _ensure_schema(self) -> None:
|
|
155
|
+
"""Create audit_events table if it doesn't exist."""
|
|
156
|
+
if self._conn is None:
|
|
157
|
+
return
|
|
158
|
+
try:
|
|
159
|
+
with self._conn.cursor() as cur:
|
|
160
|
+
cur.execute(_SCHEMA_DDL)
|
|
161
|
+
except Exception as e:
|
|
162
|
+
_logger.warning("AuditLogger: schema creation failed: %s", e)
|
|
163
|
+
|
|
164
|
+
def _try_pg_insert(self, event: dict) -> bool:
|
|
165
|
+
"""Attempt Postgres INSERT. Returns True on success."""
|
|
166
|
+
if self._conn is None:
|
|
167
|
+
if not self._connect():
|
|
168
|
+
return False
|
|
169
|
+
|
|
170
|
+
try:
|
|
171
|
+
with self._conn.cursor() as cur:
|
|
172
|
+
cur.execute(
|
|
173
|
+
"""INSERT INTO audit_events
|
|
174
|
+
(id, team_id, actor_user_id, operation,
|
|
175
|
+
resource_type, resource_id, ip_address,
|
|
176
|
+
user_agent, created_at)
|
|
177
|
+
VALUES (%(id)s, %(team_id)s, %(actor_user_id)s,
|
|
178
|
+
%(operation)s, %(resource_type)s,
|
|
179
|
+
%(resource_id)s, %(ip_address)s,
|
|
180
|
+
%(user_agent)s, %(created_at)s)""",
|
|
181
|
+
event,
|
|
182
|
+
)
|
|
183
|
+
return True
|
|
184
|
+
except Exception as e:
|
|
185
|
+
_logger.warning("AuditLogger: Postgres INSERT failed: %s", e)
|
|
186
|
+
# Connection may be dead — reset for reconnect on next append
|
|
187
|
+
try:
|
|
188
|
+
self._conn.close()
|
|
189
|
+
except Exception:
|
|
190
|
+
pass
|
|
191
|
+
self._conn = None
|
|
192
|
+
# Exponential backoff before allowing reconnect
|
|
193
|
+
time.sleep(min(self._replay_backoff, 30))
|
|
194
|
+
self._replay_backoff = min(self._replay_backoff * 2, 30)
|
|
195
|
+
return False
|
|
196
|
+
|
|
197
|
+
def _write_fallback(self, event: dict) -> None:
|
|
198
|
+
"""Append event to local JSONL fallback file.
|
|
199
|
+
|
|
200
|
+
Ensures the parent directory exists so a reassigned fallback path
|
|
201
|
+
(or a deleted dir) never silently drops audit events.
|
|
202
|
+
"""
|
|
203
|
+
try:
|
|
204
|
+
self._fallback_path.parent.mkdir(parents=True, exist_ok=True)
|
|
205
|
+
with open(self._fallback_path, "a") as f:
|
|
206
|
+
f.write(json.dumps(event, default=str) + "\n")
|
|
207
|
+
except Exception as e:
|
|
208
|
+
_logger.error("AuditLogger: fallback write failed: %s", e)
|
|
209
|
+
|
|
210
|
+
def _replay_fallback(self) -> None:
|
|
211
|
+
"""Replay accumulated fallback entries into Postgres.
|
|
212
|
+
|
|
213
|
+
Uses a lock to prevent concurrent replay. Reads the fallback file,
|
|
214
|
+
replays each line, and truncates on success.
|
|
215
|
+
"""
|
|
216
|
+
if not self._fallback_path.exists():
|
|
217
|
+
return
|
|
218
|
+
|
|
219
|
+
acquired = self._replay_lock.acquire(blocking=False)
|
|
220
|
+
if not acquired:
|
|
221
|
+
return # Another thread is replaying
|
|
222
|
+
|
|
223
|
+
try:
|
|
224
|
+
if not self._fallback_path.exists():
|
|
225
|
+
return
|
|
226
|
+
|
|
227
|
+
# Read all fallback lines
|
|
228
|
+
lines = self._fallback_path.read_text().strip().split("\n")
|
|
229
|
+
if not lines or lines == [""]:
|
|
230
|
+
return
|
|
231
|
+
|
|
232
|
+
events = []
|
|
233
|
+
for line in lines:
|
|
234
|
+
line = line.strip()
|
|
235
|
+
if not line:
|
|
236
|
+
continue
|
|
237
|
+
try:
|
|
238
|
+
events.append(json.loads(line))
|
|
239
|
+
except json.JSONDecodeError:
|
|
240
|
+
_logger.warning("AuditLogger: corrupt fallback line, skipping")
|
|
241
|
+
|
|
242
|
+
if not events:
|
|
243
|
+
return
|
|
244
|
+
|
|
245
|
+
# Re-ensure connection before replay
|
|
246
|
+
if self._conn is None and not self._connect():
|
|
247
|
+
return
|
|
248
|
+
|
|
249
|
+
# Insert all events
|
|
250
|
+
success_count = 0
|
|
251
|
+
for event in events:
|
|
252
|
+
try:
|
|
253
|
+
with self._conn.cursor() as cur:
|
|
254
|
+
cur.execute(
|
|
255
|
+
"""INSERT INTO audit_events
|
|
256
|
+
(id, team_id, actor_user_id, operation,
|
|
257
|
+
resource_type, resource_id, ip_address,
|
|
258
|
+
user_agent, created_at)
|
|
259
|
+
VALUES (%(id)s, %(team_id)s, %(actor_user_id)s,
|
|
260
|
+
%(operation)s, %(resource_type)s,
|
|
261
|
+
%(resource_id)s, %(ip_address)s,
|
|
262
|
+
%(user_agent)s, %(created_at)s)""",
|
|
263
|
+
event,
|
|
264
|
+
)
|
|
265
|
+
success_count += 1
|
|
266
|
+
except Exception as e:
|
|
267
|
+
_logger.warning("AuditLogger: replay insert failed: %s", e)
|
|
268
|
+
# Write failed events back to fallback
|
|
269
|
+
with open(self._fallback_path, "a") as f:
|
|
270
|
+
f.write(json.dumps(event, default=str) + "\n")
|
|
271
|
+
|
|
272
|
+
# Truncate fallback file on full success
|
|
273
|
+
if success_count == len(events):
|
|
274
|
+
self._fallback_path.write_text("")
|
|
275
|
+
elif success_count > 0:
|
|
276
|
+
# Partial success — only keep failed events
|
|
277
|
+
remaining = events[success_count:]
|
|
278
|
+
self._fallback_path.write_text(
|
|
279
|
+
"\n".join(json.dumps(e, default=str) for e in remaining) + "\n"
|
|
280
|
+
)
|
|
281
|
+
except Exception as e:
|
|
282
|
+
_logger.error("AuditLogger: replay failed: %s", e)
|
|
283
|
+
finally:
|
|
284
|
+
self._replay_lock.release()
|
tortoise/auth.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""P1-9 #6984: API key Bearer token auth + dev bypass + secret hashing.
|
|
2
|
+
|
|
3
|
+
If TORTOISE_API_KEY is set, require `Authorization: Bearer <key>`.
|
|
4
|
+
If not set, warn but allow (dev mode).
|
|
5
|
+
|
|
6
|
+
#7395: hash_api_key() for encrypting secrets at rest in the graph.
|
|
7
|
+
Uses PBKDF2-HMAC-SHA256 with per-key random salt stored alongside the hash.
|
|
8
|
+
TORTOISE_SECRET_PEPPER is mandatory — injected as additional PBKDF2 input.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import hashlib
|
|
13
|
+
import hmac as _hmac
|
|
14
|
+
import logging
|
|
15
|
+
import os
|
|
16
|
+
import secrets
|
|
17
|
+
|
|
18
|
+
_logger = logging.getLogger(__name__)
|
|
19
|
+
|
|
20
|
+
# TORTOISE_SECRET_PEPPER is mandatory in PRODUCTION. Without a stable pepper,
|
|
21
|
+
# API key hashes cannot be verified across process restarts (#67).
|
|
22
|
+
# Dev mode (no TORTOISE_API_KEY): auth is bypassed and hashing is never used,
|
|
23
|
+
# so fall back to a stable dev-only pepper instead of failing at import
|
|
24
|
+
# (which broke local MCP server / pi sessions and the test suite).
|
|
25
|
+
_DEV_PEPPER = "dev-mode-tortoise-pepper-do-not-use-in-production"
|
|
26
|
+
_SECRET_PEPPER = os.environ.get("TORTOISE_SECRET_PEPPER", "")
|
|
27
|
+
if not _SECRET_PEPPER:
|
|
28
|
+
if os.environ.get("TORTOISE_API_KEY"):
|
|
29
|
+
raise RuntimeError(
|
|
30
|
+
"TORTOISE_SECRET_PEPPER is not set. "
|
|
31
|
+
"Set TORTOISE_SECRET_PEPPER in production to ensure API key hashes "
|
|
32
|
+
"survive process restart. API key hashes cannot be verified without "
|
|
33
|
+
"a stable pepper value."
|
|
34
|
+
)
|
|
35
|
+
_logger.warning(
|
|
36
|
+
"TORTOISE_SECRET_PEPPER not set — using dev-mode pepper. "
|
|
37
|
+
"DO NOT run in production without setting it."
|
|
38
|
+
)
|
|
39
|
+
_SECRET_PEPPER = _DEV_PEPPER
|
|
40
|
+
|
|
41
|
+
_PEPPER_BYTES = _SECRET_PEPPER.encode()
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def require_auth(headers: dict | None = None) -> bool:
|
|
45
|
+
"""Check if the request is authorized. Returns True if allowed.
|
|
46
|
+
|
|
47
|
+
Dev mode (no TORTOISE_API_KEY set): always True.
|
|
48
|
+
Production mode: requires `Authorization: Bearer <key>` header match.
|
|
49
|
+
"""
|
|
50
|
+
api_key = os.environ.get("TORTOISE_API_KEY", "")
|
|
51
|
+
if not api_key:
|
|
52
|
+
_logger.warning("TORTOISE_API_KEY not set — running in dev mode (no auth)")
|
|
53
|
+
return True
|
|
54
|
+
|
|
55
|
+
if headers is None:
|
|
56
|
+
return False
|
|
57
|
+
|
|
58
|
+
auth = headers.get("authorization", "")
|
|
59
|
+
if auth.startswith("Bearer "):
|
|
60
|
+
token = auth[7:]
|
|
61
|
+
return _hmac.compare_digest(token, api_key)
|
|
62
|
+
|
|
63
|
+
return False
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def is_dev_mode() -> bool:
|
|
67
|
+
"""Return True if no API key is configured (dev bypass active)."""
|
|
68
|
+
return not bool(os.environ.get("TORTOISE_API_KEY", ""))
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def hash_api_key(key: str) -> str:
|
|
72
|
+
"""PBKDF2-HMAC-SHA256 hash an API key for at-rest storage. Not reversible.
|
|
73
|
+
|
|
74
|
+
Uses a per-key 32-byte random salt stored alongside the hash.
|
|
75
|
+
TORTOISE_SECRET_PEPPER is injected as additional key material.
|
|
76
|
+
100,000 iterations.
|
|
77
|
+
|
|
78
|
+
Returns "salt_hex:hash_hex" — store this full string; pass it to
|
|
79
|
+
verify_api_key() which extracts the salt.
|
|
80
|
+
"""
|
|
81
|
+
per_key_salt = secrets.token_bytes(32)
|
|
82
|
+
# Pepper is mixed into the key material (not used as salt)
|
|
83
|
+
key_material = key.encode() + _PEPPER_BYTES
|
|
84
|
+
digest = hashlib.pbkdf2_hmac(
|
|
85
|
+
"sha256", key_material, per_key_salt, 100_000
|
|
86
|
+
)
|
|
87
|
+
return f"{per_key_salt.hex()}:{digest.hex()}"
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def verify_api_key(key: str, stored: str) -> bool:
|
|
91
|
+
"""Verify a provided API key against a stored "salt:hash" string.
|
|
92
|
+
|
|
93
|
+
Parses the per-key salt from the stored value, recomputes the hash,
|
|
94
|
+
and compares in constant time via hashlib.compare_digest.
|
|
95
|
+
"""
|
|
96
|
+
try:
|
|
97
|
+
salt_hex, expected_hex = stored.split(":", 1)
|
|
98
|
+
if len(salt_hex) != 64:
|
|
99
|
+
return False
|
|
100
|
+
except (ValueError, AttributeError):
|
|
101
|
+
return False
|
|
102
|
+
per_key_salt = bytes.fromhex(salt_hex)
|
|
103
|
+
key_material = key.encode() + _PEPPER_BYTES
|
|
104
|
+
computed = hashlib.pbkdf2_hmac(
|
|
105
|
+
"sha256", key_material, per_key_salt, 100_000
|
|
106
|
+
)
|
|
107
|
+
return _hmac.compare_digest(computed.hex(), expected_hex)
|
tortoise/backup.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""P1-10 #6982: Backup/restore — JSONL archiver + FalkorDB BGSAVE.
|
|
2
|
+
|
|
3
|
+
Backup: copies events.jsonl to timestamped dir, triggers BGSAVE on FalkorDB.
|
|
4
|
+
Restore: replays backup JSONL into a fresh projection.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import logging
|
|
9
|
+
import os
|
|
10
|
+
import shutil
|
|
11
|
+
from datetime import datetime, timezone
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger(__name__)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _timestamp() -> str:
|
|
18
|
+
return datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def backup(db_path: str, events_path: str = "events.jsonl",
|
|
22
|
+
target_dir: str | None = None) -> Path:
|
|
23
|
+
"""Copy database + event log to a timestamped backup directory.
|
|
24
|
+
|
|
25
|
+
Returns the backup directory path.
|
|
26
|
+
"""
|
|
27
|
+
if target_dir is None:
|
|
28
|
+
target_dir = f"backups/{_timestamp()}"
|
|
29
|
+
|
|
30
|
+
target = Path(target_dir)
|
|
31
|
+
target.mkdir(parents=True, exist_ok=True)
|
|
32
|
+
|
|
33
|
+
# Copy FalkorDB
|
|
34
|
+
db = Path(db_path)
|
|
35
|
+
if db.exists():
|
|
36
|
+
shutil.copy2(db, target / db.name)
|
|
37
|
+
|
|
38
|
+
# Copy event log
|
|
39
|
+
ev = Path(events_path)
|
|
40
|
+
if ev.exists():
|
|
41
|
+
shutil.copy2(ev, target / ev.name)
|
|
42
|
+
|
|
43
|
+
# Trigger FalkorDB BGSAVE if available
|
|
44
|
+
_bgsave()
|
|
45
|
+
|
|
46
|
+
# Write manifest
|
|
47
|
+
manifest = target / "manifest.json"
|
|
48
|
+
import json
|
|
49
|
+
manifest.write_text(json.dumps({
|
|
50
|
+
"backed_up_at": _timestamp(),
|
|
51
|
+
"db": db.name,
|
|
52
|
+
"events": ev.name,
|
|
53
|
+
}, indent=2))
|
|
54
|
+
|
|
55
|
+
return target
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def restore(backup_dir: str, db_path: str,
|
|
59
|
+
events_path: str = "events.jsonl", into_falkor: bool = False) -> dict:
|
|
60
|
+
"""Restore from backup directory. Replays events into a fresh projection.
|
|
61
|
+
|
|
62
|
+
Returns {events, status}.
|
|
63
|
+
|
|
64
|
+
Event-sourcing contract (#114): when the backup contains a FalkorDB
|
|
65
|
+
snapshot (tortoise.db — BGSAVE RDB), into_falkor mode opens that
|
|
66
|
+
snapshot directly. The RDB is the complete graph state INCLUDING
|
|
67
|
+
SDK-created points (which never appear in events.jsonl, since the SDK
|
|
68
|
+
writes via Cypher). Replaying only events.jsonl would silently drop
|
|
69
|
+
every SDK-created point. RDB-first restore preserves the full graph;
|
|
70
|
+
JSONL replay is the fallback when no snapshot exists.
|
|
71
|
+
"""
|
|
72
|
+
source = Path(backup_dir)
|
|
73
|
+
if not source.exists():
|
|
74
|
+
return {"events": 0, "status": "error: backup dir not found"}
|
|
75
|
+
|
|
76
|
+
manifest_file = source / "manifest.json"
|
|
77
|
+
events_file = source / "events.jsonl"
|
|
78
|
+
# Read DB filename from manifest (issue #176, plan Task 11): pre-migration
|
|
79
|
+
# backups may have embedded.db in their manifest — never hardcode.
|
|
80
|
+
import json as _json
|
|
81
|
+
_db_name = "tortoise.db"
|
|
82
|
+
if manifest_file.exists():
|
|
83
|
+
try:
|
|
84
|
+
_db_name = _json.loads(manifest_file.read_text()).get("db", "tortoise.db")
|
|
85
|
+
except Exception:
|
|
86
|
+
pass
|
|
87
|
+
db_file = source / _db_name
|
|
88
|
+
# Graceful fallback for pre-migration backups that lack the manifest 'db'
|
|
89
|
+
# key (embedded.db was the legacy filename). Also try scanning for any
|
|
90
|
+
# *.db file if the manifest-derived name doesn't exist.
|
|
91
|
+
if not db_file.exists():
|
|
92
|
+
fallback = source / "embedded.db"
|
|
93
|
+
if fallback.exists():
|
|
94
|
+
logger.warning(
|
|
95
|
+
"manifest db %r not found — falling back to embedded.db in %s",
|
|
96
|
+
_db_name, source)
|
|
97
|
+
db_file = fallback
|
|
98
|
+
_db_name = "embedded.db"
|
|
99
|
+
else:
|
|
100
|
+
# Last resort: scan for any *.db file in the backup dir
|
|
101
|
+
db_candidates = sorted(source.glob("*.db"))
|
|
102
|
+
if db_candidates:
|
|
103
|
+
logger.warning(
|
|
104
|
+
"manifest db %r not found, embedded.db not found — "
|
|
105
|
+
"falling back to %s", _db_name, db_candidates[0].name)
|
|
106
|
+
db_file = db_candidates[0]
|
|
107
|
+
_db_name = db_file.name
|
|
108
|
+
|
|
109
|
+
if not events_file.exists():
|
|
110
|
+
return {"events": 0, "status": "error: no events.jsonl in backup"}
|
|
111
|
+
|
|
112
|
+
# Copy files to target
|
|
113
|
+
shutil.copy2(events_file, events_path)
|
|
114
|
+
if db_file.exists():
|
|
115
|
+
shutil.copy2(db_file, db_path)
|
|
116
|
+
|
|
117
|
+
# Count events
|
|
118
|
+
with open(events_file) as f:
|
|
119
|
+
count = sum(1 for _ in f)
|
|
120
|
+
|
|
121
|
+
# Restore into FalkorDB if requested
|
|
122
|
+
if into_falkor:
|
|
123
|
+
from tortoise.projection import FalkorProjection
|
|
124
|
+
from tortoise.log import EventLog
|
|
125
|
+
# RDB-first: open the snapshot directly — it holds the full graph
|
|
126
|
+
# incl. SDK-created points that never made it into events.jsonl.
|
|
127
|
+
if db_file.exists():
|
|
128
|
+
proj = FalkorProjection(db_path)
|
|
129
|
+
try:
|
|
130
|
+
# Verify the snapshot actually has data; if the RDB is a
|
|
131
|
+
# stub/empty, fall through to JSONL replay below.
|
|
132
|
+
rows = proj.g.query("MATCH (n) RETURN count(n)").result_set
|
|
133
|
+
if rows and rows[0][0]:
|
|
134
|
+
return {"events": count, "status": "ok", "restored_via": "rdb"}
|
|
135
|
+
finally:
|
|
136
|
+
proj.close()
|
|
137
|
+
# JSONL replay fallback (no RDB, or RDB was empty)
|
|
138
|
+
proj = FalkorProjection(db_path)
|
|
139
|
+
try:
|
|
140
|
+
for ev in EventLog(events_path).read_all():
|
|
141
|
+
proj.apply(ev)
|
|
142
|
+
finally:
|
|
143
|
+
proj.close()
|
|
144
|
+
|
|
145
|
+
return {"events": count, "status": "ok"}
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _bgsave() -> None:
|
|
149
|
+
"""Trigger FalkorDB BGSAVE if connected."""
|
|
150
|
+
try:
|
|
151
|
+
from falkordb import FalkorDB
|
|
152
|
+
db = FalkorDB(host=os.environ.get("FALKORDB_HOST", "localhost"), port=int(os.environ.get("FALKORDB_PORT", "16379")))
|
|
153
|
+
db.connection.execute_command("BGSAVE")
|
|
154
|
+
except Exception:
|
|
155
|
+
pass # ponytail: embedded/redislite doesn't support BGSAVE, skip
|
tortoise/config.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""Tortoise configuration — canonical embedded DB path resolution.
|
|
2
|
+
|
|
3
|
+
Child 2 (issue #176): unify all embedded connection points on ONE canonical
|
|
4
|
+
path so redislite's native path-keyed reuse works (one redis-server per
|
|
5
|
+
machine instead of one per connection/path).
|
|
6
|
+
|
|
7
|
+
Env precedence (plan Task 6):
|
|
8
|
+
1. TORTOISE_DB_URI with `docker://` prefix -> URI mode (resolve_db_path()
|
|
9
|
+
is NEVER called — the caller handles docker separately)
|
|
10
|
+
2. TORTOISE_DB_PATH env -> file path (canonical for embedded)
|
|
11
|
+
3. TORTOISE_DB_URI without `docker://` -> treated as a file path
|
|
12
|
+
(backward compat)
|
|
13
|
+
4. default ~/.tortoise/tortoise.db
|
|
14
|
+
|
|
15
|
+
When both a non-docker URI and PATH are set, PATH wins with a logged warning.
|
|
16
|
+
Empty/whitespace TORTOISE_DB_PATH falls through to the default (never passes
|
|
17
|
+
"" to FalkorProjection).
|
|
18
|
+
"""
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import logging
|
|
22
|
+
import os
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
|
|
25
|
+
logger = logging.getLogger(__name__)
|
|
26
|
+
|
|
27
|
+
DEFAULT_DB_PATH = os.path.join(os.path.expanduser("~"), ".tortoise", "tortoise.db")
|
|
28
|
+
|
|
29
|
+
# Shared error message for relative-path rejection (plan Task 7). All call
|
|
30
|
+
# sites (FalkorProjection hard-reject, ingest.py pre-check, mcp_server error
|
|
31
|
+
# surface) reference this constant so they cannot drift.
|
|
32
|
+
RELATIVE_PATH_ERROR = (
|
|
33
|
+
"Relative DB path {path!r} rejected. Use (1) the canonical path "
|
|
34
|
+
"(no-arg FalkorProjection() or TORTOISE_DB_PATH), (2) an absolute path, "
|
|
35
|
+
"or (3) allow_nonstandard_path=True (env TORTOISE_ALLOW_NONSTANDARD_PATH=1) "
|
|
36
|
+
"for absolute non-canonical paths. Relative paths are never permitted."
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def resolve_db_path(explicit: str | None = None) -> str:
|
|
41
|
+
"""Resolve the canonical embedded DB path with explicit precedence.
|
|
42
|
+
|
|
43
|
+
Args:
|
|
44
|
+
explicit: caller-provided path (e.g. from CLI --db). Wins if present.
|
|
45
|
+
|
|
46
|
+
Returns an absolute path string. Raises nothing — falls through to the
|
|
47
|
+
default on empty/whitespace env values.
|
|
48
|
+
"""
|
|
49
|
+
if explicit:
|
|
50
|
+
return _abs(explicit)
|
|
51
|
+
|
|
52
|
+
# 2. TORTOISE_DB_PATH env -> file path
|
|
53
|
+
env_path = os.environ.get("TORTOISE_DB_PATH")
|
|
54
|
+
if env_path is not None and env_path.strip():
|
|
55
|
+
return _abs(env_path.strip())
|
|
56
|
+
if env_path is not None and not env_path.strip():
|
|
57
|
+
logger.warning(
|
|
58
|
+
"TORTOISE_DB_PATH is empty/whitespace — using default %s",
|
|
59
|
+
DEFAULT_DB_PATH)
|
|
60
|
+
|
|
61
|
+
# 3. TORTOISE_DB_URI without docker:// -> treated as file path (backward compat)
|
|
62
|
+
uri = os.environ.get("TORTOISE_DB_URI")
|
|
63
|
+
if uri and not uri.startswith("docker://"):
|
|
64
|
+
# Reject relative paths BEFORE _abs() normalizes them — otherwise
|
|
65
|
+
# FalkorProjection's hard-reject is defeated (plan Task 7).
|
|
66
|
+
expanded = os.path.expanduser(uri)
|
|
67
|
+
if not os.path.isabs(expanded):
|
|
68
|
+
raise ValueError(RELATIVE_PATH_ERROR.format(path=uri))
|
|
69
|
+
logger.warning(
|
|
70
|
+
"TORTOISE_DB_URI=%r is a file path (not docker://) — treating as "
|
|
71
|
+
"embedded DB path (backward compat)", uri)
|
|
72
|
+
return _abs(uri)
|
|
73
|
+
|
|
74
|
+
# 4. default
|
|
75
|
+
return _abs(DEFAULT_DB_PATH)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def is_docker_uri(uri: str | None) -> bool:
|
|
79
|
+
"""True if a TORTOISE_DB_URI value is a docker:// connection string."""
|
|
80
|
+
return bool(uri and uri.startswith("docker://"))
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _abs(path: str) -> str:
|
|
84
|
+
"""Expand ~ and make absolute.
|
|
85
|
+
|
|
86
|
+
REJECTS relative paths (plan Task 7): a relative path like 'tortoise.db'
|
|
87
|
+
resolves per-CWD and silently creates a per-directory redislite server
|
|
88
|
+
(Category-3 leak). This guard in the single choke-point covers ALL
|
|
89
|
+
branches (explicit arg, TORTOISE_DB_PATH, TORTOISE_DB_URI) uniformly.
|
|
90
|
+
"""
|
|
91
|
+
expanded = os.path.expanduser(path)
|
|
92
|
+
if not os.path.isabs(expanded):
|
|
93
|
+
raise ValueError(RELATIVE_PATH_ERROR.format(path=path))
|
|
94
|
+
return os.path.abspath(expanded)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def canonical_path_exists() -> bool:
|
|
98
|
+
"""True if the canonical embedded DB file already exists."""
|
|
99
|
+
return Path(resolve_db_path()).exists()
|