lokra 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.
lokra/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.2.0"
lokra/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
File without changes
Binary file
Binary file
lokra/check.py ADDED
@@ -0,0 +1,62 @@
1
+ """Validate a policy against the real database it will run on.
2
+
3
+ Catches the mistakes that make a policy wrong or unsafe: grants on tables or
4
+ columns that do not exist, sensitive columns an agent can read with nothing
5
+ masking them, writes without a matching read, and masking rules that never match.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from .config import Config
10
+ from .introspect import _match, introspect
11
+
12
+
13
+ def check(cfg: Config, dsn: str) -> list[tuple[str, str]]:
14
+ """Introspect the database (read-only) and validate the policy against it."""
15
+ tables = introspect(dsn)
16
+ return analyze(cfg, {t: {c for c, _ in cols} for t, cols in tables.items()})
17
+
18
+
19
+ def analyze(cfg: Config, colmap: dict[str, set[str]]) -> list[tuple[str, str]]:
20
+ """Return a list of (level, message); level is 'error', 'warn' or 'info'."""
21
+ all_columns = {c.lower() for cols in colmap.values() for c in cols}
22
+ masked = set(cfg.masking_columns) # already lowercased by load_config
23
+ detectors = set(cfg.masking_detectors)
24
+ findings: list[tuple[str, str]] = []
25
+
26
+ for agent in cfg.agents.values():
27
+ for table, cols in agent.read.items():
28
+ if table not in colmap:
29
+ findings.append(("error", f"{agent.name}: reads table '{table}' which does not exist"))
30
+ continue
31
+ if cols in ("*", ["*"]):
32
+ wanted = colmap[table]
33
+ else:
34
+ wanted = set(cols)
35
+ for c in sorted(wanted - colmap[table]):
36
+ findings.append(("error", f"{agent.name}: reads column '{table}.{c}' which does not exist"))
37
+ wanted &= colmap[table]
38
+ for c in sorted(wanted):
39
+ m = _match(c)
40
+ if not m or c.lower() in masked:
41
+ continue
42
+ if m[1] and m[1] in detectors:
43
+ continue
44
+ findings.append(("warn", f"{agent.name}: can read '{table}.{c}', which looks sensitive, "
45
+ f"with no masking rule or detector"))
46
+ if agent.rows:
47
+ for table in sorted((set(agent.read) | set(agent.write)) & set(colmap)):
48
+ column = agent.rows.column_for(table)
49
+ if column not in colmap[table]:
50
+ findings.append(("warn", f"{agent.name}: sees every row of '{table}', which has no "
51
+ f"'{column}' column to lock rows by"))
52
+ for table in agent.write:
53
+ if table not in colmap:
54
+ findings.append(("error", f"{agent.name}: writes table '{table}' which does not exist"))
55
+ elif table not in agent.read:
56
+ findings.append(("warn", f"{agent.name}: can write '{table}' but cannot read it"))
57
+
58
+ for mc in sorted(masked):
59
+ if mc not in all_columns:
60
+ findings.append(("info", f"masking rule for column '{mc}' matches no column in the database"))
61
+
62
+ return findings
lokra/cli.py ADDED
@@ -0,0 +1,289 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import getpass
5
+ import json
6
+ import os
7
+ import sys
8
+ import time
9
+
10
+ from . import tokens
11
+ from .config import ConfigError, LAB_ADMIN_DSN, load_config
12
+ from .gateway import Gateway, GatewayError, decide, list_pending
13
+ from .ledger import Ledger
14
+
15
+
16
+ def _cfg(args):
17
+ return load_config(args.config, args.home)
18
+
19
+
20
+ def cmd_init(args):
21
+ from pathlib import Path
22
+
23
+ from .config import dump_policy
24
+ from .introspect import build_policy, introspect
25
+
26
+ out = Path(args.out or "policies.yaml")
27
+ if out.exists() and not args.force:
28
+ print(f"error: {out} already exists (use --out PATH or --force to overwrite)", file=sys.stderr)
29
+ return 1
30
+ tables = introspect(args.dsn)
31
+ if not tables:
32
+ print("no base tables found in schema 'public'", file=sys.stderr)
33
+ return 1
34
+ doc = build_policy(args.dsn, tables)
35
+ out.write_text(dump_policy(doc))
36
+ cols = doc["masking"]["columns"]
37
+ n_cols = sum(len(c) for c in tables.values())
38
+ print(f"introspected {len(tables)} table(s), {n_cols} column(s) (read-only)")
39
+ print(f"flagged {len(cols)} column(s) to mask: {', '.join(sorted(cols)) or '(none)'}")
40
+ print(f"wrote {out}")
41
+ print("\nnext steps:")
42
+ print(" 1. review the policy and tighten the agent's read grants")
43
+ print(' 2. lokra provision --admin-dsn "<admin connection string>"')
44
+ print(" 3. lokra dashboard")
45
+ return 0
46
+
47
+
48
+ def cmd_check(args):
49
+ from .check import check
50
+ cfg = _cfg(args)
51
+ dsn = args.dsn or os.environ.get("LOKRA_ADMIN_DSN") or LAB_ADMIN_DSN
52
+ findings = check(cfg, dsn)
53
+ errors = sum(1 for lvl, _ in findings if lvl == "error")
54
+ warns = sum(1 for lvl, _ in findings if lvl == "warn")
55
+ label = {"error": "ERROR", "warn": "WARN ", "info": "INFO "}
56
+ for lvl, msg in findings:
57
+ print(f" {label[lvl]} {msg}")
58
+ if not findings:
59
+ print(" OK policy matches the database, nothing sensitive left unmasked")
60
+ print(f"\n{errors} error(s), {warns} warning(s)")
61
+ return 1 if errors else 0
62
+
63
+
64
+ def cmd_provision(args):
65
+ from .provision import provision
66
+ cfg = _cfg(args)
67
+ dsn = args.admin_dsn or os.environ.get("LOKRA_ADMIN_DSN") or LAB_ADMIN_DSN
68
+ for line in provision(cfg, dsn):
69
+ print(line)
70
+ print(f"secrets saved to {cfg.secrets_path}")
71
+
72
+
73
+ def cmd_mint(args):
74
+ cfg = _cfg(args)
75
+ cfg.agent(args.agent)
76
+ print(tokens.mint(cfg.signing_key(), args.agent, args.on_behalf_of or getpass.getuser(),
77
+ args.ttl, purpose=args.purpose))
78
+
79
+
80
+ def cmd_try(args):
81
+ cfg = _cfg(args)
82
+ token = tokens.mint(cfg.signing_key(), args.agent, getpass.getuser(), 300, purpose=args.purpose)
83
+ gw = Gateway(cfg, token)
84
+ try:
85
+ if args.write:
86
+ out = gw.propose_write(args.sql, args.reason or "manual test")
87
+ else:
88
+ out = gw.query(args.sql)
89
+ except GatewayError as e:
90
+ print(f"REFUSED: {e}")
91
+ return 1
92
+ print(json.dumps(out, indent=2, default=str))
93
+
94
+
95
+ def cmd_pending(args):
96
+ cfg = _cfg(args)
97
+ rows = [r for r in list_pending(cfg) if args.all or r["status"] == "pending"]
98
+ if not rows:
99
+ print("no pending writes")
100
+ for r in rows:
101
+ age = int(time.time() - r["created_at"])
102
+ print(f"{r['id']} [{r['status']}] agent={r['agent']} for={r.get('on_behalf_of')} "
103
+ f"rows={r['would_affect_rows']} {age}s ago")
104
+ print(f" reason: {r['reason']}")
105
+ print(f" sql: {r['sql']}")
106
+ for w in r.get("warnings", []):
107
+ print(f" WARNING: {w}")
108
+
109
+
110
+ def _decide(args, approve: bool):
111
+ cfg = _cfg(args)
112
+ by = args.by or getpass.getuser()
113
+ from .gateway import _load_pending
114
+ r = _load_pending(cfg, args.write_id)
115
+ print(f"agent: {r['agent']} (for {r.get('on_behalf_of')})\nreason: {r['reason']}\nsql: {r['sql']}\n"
116
+ f"would affect {r['would_affect_rows']} row(s)")
117
+ for w in r.get("warnings", []):
118
+ print(f"WARNING: {w}")
119
+ if approve and not args.yes:
120
+ if input("approve? [y/N] ").strip().lower() != "y":
121
+ print("not approved")
122
+ return 1
123
+ decide(cfg, args.write_id, approve, by)
124
+ print(("approved" if approve else "denied") + f" by {by}")
125
+
126
+
127
+ def cmd_evidence(args):
128
+ from . import evidence as ev_mod
129
+ cfg = _cfg(args)
130
+ led = Ledger(cfg.ledger_path, cfg.signing_key())
131
+ ev = ev_mod.build(cfg, led.entries(), led.verify()[0])
132
+ if args.json:
133
+ print(json.dumps(ev, indent=2, default=str))
134
+ return 0
135
+ text = ev_mod.format_markdown(ev)
136
+ if args.out:
137
+ from pathlib import Path
138
+ Path(args.out).write_text(text)
139
+ print(f"wrote {args.out}")
140
+ else:
141
+ print(text)
142
+ return 0
143
+
144
+
145
+ def cmd_verify(args):
146
+ cfg = _cfg(args)
147
+ ok, n, msg = Ledger(cfg.ledger_path, cfg.signing_key()).verify()
148
+ print(msg)
149
+ return 0 if ok else 2
150
+
151
+
152
+ def cmd_log(args):
153
+ cfg = _cfg(args)
154
+ for e in Ledger(cfg.ledger_path, cfg.signing_key()).entries()[-args.n:]:
155
+ detail = e.get("sql") or e.get("reason") or e.get("write_id") or ""
156
+ print(f"{e['seq']:>5} {e['ts'][:19]} {e.get('agent', '-'):<18} {e['event']:<15} {str(detail)[:90]}")
157
+
158
+
159
+ def cmd_report(args):
160
+ import json as _json
161
+ from .report import build_report, format_text, to_dict
162
+ cfg = _cfg(args)
163
+ led = Ledger(cfg.ledger_path, cfg.signing_key())
164
+ chain_ok = led.verify()[0]
165
+ entries = led.entries()
166
+ if args.agent:
167
+ entries = [e for e in entries if e.get("agent") == args.agent or e.get("event") == "denied"]
168
+ report = build_report(entries)
169
+ if args.json:
170
+ print(_json.dumps(to_dict(report, chain_ok), indent=2, default=str))
171
+ else:
172
+ print(format_text(report, chain_ok))
173
+ return 0 if chain_ok else 2
174
+
175
+
176
+ def cmd_dashboard(args):
177
+ from .dashboard import serve
178
+ dsn = args.admin_dsn or os.environ.get("LOKRA_ADMIN_DSN") or LAB_ADMIN_DSN
179
+ serve(_cfg(args), args.port, dsn)
180
+ return 0
181
+
182
+
183
+ def cmd_serve(args):
184
+ if args.config:
185
+ os.environ["LOKRA_CONFIG"] = args.config
186
+ if args.home:
187
+ os.environ["LOKRA_HOME"] = args.home
188
+ if args.dev_agent and not os.environ.get("LOKRA_TOKEN"):
189
+ cfg = _cfg(args)
190
+ cfg.agent(args.dev_agent)
191
+ os.environ["LOKRA_TOKEN"] = tokens.mint(cfg.signing_key(), args.dev_agent,
192
+ args.on_behalf_of or getpass.getuser(), 8 * 3600)
193
+ print(f"lokra: dev mode, issued an 8h token for {args.dev_agent}", file=sys.stderr)
194
+ from .server import main
195
+ main()
196
+
197
+
198
+ def main(argv=None):
199
+ p = argparse.ArgumentParser(prog="lokra", description="Policy proxy between AI agents and your database")
200
+ p.add_argument("--config", help="path to policies.yaml (default: ./policies.yaml or $LOKRA_CONFIG)")
201
+ p.add_argument("--home", help="state directory (default: .lokra next to the config)")
202
+ sub = p.add_subparsers(dest="cmd", required=True)
203
+
204
+ s = sub.add_parser("init", help="introspect a database (read-only) and scaffold a starter policies.yaml")
205
+ s.add_argument("dsn", help="connection string to the target database, e.g. a Supabase or local Postgres")
206
+ s.add_argument("--out", help="where to write the policy (default: policies.yaml)")
207
+ s.add_argument("--force", action="store_true", help="overwrite the file if it already exists")
208
+ s.set_defaults(fn=cmd_init)
209
+
210
+ s = sub.add_parser("check", help="validate the policy against the database (read-only)")
211
+ s.add_argument("--dsn", help="connection string to check against (default: lab database)")
212
+ s.set_defaults(fn=cmd_check)
213
+
214
+ s = sub.add_parser("provision", help="create or update one DB role per agent")
215
+ s.add_argument("--admin-dsn", help="admin connection string (default: lab database)")
216
+ s.set_defaults(fn=cmd_provision)
217
+
218
+ s = sub.add_parser("mint-token", help="issue a short-lived token for an agent")
219
+ s.add_argument("agent")
220
+ s.add_argument("--on-behalf-of", help="the human launching the agent (default: your username)")
221
+ s.add_argument("--ttl", type=int, default=3600, help="seconds, max 8 hours")
222
+ s.add_argument("--purpose", help="declared purpose-of-use, recorded on every request")
223
+ s.set_defaults(fn=cmd_mint)
224
+
225
+ s = sub.add_parser("try", help="run SQL as an agent from the terminal")
226
+ s.add_argument("agent")
227
+ s.add_argument("sql")
228
+ s.add_argument("--write", action="store_true", help="propose a write instead of a read")
229
+ s.add_argument("--reason")
230
+ s.add_argument("--purpose", help="declared purpose-of-use for this request")
231
+ s.set_defaults(fn=cmd_try)
232
+
233
+ s = sub.add_parser("pending", help="list writes waiting for approval")
234
+ s.add_argument("--all", action="store_true")
235
+ s.set_defaults(fn=cmd_pending)
236
+
237
+ for name, approve in (("approve", True), ("deny", False)):
238
+ s = sub.add_parser(name, help=f"{name} a proposed write")
239
+ s.add_argument("write_id")
240
+ s.add_argument("--by", help="your name for the audit log")
241
+ if approve:
242
+ s.add_argument("--yes", action="store_true", help="skip the confirmation prompt")
243
+ s.set_defaults(fn=lambda a, approve=approve: _decide(a, approve))
244
+
245
+ s = sub.add_parser("verify-ledger", help="check the audit ledger has not been tampered with")
246
+ s.set_defaults(fn=cmd_verify)
247
+
248
+ s = sub.add_parser("log", help="show recent audit entries")
249
+ s.add_argument("-n", type=int, default=20)
250
+ s.set_defaults(fn=cmd_log)
251
+
252
+ s = sub.add_parser("report", help="activity and risk report from the audit ledger")
253
+ s.add_argument("--agent", help="limit to one agent")
254
+ s.add_argument("--json", action="store_true")
255
+ s.set_defaults(fn=cmd_report)
256
+
257
+ s = sub.add_parser("evidence", help="generate a control evidence pack from the policy and ledger")
258
+ s.add_argument("--out", help="write the Markdown pack to this file instead of stdout")
259
+ s.add_argument("--json", action="store_true", help="emit structured JSON instead of Markdown")
260
+ s.set_defaults(fn=cmd_evidence)
261
+
262
+ s = sub.add_parser("dashboard", help="serve a local web dashboard of the ledger and policy")
263
+ s.add_argument("--port", type=int, default=8900)
264
+ s.add_argument("--admin-dsn", help="admin connection string used when applying policy (default: lab database)")
265
+ s.set_defaults(fn=cmd_dashboard)
266
+
267
+ s = sub.add_parser("serve", help="run the MCP server (used by Claude Code)")
268
+ s.add_argument("--dev-agent", help="LOCAL DEV ONLY: issue an 8h token for this agent at startup "
269
+ "if LOKRA_TOKEN is not set")
270
+ s.add_argument("--on-behalf-of", help="human recorded in the audit log (default: your username)")
271
+ s.set_defaults(fn=cmd_serve)
272
+
273
+ args = p.parse_args(argv)
274
+ try:
275
+ return args.fn(args) or 0
276
+ except ConfigError as e:
277
+ print(f"error: {e}", file=sys.stderr)
278
+ print("hint: run this from your project folder (where policies.yaml lives), "
279
+ "or pass --config /path/to/policies.yaml", file=sys.stderr)
280
+ return 1
281
+ except Exception as e:
282
+ if os.environ.get("LOKRA_DEBUG"):
283
+ raise
284
+ print(f"error: {e}", file=sys.stderr)
285
+ return 1
286
+
287
+
288
+ if __name__ == "__main__":
289
+ sys.exit(main())
lokra/config.py ADDED
@@ -0,0 +1,165 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ import re
6
+ import secrets
7
+ from dataclasses import dataclass, field
8
+ from pathlib import Path
9
+
10
+ import yaml
11
+
12
+ LAB_ADMIN_DSN = "postgresql://postgres:postgres@127.0.0.1:55432/clinic"
13
+
14
+
15
+ class ConfigError(Exception):
16
+ pass
17
+
18
+
19
+ @dataclass
20
+ class RowLock:
21
+ column: str
22
+ values: list[int | str]
23
+ tables: dict[str, str] = field(default_factory=dict)
24
+
25
+ def column_for(self, table: str) -> str:
26
+ return self.tables.get(table, self.column)
27
+
28
+ def describe(self) -> str:
29
+ text = f"rows where {self.column} in {self.values}"
30
+ for table, column in sorted(self.tables.items()):
31
+ text += f" ({table}: {column})"
32
+ return text
33
+
34
+
35
+ @dataclass
36
+ class AgentPolicy:
37
+ name: str
38
+ description: str = ""
39
+ rows: RowLock | None = None
40
+ read: dict[str, list[str] | str] = field(default_factory=dict)
41
+ write: dict[str, list[str]] = field(default_factory=dict)
42
+ max_rows: int = 200
43
+ purposes: list[str] = field(default_factory=list)
44
+
45
+ @property
46
+ def role(self) -> str:
47
+ return "lokra_" + re.sub(r"[^a-z0-9]+", "_", self.name.lower()).strip("_")
48
+
49
+
50
+ @dataclass
51
+ class Config:
52
+ path: Path
53
+ home: Path
54
+ db_host: str
55
+ db_port: int
56
+ db_name: str
57
+ agents: dict[str, AgentPolicy]
58
+ masking_columns: dict[str, str]
59
+ masking_detectors: list[str]
60
+ approval_ttl_seconds: int = 3600
61
+ require_purpose: bool = False
62
+
63
+ @property
64
+ def ledger_path(self) -> Path:
65
+ return self.home / "ledger.jsonl"
66
+
67
+ @property
68
+ def pending_dir(self) -> Path:
69
+ return self.home / "pending"
70
+
71
+ @property
72
+ def secrets_path(self) -> Path:
73
+ return self.home / "secrets.json"
74
+
75
+ def ensure_home(self) -> None:
76
+ self.home.mkdir(parents=True, exist_ok=True, mode=0o700)
77
+ self.pending_dir.mkdir(exist_ok=True, mode=0o700)
78
+
79
+ def signing_key(self) -> bytes:
80
+ self.ensure_home()
81
+ p = self.home / "signing.key"
82
+ if not p.exists():
83
+ p.write_bytes(secrets.token_bytes(32))
84
+ p.chmod(0o600)
85
+ return p.read_bytes()
86
+
87
+ def db_secrets(self) -> dict[str, str]:
88
+ if not self.secrets_path.exists():
89
+ return {}
90
+ return json.loads(self.secrets_path.read_text())
91
+
92
+ def save_db_secrets(self, data: dict[str, str]) -> None:
93
+ self.ensure_home()
94
+ self.secrets_path.write_text(json.dumps(data, indent=2))
95
+ self.secrets_path.chmod(0o600)
96
+
97
+ def agent(self, name: str) -> AgentPolicy:
98
+ try:
99
+ return self.agents[name]
100
+ except KeyError:
101
+ raise ConfigError(f"unknown agent '{name}'") from None
102
+
103
+
104
+ def dump_policy(doc: dict) -> str:
105
+ class Dumper(yaml.SafeDumper):
106
+ pass
107
+
108
+ def seq(dumper, data):
109
+ flow = all(isinstance(x, (str, int, float, bool)) for x in data)
110
+ return dumper.represent_sequence("tag:yaml.org,2002:seq", data, flow_style=flow)
111
+
112
+ Dumper.add_representer(list, seq)
113
+ return yaml.dump(doc, Dumper=Dumper, sort_keys=False, default_flow_style=False, allow_unicode=True)
114
+
115
+
116
+ def _row_lock(agent: str, raw) -> RowLock | None:
117
+ if not raw:
118
+ return None
119
+ if not isinstance(raw, dict) or not raw.get("column") or raw.get("values") in (None, [], ""):
120
+ raise ConfigError(f"{agent}: rows needs a column and at least one value, "
121
+ f"e.g. rows: {{column: org_id, values: [42]}}")
122
+ values = raw["values"] if isinstance(raw["values"], list) else [raw["values"]]
123
+ if not all(isinstance(v, (int, str)) and not isinstance(v, bool) for v in values):
124
+ raise ConfigError(f"{agent}: row values must be numbers or strings")
125
+ tables = raw.get("tables") or {}
126
+ if not isinstance(tables, dict):
127
+ raise ConfigError(f"{agent}: rows.tables maps a table to the column that holds its scope")
128
+ return RowLock(str(raw["column"]), values, {str(t): str(c) for t, c in tables.items()})
129
+
130
+
131
+ def load_config(path: str | os.PathLike | None = None, home: str | os.PathLike | None = None) -> Config:
132
+ path = Path(path or os.environ.get("LOKRA_CONFIG", "policies.yaml")).resolve()
133
+ if not path.exists():
134
+ raise ConfigError(f"config not found: {path}")
135
+ raw = yaml.safe_load(path.read_text()) or {}
136
+ db = raw.get("database", {})
137
+ agents = {}
138
+ for name, a in (raw.get("agents") or {}).items():
139
+ a = a or {}
140
+ if "clinic_ids" in a:
141
+ raise ConfigError(f"{name}: clinic_ids was replaced by rows, e.g. "
142
+ f"rows: {{column: clinic_id, values: {a['clinic_ids']}, tables: {{clinics: id}}}}")
143
+ agents[name] = AgentPolicy(
144
+ name=name,
145
+ description=a.get("description", ""),
146
+ rows=_row_lock(name, a.get("rows")),
147
+ read=a.get("read", {}) or {},
148
+ write=a.get("write", {}) or {},
149
+ max_rows=int(a.get("max_rows", 200)),
150
+ purposes=[str(p) for p in (a.get("purposes") or [])],
151
+ )
152
+ masking = raw.get("masking", {}) or {}
153
+ home = Path(home or os.environ.get("LOKRA_HOME") or path.parent / ".lokra").resolve()
154
+ return Config(
155
+ path=path,
156
+ home=home,
157
+ db_host=db.get("host", "127.0.0.1"),
158
+ db_port=int(db.get("port", 55432)),
159
+ db_name=db.get("dbname", "clinic"),
160
+ agents=agents,
161
+ masking_columns={k.lower(): v for k, v in (masking.get("columns") or {}).items()},
162
+ masking_detectors=list(masking.get("detectors") or []),
163
+ approval_ttl_seconds=int(raw.get("approval_ttl_seconds", 3600)),
164
+ require_purpose=bool(raw.get("require_purpose", False)),
165
+ )