aienos.com
Source of www.aienos.com, served from my own hardware
Brought by drakestapleton
aienos.com / scripts / allen / contacts / allen_contacts_ingest.py
| 1 | #!/usr/bin/python3 -I |
| 2 | """Private contact store for public Allen: Python reference (parity oracle) and CLI library. |
| 3 | |
| 4 | The production ingest is the seeded-Omega port `allen_contacts_ingest.om`; this file |
| 5 | specifies the same behaviour and is run against it on a shared fixture set |
| 6 | (test_parity.py). The `allen-contacts` CLI imports this module. |
| 7 | |
| 8 | `ingest` moves consented contact drops written by the gateway |
| 9 | (/var/lib/allen-chat/contacts-drop/<16 hex>.json, see CONTRACT.md) into the private |
| 10 | store /var/lib/allen-contacts/contacts.jsonl: |
| 11 | |
| 12 | introduce -> the drop bytes plus "\\n" are appended (O_APPEND, fsync). Append-only. |
| 13 | forget -> the store is rewritten without the record only when the ids match |
| 14 | and hmac.compare_digest(token_sha256, record.delete_token_sha256) |
| 15 | holds (tmp file + fsync + rename). |
| 16 | forget_visitor -> the store is rewritten without every record whose "vid" equals the |
| 17 | drop's 64-hex vid (an empty vid is invalid, so "" never matches). |
| 18 | anything else -> copied to <store>/quarantine/, nothing stored. |
| 19 | |
| 20 | A drop is accepted only in the gateway's exact serialization, |
| 21 | json.dumps(record, ensure_ascii=False, sort_keys=True), with the CONTRACT field |
| 22 | rules. So a store line is the canonical drop, byte for byte. |
| 23 | |
| 24 | Every processed drop is deleted. The journal gets one summary line of counts. No |
| 25 | contact field is ever logged. audit.log keeps one tombstone line per deletion with |
| 26 | the timestamp, the event and the count removed; it records no id and no field. |
| 27 | |
| 28 | Store writers (ingest, CLI delete) serialize through the lock directory |
| 29 | <store>/.lock.d (mkdir is atomic); a lock older than LOCK_STALE_S is broken. |
| 30 | """ |
| 31 | import errno |
| 32 | import hmac |
| 33 | import json |
| 34 | import os |
| 35 | import re |
| 36 | import secrets |
| 37 | import stat |
| 38 | import sys |
| 39 | import time |
| 40 | |
| 41 | # Environment overrides exist for the tests' temporary directories only; the unit |
| 42 | # and the sudo re-exec of the CLI run with a clean environment. |
| 43 | DROP_DIR = os.environ.get("ALLEN_CONTACTS_DROP", "/var/lib/allen-chat/contacts-drop") |
| 44 | STORE_DIR = os.environ.get("ALLEN_CONTACTS_STORE", "/var/lib/allen-contacts") |
| 45 | STORE_NAME = "contacts.jsonl" |
| 46 | AUDIT_NAME = "audit.log" |
| 47 | LOCK_NAME = ".lock.d" |
| 48 | QUARANTINE = "quarantine" |
| 49 | |
| 50 | MAX_DROP_BYTES = 64 * 1024 |
| 51 | MAX_ENTRIES = 4096 |
| 52 | QUARANTINE_CAP = 1000 |
| 53 | TEMP_STALE_S = 60 |
| 54 | LOCK_WAIT_S = 10 |
| 55 | LOCK_STALE_S = 300 |
| 56 | |
| 57 | DROP_NAME = re.compile(rb"[0-9a-f]{16}\.json") |
| 58 | ID_RE = re.compile(r"c_[0-9a-f]{16}", re.ASCII) |
| 59 | SHA_RE = re.compile(r"[0-9a-f]{64}", re.ASCII) |
| 60 | RECEIVED_RE = re.compile(r"([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})Z", |
| 61 | re.ASCII) |
| 62 | HOMEPAGE_RE = re.compile(r"https://[^\s]{4,}") |
| 63 | |
| 64 | # Field caps from CONTRACT.md (POST introduce); same table as the gateway. |
| 65 | TEXT_FIELDS = {"name": 100, "org": 100, "contact": 200, "github": 39, "origin": 200, |
| 66 | "purpose": 1000, "homepage": 200, "framework": 100, "model": 100, |
| 67 | "human": 200} |
| 68 | INTRODUCE_KEYS = frozenset(TEXT_FIELDS) | {"v", "type", "id", "received", "via", "kind", |
| 69 | "delete_token_sha256", "vid"} |
| 70 | FORGET_KEYS = frozenset({"v", "type", "id", "token_sha256", "received"}) |
| 71 | FORGET_VISITOR_KEYS = frozenset({"v", "type", "vid", "received"}) |
| 72 | |
| 73 | O_DIR = os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC |
| 74 | |
| 75 | |
| 76 | class Invalid(Exception): |
| 77 | """A drop that fails validation.""" |
| 78 | |
| 79 | |
| 80 | def _reject(*_): |
| 81 | raise Invalid() |
| 82 | |
| 83 | |
| 84 | def _text(v, cap): |
| 85 | if not isinstance(v, str) or len(v) > cap or v != v.strip(): |
| 86 | raise Invalid() |
| 87 | for c in v: |
| 88 | o = ord(c) |
| 89 | if (o < 32 and c not in "\n\t") or o == 127: |
| 90 | raise Invalid() |
| 91 | |
| 92 | |
| 93 | def _received(v): |
| 94 | m = RECEIVED_RE.fullmatch(v) if isinstance(v, str) else None |
| 95 | if not m: |
| 96 | raise Invalid() |
| 97 | y, mo, d, h, mi, s = (int(x) for x in m.groups()) |
| 98 | leap = y % 4 == 0 and (y % 100 != 0 or y % 400 == 0) |
| 99 | dim = (31, 29 if leap else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) |
| 100 | if not (y >= 1 and 1 <= mo <= 12 and 1 <= d <= dim[mo - 1] and h <= 23 and mi <= 59 |
| 101 | and s <= 59): |
| 102 | raise Invalid() |
| 103 | |
| 104 | |
| 105 | def parse_drop(data): |
| 106 | """Bytes -> validated record dict. Raises Invalid.""" |
| 107 | try: |
| 108 | rec = json.loads(data.decode("utf-8"), object_pairs_hook=_pairs, |
| 109 | parse_constant=_reject) |
| 110 | except (ValueError, RecursionError): |
| 111 | raise Invalid() from None |
| 112 | if not isinstance(rec, dict): |
| 113 | raise Invalid() |
| 114 | if json.dumps(rec, ensure_ascii=False, sort_keys=True).encode("utf-8") != data: |
| 115 | raise Invalid() |
| 116 | if type(rec.get("v")) is not int or rec["v"] != 1: |
| 117 | raise Invalid() |
| 118 | kind = rec.get("type") |
| 119 | if kind == "introduce": |
| 120 | if set(rec) != INTRODUCE_KEYS: |
| 121 | raise Invalid() |
| 122 | for k, cap in TEXT_FIELDS.items(): |
| 123 | _text(rec[k], cap) |
| 124 | if rec["kind"] not in ("human", "agent") or rec["via"] not in ("chat", "api"): |
| 125 | raise Invalid() |
| 126 | if not (rec["name"] or rec["contact"]): |
| 127 | raise Invalid() |
| 128 | if rec["homepage"] and not HOMEPAGE_RE.fullmatch(rec["homepage"]): |
| 129 | raise Invalid() |
| 130 | if rec["vid"] != "" and not (isinstance(rec["vid"], str) and SHA_RE.fullmatch(rec["vid"])): |
| 131 | raise Invalid() |
| 132 | sha = rec["delete_token_sha256"] |
| 133 | elif kind == "forget": |
| 134 | if set(rec) != FORGET_KEYS: |
| 135 | raise Invalid() |
| 136 | sha = rec["token_sha256"] |
| 137 | elif kind == "forget_visitor": |
| 138 | if set(rec) != FORGET_VISITOR_KEYS: |
| 139 | raise Invalid() |
| 140 | if not isinstance(rec["vid"], str) or not SHA_RE.fullmatch(rec["vid"]): |
| 141 | raise Invalid() # an empty vid never matches anything |
| 142 | _received(rec["received"]) |
| 143 | return rec |
| 144 | else: |
| 145 | raise Invalid() |
| 146 | if not isinstance(sha, str) or not SHA_RE.fullmatch(sha): |
| 147 | raise Invalid() |
| 148 | if not isinstance(rec["id"], str) or not ID_RE.fullmatch(rec["id"]): |
| 149 | raise Invalid() |
| 150 | _received(rec["received"]) |
| 151 | return rec |
| 152 | |
| 153 | |
| 154 | def _pairs(pairs): |
| 155 | d = {} |
| 156 | for k, v in pairs: |
| 157 | if k in d: |
| 158 | raise Invalid() |
| 159 | d[k] = v |
| 160 | return d |
| 161 | |
| 162 | |
| 163 | # ---------------------------------------------------------------- store |
| 164 | |
| 165 | def _fsync_dir(path): |
| 166 | fd = os.open(path, O_DIR) |
| 167 | try: |
| 168 | os.fsync(fd) |
| 169 | finally: |
| 170 | os.close(fd) |
| 171 | |
| 172 | |
| 173 | def _check_private_dir(path, group_ok=0): |
| 174 | """Fail closed unless `path` is a real directory we own with no access beyond |
| 175 | owner (+ the `group_ok` group bits: the drop dir is allen-contacts:allen-drop 2730).""" |
| 176 | st = os.lstat(path) |
| 177 | if not stat.S_ISDIR(st.st_mode): |
| 178 | raise SystemExit("allen-contacts: %s is not a directory" % path) |
| 179 | if st.st_uid != os.getuid() or st.st_mode & 0o077 & ~group_ok: |
| 180 | raise SystemExit("allen-contacts: %s must be owned by uid %d, mode 0700%s" |
| 181 | % (path, os.getuid(), " or 2730" if group_ok else "")) |
| 182 | |
| 183 | |
| 184 | def stamp(fmt, now=None): |
| 185 | return time.strftime(fmt, time.gmtime(time.time() if now is None else now)) |
| 186 | |
| 187 | |
| 188 | class Store: |
| 189 | """contacts.jsonl; writers hold the lock directory <store>/.lock.d.""" |
| 190 | |
| 191 | def __init__(self, root=None, now=None): |
| 192 | self.root = root or STORE_DIR |
| 193 | _check_private_dir(self.root) |
| 194 | self.path = os.path.join(self.root, STORE_NAME) |
| 195 | self.lock = os.path.join(self.root, LOCK_NAME) |
| 196 | self.now = now |
| 197 | |
| 198 | def __enter__(self): |
| 199 | deadline = time.monotonic() + LOCK_WAIT_S |
| 200 | while True: |
| 201 | try: |
| 202 | os.mkdir(self.lock, 0o700) |
| 203 | return self |
| 204 | except FileExistsError: |
| 205 | pass |
| 206 | try: |
| 207 | if time.time() - os.lstat(self.lock).st_mtime > LOCK_STALE_S: |
| 208 | os.rmdir(self.lock) |
| 209 | continue |
| 210 | except FileNotFoundError: |
| 211 | continue |
| 212 | if time.monotonic() >= deadline: |
| 213 | raise SystemExit("allen-contacts: store is locked (%s)" % self.lock) |
| 214 | time.sleep(0.05) |
| 215 | |
| 216 | def __exit__(self, *exc): |
| 217 | os.rmdir(self.lock) |
| 218 | |
| 219 | def raw(self): |
| 220 | try: |
| 221 | fd = os.open(self.path, os.O_RDONLY | os.O_CLOEXEC | os.O_NOFOLLOW) |
| 222 | except FileNotFoundError: |
| 223 | return b"" |
| 224 | with os.fdopen(fd, "rb") as f: |
| 225 | return f.read() |
| 226 | |
| 227 | def lines(self): |
| 228 | """[(raw_line, record_or_None)]; unparsable lines are kept verbatim.""" |
| 229 | out = [] |
| 230 | for raw in self.raw().split(b"\n"): |
| 231 | if not raw.strip(): |
| 232 | continue |
| 233 | try: |
| 234 | rec = json.loads(raw) |
| 235 | if not isinstance(rec, dict): |
| 236 | rec = None |
| 237 | except ValueError: |
| 238 | rec = None |
| 239 | out.append((raw, rec)) |
| 240 | return out |
| 241 | |
| 242 | def records(self): |
| 243 | return [r for _, r in self.lines() if r is not None] |
| 244 | |
| 245 | def find(self, cid): |
| 246 | for raw, r in self.lines(): |
| 247 | if r is not None and r.get("id") == cid: |
| 248 | return raw, r |
| 249 | return None, None |
| 250 | |
| 251 | def append(self, line): |
| 252 | created = not os.path.exists(self.path) |
| 253 | fd = os.open(self.path, os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_CLOEXEC |
| 254 | | os.O_NOFOLLOW, 0o600) |
| 255 | try: |
| 256 | os.fchmod(fd, 0o600) |
| 257 | view = memoryview(line + b"\n") |
| 258 | while view: |
| 259 | view = view[os.write(fd, view):] |
| 260 | os.fsync(fd) |
| 261 | finally: |
| 262 | os.close(fd) |
| 263 | if created: |
| 264 | _fsync_dir(self.root) |
| 265 | |
| 266 | def remove(self, key, value): |
| 267 | """Atomically rewrite without the records whose `key` equals `value` (a non-empty |
| 268 | id or vid). Unparsable lines are kept. Returns (removed, remaining).""" |
| 269 | entries = self.lines() |
| 270 | kept = [raw for raw, rec in entries if rec is None or rec.get(key) != value] |
| 271 | removed = len(entries) - len(kept) |
| 272 | if removed == 0: |
| 273 | return 0, len(kept) |
| 274 | tmp = os.path.join(self.root, ".%s.tmp-%s" % (STORE_NAME, secrets.token_hex(8))) |
| 275 | fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_CLOEXEC, 0o600) |
| 276 | try: |
| 277 | with os.fdopen(fd, "wb") as f: |
| 278 | f.write(b"".join(raw + b"\n" for raw in kept)) |
| 279 | f.flush() |
| 280 | os.fsync(f.fileno()) |
| 281 | os.replace(tmp, self.path) |
| 282 | except BaseException: |
| 283 | try: |
| 284 | os.unlink(tmp) |
| 285 | except FileNotFoundError: |
| 286 | pass |
| 287 | raise |
| 288 | _fsync_dir(self.root) |
| 289 | return removed, len(kept) |
| 290 | |
| 291 | def audit(self, event, removed): |
| 292 | line = "%s %s removed=%d\n" % (stamp("%Y-%m-%dT%H:%M:%SZ", self.now), event, removed) |
| 293 | fd = os.open(os.path.join(self.root, AUDIT_NAME), |
| 294 | os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_CLOEXEC | os.O_NOFOLLOW, 0o600) |
| 295 | try: |
| 296 | os.write(fd, line.encode("ascii")) |
| 297 | os.fsync(fd) |
| 298 | finally: |
| 299 | os.close(fd) |
| 300 | |
| 301 | |
| 302 | # ---------------------------------------------------------------- ingest |
| 303 | |
| 304 | def _bump(counts, key): |
| 305 | counts[key] = counts.get(key, 0) + 1 |
| 306 | |
| 307 | |
| 308 | def _quarantine(store, data, counts): |
| 309 | qdir = os.path.join(store.root, QUARANTINE) |
| 310 | try: |
| 311 | os.mkdir(qdir, 0o700) |
| 312 | except FileExistsError: |
| 313 | pass |
| 314 | _check_private_dir(qdir) |
| 315 | if len(os.listdir(qdir)) >= QUARANTINE_CAP: |
| 316 | _bump(counts, "quarantine_full_discarded") |
| 317 | return |
| 318 | name = "%s-%s.json" % (stamp("%Y%m%dT%H%M%SZ", store.now), secrets.token_hex(4)) |
| 319 | fd = os.open(os.path.join(qdir, name), |
| 320 | os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_CLOEXEC | os.O_NOFOLLOW, 0o600) |
| 321 | with os.fdopen(fd, "wb") as f: |
| 322 | f.write(data[:MAX_DROP_BYTES]) |
| 323 | f.flush() |
| 324 | os.fsync(f.fileno()) |
| 325 | _fsync_dir(qdir) |
| 326 | |
| 327 | |
| 328 | def _remove_entry(dfd, name, counts, key): |
| 329 | """Remove an entry without following it: unlink, else rmdir (an empty directory).""" |
| 330 | try: |
| 331 | os.unlink(name, dir_fd=dfd) |
| 332 | except FileNotFoundError: |
| 333 | return |
| 334 | except OSError: |
| 335 | try: |
| 336 | os.rmdir(name, dir_fd=dfd) |
| 337 | except OSError: |
| 338 | _bump(counts, "stuck_nonregular") |
| 339 | return |
| 340 | _bump(counts, key) |
| 341 | |
| 342 | |
| 343 | def _process(dfd, name, store, counts): |
| 344 | try: |
| 345 | fd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC, |
| 346 | dir_fd=dfd) |
| 347 | except FileNotFoundError: |
| 348 | return |
| 349 | except OSError: |
| 350 | _remove_entry(dfd, name, counts, "removed_nonregular") |
| 351 | return |
| 352 | try: |
| 353 | st = os.fstat(fd) |
| 354 | regular = stat.S_ISREG(st.st_mode) and st.st_nlink == 1 |
| 355 | data = b"" |
| 356 | while regular and len(data) <= MAX_DROP_BYTES: |
| 357 | b = os.read(fd, MAX_DROP_BYTES + 1 - len(data)) |
| 358 | if not b: |
| 359 | break |
| 360 | data += b |
| 361 | finally: |
| 362 | os.close(fd) |
| 363 | if not regular: |
| 364 | _remove_entry(dfd, name, counts, "removed_nonregular") |
| 365 | return |
| 366 | |
| 367 | reason = None |
| 368 | rec = None |
| 369 | if not DROP_NAME.fullmatch(name): |
| 370 | reason = "q_name" |
| 371 | elif len(data) > MAX_DROP_BYTES: |
| 372 | reason = "q_oversize" |
| 373 | else: |
| 374 | try: |
| 375 | rec = parse_drop(data) |
| 376 | except Invalid: |
| 377 | reason = "q_invalid" |
| 378 | if reason is None and rec["type"] == "introduce": |
| 379 | existing, _ = store.find(rec["id"]) |
| 380 | if existing is None: |
| 381 | store.append(data) |
| 382 | _bump(counts, "introduce_stored") |
| 383 | elif existing == data: |
| 384 | _bump(counts, "introduce_already_stored") |
| 385 | else: |
| 386 | reason = "q_duplicate_id" |
| 387 | elif reason is None and rec["type"] == "forget": |
| 388 | _, target = store.find(rec["id"]) |
| 389 | have = target.get("delete_token_sha256") if target else None |
| 390 | if not (isinstance(have, str) and SHA_RE.fullmatch(have)): |
| 391 | have = "0" * 64 |
| 392 | match = hmac.compare_digest(rec["token_sha256"].encode("ascii"), have.encode("ascii")) |
| 393 | if match and target is not None: |
| 394 | removed, _ = store.remove("id", rec["id"]) |
| 395 | store.audit("forget", removed) |
| 396 | _bump(counts, "forget_matched") |
| 397 | else: |
| 398 | _bump(counts, "forget_unmatched") |
| 399 | elif reason is None: |
| 400 | removed, _ = store.remove("vid", rec["vid"]) |
| 401 | if removed: |
| 402 | store.audit("forget_visitor", removed) |
| 403 | _bump(counts, "forget_visitor_matched") |
| 404 | else: |
| 405 | _bump(counts, "forget_visitor_unmatched") |
| 406 | if reason is not None: |
| 407 | _quarantine(store, data, counts) |
| 408 | _bump(counts, "quarantined") |
| 409 | _bump(counts, reason) |
| 410 | os.unlink(name, dir_fd=dfd) |
| 411 | |
| 412 | |
| 413 | def ingest(drop_dir=None, store_root=None, now=None): |
| 414 | """One pass over the drop directory. Dot files are the gateway's in-flight temp files |
| 415 | (".tmp-<16hex>"); systemd's DirectoryNotEmpty= ignores hidden entries, so they never |
| 416 | trigger a run, and the rename to "<16hex>.json" triggers the next one. Temp files older |
| 417 | than TEMP_STALE_S (a writer that died mid-write) are removed. Entries are taken in |
| 418 | (mtime, name) order, at most MAX_ENTRIES per run.""" |
| 419 | drop_dir = drop_dir or DROP_DIR |
| 420 | _check_private_dir(drop_dir, group_ok=0o030) |
| 421 | store = Store(store_root, now) |
| 422 | counts = {} |
| 423 | dfd = os.open(drop_dir, O_DIR) |
| 424 | try: |
| 425 | entries = [] |
| 426 | with os.scandir(dfd) as it: |
| 427 | for e in it: |
| 428 | if len(entries) >= MAX_ENTRIES: |
| 429 | break |
| 430 | try: |
| 431 | st = e.stat(follow_symlinks=False) |
| 432 | except FileNotFoundError: |
| 433 | continue |
| 434 | entries.append((st.st_mtime_ns, os.fsencode(e.name))) |
| 435 | with store: |
| 436 | for mtime_ns, name in sorted(entries): |
| 437 | if name.startswith(b"."): |
| 438 | if time.time_ns() - mtime_ns > TEMP_STALE_S * 1_000_000_000: |
| 439 | _remove_entry(dfd, name, counts, "temp_stale_removed") |
| 440 | else: |
| 441 | _bump(counts, "temp_pending") |
| 442 | continue |
| 443 | _process(dfd, name, store, counts) |
| 444 | finally: |
| 445 | os.close(dfd) |
| 446 | summary = " ".join("%s=%d" % kv for kv in sorted(counts.items())) or "nothing" |
| 447 | print("allen-contacts-ingest: " + summary, flush=True) |
| 448 | return counts |
| 449 | |
| 450 | |
| 451 | def main(argv): |
| 452 | if argv == ["ingest"]: |
| 453 | ingest() |
| 454 | return 0 |
| 455 | if len(argv) == 4 and argv[0] == "ingest" and argv[3].isdigit(): |
| 456 | ingest(argv[1], argv[2], int(argv[3])) |
| 457 | return 0 |
| 458 | sys.stderr.write("usage: allen_contacts_ingest.py ingest [DROP STORE EPOCH]\n") |
| 459 | return 64 |
| 460 | |
| 461 | |
| 462 | if __name__ == "__main__": |
| 463 | sys.exit(main(sys.argv[1:])) |