intentdataflow 0.3.10__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.
Files changed (83) hide show
  1. intentdataflow-0.3.10.dist-info/METADATA +191 -0
  2. intentdataflow-0.3.10.dist-info/RECORD +83 -0
  3. intentdataflow-0.3.10.dist-info/WHEEL +5 -0
  4. intentdataflow-0.3.10.dist-info/entry_points.txt +2 -0
  5. intentdataflow-0.3.10.dist-info/licenses/LICENSE +202 -0
  6. intentdataflow-0.3.10.dist-info/licenses/NOTICE +4 -0
  7. intentdataflow-0.3.10.dist-info/top_level.txt +1 -0
  8. intentflow/__init__.py +2 -0
  9. intentflow/auth.py +30 -0
  10. intentflow/business_rules.py +77 -0
  11. intentflow/catalogs.py +100 -0
  12. intentflow/change_review.py +331 -0
  13. intentflow/checks/__init__.py +92 -0
  14. intentflow/checks/airflow3.py +174 -0
  15. intentflow/checks/business.py +27 -0
  16. intentflow/checks/catalog.py +43 -0
  17. intentflow/checks/cluster.py +81 -0
  18. intentflow/checks/contracts.py +79 -0
  19. intentflow/checks/cost.py +35 -0
  20. intentflow/checks/dbt_quality.py +90 -0
  21. intentflow/checks/dbt_run.py +83 -0
  22. intentflow/checks/deep.py +180 -0
  23. intentflow/checks/dq.py +53 -0
  24. intentflow/checks/elementary.py +50 -0
  25. intentflow/checks/external.py +91 -0
  26. intentflow/checks/lakehouse.py +46 -0
  27. intentflow/checks/lint.py +81 -0
  28. intentflow/checks/orchestration.py +148 -0
  29. intentflow/checks/probes.py +66 -0
  30. intentflow/checks/runtime_history.py +94 -0
  31. intentflow/checks/schema_drift.py +92 -0
  32. intentflow/checks/sql_quality.py +274 -0
  33. intentflow/checks/streaming.py +62 -0
  34. intentflow/cli.py +914 -0
  35. intentflow/contracts.py +107 -0
  36. intentflow/datadiff.py +172 -0
  37. intentflow/dbt_loader.py +194 -0
  38. intentflow/dbt_results.py +55 -0
  39. intentflow/dq_results.py +108 -0
  40. intentflow/extensions.py +51 -0
  41. intentflow/external.py +381 -0
  42. intentflow/http_utils.py +89 -0
  43. intentflow/i18n.py +76 -0
  44. intentflow/incidents.py +83 -0
  45. intentflow/integrations.py +139 -0
  46. intentflow/lakehouse.py +62 -0
  47. intentflow/lineage.py +336 -0
  48. intentflow/lineage_api.py +244 -0
  49. intentflow/lineage_oracle.py +374 -0
  50. intentflow/locale/pt.json +1300 -0
  51. intentflow/model.py +43 -0
  52. intentflow/monitoring.py +197 -0
  53. intentflow/notify.py +154 -0
  54. intentflow/ol_emit.py +93 -0
  55. intentflow/openlineage.py +168 -0
  56. intentflow/orchestrators/__init__.py +53 -0
  57. intentflow/orchestrators/airflow.py +69 -0
  58. intentflow/orchestrators/aws.py +93 -0
  59. intentflow/orchestrators/dagster.py +48 -0
  60. intentflow/orchestrators/dbtcloud.py +68 -0
  61. intentflow/orchestrators/extra.py +135 -0
  62. intentflow/orchestrators/ingestion.py +112 -0
  63. intentflow/orchestrators/kestra.py +27 -0
  64. intentflow/orchestrators/more.py +135 -0
  65. intentflow/orchestrators/prefect.py +53 -0
  66. intentflow/orchestrators/spark.py +118 -0
  67. intentflow/otel.py +53 -0
  68. intentflow/overview.py +123 -0
  69. intentflow/preflight.py +363 -0
  70. intentflow/promexport.py +39 -0
  71. intentflow/pyflow.py +554 -0
  72. intentflow/risks.py +178 -0
  73. intentflow/runner.py +264 -0
  74. intentflow/secrets_box.py +84 -0
  75. intentflow/sqlmesh_loader.py +134 -0
  76. intentflow/store.py +1006 -0
  77. intentflow/streaming.py +115 -0
  78. intentflow/totp.py +38 -0
  79. intentflow/warehouses/__init__.py +190 -0
  80. intentflow/warehouses/cloud.py +160 -0
  81. intentflow/warehouses/more.py +342 -0
  82. intentflow/web.html +878 -0
  83. intentflow/web.py +726 -0
