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/store.py ADDED
@@ -0,0 +1,1006 @@
1
+ """Store (SQLite or PostgreSQL): findings with a lifecycle, history, samples, runs, proposals and audit trail."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ import sqlite3
7
+ import threading
8
+ import time
9
+
10
+ from .i18n import tr
11
+ from .model import Finding
12
+
13
+ _INITIALIZED: set = set() # paths whose schema was already prepared in this process
14
+ _WLOCKS: dict = {} # one write lock per file (within the process)
15
+ _WLOCKS_GUARD = threading.Lock()
16
+ _WRITE_PREFIX = ("insert", "update", "delete", "replace", "create", "alter", "drop")
17
+
18
+
19
+ class _Conn(sqlite3.Connection):
20
+ """Serialize this process's write transactions: with hundreds of writers SQLite's backoff turns into an unfair queue
21
+ (throughput collapsed and 'database is locked' showed up). The lock is taken on the first write and released on commit/rollback."""
22
+ _wl = None
23
+ _held = 0
24
+
25
+ def _acquire(self):
26
+ if self._wl is not None and not self._held:
27
+ self._wl.acquire()
28
+ self._held = 1
29
+
30
+ def _release(self):
31
+ if self._wl is not None and self._held:
32
+ self._held = 0
33
+ self._wl.release()
34
+
35
+ def execute(self, sql, *a, **k):
36
+ head = sql.lstrip()[:7].lower()
37
+ ddl = head.startswith(("create", "alter", "drop")) # DDL autocommits: the lock only lasts for the statement
38
+ if head.startswith(_WRITE_PREFIX):
39
+ self._acquire()
40
+ try:
41
+ return super().execute(sql, *a, **k)
42
+ except Exception:
43
+ if not self.in_transaction:
44
+ self._release()
45
+ raise
46
+ finally:
47
+ if ddl:
48
+ self._release()
49
+
50
+ def executemany(self, sql, *a, **k):
51
+ self._acquire()
52
+ try:
53
+ return super().executemany(sql, *a, **k)
54
+ except Exception:
55
+ if not self.in_transaction:
56
+ self._release()
57
+ raise
58
+
59
+ def executescript(self, sql):
60
+ self._acquire()
61
+ try:
62
+ return super().executescript(sql)
63
+ finally:
64
+ self._release()
65
+
66
+ def commit(self):
67
+ try:
68
+ super().commit()
69
+ finally:
70
+ self._release()
71
+
72
+ def rollback(self):
73
+ try:
74
+ super().rollback()
75
+ finally:
76
+ self._release()
77
+
78
+ def close(self):
79
+ self._release()
80
+ super().close()
81
+
82
+ def __del__(self):
83
+ try:
84
+ self._release()
85
+ except Exception:
86
+ pass
87
+
88
+
89
+ # ====================================================================== PostgreSQL
90
+ _PG_POOLS: dict = {}
91
+ _PG_GUARD = threading.Lock()
92
+ _PG_LOCK_KEY = 727274 # advisory lock to create/migrate the schema without races between processes
93
+
94
+
95
+ class _Row(tuple):
96
+ """Row accessible by index and by name (compatible with sqlite3.Row in the Store's uses)."""
97
+ _names: tuple = ()
98
+
99
+ def __new__(cls, names, values):
100
+ o = super().__new__(cls, values)
101
+ o._names = tuple(names)
102
+ return o
103
+
104
+ def __getitem__(self, k):
105
+ if isinstance(k, str):
106
+ return tuple.__getitem__(self, self._names.index(k))
107
+ return tuple.__getitem__(self, k)
108
+
109
+ def keys(self):
110
+ return list(self._names)
111
+
112
+
113
+ class _Cur:
114
+ def __init__(self, cur):
115
+ self._c = cur
116
+ self._names = [d.name for d in cur.description] if cur.description else []
117
+ self.rowcount = cur.rowcount
118
+
119
+ def fetchone(self):
120
+ r = self._c.fetchone()
121
+ return _Row(self._names, r) if r is not None else None
122
+
123
+ def fetchall(self):
124
+ return [_Row(self._names, r) for r in self._c.fetchall()]
125
+
126
+ def __iter__(self):
127
+ return iter(self.fetchall())
128
+
129
+
130
+ def _pg_pool(dsn: str):
131
+ import queue
132
+ with _PG_GUARD:
133
+ if dsn not in _PG_POOLS:
134
+ n = int(os.environ.get("INTENTFLOW_PG_POOL", "24"))
135
+ _PG_POOLS[dsn] = (queue.LifoQueue(), threading.BoundedSemaphore(n))
136
+ return _PG_POOLS[dsn]
137
+
138
+
139
+ def close_pools(dsn: str | None = None) -> None:
140
+ """Close idle pool connections (all of them, or only those of one DSN). Useful when switching databases or in tests."""
141
+ with _PG_GUARD:
142
+ for k in [dsn] if dsn else list(_PG_POOLS):
143
+ q, _ = _PG_POOLS.pop(k, (None, None))
144
+ while q is not None and not q.empty():
145
+ try:
146
+ q.get_nowait().close()
147
+ except Exception:
148
+ pass
149
+
150
+
151
+ class _PgConn:
152
+ """Pool connection with the same minimal surface the Store uses (execute/commit/rollback/close).
153
+ Autocommit for reads (no idle transactions); writes open an explicit BEGIN and close it on commit()."""
154
+
155
+ def __init__(self, dsn: str):
156
+ import psycopg2
157
+ self.dsn = dsn
158
+ self._q, self._sem = _pg_pool(dsn)
159
+ if not self._sem.acquire(timeout=60):
160
+ raise RuntimeError(tr("PostgreSQL connection pool exhausted"))
161
+ try:
162
+ self._c = self._pooled()
163
+ except Exception:
164
+ try:
165
+ self._c = psycopg2.connect(dsn, connect_timeout=10)
166
+ except Exception:
167
+ self._sem.release()
168
+ raise
169
+ try:
170
+ self._c.autocommit = True
171
+ except Exception:
172
+ self._sem.release() # the slot would leak: __del__/close never run for a half-built object
173
+ raise
174
+ self._tx = False
175
+ self._open = True
176
+
177
+ def _pooled(self):
178
+ """Next live idle connection. A pooled one may be dead (server restarted/killed): ping it, drop it and try the next."""
179
+ while True:
180
+ c = self._q.get_nowait() # queue.Empty when none left: caller opens a new connection
181
+ try:
182
+ if not c.closed:
183
+ with c.cursor() as cur:
184
+ cur.execute("select 1")
185
+ return c
186
+ except Exception:
187
+ pass
188
+ try:
189
+ c.close()
190
+ except Exception:
191
+ pass
192
+
193
+ @property
194
+ def in_transaction(self) -> bool:
195
+ return self._tx
196
+
197
+ def execute(self, sql: str, params=()):
198
+ low = sql.lstrip()[:8].lower()
199
+ cur = self._c.cursor()
200
+ if low.startswith(("insert", "update", "delete", "create", "alter", "drop")) and not self._tx:
201
+ cur.execute("BEGIN")
202
+ self._tx = True
203
+ try:
204
+ cur.execute(sql.replace("?", "%s") if params else sql, tuple(params) if params else None)
205
+ except Exception:
206
+ self.rollback()
207
+ raise
208
+ return _Cur(cur)
209
+
210
+ def executemany(self, sql: str, seq):
211
+ cur = None
212
+ for row in seq:
213
+ cur = self.execute(sql, row)
214
+ return cur
215
+
216
+ def executescript(self, script: str):
217
+ for stmt in [x.strip() for x in script.split(";") if x.strip()]:
218
+ self.execute(stmt)
219
+ self.commit()
220
+
221
+ def commit(self):
222
+ if self._tx:
223
+ self._tx = False
224
+ self._c.cursor().execute("COMMIT")
225
+
226
+ def rollback(self):
227
+ if self._tx:
228
+ self._tx = False
229
+ try:
230
+ self._c.cursor().execute("ROLLBACK")
231
+ except Exception:
232
+ pass
233
+
234
+ def close(self):
235
+ if not self._open:
236
+ return
237
+ self._open = False
238
+ try:
239
+ self.rollback()
240
+ if not self._c.closed:
241
+ self._q.put(self._c)
242
+ finally:
243
+ self._sem.release()
244
+
245
+ def __del__(self):
246
+ try:
247
+ self.close()
248
+ except Exception:
249
+ pass
250
+
251
+
252
+ def _is_pg(spec: str) -> bool:
253
+ return spec.startswith(("postgresql://", "postgres://", "env:"))
254
+
255
+
256
+ def resolve_spec(spec: str) -> str:
257
+ """`env:VAR` keeps the URL (with its password) out of the command line and of files."""
258
+ if spec.startswith("env:"):
259
+ v = os.environ.get(spec[4:])
260
+ if not v:
261
+ raise ValueError(tr("environment variable {name} is not set (PostgreSQL URL)", name=spec[4:]))
262
+ return v
263
+ return spec
264
+
265
+
266
+ SCHEMA = """
267
+ create table if not exists findings(id text primary key, check_id text, severity text, title text, detail text,
268
+ nodes text, stage text, evidence text, fix text, confidence real, status text default 'open',
269
+ first_seen real, last_seen real, ack_until real, ack_reason text, ack_by text);
270
+ create table if not exists history(key text, ts real, value real);
271
+ create index if not exists h_key on history(key, ts);
272
+ create table if not exists samples(ts real, source text, scope text, metric text, value real, lim real);
273
+ create table if not exists runs(system text, pipeline text, run_id text, state text, start real, "end" real, duration real, url text,
274
+ primary key(system, pipeline, run_id));
275
+ create table if not exists proposals(id text primary key, json text, status text, updated real);
276
+ create table if not exists audit(ts real, actor text, event text, detail text);
277
+ create table if not exists ol_jobs(job text primary key, inputs text, outputs text, last_event real);
278
+ create table if not exists ol_edges(job text, src_ds text, src_col text, dst_ds text, dst_col text, primary key(job, src_ds, src_col, dst_ds, dst_col));
279
+ create table if not exists lineage_cache(key text primary key, value text);
280
+ create table if not exists users(name text primary key, role text not null, token_hash text not null, created real, disabled integer default 0, last_seen real);
281
+ create table if not exists notes(id integer primary key autoincrement, finding_id text, author text, ts real, text text);
282
+ create index if not exists notes_f on notes(finding_id);
283
+ create table if not exists sessions(id_hash text primary key, "user" text, created real, expires real, via text);
284
+ create table if not exists login_attempts(ip text, ts real);
285
+ create index if not exists la_ip on login_attempts(ip, ts);
286
+ create table if not exists settings(key text primary key, value text, updated real);
287
+ create table if not exists schema_version(version integer not null);
288
+ create index if not exists users_token_hash on users(token_hash);
289
+ create index if not exists audit_ts on audit(ts);
290
+ create index if not exists samples_ts on samples(ts);
291
+ create index if not exists findings_status on findings(status);
292
+ """
293
+
294
+
295
+ class Store:
296
+ """Metadata store. Backends: SQLite (file or :memory:; the default, zero configuration) and PostgreSQL (production;
297
+ `postgresql://…` or `env:VARIABLE` holding the URL). The API is the same for both."""
298
+
299
+ _MIGRATIONS = (
300
+ ("findings", "assignee", "text"), ("findings", "assigned_by", "text"),
301
+ ("users", "project_roles", "text default '{}'"), ("users", "totp_secret", "text"),
302
+ ("users", "totp_enabled", "integer default 0"), ("users", "totp_last_step", "integer default 0"),
303
+ ("users", "email", "text"), ("sessions", "id_token", "text"), ("users", "sso_managed", "integer default 0"),
304
+ ("sessions", "sub", "text"), ("sessions", "sid", "text"), ("sessions", "refresh_token", "text"),
305
+ ("sessions", "refreshed_at", "real"), ("users", "token_expires", "real"), ("users", "recovery_hashes", "text"),
306
+ ("users", "scopes", "text default '{}'"),
307
+ )
308
+
309
+ def __init__(self, path: str = ":memory:"):
310
+ self.spec = path
311
+ self.backend = "postgres" if _is_pg(path) else "sqlite"
312
+ self._box = None
313
+ if self.backend == "postgres":
314
+ self.path = resolve_spec(path) # resolved DSN (never display it: it may contain a password)
315
+ self.con = _PgConn(self.path)
316
+ self._init_pg()
317
+ return
318
+ # SQLite: timeout/WAL; escritas serializadas por arquivo dentro do processo
319
+ self.path = path
320
+ self.con = sqlite3.connect(path, timeout=30, factory=_Conn)
321
+ if path != ":memory:":
322
+ ap = os.path.abspath(path)
323
+ with _WLOCKS_GUARD:
324
+ self.con._wl = _WLOCKS.setdefault(ap, threading.Lock())
325
+ self.con.row_factory = sqlite3.Row
326
+ if path != ":memory:":
327
+ self.con.execute("pragma busy_timeout=30000")
328
+ self.con.execute("pragma synchronous=NORMAL") # safe in WAL: no loss of integrity
329
+ key = os.path.abspath(path) if path != ":memory:" else None
330
+ if key and key in _INITIALIZED and os.path.exists(path):
331
+ return # schema/migrations already applied by this process
332
+ if path != ":memory:":
333
+ self.con.execute("pragma journal_mode=wal")
334
+ self.con.executescript(SCHEMA)
335
+ for table, col, typ in self._MIGRATIONS:
336
+ try: # migration of databases created before team mode
337
+ self.con.execute(f"alter table {table} add column {col} {typ}")
338
+ except sqlite3.OperationalError:
339
+ pass
340
+ self._check_schema_version()
341
+ if key:
342
+ _INITIALIZED.add(key)
343
+
344
+ def _check_schema_version(self) -> None:
345
+ """Refuse a store migrated by a newer IntentFlow (its columns/semantics are unknown here); record ours otherwise."""
346
+ mine = len(self._MIGRATIONS)
347
+ r = self.con.execute("select max(version) v from schema_version").fetchone()
348
+ theirs = (r["v"] if r else None) or 0
349
+ if theirs > mine:
350
+ raise SystemExit(tr("store schema version {theirs} is newer than this IntentFlow supports ({mine}): upgrade IntentFlow",
351
+ theirs=theirs, mine=mine))
352
+ if theirs < mine:
353
+ self.con.execute("delete from schema_version")
354
+ self.con.execute("insert into schema_version(version) values(?)", (mine,))
355
+ self.con.commit()
356
+
357
+ def _init_pg(self) -> None:
358
+ if self.path in _INITIALIZED:
359
+ return
360
+ c = self.con
361
+ c.execute("select pg_advisory_lock(?)", (_PG_LOCK_KEY,))
362
+ try:
363
+ ddl = (SCHEMA.replace(" real", " double precision").replace("integer primary key autoincrement", "bigserial primary key"))
364
+ c.executescript(ddl)
365
+ for table, col, typ in self._MIGRATIONS:
366
+ c.execute(f"alter table {table} add column if not exists {col} {typ.replace('real', 'double precision')}")
367
+ c.commit()
368
+ self._check_schema_version()
369
+ finally:
370
+ c.execute("select pg_advisory_unlock(?)", (_PG_LOCK_KEY,))
371
+ _INITIALIZED.add(self.path)
372
+
373
+ def close(self) -> None:
374
+ self.con.close()
375
+
376
+ def __enter__(self):
377
+ return self
378
+
379
+ def __exit__(self, exc_type, exc, traceback):
380
+ self.close()
381
+
382
+ def _upsert(self, table: str, cols: tuple, pk: tuple, rows, ignore: bool = False) -> None:
383
+ """INSERT … ON CONFLICT (valid in SQLite ≥ 3.24 and PostgreSQL)."""
384
+ q = lambda c: '"end"' if c == "end" else c # noqa: E731
385
+ names = ", ".join(q(c) for c in cols)
386
+ ph = ",".join("?" * len(cols))
387
+ if ignore:
388
+ tail = "on conflict do nothing"
389
+ else:
390
+ tail = f"on conflict ({', '.join(pk)}) do update set " + ", ".join(f"{q(c)}=excluded.{q(c)}" for c in cols if c not in pk)
391
+ self.con.executemany(f"insert into {table}({names}) values({ph}) {tail}", rows)
392
+
393
+ # achados -----------------------------------------------------------------
394
+ def sync_findings(self, findings: list[Finding], checks_run: set[str], now: float | None = None) -> dict:
395
+ now = now or time.time()
396
+ seen = set()
397
+ new = 0
398
+ for f in findings:
399
+ seen.add(f.id)
400
+ row = self.con.execute("select status, ack_until from findings where id=?", (f.id,)).fetchone()
401
+ if row is None:
402
+ new += 1
403
+ self.con.execute("insert into findings(id, check_id, severity, title, detail, nodes, stage, evidence, fix, confidence, status, first_seen, last_seen, ack_until, ack_reason, ack_by) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
404
+ (f.id, f.check, f.severity, f.title, f.detail, json.dumps(f.nodes), f.stage, json.dumps(f.evidence, default=str),
405
+ json.dumps(f.fix) if f.fix else None, f.confidence, "open", now, now, None, None, None))
406
+ else:
407
+ status = row["status"]
408
+ if status == "false_positive":
409
+ self.con.execute("update findings set last_seen=? where id=?", (now, f.id))
410
+ continue
411
+ if status == "resolved":
412
+ status = "open"
413
+ if status == "acked" and row["ack_until"] and row["ack_until"] < now:
414
+ status = "open"
415
+ self.con.execute("update findings set severity=?, detail=?, evidence=?, fix=?, last_seen=?, status=? where id=?",
416
+ (f.severity, f.detail, json.dumps(f.evidence, default=str), json.dumps(f.fix) if f.fix else None, now, status, f.id))
417
+ resolved = 0
418
+ for r in self.con.execute("select id, check_id from findings where status in ('open','acked')").fetchall():
419
+ if r["id"] not in seen and r["check_id"] in checks_run:
420
+ self.con.execute("update findings set status='resolved', last_seen=? where id=?", (now, r["id"]))
421
+ resolved += 1
422
+ self.con.commit()
423
+ return {"new": new, "resolved": resolved, "total": len(findings)}
424
+
425
+ def findings(self, status: str | None = "open") -> list[dict]:
426
+ q = ("select f.*, coalesce(n.note_count, 0) as notes from findings f "
427
+ "left join (select finding_id, count(*) as note_count from notes group by finding_id) n "
428
+ "on n.finding_id=f.id" + (" where f.status=?" if status else ""))
429
+ rows = self.con.execute(q, (status,) if status else ()).fetchall()
430
+ out = [self._finding_row(r) for r in rows]
431
+ order = {"critical": 0, "high": 1, "medium": 2, "low": 3, "info": 4}
432
+ out.sort(key=lambda d: (order.get(d["severity"], 9), d["id"]))
433
+ return out
434
+
435
+ @staticmethod
436
+ def _finding_row(row) -> dict:
437
+ finding = dict(row)
438
+ finding["nodes"] = json.loads(finding["nodes"] or "[]")
439
+ finding["evidence"] = json.loads(finding["evidence"] or "{}")
440
+ finding["fix"] = json.loads(finding["fix"]) if finding["fix"] else None
441
+ return finding
442
+
443
+ def finding(self, finding_id: str) -> dict | None:
444
+ """Load one finding and its note count without materializing the full findings list."""
445
+ row = self.con.execute(
446
+ "select f.*, (select count(*) from notes n where n.finding_id=f.id) as notes "
447
+ "from findings f where f.id=?", (finding_id,)
448
+ ).fetchone()
449
+ return self._finding_row(row) if row else None
450
+
451
+ def finding_by_prefix(self, prefix: str) -> dict | None:
452
+ """Resolve a CLI-friendly ID prefix, retaining the same severity/ID tie-break as findings()."""
453
+ if not prefix:
454
+ return None
455
+ row = self.con.execute(
456
+ "select f.*, (select count(*) from notes n where n.finding_id=f.id) as notes "
457
+ "from findings f where substr(f.id, 1, ?) = ? "
458
+ "order by case f.severity when 'critical' then 0 when 'high' then 1 "
459
+ "when 'medium' then 2 when 'low' then 3 when 'info' then 4 else 9 end, f.id limit 1",
460
+ (len(prefix), prefix)
461
+ ).fetchone()
462
+ return self._finding_row(row) if row else None
463
+
464
+ def mark_false_positive(self, finding_id: str, actor: str, reason: str = "") -> None:
465
+ self.con.execute("update findings set status='false_positive', ack_by=?, ack_reason=? where id=?", (actor, reason, finding_id))
466
+ self.audit(actor, "false_positive", {"id": finding_id, "reason": reason})
467
+ self.con.commit()
468
+
469
+ def check_stats(self) -> list[dict]:
470
+ """Por check: total, abertos, resolvidos, falsos positivos e taxa de falso positivo."""
471
+ out = []
472
+ for r in self.con.execute(
473
+ "select check_id, count(*) n, sum(case when status='open' then 1 else 0 end) o, "
474
+ "sum(case when status='resolved' then 1 else 0 end) r, sum(case when status='false_positive' then 1 else 0 end) fp, "
475
+ "sum(case when status='acked' then 1 else 0 end) a from findings group by check_id order by check_id"):
476
+ decided = (r["fp"] or 0) + (r["r"] or 0)
477
+ out.append({"check": r["check_id"], "total": r["n"], "open": r["o"] or 0, "resolved": r["r"] or 0,
478
+ "false_positive": r["fp"] or 0, "acked": r["a"] or 0,
479
+ "fp_rate": round((r["fp"] or 0) / decided, 2) if decided else None})
480
+ return out
481
+
482
+ def backup(self, dest: str) -> int:
483
+ """Consistent copy of the store. SQLite→SQLite uses the backup API; any other pair uses `copy_store`
484
+ (PostgreSQL→SQLite file is a portable logical backup). Returns the copied rows or, for a file, its size in bytes."""
485
+ if self.backend == "sqlite" and not _is_pg(dest):
486
+ os.close(os.open(dest, os.O_CREAT | os.O_WRONLY, 0o600)) # owner-only from the first byte (holds token hashes)
487
+ out = sqlite3.connect(dest)
488
+ try:
489
+ self.con.backup(out)
490
+ finally:
491
+ out.close()
492
+ os.chmod(dest, 0o600) # holds token hashes and metadata: only the owner reads it
493
+ self._copy_key(dest)
494
+ return os.path.getsize(dest)
495
+ if not _is_pg(dest) and not os.path.exists(dest):
496
+ os.close(os.open(dest, os.O_CREAT | os.O_WRONLY, 0o600))
497
+ with Store(dest) as out:
498
+ n = copy_store(self, out)
499
+ if not _is_pg(dest) and os.path.exists(dest):
500
+ os.chmod(dest, 0o600)
501
+ self._copy_key(dest)
502
+ return os.path.getsize(dest)
503
+ return n
504
+
505
+ def _copy_key(self, dest: str) -> None:
506
+ """Encrypted secrets in a SQLite backup are unreadable without the store's key file: keep it next to the copy (0600)."""
507
+ src = self.path + ".key"
508
+ if self.backend == "sqlite" and os.path.exists(src) and not os.environ.get("INTENTFLOW_SECRET_KEY"):
509
+ fd = os.open(dest + ".key", os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
510
+ with os.fdopen(fd, "wb") as f, open(src, "rb") as k:
511
+ f.write(k.read())
512
+
513
+ def prune(self, days: float, now: float | None = None, keep_lineage: set[str] | None = None) -> dict:
514
+ """`keep_lineage`: cache keys of the current project; others are dropped. None leaves the lineage cache alone."""
515
+ cut = (now or time.time()) - days * 86400
516
+ c = self.con
517
+ res = {}
518
+ for name, sql in (("samples", "delete from samples where ts < ?"), ("history", "delete from history where ts < ?"),
519
+ ("audit", "delete from audit where ts < ?"),
520
+ ("findings", "delete from findings where status in ('resolved','false_positive') and last_seen < ?"),
521
+ ("runs", "delete from runs where coalesce(start, 0) < ?"),
522
+ ("ol_edges", "delete from ol_edges where job in (select job from ol_jobs where last_event < ?)"),
523
+ ("ol_jobs", "delete from ol_jobs where last_event < ?"),
524
+ ("sessions", "delete from sessions where expires < ?"),
525
+ ("login_attempts", "delete from login_attempts where ts < ?")):
526
+ res[name] = c.execute(sql, (cut,)).rowcount
527
+ # notification cooldown markers (state.notified.*) only matter for COOLDOWN
528
+ res["notified"] = c.execute("delete from settings where key like ? and updated < ?",
529
+ ("state.notified.%", cut)).rowcount # '%' as a parameter: psycopg2 reads a literal % as a placeholder
530
+ if keep_lineage is not None:
531
+ stale = [(r["key"],) for r in c.execute("select key from lineage_cache").fetchall() if r["key"] not in keep_lineage]
532
+ if stale:
533
+ c.executemany("delete from lineage_cache where key=?", stale)
534
+ res["lineage_cache"] = len(stale)
535
+ c.commit()
536
+ return res
537
+
538
+ def ack(self, finding_id: str, actor: str, reason: str, until: float | None = None) -> None:
539
+ self.con.execute("update findings set status='acked', ack_by=?, ack_reason=?, ack_until=? where id=?", (actor, reason, until, finding_id))
540
+ self.audit(actor, "ack", {"id": finding_id, "reason": reason, "until": until})
541
+ self.con.commit()
542
+
543
+ # history / samples / runs ------------------------------------------------
544
+ def add_history(self, key: str, ts: float, value: float) -> None:
545
+ self.con.execute("insert into history values(?,?,?)", (key, ts, value))
546
+ self.con.commit()
547
+
548
+ def history(self, key: str) -> list[tuple[float, float]]:
549
+ return [(r[0], r[1]) for r in self.con.execute("select ts, value from history where key=? order by ts", (key,))]
550
+
551
+ def add_samples(self, samples) -> None:
552
+ self.con.executemany("insert into samples values(?,?,?,?,?,?)", [(s.ts, s.source, s.scope, s.metric, s.value, s.limit) for s in samples])
553
+ self.con.commit()
554
+
555
+ def recent_samples(self, since: float):
556
+ from .monitoring import Sample
557
+ return [Sample(r["ts"], r["source"], r["scope"], r["metric"], r["value"], r["lim"])
558
+ for r in self.con.execute("select * from samples where ts>=? order by ts", (since,))]
559
+
560
+ def upsert_runs(self, runs) -> None:
561
+ self._upsert("runs", ("system", "pipeline", "run_id", "state", "start", "end", "duration", "url"), ("system", "pipeline", "run_id"),
562
+ [(r.system, r.pipeline, r.run_id, r.state, r.start, r.end, r.duration, r.url) for r in runs])
563
+ self.con.commit()
564
+
565
+ def runs(self, limit: int = 200) -> list[dict]:
566
+ return [dict(r) for r in self.con.execute("select * from runs order by coalesce(start,0) desc limit ?", (limit,))]
567
+
568
+ def upsert_ol_job(self, job: str, inputs: list, outputs: list, ts: float) -> None:
569
+ self._upsert("ol_jobs", ("job", "inputs", "outputs", "last_event"), ("job",), [(job, json.dumps(inputs), json.dumps(outputs), ts)])
570
+ self.con.commit()
571
+
572
+ def add_ol_edges(self, job: str, edges: list[tuple]) -> None:
573
+ self._upsert("ol_edges", ("job", "src_ds", "src_col", "dst_ds", "dst_col"), (), [(job, *e) for e in edges], ignore=True)
574
+ self.con.commit()
575
+
576
+ def ol_jobs(self) -> list[dict]:
577
+ return [{"job": r["job"], "inputs": json.loads(r["inputs"]), "outputs": json.loads(r["outputs"]), "last_event": r["last_event"]}
578
+ for r in self.con.execute("select * from ol_jobs order by job")]
579
+
580
+ def ol_edges(self) -> list[dict]:
581
+ return [dict(r) for r in self.con.execute("select * from ol_edges order by job, dst_ds, dst_col")]
582
+
583
+ # team: users, roles, assignment and comments ----------------------------
584
+ @staticmethod
585
+ def _hash(token: str) -> str:
586
+ import hashlib
587
+ return hashlib.sha256(("intentflow|" + token).encode()).hexdigest()
588
+
589
+ def add_user(self, name: str, role: str, email: str | None = None, random_token: bool = False, expires_days: float | None = None) -> str:
590
+ """Create the user and return the token (shown only once; only its hash is stored)."""
591
+ import re, secrets
592
+ if role not in ("viewer", "engineer", "admin"):
593
+ raise ValueError(tr("invalid role (viewer, engineer, admin)"))
594
+ if not re.fullmatch(r"[A-Za-z0-9_.@+-]{2,128}", name):
595
+ raise ValueError(tr("invalid name (2–128 characters: letters, digits, _ . @ + -)"))
596
+ if self.con.execute("select 1 from users where name=?", (name,)).fetchone():
597
+ raise ValueError(tr("user '{name}' already exists", name=name))
598
+ token = "if_" + secrets.token_urlsafe(32)
599
+ exp = time.time() + expires_days * 86400 if expires_days else None
600
+ self.con.execute("insert into users(name, role, token_hash, created, disabled, last_seen, email, token_expires) values(?,?,?,?,0,NULL,?,?)",
601
+ (name, role, self._hash(token), time.time(), email, exp))
602
+ self.con.commit()
603
+ return token
604
+
605
+ def rotate_token(self, name: str, expires_days: float | None = None) -> str:
606
+ import secrets
607
+ if not self.con.execute("select 1 from users where name=?", (name,)).fetchone():
608
+ raise ValueError(tr("user not found"))
609
+ token = "if_" + secrets.token_urlsafe(32)
610
+ if expires_days is None: # inherit the policy: the server's default validity, if any
611
+ d = self.get_setting("policy.token_max_age_days")
612
+ expires_days = float(d) if d else None
613
+ exp = time.time() + expires_days * 86400 if expires_days else None
614
+ self.con.execute("update users set token_hash=?, token_expires=? where name=?", (self._hash(token), exp, name))
615
+ self.con.execute("delete from sessions where \"user\"=?", (name,)) # rotating ends open sessions
616
+ self.con.commit()
617
+ return token
618
+
619
+ def users_admin(self) -> list[dict]:
620
+ """For team management: includes projects, MFA and e-mail (never the token hash)."""
621
+ out = []
622
+ for r in self.con.execute("select name, role, created, disabled, last_seen, project_roles, totp_enabled, email, token_expires, scopes from users order by name"):
623
+ d = dict(r)
624
+ d["project_roles"] = json.loads(d.get("project_roles") or "{}")
625
+ d["scopes"] = json.loads(d.get("scopes") or "{}")
626
+ d["mfa"] = bool(d.pop("totp_enabled"))
627
+ out.append(d)
628
+ return out
629
+
630
+ def users(self) -> list[dict]:
631
+ return [dict(r) for r in self.con.execute("select name, role, created, disabled, last_seen from users order by name")]
632
+
633
+ def has_users(self) -> bool:
634
+ return self.con.execute("select 1 from users limit 1").fetchone() is not None
635
+
636
+ def user_by_token(self, token: str):
637
+ import hmac
638
+ h = self._hash(token or "")
639
+ rows = self.con.execute("select name, role, token_hash, disabled, last_seen, project_roles, totp_enabled, token_expires, scopes from users where token_hash=?", (h,)).fetchall() # busca indexada; cursor fechado antes de escrever
640
+ for r in rows:
641
+ if hmac.compare_digest(r["token_hash"], h):
642
+ if r["disabled"]:
643
+ return None
644
+ now = time.time()
645
+ if r["token_expires"] and now > r["token_expires"]:
646
+ return None # expired token: requires rotation
647
+ if not r["last_seen"] or now - r["last_seen"] > 60: # at most one write per minute per person
648
+ self.con.execute("update users set last_seen=? where name=?", (now, r["name"]))
649
+ self.con.commit()
650
+ return {"name": r["name"], "role": r["role"], "project_roles": json.loads(r["project_roles"] or "{}"),
651
+ "mfa": bool(r["totp_enabled"]), "scopes": json.loads(r["scopes"] or "{}")}
652
+ return None
653
+
654
+ # sessions (the browser cookie holds a random id, never the long-lived token)
655
+ def create_session(self, user: str, via: str = "token", ttl: float = 12 * 3600, id_token: str | None = None,
656
+ sub: str | None = None, sid: str | None = None, refresh_token: str | None = None) -> str:
657
+ import secrets
658
+ sess = "ifs_" + secrets.token_urlsafe(32)
659
+ now = time.time()
660
+ self.con.execute("insert into sessions(id_hash, \"user\", created, expires, via, id_token, sub, sid, refresh_token, refreshed_at) "
661
+ "values(?,?,?,?,?,?,?,?,?,?)", (self._hash(sess), user, now, now + ttl, via, self.box.enc(id_token), sub, sid,
662
+ self.box.enc(refresh_token), now))
663
+ self.con.execute("delete from sessions where expires < ?", (now,))
664
+ self.con.commit()
665
+ return sess
666
+
667
+ def user_by_session(self, sid: str):
668
+ r = self.con.execute("select s.\"user\", s.expires, s.via, u.role, u.disabled, u.project_roles, u.totp_enabled, u.scopes from sessions s "
669
+ "join users u on u.name = s.\"user\" where s.id_hash=?", (self._hash(sid or ""),)).fetchone()
670
+ if not r or r["expires"] < time.time() or r["disabled"]:
671
+ return None
672
+ return {"name": r["user"], "role": r["role"], "project_roles": json.loads(r["project_roles"] or "{}"), "mfa": bool(r["totp_enabled"]),
673
+ "via": r["via"], "scopes": json.loads(r["scopes"] or "{}")}
674
+
675
+ @property
676
+ def box(self):
677
+ """Encrypts/decrypts secrets at rest (see secrets_box). Created on demand, once `self.path` exists."""
678
+ if self._box is None:
679
+ from .secrets_box import Box
680
+ self._box = Box(self.path, self.backend)
681
+ return self._box
682
+
683
+ def session_info(self, sid: str):
684
+ r = self.con.execute("select \"user\", via, id_token, sub, sid, refresh_token, refreshed_at from sessions where id_hash=?",
685
+ (self._hash(sid or ""),)).fetchone()
686
+ if not r:
687
+ return None
688
+ d = dict(r)
689
+ d["id_token"], d["refresh_token"] = self.box.dec(d.get("id_token")), self.box.dec(d.get("refresh_token"))
690
+ return d
691
+
692
+ def update_session_refresh(self, sid: str, refresh_token: str | None, id_token: str | None) -> None:
693
+ self.con.execute("update sessions set refresh_token=coalesce(?, refresh_token), id_token=coalesce(?, id_token), refreshed_at=? where id_hash=?",
694
+ (self.box.enc(refresh_token), self.box.enc(id_token), time.time(), self._hash(sid)))
695
+ self.con.commit()
696
+
697
+ def end_sessions_by_provider(self, sid: str | None, sub: str | None) -> int:
698
+ """Back-channel logout: end sessions by the provider's `sid` (or, without it, by `sub`)."""
699
+ if sid:
700
+ cur = self.con.execute("delete from sessions where sid=?", (sid,))
701
+ elif sub:
702
+ cur = self.con.execute("delete from sessions where sub=?", (sub,))
703
+ else:
704
+ return 0
705
+ self.con.commit()
706
+ return cur.rowcount
707
+
708
+ def end_user_sessions(self, name: str) -> int:
709
+ cur = self.con.execute("delete from sessions where \"user\"=?", (name,))
710
+ self.con.commit()
711
+ return cur.rowcount
712
+
713
+ def sso_sync(self, name: str, role: str | None, project_roles: dict | None) -> None:
714
+ """Apply roles coming from the provider (groups) to a user managed by SSO."""
715
+ sets, vals = ["sso_managed=1"], []
716
+ if role is not None:
717
+ sets.append("role=?")
718
+ vals.append(role)
719
+ if project_roles is not None:
720
+ sets.append("project_roles=?")
721
+ vals.append(json.dumps(project_roles))
722
+ self.con.execute(f"update users set {', '.join(sets)} where name=?", (*vals, name))
723
+ self.con.commit()
724
+
725
+ def end_session(self, sid: str) -> None:
726
+ self.con.execute("delete from sessions where id_hash=?", (self._hash(sid or ""),))
727
+ self.con.commit()
728
+
729
+ def user_record(self, name: str):
730
+ r = self.con.execute("select * from users where name=?", (name,)).fetchone()
731
+ return dict(r) if r else None
732
+
733
+ # MFA (TOTP)
734
+ def mfa_begin(self, name: str) -> str:
735
+ from . import totp
736
+ record = self.user_record(name)
737
+ if not record:
738
+ raise ValueError(tr("user not found"))
739
+ if record["totp_enabled"]:
740
+ raise ValueError(tr("MFA is already on; disable it with the current code before setting it up again"))
741
+ secret = totp.new_secret()
742
+ self.con.execute("update users set totp_secret=?, totp_enabled=0, totp_last_step=0 where name=?", (self.box.enc(secret), name))
743
+ self.con.commit()
744
+ return secret
745
+
746
+ def mfa_confirm(self, name: str, code: str) -> bool:
747
+ from . import totp
748
+ u = self.user_record(name)
749
+ step = totp.verify(self.box.dec(u["totp_secret"]) or "", code) if u and u["totp_secret"] else None
750
+ if step is None or u["totp_enabled"]:
751
+ return False
752
+ changed = self.con.execute("update users set totp_enabled=1, totp_last_step=? where name=? and totp_enabled=0 and totp_secret=?",
753
+ (step, name, u["totp_secret"])).rowcount
754
+ self.con.commit()
755
+ return changed == 1
756
+
757
+ def mfa_check(self, name: str, code: str) -> bool:
758
+ """Validate the code and prevent reuse of the same step."""
759
+ from . import totp
760
+ u = self.user_record(name)
761
+ if not u or not u["totp_enabled"]:
762
+ return False
763
+ step = totp.verify(self.box.dec(u["totp_secret"]), code, last_step=u["totp_last_step"] or 0)
764
+ if step is None:
765
+ return False
766
+ changed = self.con.execute("update users set totp_last_step=? where name=? and totp_enabled=1 and totp_secret=? "
767
+ "and coalesce(totp_last_step, 0) < ?", (step, name, u["totp_secret"], step)).rowcount
768
+ self.con.commit()
769
+ return changed == 1
770
+
771
+ def mfa_recovery_codes(self, name: str) -> list[str]:
772
+ """Generate 10 single-use codes (shown once); only their hashes are stored."""
773
+ import secrets
774
+ codes = [f"{secrets.token_hex(2)}-{secrets.token_hex(2)}-{secrets.token_hex(2)}" for _ in range(10)]
775
+ self.con.execute("update users set recovery_hashes=? where name=?", (json.dumps([self._hash("rc|" + c) for c in codes]), name))
776
+ self.con.commit()
777
+ return codes
778
+
779
+ def mfa_use_recovery(self, name: str, code: str) -> bool:
780
+ u = self.user_record(name)
781
+ hashes = json.loads((u or {}).get("recovery_hashes") or "[]")
782
+ h = self._hash("rc|" + (code or "").strip().lower())
783
+ if h not in hashes:
784
+ return False
785
+ hashes.remove(h) # single use
786
+ changed = self.con.execute("update users set recovery_hashes=? where name=? and recovery_hashes=? and totp_enabled=1",
787
+ (json.dumps(hashes), name, u["recovery_hashes"])).rowcount
788
+ self.con.commit()
789
+ return changed == 1
790
+
791
+ def set_scopes(self, name: str, project: str, patterns: list[str] | None) -> None:
792
+ u = self.user_record(name)
793
+ if not u:
794
+ raise ValueError(tr("user not found"))
795
+ sc = json.loads(u.get("scopes") or "{}")
796
+ if patterns:
797
+ sc[project] = patterns
798
+ else:
799
+ sc.pop(project, None)
800
+ self.con.execute("update users set scopes=? where name=?", (json.dumps(sc), name))
801
+ self.con.commit()
802
+
803
+ def mfa_disable(self, name: str) -> None:
804
+ self.con.execute("update users set totp_secret=NULL, totp_enabled=0, totp_last_step=0, recovery_hashes=NULL where name=?", (name,))
805
+ self.con.commit()
806
+
807
+ def set_project_role(self, name: str, project: str, role: str | None) -> None:
808
+ if role not in (None, "none", "viewer", "engineer", "admin"):
809
+ raise ValueError(tr("invalid role"))
810
+ u = self.user_record(name)
811
+ if not u:
812
+ raise ValueError(tr("user not found"))
813
+ pr = json.loads(u.get("project_roles") or "{}")
814
+ if role is None:
815
+ pr.pop(project, None)
816
+ else:
817
+ pr[project] = role
818
+ self.con.execute("update users set project_roles=? where name=?", (json.dumps(pr), name))
819
+ self.con.commit()
820
+
821
+ # persistent attempt limit (survives restarts and holds across processes)
822
+ def attempts_recent(self, ip: str, window: float = 60.0) -> int:
823
+ return self.con.execute("select count(*) from login_attempts where ip=? and ts>?", (ip, time.time() - window)).fetchone()[0]
824
+
825
+ def attempt_failed(self, ip: str) -> None:
826
+ self.con.execute("insert into login_attempts values(?,?)", (ip, time.time()))
827
+ self.con.execute("delete from login_attempts where ts < ?", (time.time() - 3600,))
828
+ self.con.commit()
829
+
830
+ def set_user(self, name: str, role: str | None = None, disabled: bool | None = None) -> None:
831
+ if role is not None:
832
+ if role not in ("viewer", "engineer", "admin"):
833
+ raise ValueError(tr("invalid role"))
834
+ self.con.execute("update users set role=? where name=?", (role, name))
835
+ if disabled is not None:
836
+ self.con.execute("update users set disabled=? where name=?", (int(disabled), name))
837
+ self.con.commit()
838
+
839
+ def assign(self, finding_id: str, assignee: str | None, actor: str) -> None:
840
+ if self.con.execute("select 1 from findings where id=?", (finding_id,)).fetchone() is None:
841
+ raise ValueError(tr("finding not found"))
842
+ self.con.execute("update findings set assignee=?, assigned_by=? where id=?", (assignee or None, actor, finding_id))
843
+ self.audit(actor, "assign", {"id": finding_id, "assignee": assignee})
844
+ self.con.commit()
845
+
846
+ def add_note(self, finding_id: str, author: str, text: str) -> None:
847
+ text = (text or "").strip()
848
+ if not text or len(text) > 2000:
849
+ raise ValueError(tr("comment is empty or longer than 2000 characters"))
850
+ if self.con.execute("select 1 from findings where id=?", (finding_id,)).fetchone() is None:
851
+ raise ValueError(tr("finding not found"))
852
+ self.con.execute("insert into notes(finding_id, author, ts, text) values(?,?,?,?)", (finding_id, author, time.time(), text))
853
+ self.audit(author, "note", {"id": finding_id})
854
+ self.con.commit()
855
+
856
+ def notes(self, finding_id: str) -> list[dict]:
857
+ return [dict(r) for r in self.con.execute("select author, ts, text from notes where finding_id=? order by id", (finding_id,))]
858
+
859
+ # cache de linhagem por modelo
860
+ def get(self, key: str):
861
+ r = self.con.execute("select value from lineage_cache where key=?", (key,)).fetchone()
862
+ return json.loads(r["value"]) if r else None
863
+
864
+ def set(self, key: str, value) -> None:
865
+ self._upsert("lineage_cache", ("key", "value"), ("key",), [(key, json.dumps(value))])
866
+
867
+ def flush(self) -> None:
868
+ self.con.commit()
869
+
870
+ # settings and policies (instead of YAML files) --------------------------
871
+ def set_setting(self, key: str, value) -> None:
872
+ self._upsert("settings", ("key", "value", "updated"), ("key",), [(key, json.dumps(value), time.time())])
873
+ self.con.commit()
874
+
875
+ def claim_setting(self, key: str, value) -> bool:
876
+ """Set `key` only if absent; True if this call set it (atomic across threads and processes)."""
877
+ before = self.con.execute("insert into settings(key, value, updated) values(?,?,?) on conflict do nothing",
878
+ (key, json.dumps(value), time.time())).rowcount
879
+ self.con.commit()
880
+ return before == 1
881
+
882
+ def get_setting(self, key: str, default=None):
883
+ r = self.con.execute("select value from settings where key=?", (key,)).fetchone()
884
+ return json.loads(r["value"]) if r else default
885
+
886
+ def unset_setting(self, key: str) -> None:
887
+ self.con.execute("delete from settings where key=?", (key,))
888
+ self.con.commit()
889
+
890
+ def settings(self, prefix: str = "") -> dict:
891
+ return {r["key"]: json.loads(r["value"]) for r in self.con.execute("select key, value from settings where key like ? order by key", (prefix + "%",))}
892
+
893
+ def policies(self) -> dict:
894
+ """Policies as a plain dict (e.g. pii_allowed_models, sla.<pipeline>)."""
895
+ out: dict = {}
896
+ for k, v in self.settings("policy.").items():
897
+ out[k.removeprefix("policy.")] = v
898
+ return out
899
+
900
+ # propostas / auditoria --------------------------------------------------
901
+ def put_proposal(self, pid: str, data: dict, status: str) -> None:
902
+ self._upsert("proposals", ("id", "json", "status", "updated"), ("id",), [(pid, json.dumps(data), status, time.time())])
903
+ self.con.commit()
904
+
905
+ def proposal(self, pid: str) -> dict | None:
906
+ r = self.con.execute("select * from proposals where id=?", (pid,)).fetchone()
907
+ return {**json.loads(r["json"]), "id": r["id"], "status": r["status"]} if r else None
908
+
909
+ def proposals(self) -> list[dict]:
910
+ return [{**json.loads(r["json"]), "id": r["id"], "status": r["status"]}
911
+ for r in self.con.execute("select * from proposals order by updated desc")]
912
+
913
+ def audit(self, actor: str, event: str, detail: dict) -> None:
914
+ ts, body = time.time(), json.dumps(detail, default=str)
915
+ self.con.execute("insert into audit values(?,?,?,?)", (ts, actor, event, body))
916
+ self.con.commit()
917
+ mode = os.environ.get("INTENTFLOW_AUDIT_LOG", "").lower() # mirror to stderr for log shippers (default off)
918
+ if mode in ("json", "text"):
919
+ import sys
920
+ line = (json.dumps({"ts": round(ts, 3), "actor": actor, "event": event, "detail": detail}, default=str) if mode == "json"
921
+ else f"{actor} {event} {body}")
922
+ print(line, file=sys.stderr, flush=True)
923
+
924
+ def audit_log(self, limit: int | None = None) -> list[dict]:
925
+ if limit is None:
926
+ return [dict(r) for r in self.con.execute("select * from audit order by ts")]
927
+ rows = self.con.execute("select * from audit order by ts desc limit ?", (max(0, limit),)).fetchall()
928
+ return [dict(r) for r in reversed(rows)]
929
+
930
+
931
+ TABLES = ("findings", "history", "samples", "runs", "proposals", "audit", "ol_jobs", "ol_edges", "lineage_cache",
932
+ "users", "notes", "sessions", "login_attempts", "settings")
933
+
934
+
935
+ def copy_store(src: Store, dst: Store, clear: bool = True) -> int:
936
+ """Copy every table from `src` to `dst` (SQLite→PostgreSQL migration, logical backup, restore).
937
+ Reads `src` in one consistent snapshot (a single repeatable-read transaction on PostgreSQL). Returns the total number of rows."""
938
+ if src.backend != "postgres":
939
+ return _copy_rows(src, dst, clear)
940
+ c = src.con._c
941
+ c.autocommit = False
942
+ try:
943
+ c.cursor().execute("set transaction isolation level repeatable read read only") # first statement of the transaction
944
+ return _copy_rows(src, dst, clear)
945
+ finally:
946
+ c.rollback()
947
+ c.autocommit = True
948
+
949
+
950
+ def _copy_rows(src: Store, dst: Store, clear: bool) -> int:
951
+ q = lambda c: f'"{c}"' if c in ("end", "user") else c # noqa: E731
952
+ total = 0
953
+ if clear:
954
+ for t in reversed(TABLES):
955
+ dst.con.execute(f"delete from {t}")
956
+ dst.con.commit()
957
+ for t in TABLES:
958
+ rows = src.con.execute(f"select * from {t}").fetchall()
959
+ if not rows:
960
+ continue
961
+ cols = list(rows[0].keys())
962
+ cols_dst = {r[1] for r in dst.con.execute(f"pragma table_info({t})").fetchall()} if dst.backend == "sqlite" else None
963
+ use = [c for c in cols if cols_dst is None or c in cols_dst]
964
+ ph = ",".join("?" * len(use))
965
+ sql = f"insert into {t}({', '.join(q(c) for c in use)}) values({ph})"
966
+ for r in rows:
967
+ dst.con.execute(sql, tuple(r[c] for c in use))
968
+ total += len(rows)
969
+ if dst.backend == "postgres":
970
+ dst.con.execute("select setval(pg_get_serial_sequence('notes','id'), greatest(coalesce((select max(id) from notes), 0), 1))")
971
+ dst.con.commit()
972
+ return total
973
+
974
+
975
+ def rotate_secrets(store: Store) -> dict:
976
+ """Re-encrypt every stored secret with the current INTENTFLOW_SECRET_KEY (old keys in INTENTFLOW_SECRET_KEY_OLD)."""
977
+ if not store.box.enabled:
978
+ raise RuntimeError(tr("no key: set INTENTFLOW_SECRET_KEY (or use a SQLite file)"))
979
+ b, n = store.box, {"totp": 0, "sessions": 0}
980
+ for r in store.con.execute("select name, totp_secret from users where totp_secret is not null and totp_secret <> ''").fetchall():
981
+ store.con.execute("update users set totp_secret=? where name=?", (b.rotate(r["totp_secret"]), r["name"]))
982
+ n["totp"] += 1
983
+ for r in store.con.execute("select id_hash, id_token, refresh_token from sessions where id_token is not null or refresh_token is not null").fetchall():
984
+ store.con.execute("update sessions set id_token=?, refresh_token=? where id_hash=?",
985
+ (b.rotate(r["id_token"]), b.rotate(r["refresh_token"]), r["id_hash"]))
986
+ n["sessions"] += 1
987
+ store.con.commit()
988
+ return n
989
+
990
+
991
+ def migrate_secrets(store: Store) -> dict:
992
+ """Encrypt secrets still in plain text (stores created before encryption at rest). Idempotent."""
993
+ if not store.box.enabled:
994
+ raise RuntimeError(tr("no key: set INTENTFLOW_SECRET_KEY (or use a SQLite file)"))
995
+ n = {"totp": 0, "sessions": 0}
996
+ for r in store.con.execute("select name, totp_secret from users where totp_secret is not null").fetchall():
997
+ if r["totp_secret"] and not str(r["totp_secret"]).startswith("enc:v1:"):
998
+ store.con.execute("update users set totp_secret=? where name=?", (store.box.enc(r["totp_secret"]), r["name"]))
999
+ n["totp"] += 1
1000
+ for r in store.con.execute("select id_hash, id_token, refresh_token from sessions").fetchall():
1001
+ if any(v and not str(v).startswith("enc:v1:") for v in (r["id_token"], r["refresh_token"])):
1002
+ store.con.execute("update sessions set id_token=?, refresh_token=? where id_hash=?",
1003
+ (store.box.enc(r["id_token"]), store.box.enc(r["refresh_token"]), r["id_hash"]))
1004
+ n["sessions"] += 1
1005
+ store.con.commit()
1006
+ return n