aienos.com
Source of www.aienos.com, served from my own hardware
Brought by drakestapleton
aienos.com / scripts / allen / contacts / test_contacts.py
| 1 | #!/usr/bin/python3 |
| 2 | """Tests for allen_contacts_ingest + allen-contacts. Every positive check has a negative |
| 3 | control. Run: nice -n 19 python3 test_contacts.py (temporary dirs only) |
| 4 | RUN_INSTALLED=1 nice -n 19 python3 test_contacts.py (+ installed smoke) |
| 5 | """ |
| 6 | import contextlib |
| 7 | import hashlib |
| 8 | import io |
| 9 | import json |
| 10 | import os |
| 11 | import secrets |
| 12 | import shutil |
| 13 | import stat |
| 14 | import subprocess |
| 15 | import sys |
| 16 | import tempfile |
| 17 | import time |
| 18 | import unittest |
| 19 | |
| 20 | HERE = os.path.dirname(os.path.abspath(__file__)) |
| 21 | sys.path.insert(0, HERE) |
| 22 | import allen_contacts_ingest as aci # noqa: E402 |
| 23 | |
| 24 | REAL_DROP = "/var/lib/allen-chat/contacts-drop" |
| 25 | REAL_STORE_DIR = "/var/lib/allen-contacts" |
| 26 | REAL_STORE = REAL_STORE_DIR + "/contacts.jsonl" |
| 27 | INSTALLED_CLI = "/usr/local/bin/allen-contacts" |
| 28 | |
| 29 | # The gateway-side properties under test (CONTRACT.md: system unit, User=allen-chat). |
| 30 | GATEWAY_PROPS = [ |
| 31 | "User=allen-chat", |
| 32 | "NoNewPrivileges=yes", |
| 33 | "CapabilityBoundingSet=", |
| 34 | "PrivateUsers=yes", |
| 35 | "ProtectProc=invisible", |
| 36 | "ProtectSystem=strict", |
| 37 | "ProtectHome=yes", |
| 38 | "PrivateTmp=yes", |
| 39 | "ReadWritePaths=/var/lib/allen-chat/contacts-drop /var/lib/allen-chat/spool-in", |
| 40 | ] |
| 41 | |
| 42 | |
| 43 | def sha(token): |
| 44 | return hashlib.sha256(token.encode()).hexdigest() |
| 45 | |
| 46 | |
| 47 | def intro(**over): |
| 48 | rec = {"v": 1, "type": "introduce", "id": "c_" + secrets.token_hex(8), |
| 49 | "received": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "via": "chat", |
| 50 | "kind": "human", "name": "Ada Canary", "org": "Canary Org", |
| 51 | "contact": "ada@example.invalid", "github": "ada-canary", "origin": "Dublin", |
| 52 | "purpose": "Building a canary\nsecond line", "homepage": "https://example.invalid/x", |
| 53 | "framework": "", "model": "", "human": "", "delete_token_sha256": sha("tok-A"), |
| 54 | "vid": ""} |
| 55 | rec.update(over) |
| 56 | return rec |
| 57 | |
| 58 | |
| 59 | def canon(obj): |
| 60 | """The gateway's exact drop serialization.""" |
| 61 | return json.dumps(obj, ensure_ascii=False, sort_keys=True).encode() |
| 62 | |
| 63 | |
| 64 | def write_drop(d, obj, name=None): |
| 65 | """Gateway-style: '.tmp-<hex>' then rename to '<hex>.json'.""" |
| 66 | name = name or secrets.token_hex(8) + ".json" |
| 67 | data = obj if isinstance(obj, bytes) else canon(obj) |
| 68 | tmp = os.path.join(d, ".tmp-" + secrets.token_hex(8)) |
| 69 | fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) |
| 70 | with os.fdopen(fd, "wb") as f: |
| 71 | f.write(data) |
| 72 | os.rename(tmp, os.path.join(d, name)) |
| 73 | return name |
| 74 | |
| 75 | |
| 76 | def rd(path): |
| 77 | with open(path) as f: |
| 78 | return f.read() |
| 79 | |
| 80 | |
| 81 | def wr(path, text): |
| 82 | with open(path, "w") as f: |
| 83 | f.write(text) |
| 84 | |
| 85 | |
| 86 | class Tmp(unittest.TestCase): |
| 87 | def setUp(self): |
| 88 | self.base = tempfile.mkdtemp(prefix="allen-contacts-test-") |
| 89 | self.drop = os.path.join(self.base, "drop") |
| 90 | self.store = os.path.join(self.base, "store") |
| 91 | os.mkdir(self.drop, 0o700) |
| 92 | os.mkdir(self.store, 0o700) |
| 93 | |
| 94 | def tearDown(self): |
| 95 | shutil.rmtree(self.base) |
| 96 | |
| 97 | def ingest(self): |
| 98 | out = io.StringIO() |
| 99 | with contextlib.redirect_stdout(out): |
| 100 | counts = aci.ingest(self.drop, self.store) |
| 101 | self.log = out.getvalue() |
| 102 | for canary in ("Ada", "Canary", "ada@", "Dublin", "example.invalid"): |
| 103 | self.assertNotIn(canary, self.log, "a contact field reached the log") |
| 104 | return counts |
| 105 | |
| 106 | def cli(self, *args, cli=os.path.join(HERE, "allen-contacts")): |
| 107 | env = dict(os.environ, ALLEN_CONTACTS_STORE=self.store) |
| 108 | return subprocess.run([sys.executable, "-I", cli, *args], env=env, |
| 109 | capture_output=True, text=True, timeout=30) |
| 110 | |
| 111 | def records(self): |
| 112 | with aci.Store(self.store) as s: |
| 113 | return s.records() |
| 114 | |
| 115 | def quarantined(self): |
| 116 | q = os.path.join(self.store, "quarantine") |
| 117 | return len(os.listdir(q)) if os.path.isdir(q) else 0 |
| 118 | |
| 119 | |
| 120 | class TestIngest(Tmp): |
| 121 | def test_valid_introduce_lands_and_cli_show(self): |
| 122 | rec = intro() |
| 123 | name = write_drop(self.drop, rec) |
| 124 | c = self.ingest() |
| 125 | self.assertEqual(c.get("introduce_stored"), 1) |
| 126 | self.assertFalse(os.path.exists(os.path.join(self.drop, name)), "drop not deleted") |
| 127 | self.assertEqual(self.records(), [rec]) |
| 128 | self.assertEqual(stat.S_IMODE(os.stat(os.path.join(self.store, "contacts.jsonl")).st_mode), 0o600) |
| 129 | r = self.cli("show", rec["id"]) |
| 130 | self.assertEqual(r.returncode, 0, r.stderr) |
| 131 | for line in ("id: " + rec["id"], "name: Ada Canary", "org: Canary Org", |
| 132 | "contact: ada@example.invalid", "purpose: Building a canary\\nsecond line"): |
| 133 | self.assertIn(line, r.stdout.splitlines()) |
| 134 | self.assertNotIn(rec["delete_token_sha256"], r.stdout) |
| 135 | r = self.cli("list") |
| 136 | self.assertEqual(r.stdout, "\t".join([rec["id"], rec["received"], "human", "Ada Canary", |
| 137 | "Canary Org"]) + "\n") |
| 138 | # negative control: an unknown id shows nothing |
| 139 | r = self.cli("show", "c_" + "0" * 16) |
| 140 | self.assertEqual(r.returncode, 1) |
| 141 | self.assertEqual(r.stdout, "") |
| 142 | |
| 143 | def test_malformed_quarantined_not_stored(self): |
| 144 | good = intro() |
| 145 | bad = { |
| 146 | "json": b"{not json", |
| 147 | "list": b"[1,2]", |
| 148 | "nan": canon(intro()).replace(b'"v": 1', b'"v": NaN'), |
| 149 | "dupkey": canon(intro()).replace(b'"v": 1', b'"v": 1, "v": 1'), |
| 150 | "unsorted": json.dumps(intro(), ensure_ascii=False).encode(), |
| 151 | "compact": json.dumps(intro(), ensure_ascii=False, sort_keys=True, |
| 152 | separators=(",", ":")).encode(), |
| 153 | "ascii_escaped": canon(intro(name="Zoë")).replace("ë".encode(), b"\\u00eb"), |
| 154 | "trailing_nl": canon(intro()) + b"\n", |
| 155 | "bad_utf8": canon(intro()).replace(b"Ada", b"A\xffa"), |
| 156 | "extra": intro(extra="x"), |
| 157 | "missing": {k: v for k, v in intro().items() if k != "org"}, |
| 158 | "id": intro(id="c_XYZ"), |
| 159 | "id_upper": intro(id="c_" + "A" * 16), |
| 160 | "too_long": intro(name="x" * 101), |
| 161 | "v_true": intro(v=True), |
| 162 | "v_2": intro(v=2), |
| 163 | "type": intro(type="other"), |
| 164 | "kind": intro(kind="robot"), |
| 165 | "via": intro(via="email"), |
| 166 | "sha_short": intro(delete_token_sha256="a" * 63), |
| 167 | "sha_upper": intro(delete_token_sha256="A" * 64), |
| 168 | "control": intro(name="Ada\x07"), |
| 169 | "not_str": intro(org=5), |
| 170 | "homepage": intro(homepage="http://example.invalid/"), |
| 171 | "received": intro(received="2026-10-26 10:00:00"), |
| 172 | "received_date": intro(received="2026-13-40T10:00:00Z"), |
| 173 | "nobody": intro(name="", contact=""), |
| 174 | "padded": intro(name=" Ada"), |
| 175 | "forget_bad_sha": {"v": 1, "type": "forget", "id": good["id"], "token_sha256": "zz", |
| 176 | "received": good["received"]}, |
| 177 | "oversize": b" " * (aci.MAX_DROP_BYTES + 10) + b"{}", |
| 178 | } |
| 179 | n = 0 |
| 180 | for label, payload in bad.items(): |
| 181 | with self.subTest(label): |
| 182 | name = write_drop(self.drop, payload) |
| 183 | c = self.ingest() |
| 184 | n += 1 |
| 185 | self.assertEqual(c.get("quarantined"), 1, label) |
| 186 | self.assertNotIn("introduce_stored", c) |
| 187 | self.assertEqual(self.quarantined(), n) |
| 188 | self.assertFalse(os.path.exists(os.path.join(self.drop, name))) |
| 189 | self.assertEqual(self.records(), []) |
| 190 | # a valid record under a non-contract file name is quarantined too |
| 191 | write_drop(self.drop, intro(), name="notes.txt") |
| 192 | self.assertEqual(self.ingest().get("q_name"), 1) |
| 193 | self.assertEqual(self.records(), []) |
| 194 | # positive control: the same machinery stores a good record |
| 195 | write_drop(self.drop, good) |
| 196 | self.assertEqual(self.ingest().get("introduce_stored"), 1) |
| 197 | self.assertEqual(self.records(), [good]) |
| 198 | q = os.path.join(self.store, "quarantine") |
| 199 | self.assertEqual(stat.S_IMODE(os.stat(q).st_mode), 0o700) |
| 200 | for f in os.listdir(q): |
| 201 | self.assertEqual(stat.S_IMODE(os.stat(os.path.join(q, f)).st_mode), 0o600) |
| 202 | |
| 203 | def test_forget_wrong_token_then_right_token(self): |
| 204 | a = intro(delete_token_sha256=sha("tok-A")) |
| 205 | b = intro(name="Bob Canary", delete_token_sha256=sha("tok-B")) |
| 206 | write_drop(self.drop, a) |
| 207 | self.ingest() |
| 208 | write_drop(self.drop, b) |
| 209 | self.ingest() |
| 210 | self.assertEqual(self.records(), [a, b]) |
| 211 | |
| 212 | def forget(cid, token): |
| 213 | return {"v": 1, "type": "forget", "id": cid, "token_sha256": sha(token), |
| 214 | "received": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())} |
| 215 | # negative controls: wrong token; right token of another record; unknown id |
| 216 | for cid, tok in ((a["id"], "tok-WRONG"), (a["id"], "tok-B"), ("c_" + "1" * 16, "tok-A")): |
| 217 | write_drop(self.drop, forget(cid, tok)) |
| 218 | c = self.ingest() |
| 219 | self.assertEqual(c.get("forget_unmatched"), 1) |
| 220 | self.assertEqual(self.records(), [a, b]) |
| 221 | self.assertFalse(os.path.exists(os.path.join(self.store, "audit.log"))) |
| 222 | # right token: exactly record a goes |
| 223 | write_drop(self.drop, forget(a["id"], "tok-A")) |
| 224 | c = self.ingest() |
| 225 | self.assertEqual(c.get("forget_matched"), 1) |
| 226 | self.assertEqual(self.records(), [b]) |
| 227 | audit = rd(os.path.join(self.store, "audit.log")) |
| 228 | self.assertRegex(audit, r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ forget removed=1\n$") |
| 229 | self.assertEqual(os.listdir(self.drop), []) |
| 230 | self.assertEqual(sorted(f for f in os.listdir(self.store) if f.startswith(".contacts")), []) |
| 231 | |
| 232 | def test_forget_visitor_removes_only_that_vid(self): |
| 233 | va, vb = sha("visitor-a"), sha("visitor-b") |
| 234 | a1, a2, b, none = intro(vid=va), intro(vid=va), intro(vid=vb), intro() |
| 235 | for r in (a1, a2, b, none): |
| 236 | write_drop(self.drop, r) |
| 237 | self.ingest() |
| 238 | self.assertEqual(len(self.records()), 4) |
| 239 | |
| 240 | def fv(vid): |
| 241 | return {"v": 1, "type": "forget_visitor", "vid": vid, |
| 242 | "received": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())} |
| 243 | # negative controls: an unknown vid and an empty vid remove nothing |
| 244 | write_drop(self.drop, fv(sha("visitor-c"))) |
| 245 | self.assertEqual(self.ingest().get("forget_visitor_unmatched"), 1) |
| 246 | write_drop(self.drop, fv("")) |
| 247 | self.assertEqual(self.ingest().get("q_invalid"), 1) |
| 248 | self.assertEqual(len(self.records()), 4) |
| 249 | write_drop(self.drop, fv(va)) |
| 250 | self.assertEqual(self.ingest().get("forget_visitor_matched"), 1) |
| 251 | self.assertEqual(self.records(), [b, none]) |
| 252 | audit = rd(os.path.join(self.store, "audit.log")) |
| 253 | self.assertRegex(audit, r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ forget_visitor removed=2\n$") |
| 254 | self.assertNotIn(va, audit) |
| 255 | |
| 256 | def test_cli_delete(self): |
| 257 | a, b = intro(), intro(name="Bob Canary") |
| 258 | write_drop(self.drop, a) |
| 259 | write_drop(self.drop, b) |
| 260 | self.ingest() |
| 261 | self.assertEqual(len(self.records()), 2) |
| 262 | r = self.cli("delete", "c_" + "2" * 16) # negative control |
| 263 | self.assertEqual(r.returncode, 1) |
| 264 | self.assertEqual(len(self.records()), 2) |
| 265 | r = self.cli("delete", a["id"]) |
| 266 | self.assertEqual(r.returncode, 0, r.stderr) |
| 267 | self.assertEqual(self.records(), [b]) |
| 268 | self.assertEqual(self.cli("list").stdout.count("\n"), 1) |
| 269 | self.assertEqual(self.cli("delete", a["id"]).returncode, 1) |
| 270 | self.assertEqual(self.cli("show", "../etc").returncode, 64) |
| 271 | audit = rd(os.path.join(self.store, "audit.log")) |
| 272 | self.assertTrue(audit.endswith(" cli-delete removed=1\n")) |
| 273 | self.assertNotIn(a["id"], audit) |
| 274 | |
| 275 | def test_temp_symlink_and_duplicates(self): |
| 276 | fresh = os.path.join(self.drop, ".tmp-" + secrets.token_hex(8)) |
| 277 | stale = os.path.join(self.drop, ".tmp-" + secrets.token_hex(8)) |
| 278 | for p in (fresh, stale): |
| 279 | wr(p, canon(intro()).decode()) |
| 280 | old = time.time() - aci.TEMP_STALE_S - 5 |
| 281 | os.utime(stale, (old, old)) |
| 282 | outside = os.path.join(self.base, "outside.txt") |
| 283 | wr(outside, "keep me") |
| 284 | os.symlink(outside, os.path.join(self.drop, "a" * 16 + ".json")) |
| 285 | c = self.ingest() |
| 286 | self.assertEqual(c.get("temp_pending"), 1) |
| 287 | self.assertEqual(c.get("temp_stale_removed"), 1) |
| 288 | self.assertEqual(c.get("removed_nonregular"), 1) |
| 289 | self.assertTrue(os.path.exists(fresh), "a fresh temp file must be left for the writer") |
| 290 | self.assertFalse(os.path.exists(stale)) |
| 291 | self.assertEqual(rd(outside), "keep me") |
| 292 | self.assertEqual(self.quarantined(), 0) |
| 293 | self.assertEqual(self.records(), []) |
| 294 | os.unlink(fresh) |
| 295 | a = intro() |
| 296 | write_drop(self.drop, a) |
| 297 | write_drop(self.drop, a) # replay of the same drop |
| 298 | write_drop(self.drop, dict(a, name="Mallory")) # same id, other content |
| 299 | c = self.ingest() |
| 300 | self.assertEqual((c.get("introduce_stored"), c.get("introduce_already_stored"), |
| 301 | c.get("q_duplicate_id")), (1, 1, 1)) |
| 302 | self.assertEqual(self.records(), [a]) |
| 303 | |
| 304 | def test_refuses_open_store_dir(self): |
| 305 | os.chmod(self.store, 0o755) |
| 306 | write_drop(self.drop, intro()) |
| 307 | with self.assertRaises(SystemExit): |
| 308 | aci.ingest(self.drop, self.store) |
| 309 | self.assertEqual(len(os.listdir(self.drop)), 1, "drop must stay when the store is unsafe") |
| 310 | os.chmod(self.store, 0o700) |
| 311 | os.chmod(self.drop, 0o2733) # world-writable drop dir: refuse |
| 312 | with self.assertRaises(SystemExit): |
| 313 | aci.ingest(self.drop, self.store) |
| 314 | os.chmod(self.drop, 0o2730) # the contract mode: accepted |
| 315 | self.assertEqual(self.ingest().get("introduce_stored"), 1) |
| 316 | |
| 317 | |
| 318 | def systemd_run(props, cmd): |
| 319 | argv = ["sudo", "-n", "systemd-run", "--wait", "--pipe", "-q"] |
| 320 | for p in props: |
| 321 | argv += ["-p", p] |
| 322 | return subprocess.run(argv + ["/bin/sh", "-c", cmd], capture_output=True, text=True, |
| 323 | timeout=60, stdin=subprocess.DEVNULL) |
| 324 | |
| 325 | |
| 326 | GW_WRITE = r""" |
| 327 | import os, secrets, sys |
| 328 | os.umask(0o027) |
| 329 | d = sys.argv[1] |
| 330 | n = secrets.token_hex(8) |
| 331 | t = os.path.join(d, ".tmp-" + n) |
| 332 | fd = os.open(t, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o640) |
| 333 | os.write(fd, sys.stdin.buffer.read()) |
| 334 | os.fsync(fd) |
| 335 | os.close(fd) |
| 336 | os.rename(t, os.path.join(d, n + ".json")) |
| 337 | print(n + ".json") |
| 338 | """ |
| 339 | |
| 340 | |
| 341 | def as_user(user, argv, data=None): |
| 342 | return subprocess.run(["sudo", "-n", "-u", user, "--"] + argv, input=data, |
| 343 | capture_output=True, timeout=60) |
| 344 | |
| 345 | |
| 346 | def gw_drop(obj): |
| 347 | """Write a drop exactly as the gateway user allen-chat does (0640, group allen-drop).""" |
| 348 | r = as_user("allen-chat", ["/usr/bin/python3", "-I", "-c", GW_WRITE, REAL_DROP], |
| 349 | canon(obj)) |
| 350 | assert r.returncode == 0, r.stderr |
| 351 | return r.stdout.decode().strip() |
| 352 | |
| 353 | |
| 354 | def drop_entries(): |
| 355 | r = as_user("allen-contacts", ["/bin/ls", "-A", REAL_DROP]) |
| 356 | assert r.returncode == 0, r.stderr |
| 357 | return r.stdout.decode().split() |
| 358 | |
| 359 | |
| 360 | @unittest.skipUnless(os.environ.get("RUN_INSTALLED") == "1", "set RUN_INSTALLED=1") |
| 361 | class TestInstalled(unittest.TestCase): |
| 362 | def test_installed_smoke_invisibility_and_delete(self): |
| 363 | r = subprocess.run(["systemctl", "is-active", "allen-contacts-ingest.path"], |
| 364 | capture_output=True, text=True) |
| 365 | self.assertEqual(r.stdout.strip(), "active") |
| 366 | since = time.strftime("%Y-%m-%d %H:%M:%S") |
| 367 | rec = intro(name="Smoke Test " + secrets.token_hex(4), org="allen-contacts smoke", |
| 368 | contact="", github="", origin="", purpose="installed-path smoke", |
| 369 | homepage="", delete_token_sha256=sha("smoke-token")) |
| 370 | gw_drop(rec) |
| 371 | cli = lambda *a: subprocess.run([INSTALLED_CLI, *a], capture_output=True, text=True, |
| 372 | timeout=30) |
| 373 | deadline = time.time() + 30 |
| 374 | while time.time() < deadline and (drop_entries() or cli("show", rec["id"]).returncode): |
| 375 | time.sleep(0.5) |
| 376 | try: |
| 377 | r = cli("show", rec["id"]) |
| 378 | self.assertEqual(r.returncode, 0, "path unit did not ingest the smoke drop") |
| 379 | self.assertIn("name: " + rec["name"], r.stdout.splitlines()) |
| 380 | self.assertEqual(drop_entries(), []) |
| 381 | j = subprocess.run(["sudo", "-n", "journalctl", "-u", "allen-contacts-ingest.service", |
| 382 | "--since", since, "--no-pager", "-o", "cat"], |
| 383 | capture_output=True, text=True).stdout |
| 384 | self.assertIn("introduce_stored=1", j) |
| 385 | self.assertNotIn(rec["name"], j) |
| 386 | |
| 387 | # The gateway user cannot read the store; the store user can (control). |
| 388 | gw = as_user("allen-chat", ["/bin/cat", REAL_STORE]) |
| 389 | self.assertNotEqual(gw.returncode, 0) |
| 390 | self.assertEqual(gw.stdout, b"") |
| 391 | ctl = as_user("allen-contacts", ["/bin/cat", REAL_STORE]) |
| 392 | self.assertEqual(ctl.returncode, 0, ctl.stderr) |
| 393 | self.assertIn(rec["id"].encode(), ctl.stdout) |
| 394 | print("\n[sudo -u allen-chat cat] rc=%d %s" % (gw.returncode, gw.stderr.decode().strip())) |
| 395 | # Same inside the gateway unit's properties; control: same command as allen-contacts. |
| 396 | cmd = "cat %s; ls %s" % (REAL_STORE, REAL_STORE_DIR) |
| 397 | gwu = systemd_run(GATEWAY_PROPS, cmd) |
| 398 | self.assertNotEqual(gwu.returncode, 0) |
| 399 | self.assertEqual(gwu.stdout, "") |
| 400 | print("[gateway unit props] rc=%d\n%s" % (gwu.returncode, gwu.stderr.strip())) |
| 401 | ctlu = systemd_run(["User=allen-contacts"], "cat " + REAL_STORE) |
| 402 | self.assertEqual(ctlu.returncode, 0, ctlu.stderr) |
| 403 | self.assertIn(rec["id"], ctlu.stdout) |
| 404 | # Drake's own login cannot read it without sudo either. |
| 405 | with self.assertRaises(PermissionError): |
| 406 | rd(REAL_STORE) |
| 407 | |
| 408 | def settle(): |
| 409 | deadline = time.time() + 30 |
| 410 | while time.time() < deadline and drop_entries(): |
| 411 | time.sleep(0.5) |
| 412 | self.assertEqual(drop_entries(), []) |
| 413 | |
| 414 | def now(): |
| 415 | return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) |
| 416 | |
| 417 | # forget with a wrong token through the real path unit changes nothing |
| 418 | gw_drop({"v": 1, "type": "forget", "id": rec["id"], "token_sha256": sha("wrong"), |
| 419 | "received": now()}) |
| 420 | settle() |
| 421 | self.assertEqual(cli("show", rec["id"]).returncode, 0) |
| 422 | |
| 423 | # a second record, forgotten with its right token: removed, the first stays |
| 424 | rec2 = dict(rec, id="c_" + secrets.token_hex(8), delete_token_sha256=sha("smoke-2")) |
| 425 | gw_drop(rec2) |
| 426 | settle() |
| 427 | self.assertEqual(cli("show", rec2["id"]).returncode, 0) |
| 428 | gw_drop({"v": 1, "type": "forget", "id": rec2["id"], "token_sha256": sha("smoke-2"), |
| 429 | "received": now()}) |
| 430 | settle() |
| 431 | self.assertEqual(cli("show", rec2["id"]).returncode, 1) |
| 432 | self.assertEqual(cli("show", rec["id"]).returncode, 0) |
| 433 | audit = as_user("allen-contacts", ["/usr/bin/tail", "-n", "1", |
| 434 | REAL_STORE_DIR + "/audit.log"]).stdout.decode() |
| 435 | self.assertRegex(audit, r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ forget removed=1\n$") |
| 436 | |
| 437 | # a malformed drop is quarantined (random name, getrandom under the unit's filter) |
| 438 | qdir = REAL_STORE_DIR + "/quarantine" |
| 439 | before = set(as_user("allen-contacts", ["/bin/ls", "-A", qdir]).stdout.split()) |
| 440 | gw_drop({"v": 1, "type": "introduce", "smoke": "malformed"}) |
| 441 | settle() |
| 442 | new = set(as_user("allen-contacts", ["/bin/ls", "-A", qdir]).stdout.split()) - before |
| 443 | self.assertEqual(len(new), 1) |
| 444 | q = new.pop().decode() |
| 445 | got = as_user("allen-contacts", ["/bin/cat", qdir + "/" + q]).stdout |
| 446 | self.assertEqual(got, canon({"v": 1, "type": "introduce", "smoke": "malformed"})) |
| 447 | self.assertEqual(as_user("allen-contacts", ["/bin/rm", qdir + "/" + q]).returncode, 0) |
| 448 | finally: |
| 449 | d = cli("delete", rec["id"]) |
| 450 | self.assertEqual(d.returncode, 0, d.stderr) |
| 451 | self.assertEqual(cli("show", rec["id"]).returncode, 1) |
| 452 | |
| 453 | |
| 454 | if __name__ == "__main__": |
| 455 | unittest.main(verbosity=2) |