intentflow/web.py ADDED
@@ -0,0 +1,726 @@
1
+ """Local or team UI/API. Security: allowed Host, anti-CSRF header, HttpOnly/SameSite cookies, roles, optional MFA (TOTP),
2
+ persistent login rate limit, TLS. Extensions (see `extensions`) add SSO, per-project roles, governed fixes and AI."""
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import secrets
8
+ import threading
9
+ import time
10
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
11
+ from pathlib import Path
12
+ from urllib.parse import parse_qsl, urlparse
13
+
14
+ from . import auth, extensions, i18n, lineage_api, overview, runner, totp
15
+ from .i18n import tr
16
+ from .store import Store
17
+ from .http_utils import RequestError, read_body
18
+
19
+ PAGE_FILE = Path(__file__).parent / "web.html"
20
+ DEFAULT_PROJECT = "main"
21
+ ThreadingHTTPServer.request_queue_size = 256 # preserve the larger accept backlog for embedded/test servers too
22
+
23
+
24
+ class BoundedThreadingHTTPServer(ThreadingHTTPServer):
25
+ """Thread-per-request HTTP server with a hard cap on concurrent handlers."""
26
+
27
+ daemon_threads = True
28
+ request_queue_size = 256
29
+
30
+ def __init__(self, server_address, RequestHandlerClass, max_workers: int = 128):
31
+ if not 1 <= max_workers <= 1024:
32
+ raise ValueError("max_workers must be between 1 and 1024")
33
+ self._request_slots = threading.BoundedSemaphore(max_workers)
34
+ super().__init__(server_address, RequestHandlerClass)
35
+
36
+ def process_request(self, request, client_address):
37
+ # Close excess connections instead of spawning unbounded threads or blocking the accept loop.
38
+ if not self._request_slots.acquire(blocking=False):
39
+ self.shutdown_request(request)
40
+ return
41
+ worker = threading.Thread(target=self.process_request_thread, args=(request, client_address), daemon=True)
42
+ try:
43
+ worker.start()
44
+ except Exception:
45
+ self._request_slots.release()
46
+ self.handle_error(request, client_address)
47
+ self.shutdown_request(request)
48
+
49
+ def process_request_thread(self, request, client_address):
50
+ try:
51
+ super().process_request_thread(request, client_address)
52
+ finally:
53
+ self._request_slots.release()
54
+
55
+
56
+ class _Handled(Exception):
57
+ """The response (401/403/...) was already sent."""
58
+
59
+
60
+ SAFE_SETTING_PREFIXES = ("policy.", "scan.", "watch.", "lineage.", "dbt.") # tuning a project admin may change...
61
+ # ...except paths the server will read from (an admin of one project could point them at another project's files) and
62
+ # security policy that applies to everyone.
63
+ GLOBAL_ONLY_SETTINGS = {"dbt.root", "dbt.target", "dbt.base_target", "dbt.base_root", "dbt.base_revision", "lineage.declared",
64
+ "policy.separate_approver", "policy.token_max_age_days"}
65
+
66
+
67
+ def _redact_dsn(spec) -> str:
68
+ """Registry values may be PostgreSQL DSNs with a password: in the authority part and/or in query parameters
69
+ (`?password=`, `sslpassword=`), or libpq key=value form."""
70
+ import re
71
+ from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
72
+ text = str(spec)
73
+ # password up to the LAST "@" (an unescaped "/" or "@" in it must not end the redaction early)
74
+ text = re.sub(r"(://[^:/@\s]+):\S*@(?=[^@\s]*$)", r"\1:***@", text)
75
+ if "://" in text:
76
+ try:
77
+ u = urlsplit(text)
78
+ netloc = u.netloc
79
+ if "@" in netloc:
80
+ cred, host = netloc.rsplit("@", 1)
81
+ netloc = (cred.split(":", 1)[0] + ":***@" if ":" in cred else cred + "@") + host
82
+ qs = [(k, "***" if "pass" in k.lower() or "secret" in k.lower() else v) for k, v in parse_qsl(u.query, keep_blank_values=True)]
83
+ return urlunsplit((u.scheme, netloc, u.path, urlencode(qs, safe="*"), u.fragment))
84
+ except ValueError:
85
+ pass
86
+ return re.sub(r"((?:pass\w*|secret\w*)\s*=\s*)\S+", r"\1***", text, flags=re.I)
87
+
88
+
89
+ def scope_ok(who: dict, project: str, finding: dict | None, role: str | None) -> bool:
90
+ """Write scope: if the person has patterns for the project, they only act on findings whose file/nodes match one."""
91
+ if role == "admin":
92
+ return True
93
+ pats = (who.get("scopes") or {}).get(project)
94
+ if not pats:
95
+ return True
96
+ if finding is None:
97
+ return False
98
+ import fnmatch
99
+ cands = [finding.get("evidence", {}).get("file")] if finding.get("evidence", {}).get("file") else []
100
+ cands += [n.split(".")[-1] for n in finding.get("nodes", [])] + list(finding.get("nodes", []))
101
+ return any(fnmatch.fnmatch(c, p) for c in cands if c for p in pats)
102
+
103
+
104
+ def cookie(header: str, name: str) -> str | None:
105
+ for part in (header or "").split(";"):
106
+ k, _, v = part.strip().partition("=")
107
+ if k == name:
108
+ return v
109
+ return None
110
+
111
+
112
+ def make_handler(store_path: str, user: str = "local", token: str | None = None, **ext_opts):
113
+ """`token`/INTENTFLOW_UI_TOKEN (legacy): a single admin token, only without users. `ext_opts`: passed to extensions (tests)."""
114
+ legacy = token if token is not None else os.environ.get("INTENTFLOW_UI_TOKEN")
115
+ try:
116
+ api_rate = int(os.environ.get("INTENTFLOW_API_RATE_PER_MIN", "600")) # per client IP; 0 disables
117
+ except ValueError:
118
+ api_rate = 600
119
+ hits: dict[str, list] = {}
120
+ hits_lock = threading.Lock()
121
+
122
+ class H(BaseHTTPRequestHandler):
123
+ options = ext_opts
124
+ primary_store = store_path
125
+
126
+ def setup(self):
127
+ self.request.settimeout(15)
128
+ if hasattr(self.request, "do_handshake"): # TLS handshake in the worker thread, bounded by the timeout: never in accept()
129
+ self.request.do_handshake()
130
+ self._request_stores = {}
131
+ super().setup()
132
+
133
+ def _store(self, path):
134
+ if path not in self._request_stores:
135
+ self._request_stores[path] = Store(path)
136
+ return self._request_stores[path]
137
+
138
+ def finish(self):
139
+ try:
140
+ super().finish()
141
+ finally:
142
+ for store in self._request_stores.values():
143
+ store.close()
144
+
145
+ def _rate_ok(self) -> bool:
146
+ """Sliding one-minute window per client IP over /api/*. In memory, per process. Loopback is exempt (local mode,
147
+ or a same-host proxy without INTENTFLOW_TRUSTED_PROXIES where every client would share one IP)."""
148
+ if api_rate <= 0 or not urlparse(self.path).path.startswith("/api/"): # same parse as the router (absolute-form targets)
149
+ return True
150
+ now, ip = time.time(), self._client_ip()
151
+ if ip in ("127.0.0.1", "::1", "::ffff:127.0.0.1"):
152
+ return True
153
+ with hits_lock:
154
+ if len(hits) > 10000: # bound memory: drop idle clients
155
+ for k in [k for k, v in hits.items() if not v or v[-1] < now - 60]:
156
+ del hits[k]
157
+ q = [t for t in hits.get(ip, ()) if t > now - 60]
158
+ ok = len(q) < api_rate
159
+ if ok:
160
+ q.append(now)
161
+ hits[ip] = q
162
+ if not ok:
163
+ self.close_connection = True # a POST body may be unread
164
+ self._json(429, {"error": tr("too many requests; slow down")})
165
+ return ok
166
+
167
+ def log_message(self, *a):
168
+ pass
169
+
170
+ def log_request(self, code="-", size="-"):
171
+ from .http_utils import access_log
172
+ access_log(self, code)
173
+
174
+ def cookie_key(self) -> bytes:
175
+ st = self._store(store_path)
176
+ k = st.get_setting("state.cookie_key")
177
+ if not k:
178
+ k = secrets.token_hex(32)
179
+ st.set_setting("state.cookie_key", k)
180
+ return bytes.fromhex(k)
181
+
182
+ # ---- responses ----
183
+ def _send(self, code, body, ctype="application/json", cookies=(), location=None, nonce=None):
184
+ b = body.encode() if isinstance(body, str) else body
185
+ self.send_response(code)
186
+ if nonce:
187
+ self.send_header("Content-Security-Policy", f"default-src 'self'; script-src 'nonce-{nonce}'; style-src 'self' 'unsafe-inline'; "
188
+ "img-src 'self' data:; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'self'")
189
+ if self._secure_cookie():
190
+ self.send_header("Strict-Transport-Security", "max-age=31536000")
191
+ self.send_header("Content-Type", ctype + "; charset=utf-8")
192
+ self.send_header("Content-Length", str(len(b)))
193
+ self.send_header("Cache-Control", "no-store")
194
+ self.send_header("X-Content-Type-Options", "nosniff")
195
+ self.send_header("X-Frame-Options", "SAMEORIGIN")
196
+ self.send_header("Referrer-Policy", "no-referrer")
197
+ if location:
198
+ self.send_header("Location", location)
199
+ for c in cookies:
200
+ self.send_header("Set-Cookie", c)
201
+ self.end_headers()
202
+ self.wfile.write(b)
203
+
204
+ def _json(self, code, obj, cookies=()):
205
+ self._send(code, json.dumps(obj, default=str), cookies=cookies)
206
+
207
+ def _host_ok(self):
208
+ h = (self.headers.get("Host") or "").rsplit(":", 1)[0]
209
+ allow = os.environ.get("INTENTFLOW_ALLOWED_HOSTS", "")
210
+ return h in ("127.0.0.1", "localhost") or h in [x.strip() for x in allow.split(",") if x.strip()]
211
+
212
+ def _secure_cookie(self):
213
+ return "; Secure" if getattr(self.server, "scheme", "http") == "https" or self.headers.get("X-Forwarded-Proto") == "https" else ""
214
+
215
+ def _legacy_sid(self) -> str:
216
+ """The cookie never carries the legacy token itself: an HMAC of it with the server's cookie key."""
217
+ import hmac, hashlib
218
+ return "ifl_" + hmac.new(self.cookie_key(), legacy.encode(), hashlib.sha256).hexdigest()
219
+
220
+ def session_cookie(self, sid: str) -> str:
221
+ return f"if_session={sid}; HttpOnly; SameSite=Strict; Path=/{self._secure_cookie()}"
222
+
223
+ # ---- identity ----
224
+ def _identity(self, prim: Store):
225
+ sid = cookie(self.headers.get("Cookie", ""), "if_session")
226
+ bearer = (self.headers.get("Authorization") or "")
227
+ bearer = bearer[7:] if bearer.startswith("Bearer ") else None
228
+ if prim.has_users():
229
+ if sid and sid.startswith("ifs_"):
230
+ u = prim.user_by_session(sid)
231
+ if u and u.get("via") == "sso" and not extensions.first("refresh_session", self, prim, sid, u["name"]):
232
+ return None # SSO session without the extension that issued it, or refused by the provider
233
+ return prim.user_by_session(sid) if u else None
234
+ if bearer:
235
+ u = prim.user_by_token(bearer)
236
+ return None if (u and u.get("mfa")) else u # a bare token is not enough once MFA is on
237
+ return None
238
+ if legacy:
239
+ import hmac
240
+ ok = (sid is not None and hmac.compare_digest(sid.encode(), self._legacy_sid().encode())) or \
241
+ (bearer is not None and hmac.compare_digest(bearer.encode(), legacy.encode()))
242
+ return {"name": "token-admin", "role": "admin", "project_roles": {}} if ok else None
243
+ return {"name": user, "role": "admin", "project_roles": {}}
244
+
245
+ def _project(self) -> str:
246
+ q = dict(parse_qsl(urlparse(self.path).query))
247
+ return self.headers.get("X-IntentFlow-Project") or q.get("project") or DEFAULT_PROJECT
248
+
249
+ def _stores(self, prim: Store):
250
+ reg = (prim.get_setting("projects", {}) or {}) if "projects" in extensions.features() else {}
251
+ return {DEFAULT_PROJECT: store_path, **reg}
252
+
253
+ def _data(self, prim: Store, who) -> Store:
254
+ proj = self._project()
255
+ reg = self._stores(prim)
256
+ if proj not in reg:
257
+ self._json(404, {"error": tr("project '{name}' does not exist", name=proj)})
258
+ raise _Handled()
259
+ if auth.role_in(who, proj) in (None, "none"):
260
+ self._json(403, {"error": tr("no access to this project")})
261
+ raise _Handled()
262
+ return prim if reg[proj] == store_path else self._store(reg[proj])
263
+
264
+ def _need(self, prim: Store, action: str):
265
+ who = self._identity(prim)
266
+ if who is None:
267
+ self._json(401, {"error": tr("authentication required"), "login": True})
268
+ raise _Handled()
269
+ role = auth.role_in(who, self._project())
270
+ if not auth.allowed(role, action):
271
+ self._json(403, {"error": tr("your role ({role}) does not allow this action", role=role)})
272
+ raise _Handled()
273
+ return who
274
+
275
+ def _global_admin(self, prim: Store):
276
+ who = self._identity(prim)
277
+ if who is None:
278
+ self._json(401, {"error": tr("authentication required")})
279
+ raise _Handled()
280
+ if auth.role_in({**who, "project_roles": {}}, None) != "admin":
281
+ self._json(403, {"error": tr("global admin only")})
282
+ raise _Handled()
283
+ return who
284
+
285
+ def _lang(self):
286
+ i18n.set_request_lang(self.headers.get("X-IntentFlow-Lang"))
287
+
288
+ def _page(self, q: dict) -> str:
289
+ """The UI with its message catalog inlined: `?lang=`, then the `if_lang` cookie, then Accept-Language."""
290
+ pick = q.get("lang") or cookie(self.headers.get("Cookie", ""), "if_lang") or (self.headers.get("Accept-Language") or "")[:2]
291
+ code = i18n.normalize(pick)
292
+ data = json.dumps({"lang": code, "messages": i18n.catalog(code) if code != "en" else {}}, ensure_ascii=False)
293
+ page = PAGE_FILE.read_text().replace('/*I18N*/{"lang":"en","messages":{}}', data.replace("</", "<\\/"), 1)
294
+ return page.replace("<script>", f'<script nonce="{self._nonce}">')
295
+
296
+ # ---- GET ----
297
+ def do_GET(self):
298
+ self._lang()
299
+ if not self._host_ok():
300
+ return self._send(403, "forbidden host", "text/plain")
301
+ if not self._rate_ok():
302
+ return
303
+ u = urlparse(self.path)
304
+ path, q = u.path, dict(parse_qsl(u.query))
305
+ prim = self._store(store_path)
306
+ try:
307
+ if extensions.first("web_get", self, prim, path, q):
308
+ return
309
+ if path == "/" and "token" in q:
310
+ return self._send(401, tr("URL token login is disabled; use the login form"), "text/plain")
311
+ if path == "/":
312
+ self._nonce = secrets.token_urlsafe(16)
313
+ return self._send(200, self._page(q), "text/html", nonce=self._nonce)
314
+ if path == "/api/i18n":
315
+ code = i18n.normalize(q.get("lang"))
316
+ return self._json(200, {"lang": code, "messages": i18n.catalog(code) if code != "en" else {}})
317
+ if path == "/api/me":
318
+ who = self._identity(prim)
319
+ reg = self._stores(prim)
320
+ projs = [{"name": n, "role": auth.role_in(who, n)} for n in reg if who and auth.role_in(who, n) not in (None, "none")]
321
+ out = {"user": ({k: who[k] for k in ("name", "role", "mfa", "via") if k in who} if who else None),
322
+ "auth_required": prim.has_users() or legacy is not None, "team": prim.has_users(), "sso": False,
323
+ "projects": projs, "default_project": DEFAULT_PROJECT, "features": extensions.features()}
324
+ out.update(extensions.first("me", self, prim, who) or {})
325
+ return self._json(200, out)
326
+ mtok = os.environ.get("INTENTFLOW_METRICS_TOKEN")
327
+ bearer = (self.headers.get("Authorization") or "").removeprefix("Bearer ")
328
+ if path == "/metrics" and mtok and secrets.compare_digest(bearer.encode(), mtok.encode()):
329
+ from . import promexport
330
+ return self._send(200, promexport.render(prim), "text/plain; version=0.0.4") # main project only
331
+ self._need(prim, "read")
332
+ who = self._identity(prim)
333
+ st = self._data(prim, who)
334
+ if path == "/metrics":
335
+ from . import promexport
336
+ return self._send(200, promexport.render(st), "text/plain; version=0.0.4")
337
+ if path == "/api/team":
338
+ return self._json(200, {"team": [x["name"] for x in prim.users() if not x["disabled"]]})
339
+ if path == "/api/users":
340
+ if auth.role_in(who, None) != "admin":
341
+ return self._json(403, {"error": tr("global admin only")})
342
+ return self._json(200, {"users": prim.users_admin(), "projects": list(self._stores(prim))})
343
+ if path == "/api/projects":
344
+ return self._json(200, {"projects": {n: _redact_dsn(p) for n, p in self._stores(prim).items()}} if auth.allowed(auth.role_in(who, None), "users") else
345
+ {"projects": {n: "" for n in self._stores(prim) if auth.role_in(who, n) not in (None, "none")}})
346
+ if path.startswith("/api/notes/"):
347
+ return self._json(200, {"notes": st.notes(path.rsplit("/", 1)[1])})
348
+ if path.startswith("/api/lineage/"):
349
+ return self._lineage(st, path, q)
350
+ if path == "/api/changes":
351
+ from . import change_review
352
+ target, base = st.get_setting("dbt.target"), st.get_setting("dbt.base_target")
353
+ if not target or not base:
354
+ return self._json(400, {"error": tr("change comparison requires candidate and baseline targets")})
355
+ try:
356
+ return self._json(200, change_review.acknowledge(change_review.load(target, base, baseline_revision=st.get_setting("dbt.base_revision"))))
357
+ except ValueError as e:
358
+ return self._json(400, {"error": str(e)})
359
+ if path == "/api/rules":
360
+ from . import business_rules, dbt_loader, dbt_results
361
+ target = st.get_setting("dbt.target")
362
+ if not target:
363
+ return self._json(400, {"error": tr("configure dbt.target")})
364
+ try:
365
+ project = dbt_loader.load(target, st.get_setting("dbt.root") or Path(target).parent)
366
+ return self._json(200, business_rules.build(project, dbt_results.load(target), st))
367
+ except (ValueError, OSError, KeyError) as e:
368
+ return self._json(400, {"error": str(e)})
369
+ if path == "/api/settings":
370
+ vis = {k: v for k, v in st.settings().items()
371
+ if k != "projects" and not k.startswith(("state.", "secret.", "sso."))}
372
+ return self._json(200, {"settings": vis, "last_check": st.get_setting("state.last_check"), "running": st.get_setting("state.running"),
373
+ "store_backend": st.backend})
374
+ if path == "/api/integrations":
375
+ from . import integrations
376
+ return self._json(200, integrations.build(st))
377
+ if path == "/api/overview":
378
+ return self._json(200, overview.build_cached(st) if st.path != ":memory:" else overview.build(st))
379
+ self._json(404, {"error": "not found"})
380
+ except _Handled:
381
+ return
382
+
383
+ def _lineage(self, st: Store, path: str, q: dict):
384
+ target = st.get_setting("dbt.target")
385
+ if not target:
386
+ return self._json(400, {"error": tr("configure dbt.target")})
387
+ try:
388
+ proj, res = lineage_api.load(target, st.get_setting("dbt.root"), cache=st)
389
+ what = path.rsplit("/", 1)[1]
390
+ depth = max(1, min(6, int(q.get("depth", 3))))
391
+ if what == "models":
392
+ out = lineage_api.models(proj, st.findings("open"), bool(st.get_setting("scan.include_packages")))
393
+ elif what == "model":
394
+ d = lineage_api.model_detail(proj, q.get("model", ""))
395
+ if not d:
396
+ raise ValueError(tr("model not found"))
397
+ out = {**d, "graph": lineage_api.model_graph(proj, q["model"], min(depth, 3))}
398
+ elif what == "column":
399
+ from . import external
400
+ declared = st.get_setting("lineage.declared") or str(Path(st.get_setting("dbt.root") or Path(target).parent) / external.DECLARED_FILE)
401
+ out = {"graph": lineage_api.column_graph(proj, res, q.get("model", ""), q.get("column", ""), depth),
402
+ "impact": lineage_api.impact(proj, res, q.get("model", ""), q.get("column", ""),
403
+ external=external.load(st, declared, proj))}
404
+ elif what == "diff":
405
+ base = st.get_setting("dbt.base_target")
406
+ if not base:
407
+ raise ValueError(tr("configure dbt.base_target (the previous version) to compare lineage"))
408
+ out = lineage_api.diff(lineage_api.load(base, st.get_setting("dbt.base_root"), cache=st), (proj, res))
409
+ else:
410
+ raise ValueError(tr("unknown route"))
411
+ return self._json(200, out)
412
+ except (ValueError, KeyError, FileNotFoundError) as e:
413
+ return self._json(400, {"error": str(e)})
414
+
415
+ def _drain(self) -> None:
416
+ """After refusing a request without reading its body: closing with unread bytes makes the kernel reset the connection and
417
+ the client may lose the response. Read what is already queued, bounded in bytes and total time (a client that keeps
418
+ sending must not keep this thread)."""
419
+ deadline, left = time.monotonic() + 0.5, 256 * 1024
420
+ try:
421
+ while left > 0 and time.monotonic() < deadline:
422
+ self.connection.settimeout(max(0.01, deadline - time.monotonic()))
423
+ chunk = self.connection.recv(min(65536, left))
424
+ if not chunk:
425
+ break
426
+ left -= len(chunk)
427
+ except OSError:
428
+ pass
429
+
430
+ def _client_ip(self) -> str:
431
+ peer = self.client_address[0]
432
+ trusted = [x.strip() for x in os.environ.get("INTENTFLOW_TRUSTED_PROXIES", "").split(",") if x.strip()]
433
+ if peer in trusted:
434
+ xff = self.headers.get("X-Forwarded-For", "")
435
+ # proxies append to the header, so the first hop is client-controlled: take the right-most hop that is not a trusted proxy
436
+ hops = [h.strip() for h in xff.split(",") if h.strip()]
437
+ for hop in reversed(hops):
438
+ if hop not in trusted:
439
+ return hop
440
+ return peer
441
+
442
+ # ---- POST ----
443
+ def do_POST(self):
444
+ self.prefetched_body = None
445
+ self._lang()
446
+ if not self._host_ok():
447
+ return self._send(403, "forbidden host", "text/plain")
448
+ if not self._rate_ok():
449
+ return
450
+ u = urlparse(self.path)
451
+ query = dict(parse_qsl(u.query))
452
+ parts = u.path.strip("/").split("/")
453
+ try:
454
+ self.prefetched_body = read_body(self) # before taking a database connection: a slow client must not hold a pool slot
455
+ except RequestError as e:
456
+ self.close_connection = True
457
+ self._json(e.status, {"error": str(e)})
458
+ return self._drain()
459
+ prim = self._store(store_path)
460
+ try:
461
+ if extensions.first("web_post_raw", self, prim, parts): # provider callbacks without the anti-CSRF header
462
+ return
463
+ except _Handled:
464
+ return
465
+ if self.headers.get("X-IntentFlow") != "1":
466
+ return self._json(400, {"error": "missing X-IntentFlow header"})
467
+ try:
468
+ body = json.loads(read_body(self) or b"{}")
469
+ if not isinstance(body, dict):
470
+ raise ValueError(tr("the JSON body must be an object"))
471
+ except (ValueError, UnicodeDecodeError) as e:
472
+ self.close_connection = True
473
+ return self._json(e.status if isinstance(e, RequestError) else 400, {"error": tr("invalid request") if not isinstance(e, RequestError) else str(e)})
474
+ try:
475
+ if extensions.first("web_post", self, prim, parts, body, query):
476
+ return
477
+ if parts == ["api", "login"]:
478
+ return self._login(prim, body)
479
+ if parts == ["api", "logout"]:
480
+ sid = cookie(self.headers.get("Cookie", ""), "if_session")
481
+ out = {"ok": True}
482
+ if sid:
483
+ info = prim.session_info(sid)
484
+ if info and info["via"] == "sso":
485
+ out["logout_url"] = extensions.first("logout_url", self, prim, info)
486
+ prim.end_session(sid)
487
+ return self._json(200, out, cookies=["if_session=; Max-Age=0; HttpOnly; SameSite=Strict; Path=/"])
488
+ if parts == ["api", "mfa"]:
489
+ return self._mfa(prim, body)
490
+ if parts == ["api", "users"]:
491
+ return self._users(prim, body)
492
+ if parts == ["api", "settings"]:
493
+ who = self._need(prim, "settings")
494
+ st = self._data(prim, who)
495
+ key = str(body.get("key", "")).strip()
496
+ # llm.*/jev.* go through their own endpoint, which checks who may point the server at a custom AI endpoint
497
+ if not key or key == "projects" or key.startswith(("state.", "secret.", "sso.", "llm.", "jev.")):
498
+ raise ValueError(tr("invalid key"))
499
+ # Connection/path keys (notify.sinks, dbt.root, lineage.declared, *.url, *_env ...) make the server reach hosts, read paths or send
500
+ # environment secrets: only a global admin, never someone who is admin of just one project.
501
+ if (not key.startswith(SAFE_SETTING_PREFIXES) or key in GLOBAL_ONLY_SETTINGS) and auth.role_in({**who, "project_roles": {}}, None) != "admin":
502
+ return self._json(403, {"error": tr("global admin only")})
503
+ if body.get("value") in (None, ""):
504
+ st.unset_setting(key)
505
+ else:
506
+ v = body["value"]
507
+ if key == "policy.pii_allowed_models" and isinstance(v, str):
508
+ v = [x.strip() for x in v.split(",") if x.strip()]
509
+ st.set_setting(key, v)
510
+ st.audit(who["name"], "config_set", {"key": key})
511
+ return self._json(200, {"ok": True})
512
+ if parts == ["api", "diff"]:
513
+ return self._diff(prim, body)
514
+ if parts == ["api", "run", "check"] or parts == ["api", "run", "runs"]:
515
+ return self._run(prim, parts[2])
516
+ if parts[:2] == ["api", "findings"] and len(parts) == 4:
517
+ return self._finding_action(prim, parts[2], parts[3], body)
518
+ self._json(404, {"error": "not found"})
519
+ except _Handled:
520
+ return
521
+ except ValueError as e:
522
+ self._json(400, {"error": str(e)})
523
+
524
+ def _login(self, prim: Store, body: dict):
525
+ ip = self._client_ip()
526
+ if prim.attempts_recent(ip) >= 10:
527
+ return self._json(429, {"error": tr("too many attempts; wait 1 minute")})
528
+ tok = str(body.get("token", ""))
529
+ if prim.has_users():
530
+ who = prim.user_by_token(tok)
531
+ if not who:
532
+ prim.attempt_failed(ip)
533
+ return self._json(401, {"error": tr("invalid token")})
534
+ if who.get("mfa"):
535
+ code = str(body.get("code", ""))
536
+ if not code:
537
+ return self._json(401, {"error": tr("enter the authenticator code"), "mfa_required": True})
538
+ if not (prim.mfa_check(who["name"], code) or prim.mfa_use_recovery(who["name"], code)):
539
+ prim.attempt_failed(ip)
540
+ return self._json(401, {"error": tr("invalid code"), "mfa_required": True})
541
+ sid = prim.create_session(who["name"], "token")
542
+ prim.audit(who["name"], "login", {"via": "token", "mfa": bool(who.get("mfa"))})
543
+ return self._json(200, {"user": {"name": who["name"], "role": who["role"]}}, cookies=[self.session_cookie(sid)])
544
+ import hmac
545
+ if legacy and hmac.compare_digest(tok.encode(), legacy.encode()):
546
+ prim.audit("token-admin", "login", {"via": "legacy_token"})
547
+ return self._json(200, {"user": {"name": "token-admin", "role": "admin"}}, cookies=[self.session_cookie(self._legacy_sid())])
548
+ prim.attempt_failed(ip)
549
+ return self._json(401, {"error": tr("invalid token")})
550
+
551
+ def _mfa(self, prim: Store, body: dict):
552
+ """MFA for the person themself; an admin may disable it for others."""
553
+ who = self._identity(prim)
554
+ if who is None or not prim.has_users():
555
+ return self._json(401, {"error": tr("authentication required")})
556
+ act = body.get("action")
557
+ target = str(body.get("name") or who["name"])
558
+ if act == "begin" and target == who["name"]:
559
+ secret = prim.mfa_begin(who["name"])
560
+ return self._json(200, {"secret": secret, "uri": totp.uri(secret, who["name"])})
561
+ if act == "confirm" and target == who["name"]:
562
+ if not prim.mfa_confirm(who["name"], str(body.get("code", ""))):
563
+ return self._json(400, {"error": tr("invalid code")})
564
+ prim.audit(who["name"], "mfa_enabled", {})
565
+ return self._json(200, {"ok": True, "recovery_codes": prim.mfa_recovery_codes(who["name"]),
566
+ "note": tr("keep these codes: each works once and they are not shown again")})
567
+ if act == "recovery" and target == who["name"]:
568
+ if not prim.mfa_check(who["name"], str(body.get("code", ""))):
569
+ return self._json(400, {"error": tr("enter the current authenticator code")})
570
+ prim.audit(who["name"], "mfa_recovery_regenerated", {})
571
+ return self._json(200, {"recovery_codes": prim.mfa_recovery_codes(who["name"])})
572
+ if act == "disable":
573
+ if target != who["name"] and who["role"] != "admin":
574
+ return self._json(403, {"error": tr("only an admin can disable someone else's MFA")})
575
+ if target == who["name"] and not prim.mfa_check(who["name"], str(body.get("code", ""))):
576
+ return self._json(400, {"error": tr("enter the current code to disable")})
577
+ prim.mfa_disable(target)
578
+ prim.audit(who["name"], "mfa_disabled", {"user": target})
579
+ return self._json(200, {"ok": True})
580
+ return self._json(400, {"error": tr("invalid action")})
581
+
582
+ def _users(self, prim: Store, body: dict):
583
+ """Global administration of people: admin on the main project."""
584
+ who = self._global_admin(prim)
585
+ actor, action, name = who["name"], body.get("action"), str(body.get("name", ""))
586
+ if action == "add":
587
+ t = prim.add_user(name, str(body.get("role", "viewer")), expires_days=float(body["expires_days"]) if body.get("expires_days") else
588
+ (float(prim.get_setting("policy.token_max_age_days")) if prim.get_setting("policy.token_max_age_days") else None))
589
+ prim.audit(actor, "user_add", {"name": name, "role": body.get("role")})
590
+ return self._json(200, {"token": t, "note": tr("save it now: the token is not shown again")})
591
+ if action == "rotate":
592
+ t = prim.rotate_token(name)
593
+ prim.audit(actor, "user_rotate", {"name": name})
594
+ return self._json(200, {"token": t})
595
+ if action in ("disable", "enable", "role"):
596
+ admins = [x for x in prim.users() if x["role"] == "admin" and not x["disabled"] and x["name"] != name]
597
+ if (action == "disable" or (action == "role" and body.get("role") != "admin")) and not admins:
598
+ raise ValueError(tr("cannot remove the last active admin"))
599
+ prim.set_user(name, role=body.get("role") if action == "role" else None,
600
+ disabled=(action == "disable") if action in ("disable", "enable") else None)
601
+ prim.audit(actor, "user_" + action, {"name": name})
602
+ return self._json(200, {"ok": True})
603
+ raise ValueError(tr("unknown action"))
604
+
605
+ def _diff(self, prim: Store, body: dict):
606
+ who = self._need(prim, "diff")
607
+ if not scope_ok(who, self._project(), None, auth.role_in(who, self._project())):
608
+ return self._json(403, {"error": tr("this action is outside your scope (allowed folders/models)")}) # samples rows of any relation
609
+ st = self._data(prim, who)
610
+ from . import datadiff, warehouses
611
+ if not (st.get_setting("warehouse.type") or st.get_setting("warehouse.duckdb") or st.get_setting("warehouse.postgres_env")):
612
+ raise ValueError(tr("configure the warehouse (warehouse.type, warehouse.duckdb or warehouse.postgres_env) in Settings"))
613
+ key = [k.strip() for k in str(body.get("key", "")).split(",") if k.strip()]
614
+ if not (body.get("base") and body.get("head") and key):
615
+ raise ValueError(tr("enter the base relation, the new relation and the key"))
616
+ wh = warehouses.connect(st.get_setting)
617
+ try:
618
+ res = datadiff.diff_relations(wh, str(body["base"]), str(body["head"]), key, int(body.get("sample", 5)),
619
+ sample_pct=float(body["sample_pct"]) if body.get("sample_pct") else None)
620
+ except Exception as e:
621
+ raise ValueError(tr("diff failed: {error}", error=str(e)[:300])) from e
622
+ finally:
623
+ if wh is not None:
624
+ wh.close()
625
+ st.audit(who["name"], "data_diff", {"base": body["base"], "head": body["head"], "identical": res["identical"]})
626
+ return self._json(200, res)
627
+
628
+ def _run(self, prim: Store, what: str):
629
+ who = self._need(prim, "run_check" if what == "check" else "run_collect")
630
+ st = self._data(prim, who)
631
+ if not st.claim_setting("state.running", what): # atomic: two clicks/requests cannot both start a run
632
+ raise ValueError(tr("a run is already in progress"))
633
+ spath, code = st.path, i18n.lang()
634
+
635
+ def job():
636
+ i18n.set_request_lang(code)
637
+ s2 = None
638
+ try:
639
+ s2 = Store(spath) # inside the try: if it fails (pool exhausted) the flag is still cleared below
640
+ if what == "check":
641
+ runner.run_check(s2)
642
+ else:
643
+ runner.collect_runs(s2)
644
+ runner.collect_samples(s2)
645
+ except Exception as e:
646
+ try:
647
+ (s2 or Store(spath)).audit("system", "run_failed", {"what": what, "error": str(e)[:300]})
648
+ except Exception:
649
+ pass
650
+ finally:
651
+ try:
652
+ (s2 or Store(spath)).unset_setting("state.running")
653
+ finally:
654
+ if s2 is not None:
655
+ s2.close()
656
+ threading.Thread(target=job, daemon=True).start()
657
+ return self._json(200, {"started": what})
658
+
659
+ def _finding_action(self, prim: Store, fid: str, act: str, body: dict):
660
+ need = {"ack": "ack", "false-positive": "false_positive", "assign": "assign", "note": "note"}.get(act)
661
+ if need is None:
662
+ return self._json(404, {"error": "not found"})
663
+ who = self._need(prim, need)
664
+ st = self._data(prim, who)
665
+ actor = who["name"]
666
+ frec = st.finding(fid)
667
+ if not scope_ok(who, self._project(), frec, auth.role_in(who, self._project())):
668
+ return self._json(403, {"error": tr("this finding is outside your scope (allowed folders/models)")})
669
+ if act == "ack":
670
+ st.ack(fid, actor, tr("acknowledged in the UI"))
671
+ elif act == "false-positive":
672
+ st.mark_false_positive(fid, actor, tr("marked in the UI"))
673
+ elif act == "assign":
674
+ a = body.get("assignee") or None
675
+ if a and prim.has_users() and not any(x["name"] == a and not x["disabled"] for x in prim.users()):
676
+ raise ValueError(tr("user not found"))
677
+ st.assign(fid, a, actor)
678
+ else:
679
+ st.add_note(fid, actor, str(body.get("text", "")))
680
+ return self._json(200, {"ok": True})
681
+ return H
682
+
683
+
684
+ def build_server(store_path: str, port: int = 8787, host: str = "127.0.0.1", tls_cert: str | None = None, tls_key: str | None = None,
685
+ behind_proxy: bool = False):
686
+ """Create the server applying the exposure rules: outside loopback requires users and TLS (or a declared proxy)."""
687
+ loopback = host in ("127.0.0.1", "localhost", "::1")
688
+ with Store(store_path) as st:
689
+ has_users = st.has_users()
690
+ st.unset_setting("state.running") # a run interrupted by a crash/restart would otherwise block new runs forever
691
+ if behind_proxy and not os.environ.get("INTENTFLOW_TRUSTED_PROXIES"):
692
+ import sys
693
+ print(tr("warning: --behind-proxy without INTENTFLOW_TRUSTED_PROXIES: every client shares the proxy IP for the login rate limit"), file=sys.stderr)
694
+ if not loopback:
695
+ if not has_users:
696
+ raise SystemExit(tr("refused: to listen outside loopback, add users first (`intentflow user add NAME --role admin`)"))
697
+ if not (tls_cert and tls_key) and not behind_proxy:
698
+ raise SystemExit(tr("refused: outside loopback use HTTPS (--tls-cert/--tls-key) or declare --behind-proxy (reverse proxy with TLS)"))
699
+ from .http_utils import tls_context
700
+ ctx = tls_context(tls_cert, tls_key) if tls_cert and tls_key else None
701
+ try:
702
+ max_workers = int(os.environ.get("INTENTFLOW_UI_MAX_WORKERS", "128"))
703
+ except ValueError:
704
+ raise SystemExit(tr("INTENTFLOW_UI_MAX_WORKERS must be an integer between 1 and 1024")) from None
705
+ try:
706
+ srv = BoundedThreadingHTTPServer((host, port), make_handler(store_path), max_workers=max_workers)
707
+ except ValueError:
708
+ raise SystemExit(tr("INTENTFLOW_UI_MAX_WORKERS must be an integer between 1 and 1024")) from None
709
+ if ctx:
710
+ srv.socket = ctx.wrap_socket(srv.socket, server_side=True, do_handshake_on_connect=False)
711
+ srv.scheme = "https"
712
+ else:
713
+ srv.scheme = "http"
714
+ return srv
715
+
716
+
717
+ def serve(store_path: str, port: int = 8787, host: str = "127.0.0.1", tls_cert: str | None = None, tls_key: str | None = None,
718
+ behind_proxy: bool = False):
719
+ srv = build_server(store_path, port, host, tls_cert, tls_key, behind_proxy)
720
+ with Store(store_path) as st:
721
+ team = st.has_users()
722
+ print(f"IntentFlow UI: {srv.scheme}://{host}:{srv.server_address[1]}/ " + (tr("(team mode: token login)") if team else tr("(local mode)")))
723
+ try:
724
+ srv.serve_forever()
725
+ finally:
726
+ srv.server_close()