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/security.py
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
"""Shared security primitives for Tortoise (#329).
|
|
2
|
+
|
|
3
|
+
Stdlib-only by design — no imports from ``tortoise`` — so any module may import
|
|
4
|
+
these helpers without creating import cycles. This is the single home for the
|
|
5
|
+
genuinely shared security semantics: Cypher identifier validation (filter keys,
|
|
6
|
+
relationship types, entity types), path containment (base-dir confinement), and
|
|
7
|
+
error redaction.
|
|
8
|
+
|
|
9
|
+
Derivation note (rel-type allowlist): KNOWN_REL_TYPES is derived from the
|
|
10
|
+
codebase edge-type inventory (``grep -rhoE '\\-\\[:[A-Za-z_]+' tortoise/``)
|
|
11
|
+
unioned with the documented structural predicates (``edges.valid_predicates``),
|
|
12
|
+
the ``supersede_point`` structural_rels list, and the ``_create_edges`` op-type
|
|
13
|
+
map. A drift test (tests/test_security.py::test_known_rel_types_superset_of_inventory)
|
|
14
|
+
re-derives the inventory and asserts the allowlist still covers it, so the list
|
|
15
|
+
cannot silently go stale when a new edge type is added.
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import os
|
|
20
|
+
import re
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
# ── Filter keys (sdk.query / sdk.paginated_query) ─────────────────────────
|
|
24
|
+
|
|
25
|
+
# Reserved parameter names that sdk.query/paginated_query generate internally.
|
|
26
|
+
# ``kind`` (single-kind branch), ``kind_0..kind_{n-1}`` (expanded-kind branch
|
|
27
|
+
# placeholders from _expand_kind), and ``skip``/``limit`` (paginated_query).
|
|
28
|
+
# A filter key colliding with any of these would silently override the
|
|
29
|
+
# auto-generated parameter and corrupt the WHERE clause — reject by design.
|
|
30
|
+
_RESERVED_FILTER_KEYS = frozenset({"kind", "skip", "limit"})
|
|
31
|
+
_RESERVED_KIND_PREFIX = re.compile(r"^kind_\d+$")
|
|
32
|
+
_FILTER_KEY_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def validate_filter_key(key: str) -> str:
|
|
36
|
+
"""Validate a property filter key for sdk.query/paginated_query.
|
|
37
|
+
|
|
38
|
+
ASCII identifier only (``^[A-Za-z_][A-Za-z0-9_]*$``) — the value is always
|
|
39
|
+
parameterized so only the KEY is interpolated into Cypher (backtick-wrapped).
|
|
40
|
+
Unicode alphanumerics (e.g. ``é``, ``中``) are rejected: they pass the old
|
|
41
|
+
``str.isalnum()`` check but break Cypher parameter syntax per-query and are
|
|
42
|
+
never used as property names in this codebase (Spanish content lives in
|
|
43
|
+
property VALUES, which are parameterized and unaffected).
|
|
44
|
+
|
|
45
|
+
Reserved keys (``kind``, ``skip``, ``limit``, ``kind_<n>``) are rejected:
|
|
46
|
+
they collide with auto-generated parameter names. Accepted tradeoff: a
|
|
47
|
+
tenant property literally named ``kind_1`` can no longer be used as a filter
|
|
48
|
+
key — rename the property (documented, tested).
|
|
49
|
+
|
|
50
|
+
Returns the key (for chaining). Raises ValueError otherwise.
|
|
51
|
+
"""
|
|
52
|
+
if not isinstance(key, str) or not _FILTER_KEY_RE.match(key):
|
|
53
|
+
raise ValueError(
|
|
54
|
+
f"Invalid filter key: {key!r}. Filter keys must be ASCII identifiers "
|
|
55
|
+
f"matching [A-Za-z_][A-Za-z0-9_]* (alphanumeric + underscore)."
|
|
56
|
+
)
|
|
57
|
+
if key in _RESERVED_FILTER_KEYS or _RESERVED_KIND_PREFIX.match(key):
|
|
58
|
+
raise ValueError(
|
|
59
|
+
f"Reserved filter key: {key!r}. This name collides with internal "
|
|
60
|
+
f"query parameters (kind, skip, limit, kind_<n>). Rename the property."
|
|
61
|
+
)
|
|
62
|
+
return key
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
# ── Relationship types (sdk.traverse / supersede_point) ───────────────────
|
|
66
|
+
|
|
67
|
+
# Derived from the codebase edge-type inventory + documented predicates. See
|
|
68
|
+
# module docstring for the derivation + drift test.
|
|
69
|
+
KNOWN_REL_TYPES: frozenset[str] = frozenset({
|
|
70
|
+
# Epistemic operators
|
|
71
|
+
"IMPL", "NAND",
|
|
72
|
+
# Composition / supersession / provenance
|
|
73
|
+
"hasPart", "CORRECTS", "SUPERSEDES", "supersedes", "extractedFrom",
|
|
74
|
+
"references", "wasDerivedFrom", "INPUT", "TAGGED", "mitigated_by",
|
|
75
|
+
"mitigates", "resolves",
|
|
76
|
+
# about* edges (ontology v3.1 §3.2)
|
|
77
|
+
"aboutSubject", "aboutObject", "aboutEvent", "aboutPoint",
|
|
78
|
+
"aboutDocument", "aboutAction",
|
|
79
|
+
# Structural (edges.valid_predicates + legacy)
|
|
80
|
+
"performs", "produces", "uses", "authoredBy", "ownedBy", "managedBy",
|
|
81
|
+
"hasMember", "holdsRole", "memberOf", "reportsTo", "participatesIn",
|
|
82
|
+
"related", "dependsOn",
|
|
83
|
+
# Organisational / registry / session
|
|
84
|
+
"BELONGS_TO", "FOR_TEAM", "INSTANTIATES", "CONTAINS", "SUPPORTS",
|
|
85
|
+
"INFORMED_BY", "PRODUCES",
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def validate_rel_type(rel_type: str) -> str:
|
|
90
|
+
"""Validate a relationship type before it is interpolated into Cypher.
|
|
91
|
+
|
|
92
|
+
The relationship type appears in the query STRUCTURE (``-[:TYPE]->``) where
|
|
93
|
+
parameterization is impossible — it MUST be allowlisted. Prevents Cypher
|
|
94
|
+
injection via relationship_type (sdk.traverse) and edge-type interpolation
|
|
95
|
+
(supersede_point transfer).
|
|
96
|
+
|
|
97
|
+
Case-sensitive: ``"IMPL "``/``"impl"`` are rejected (the Cypher type token
|
|
98
|
+
must match the stored edge type exactly).
|
|
99
|
+
|
|
100
|
+
Returns the rel_type (for chaining). Raises ValueError otherwise.
|
|
101
|
+
"""
|
|
102
|
+
if not isinstance(rel_type, str) or rel_type not in KNOWN_REL_TYPES:
|
|
103
|
+
raise ValueError(
|
|
104
|
+
f"Invalid relationship type: {rel_type!r}. Must be one of the known "
|
|
105
|
+
f"edge types: {sorted(KNOWN_REL_TYPES)}."
|
|
106
|
+
)
|
|
107
|
+
return rel_type
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
# ── Entity types (search_engine runners) ───────────────────────────────────
|
|
111
|
+
|
|
112
|
+
VALID_ENTITY_TYPES: frozenset[str] = frozenset({
|
|
113
|
+
"point", "event", "subject", "document", "object", "operator", "source",
|
|
114
|
+
})
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def validate_entity_type(entity_type: str) -> str:
|
|
118
|
+
"""Validate entity_type before its capitalized form is used as a Cypher label.
|
|
119
|
+
|
|
120
|
+
``run_fts_query``/``run_vector_query``/``run_structural_query`` interpolate
|
|
121
|
+
``entity_type.capitalize()`` as a graph label — the label is query STRUCTURE
|
|
122
|
+
and must be allowlisted (defense-in-depth: the SDK already validates, but the
|
|
123
|
+
module-level runners are public).
|
|
124
|
+
|
|
125
|
+
Case-sensitive and whitespace-strict: ``"Point"``, ``"point "``, ``"POINT"``
|
|
126
|
+
are all rejected.
|
|
127
|
+
|
|
128
|
+
Returns entity_type. Raises ValueError otherwise.
|
|
129
|
+
"""
|
|
130
|
+
if not isinstance(entity_type, str) or entity_type not in VALID_ENTITY_TYPES:
|
|
131
|
+
raise ValueError(
|
|
132
|
+
f"Invalid entity_type: {entity_type!r}. Must be one of "
|
|
133
|
+
f"{sorted(VALID_ENTITY_TYPES)}."
|
|
134
|
+
)
|
|
135
|
+
return entity_type
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
# ── Document id validation (event-mint Document branch) ────────────────────
|
|
139
|
+
|
|
140
|
+
# ULIDs: canonical timestamp-hex + crockford uuid12 (see sdk._is_ulid).
|
|
141
|
+
# Operator basenames: file stems from `tortoise ingest docs/foo.md` etc. —
|
|
142
|
+
# leading ._- allowed, non-ASCII letters allowed (e.g. résumé.md).
|
|
143
|
+
# REJECTED: path separators, "..", NUL/control chars, >255 chars.
|
|
144
|
+
_CTRL_CHARS = re.compile(r"[\x00-\x1f\x7f]")
|
|
145
|
+
_DOC_ID_MAX = 255
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def validate_document_id(doc_id: str) -> str:
|
|
149
|
+
"""Validate a Document node id minted from tenant/event input.
|
|
150
|
+
|
|
151
|
+
Accepts ULIDs and operator file basenames (leading ``._-``, non-ASCII).
|
|
152
|
+
Rejects anything that could resolve to a host path (``/``, ``\\``, ``..``,
|
|
153
|
+
control characters, >255 chars). This bounds the write-side of the
|
|
154
|
+
sourcePath/d.id file-read chain: the READ side (resolve_under_base) remains
|
|
155
|
+
the security boundary and fails closed regardless.
|
|
156
|
+
|
|
157
|
+
Returns doc_id. Raises ValueError otherwise.
|
|
158
|
+
"""
|
|
159
|
+
if not isinstance(doc_id, str) or not doc_id:
|
|
160
|
+
raise ValueError(f"Invalid document id: {doc_id!r} — must be a non-empty string.")
|
|
161
|
+
if len(doc_id) > _DOC_ID_MAX:
|
|
162
|
+
raise ValueError(f"Invalid document id: {doc_id!r} — longer than {_DOC_ID_MAX} chars.")
|
|
163
|
+
if "/" in doc_id or "\\" in doc_id:
|
|
164
|
+
raise ValueError(f"Invalid document id: {doc_id!r} — path separators are not allowed.")
|
|
165
|
+
if doc_id in ("..", ".") or doc_id.startswith("../") or doc_id.startswith("..\\"):
|
|
166
|
+
raise ValueError(f"Invalid document id: {doc_id!r} — path traversal not allowed.")
|
|
167
|
+
if _CTRL_CHARS.search(doc_id):
|
|
168
|
+
raise ValueError(f"Invalid document id: {doc_id!r} — control characters are not allowed.")
|
|
169
|
+
return doc_id
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
# ── Path containment (base-dir confinement) ────────────────────────────────
|
|
173
|
+
|
|
174
|
+
def resolve_under_base(candidate: str, base: str | None) -> Path | None:
|
|
175
|
+
"""Resolve ``candidate`` strictly under ``base`` (symlink-safe).
|
|
176
|
+
|
|
177
|
+
Returns the resolved absolute Path ONLY if the realpath of the candidate is
|
|
178
|
+
strictly inside the realpath of the base. Returns None otherwise (the caller
|
|
179
|
+
must SKIP, never fall through to reading the path).
|
|
180
|
+
|
|
181
|
+
Hardening rules (OWASP path-traversal cheat sheet):
|
|
182
|
+
- ``realpath()`` on BOTH candidate and base before comparison — a symlink
|
|
183
|
+
pointing outside the base (or a parent-dir symlink) resolves outside and
|
|
184
|
+
is rejected. A lexical prefix check alone is bypassable.
|
|
185
|
+
- ``..`` components, absolute-outside-base, and relative paths that escape
|
|
186
|
+
the base when resolved against the caller's CWD are rejected.
|
|
187
|
+
- base=None (env unset) → fail-closed: returns None (nothing is provably
|
|
188
|
+
under an unset base). Callers log a one-time hint to set the env var.
|
|
189
|
+
|
|
190
|
+
Known residual: TOCTOU — the file could be swapped after realpath resolves.
|
|
191
|
+
Accepted (operator/CLI context, documented); the read happens on the
|
|
192
|
+
resolved path returned here.
|
|
193
|
+
"""
|
|
194
|
+
if not isinstance(candidate, str) or not candidate:
|
|
195
|
+
return None
|
|
196
|
+
if base is None or not isinstance(base, str) or not base:
|
|
197
|
+
return None # fail-closed: no base configured
|
|
198
|
+
try:
|
|
199
|
+
base_path = Path(base).resolve(strict=False)
|
|
200
|
+
cand_path = Path(candidate).expanduser().resolve(strict=False)
|
|
201
|
+
except (OSError, ValueError, RuntimeError):
|
|
202
|
+
return None
|
|
203
|
+
try:
|
|
204
|
+
# strict-under-base: candidate must be a proper descendant
|
|
205
|
+
cand_path.relative_to(base_path)
|
|
206
|
+
except ValueError:
|
|
207
|
+
return None
|
|
208
|
+
return cand_path
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def ingest_dir_is_safe(directory: str, base: str | None) -> bool:
|
|
212
|
+
"""Validate an ingest directory against the base-dir policy.
|
|
213
|
+
|
|
214
|
+
Returns True if the directory is safe to walk. Rules:
|
|
215
|
+
- Must be a non-empty string.
|
|
216
|
+
- Must be absolute (relative directories are rejected — CWD-dependent).
|
|
217
|
+
- Must not contain ``..`` components.
|
|
218
|
+
- If base is set: must resolve strictly under base.
|
|
219
|
+
- If base is unset: absolute + no ``..`` is accepted (operator/CLI context;
|
|
220
|
+
the caller is stdio/CLI-gated, not tenant-reachable).
|
|
221
|
+
"""
|
|
222
|
+
if not isinstance(directory, str) or not directory:
|
|
223
|
+
return False
|
|
224
|
+
if not os.path.isabs(directory):
|
|
225
|
+
return False
|
|
226
|
+
parts = Path(directory).parts
|
|
227
|
+
if ".." in parts:
|
|
228
|
+
return False
|
|
229
|
+
if base is not None and resolve_under_base(directory, base) is None:
|
|
230
|
+
return False
|
|
231
|
+
return True
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
# ── Error redaction ────────────────────────────────────────────────────────
|
|
235
|
+
|
|
236
|
+
# Patterns that commonly appear in exception messages and leak internals.
|
|
237
|
+
_REDACT_PATTERNS = [
|
|
238
|
+
(re.compile(r"://[^@\s]*@"), "://***@"), # credentials in URIs
|
|
239
|
+
(re.compile(r"(?<=/)[\w.-]+\.(?:db|jsonl|log|yaml|yml)(?=[\"'\s,)])"), "***"), # file paths
|
|
240
|
+
(re.compile(r"/[A-Za-z0-9_./-]+/(?:tortoise|data|tmp)[A-Za-z0-9_./-]*"), "/***"),
|
|
241
|
+
]
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def redact_error(e: BaseException) -> str:
|
|
245
|
+
"""Return a safe, generic error string for a caught exception.
|
|
246
|
+
|
|
247
|
+
Returns the exception class name + a redacted message (credentials, common
|
|
248
|
+
file paths, host:port stripped). Never includes full Cypher, query text, or
|
|
249
|
+
tracebacks. Used by analyze()'s error path so tenants never see DB/query
|
|
250
|
+
internals.
|
|
251
|
+
"""
|
|
252
|
+
msg = str(e) or e.__class__.__name__
|
|
253
|
+
for pattern, repl in _REDACT_PATTERNS:
|
|
254
|
+
msg = pattern.sub(repl, msg)
|
|
255
|
+
return f"{e.__class__.__name__}: {msg[:200]}"
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
# ── Env helpers ────────────────────────────────────────────────────────────
|
|
259
|
+
|
|
260
|
+
def env_int(name: str, default: int) -> int:
|
|
261
|
+
"""Read an integer env var with a default; invalid values fall back."""
|
|
262
|
+
raw = os.environ.get(name)
|
|
263
|
+
if raw is None:
|
|
264
|
+
return default
|
|
265
|
+
try:
|
|
266
|
+
return int(raw)
|
|
267
|
+
except (TypeError, ValueError):
|
|
268
|
+
return default
|
tortoise/selfhost.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"""Tortoise self-host daemon (#338 D1).
|
|
2
|
+
|
|
3
|
+
Thin single-tenant FastAPI app: MCP Streamable HTTP at /mcp + /health.
|
|
4
|
+
NO Supabase, NO hosted platform machinery (registry auth, tenant
|
|
5
|
+
provisioning, dream queue). The self-host image ships this app — grep gate:
|
|
6
|
+
no hosted_api / supabase / TeamResolutionMiddleware imports reachable from
|
|
7
|
+
this module (auth_mode is "static"|"none", so create_http_app never imports
|
|
8
|
+
TeamResolutionMiddleware).
|
|
9
|
+
|
|
10
|
+
Environment:
|
|
11
|
+
TORTOISE_DB_URI durable FalkorDB (connection string) — recommended
|
|
12
|
+
TORTOISE_DB_PATH embedded FalkorDBLite eval path (falls back to
|
|
13
|
+
/data/tortoise.db, then tempdir)
|
|
14
|
+
TORTOISE_API_KEY set → auth_mode="static"; unset → "none"
|
|
15
|
+
(⚠️ footgun: a non-localhost TORTOISE_HOST bind with
|
|
16
|
+
no key exposes an unauthenticated engine)
|
|
17
|
+
TORTOISE_HOST 127.0.0.1
|
|
18
|
+
TORTOISE_PORT 8000
|
|
19
|
+
TORTOISE_RATE_LIMIT 100 req/min per IP (MCP SSE bursts ~5-10 req/call)
|
|
20
|
+
TORTOISE_ALLOWED_ORIGINS comma-separated (default http://localhost:8000)
|
|
21
|
+
"""
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import logging
|
|
25
|
+
import os
|
|
26
|
+
from contextlib import asynccontextmanager
|
|
27
|
+
|
|
28
|
+
from fastapi import FastAPI
|
|
29
|
+
from starlette.middleware.cors import CORSMiddleware
|
|
30
|
+
from starlette.responses import JSONResponse
|
|
31
|
+
|
|
32
|
+
from tortoise.mcp_server import create_http_app
|
|
33
|
+
|
|
34
|
+
_logger = logging.getLogger(__name__)
|
|
35
|
+
|
|
36
|
+
HOST = os.environ.get("TORTOISE_HOST", "127.0.0.1")
|
|
37
|
+
PORT = int(os.environ.get("TORTOISE_PORT", "8000"))
|
|
38
|
+
RATE_LIMIT = int(os.environ.get("TORTOISE_RATE_LIMIT", "100"))
|
|
39
|
+
API_KEY = os.environ.get("TORTOISE_API_KEY")
|
|
40
|
+
ALLOWED_ORIGINS = os.environ.get(
|
|
41
|
+
"TORTOISE_ALLOWED_ORIGINS", "http://localhost:8000"
|
|
42
|
+
).split(",")
|
|
43
|
+
# Role-scoped server (#523): TORTOISE_TOOL_GROUP=memory exposes only that
|
|
44
|
+
# group's tools to the agent (keeps the tool-selection surface under ~20).
|
|
45
|
+
TOOL_GROUP = os.environ.get("TORTOISE_TOOL_GROUP")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _auth_mode() -> str:
|
|
49
|
+
"""API key set → static; unset → none (localhost-bound eval)."""
|
|
50
|
+
return "static" if API_KEY else "none"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
# ⚠️ Fail-closed startup guard (code-review P1, #338): auth_mode="none" on a
|
|
54
|
+
# non-loopback bind exposes an unauthenticated, fully writable graph API to
|
|
55
|
+
# the network. Refuse to start rather than silently degrade.
|
|
56
|
+
_LOOPBACK_HOSTS = {"127.0.0.1", "localhost", "::1"}
|
|
57
|
+
if _auth_mode() == "none" and HOST not in _LOOPBACK_HOSTS:
|
|
58
|
+
raise SystemExit(
|
|
59
|
+
"tortoise selfhost: REFUSING TO START — auth_mode=none (no TORTOISE_API_KEY) "
|
|
60
|
+
f"with TORTOISE_HOST={HOST!r} (non-loopback) would expose an unauthenticated "
|
|
61
|
+
"graph engine. Set TORTOISE_API_KEY (→ auth_mode=static) or bind a loopback "
|
|
62
|
+
"host (127.0.0.1/localhost/::1)."
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
# ⚠️ Embedded-mode durability warning (2026-08-05 incident #101: AOF-off,
|
|
67
|
+
# no automated backups, empty-state RDB re-save failed → 5,748 points lost).
|
|
68
|
+
# Embedded FalkorDBLite is for EVAL/DEV only — back up or use TORTOISE_DB_URI.
|
|
69
|
+
if not os.environ.get("TORTOISE_DB_URI"):
|
|
70
|
+
_logger.warning(
|
|
71
|
+
"tortoise selfhost: EMBEDDED MODE (no TORTOISE_DB_URI) — NOT durable. "
|
|
72
|
+
"For production use TORTOISE_DB_URI (FalkorDB with AOF) or the "
|
|
73
|
+
"docker-compose reference. See docs/license-notes.md / infra-runbook."
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
_ALLOWED_HOSTS = [o.split("//")[1].split("/")[0] for o in ALLOWED_ORIGINS if "//" in o]
|
|
77
|
+
|
|
78
|
+
mcp_http_app = create_http_app(
|
|
79
|
+
allowed_origins=ALLOWED_ORIGINS,
|
|
80
|
+
allowed_hosts=_ALLOWED_HOSTS,
|
|
81
|
+
rate_limit=RATE_LIMIT,
|
|
82
|
+
auth_mode=_auth_mode(),
|
|
83
|
+
api_key=API_KEY,
|
|
84
|
+
tool_group=TOOL_GROUP,
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@asynccontextmanager
|
|
89
|
+
async def _lifespan(app: FastAPI):
|
|
90
|
+
# Starlette Mount does NOT run the mounted sub-app's lifespan — compose
|
|
91
|
+
# explicitly (hosted_api._lifespan pattern) so the
|
|
92
|
+
# StreamableHTTPSessionManager initializes (T1.2 pin).
|
|
93
|
+
async with mcp_http_app.lifespan(mcp_http_app):
|
|
94
|
+
yield
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
app = FastAPI(title="Tortoise Self-Host", version="0.1.0", lifespan=_lifespan)
|
|
98
|
+
app.add_middleware(
|
|
99
|
+
CORSMiddleware,
|
|
100
|
+
allow_origins=ALLOWED_ORIGINS,
|
|
101
|
+
allow_methods=["*"],
|
|
102
|
+
allow_headers=["*"],
|
|
103
|
+
)
|
|
104
|
+
app.mount("/mcp", mcp_http_app)
|
|
105
|
+
|
|
106
|
+
# Self-host REST surface (#525) — registry-aligned /v1 endpoints.
|
|
107
|
+
from tortoise.selfhost_api import router as _rest_router
|
|
108
|
+
|
|
109
|
+
app.include_router(_rest_router)
|
|
110
|
+
|
|
111
|
+
# Rate limit the REST surface (code-review P2, #525): /mcp has its own limiter
|
|
112
|
+
# inside the sub-app; /v1/* needs the same protection (brute-force throttle on
|
|
113
|
+
# static keys). Reuse the MCP token-bucket middleware on the parent app.
|
|
114
|
+
from tortoise.mcp_auth import MCPRateLimitMiddleware
|
|
115
|
+
|
|
116
|
+
# Scope to /v1 only (code-review P2, #525): /mcp metadata GET, /health, and
|
|
117
|
+
# /docs must never be throttled (healthcheck false-negatives / host-protection
|
|
118
|
+
# interference). /v1 GETs are included (static-key brute-force surface).
|
|
119
|
+
app.add_middleware(
|
|
120
|
+
MCPRateLimitMiddleware,
|
|
121
|
+
max_per_minute=RATE_LIMIT,
|
|
122
|
+
limit_get=True,
|
|
123
|
+
paths_prefix=("/v1",),
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
@app.get("/health")
|
|
128
|
+
async def health():
|
|
129
|
+
"""Liveness — process up."""
|
|
130
|
+
return JSONResponse({"status": "ok", "service": "tortoise-selfhost"})
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
@app.get("/health/ready")
|
|
134
|
+
async def health_ready():
|
|
135
|
+
"""Readiness — DB reachable via the SAME path the engine uses.
|
|
136
|
+
|
|
137
|
+
503 (not 500) when DB is down. Probes TortoiseSDK(namespace="selfhost")
|
|
138
|
+
— exactly what the MCP tools resolve — so readiness reflects the engine's
|
|
139
|
+
real DB (not a divergent default path). Exception details are logged
|
|
140
|
+
server-side only (no internal info disclosure).
|
|
141
|
+
"""
|
|
142
|
+
try:
|
|
143
|
+
from tortoise.sdk import TortoiseSDK # lazy — liveness stays cheap
|
|
144
|
+
|
|
145
|
+
sdk = TortoiseSDK(namespace="selfhost")
|
|
146
|
+
sdk._get_proj() # touch the DB (hosted_api release_command pattern)
|
|
147
|
+
return JSONResponse({"status": "ready"})
|
|
148
|
+
except Exception as exc: # noqa: BLE001 — readiness reports, never raises
|
|
149
|
+
_logger.warning("health/ready failed: %s", exc)
|
|
150
|
+
return JSONResponse({"status": "not_ready"}, status_code=503)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
if __name__ == "__main__":
|
|
154
|
+
# `python -m tortoise.selfhost` (T1.4 smoke invocation)
|
|
155
|
+
import uvicorn
|
|
156
|
+
|
|
157
|
+
uvicorn.run(app, host=HOST, port=PORT)
|
tortoise/selfhost_api.py
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
"""Self-host REST surface (#525).
|
|
2
|
+
|
|
3
|
+
Single-tenant REST API for the self-host daemon, aligned with the registry
|
|
4
|
+
RestSpec paths (tortoise/tool_registry.py — single source of truth for both
|
|
5
|
+
MCP and REST surfaces). Auth follows selfhost auth_mode: `static` (Bearer
|
|
6
|
+
TORTOISE_API_KEY, hmac compare) or `none` (loopback-bound eval — the startup
|
|
7
|
+
guard in selfhost.py refuses non-loopback none-mode).
|
|
8
|
+
|
|
9
|
+
Operations mirror the MCP tools (namespace="selfhost"): create/query points,
|
|
10
|
+
hybrid search, EP dreaming.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import hmac
|
|
15
|
+
import logging
|
|
16
|
+
import os
|
|
17
|
+
|
|
18
|
+
from fastapi import APIRouter, Depends, Header, HTTPException, Query
|
|
19
|
+
from pydantic import BaseModel, Field, field_validator
|
|
20
|
+
|
|
21
|
+
from tortoise.domain_loader import known_kinds
|
|
22
|
+
|
|
23
|
+
_logger = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
router = APIRouter(prefix="/v1")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class CreatePointRequest(BaseModel):
|
|
29
|
+
content: str = Field(..., min_length=1, max_length=10000)
|
|
30
|
+
kind: str = Field(default="statement")
|
|
31
|
+
tags: list[str] = Field(default_factory=list)
|
|
32
|
+
dedup: bool = Field(default=True)
|
|
33
|
+
|
|
34
|
+
@field_validator("kind")
|
|
35
|
+
@classmethod
|
|
36
|
+
def valid_kind(cls, v: str) -> str:
|
|
37
|
+
if v not in known_kinds():
|
|
38
|
+
raise ValueError(f"kind must be one of {sorted(known_kinds())}")
|
|
39
|
+
return v
|
|
40
|
+
|
|
41
|
+
@field_validator("tags")
|
|
42
|
+
@classmethod
|
|
43
|
+
def valid_tags(cls, v: list[str]) -> list[str]:
|
|
44
|
+
for t in v:
|
|
45
|
+
if not t or len(t) > 200:
|
|
46
|
+
raise ValueError("each tag must be 1-200 characters")
|
|
47
|
+
if any(ch in t for ch in "\n\r\t"):
|
|
48
|
+
raise ValueError("tags cannot contain newlines or tabs")
|
|
49
|
+
return v
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class PointResponse(BaseModel):
|
|
53
|
+
id: str
|
|
54
|
+
content: str
|
|
55
|
+
kind: str
|
|
56
|
+
created_at: str | None = None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _require_key(authorization: str | None = Header(default=None)) -> None:
|
|
60
|
+
"""Static-key auth when auth_mode=static; allow in none mode (loopback).
|
|
61
|
+
|
|
62
|
+
Contract (code-review P2, #525): when no key is configured the daemon is
|
|
63
|
+
in auth_mode=none — the startup guard in selfhost.py refuses none-mode on
|
|
64
|
+
non-loopback binds, so allow here is loopback-scoped only. This router is
|
|
65
|
+
daemon-scoped; do not mount it in other apps without an explicit key.
|
|
66
|
+
Reads the key per request (env may be set by config/CLI before serving).
|
|
67
|
+
"""
|
|
68
|
+
api_key = os.environ.get("TORTOISE_API_KEY")
|
|
69
|
+
if not api_key:
|
|
70
|
+
return # auth_mode=none — loopback-guarded at startup
|
|
71
|
+
if (
|
|
72
|
+
not authorization
|
|
73
|
+
or not authorization.startswith("Bearer ")
|
|
74
|
+
or not hmac.compare_digest(authorization[7:].encode(), api_key.encode())
|
|
75
|
+
):
|
|
76
|
+
raise HTTPException(status_code=401, detail="Unauthorized")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _sdk():
|
|
80
|
+
from tortoise.sdk import TortoiseSDK
|
|
81
|
+
return TortoiseSDK(namespace="selfhost")
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _point_out(result: dict) -> dict:
|
|
85
|
+
# Handles raw-property dicts (pointKind/createdAt), registry REST models
|
|
86
|
+
# (kind/created_at), and FTS SearchResult.to_dict() (point_kind — code-review
|
|
87
|
+
# P2-1, #525).
|
|
88
|
+
return {
|
|
89
|
+
"id": result.get("id", ""),
|
|
90
|
+
"content": result.get("content", ""),
|
|
91
|
+
"kind": result.get("pointKind", result.get("kind", result.get("point_kind", ""))),
|
|
92
|
+
"created_at": result.get("createdAt", result.get("created_at")),
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
@router.post("/points", response_model=PointResponse, dependencies=[Depends(_require_key)])
|
|
97
|
+
async def create_point(body: CreatePointRequest):
|
|
98
|
+
"""Create a Point in the self-host graph (registry: POST /v1/points)."""
|
|
99
|
+
sdk = _sdk()
|
|
100
|
+
try:
|
|
101
|
+
result = sdk.create_point(
|
|
102
|
+
content=body.content,
|
|
103
|
+
kind=body.kind,
|
|
104
|
+
tags=body.tags,
|
|
105
|
+
dedup=body.dedup,
|
|
106
|
+
)
|
|
107
|
+
except Exception as e: # noqa: BLE001
|
|
108
|
+
_logger.exception("selfhost create_point failed")
|
|
109
|
+
raise HTTPException(status_code=500, detail="Internal error")
|
|
110
|
+
return _point_out(result)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@router.get("/points", response_model=list[PointResponse], dependencies=[Depends(_require_key)])
|
|
114
|
+
async def list_points(
|
|
115
|
+
kind: str | None = None,
|
|
116
|
+
tag: str | None = None,
|
|
117
|
+
limit: int = Query(50, ge=1, le=1000),
|
|
118
|
+
):
|
|
119
|
+
"""Query Points in the self-host graph (optional kind/tag filters)."""
|
|
120
|
+
if kind and kind not in known_kinds():
|
|
121
|
+
raise HTTPException(status_code=400, detail=f"kind must be one of {sorted(known_kinds())}")
|
|
122
|
+
sdk = _sdk()
|
|
123
|
+
proj = sdk._get_proj()
|
|
124
|
+
conditions = ["(n.is_operator IS NULL OR n.is_operator = false)"]
|
|
125
|
+
params: dict = {"limit": limit}
|
|
126
|
+
if kind:
|
|
127
|
+
conditions.append("n.pointKind = $kind")
|
|
128
|
+
params["kind"] = kind
|
|
129
|
+
tag_clause = ""
|
|
130
|
+
if tag:
|
|
131
|
+
tag_clause = "-[:TAGGED]->(t:Tag {name:$tag})"
|
|
132
|
+
params["tag"] = tag
|
|
133
|
+
query = (
|
|
134
|
+
f"MATCH (n:Point){tag_clause} WHERE "
|
|
135
|
+
+ " AND ".join(conditions)
|
|
136
|
+
+ " RETURN properties(n) ORDER BY n.createdAt DESC LIMIT $limit"
|
|
137
|
+
)
|
|
138
|
+
try:
|
|
139
|
+
rows = proj.g.query(query, params=params).result_set
|
|
140
|
+
except Exception as e: # noqa: BLE001
|
|
141
|
+
_logger.exception("selfhost list_points failed")
|
|
142
|
+
raise HTTPException(status_code=500, detail="Internal error")
|
|
143
|
+
results = []
|
|
144
|
+
for r in rows:
|
|
145
|
+
d = dict(r[0])
|
|
146
|
+
if "pointKind" in d:
|
|
147
|
+
d["kind"] = d.pop("pointKind")
|
|
148
|
+
results.append(d)
|
|
149
|
+
return results
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
@router.get("/points/{point_id}", response_model=PointResponse, dependencies=[Depends(_require_key)])
|
|
153
|
+
async def get_point(point_id: str):
|
|
154
|
+
"""Get a single Point by id."""
|
|
155
|
+
sdk = _sdk()
|
|
156
|
+
result = sdk.get_point(point_id)
|
|
157
|
+
if not result: # get_point returns {} for a missing id (code-review P2)
|
|
158
|
+
raise HTTPException(status_code=404, detail="Point not found")
|
|
159
|
+
return _point_out(result)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
@router.get("/search", response_model=list[PointResponse], dependencies=[Depends(_require_key)])
|
|
163
|
+
async def search(q: str, limit: int = Query(10, ge=1, le=100)):
|
|
164
|
+
"""Hybrid search (registry: GET /v1/search)."""
|
|
165
|
+
sdk = _sdk()
|
|
166
|
+
try:
|
|
167
|
+
# Registry-aligned hybrid search (tortoise_search → tortoise_fts_query):
|
|
168
|
+
# FTS/vector/RRF with an in-memory TF-IDF degradation path — works on
|
|
169
|
+
# remote FalkorDB AND embedded eval (code-review P1, #525).
|
|
170
|
+
results = sdk.tortoise_fts_query(query=q, limit=limit)
|
|
171
|
+
return [_point_out(r) if isinstance(r, dict) else r for r in results]
|
|
172
|
+
except Exception as e: # noqa: BLE001
|
|
173
|
+
_logger.exception("selfhost search failed")
|
|
174
|
+
# Defensive CONTAINS fallback (FTS genuinely unavailable).
|
|
175
|
+
try:
|
|
176
|
+
proj = sdk._get_proj()
|
|
177
|
+
query = (
|
|
178
|
+
"MATCH (n:Point) WHERE (n.is_operator IS NULL OR n.is_operator = false) "
|
|
179
|
+
"AND toLower(n.content) CONTAINS toLower($q) "
|
|
180
|
+
"RETURN properties(n) ORDER BY n.createdAt DESC LIMIT $limit"
|
|
181
|
+
)
|
|
182
|
+
rows = proj.g.query(query, params={"q": q, "limit": limit}).result_set
|
|
183
|
+
return [_point_out(dict(r[0])) for r in rows]
|
|
184
|
+
except Exception as e2: # noqa: BLE001
|
|
185
|
+
_logger.exception("selfhost search fallback failed")
|
|
186
|
+
raise HTTPException(status_code=500, detail="Internal error") from e2
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
@router.post("/dream", dependencies=[Depends(_require_key)])
|
|
190
|
+
async def dream(full: bool = False):
|
|
191
|
+
"""Trigger EP stabilization (registry: POST /v1/dream).
|
|
192
|
+
|
|
193
|
+
Incremental (default) or full=True whole-graph. Mirrors hosted_api.
|
|
194
|
+
"""
|
|
195
|
+
sdk = _sdk()
|
|
196
|
+
try:
|
|
197
|
+
result = sdk.dream(full=full) if full else sdk.dream(dirty_only=True)
|
|
198
|
+
return {"status": "ok", "result": result}
|
|
199
|
+
except Exception as e: # noqa: BLE001
|
|
200
|
+
_logger.exception("selfhost dream failed")
|
|
201
|
+
raise HTTPException(status_code=500, detail="Internal error")
|