#!/usr/bin/env python3 """Generate synthetic LastPass CSV fixtures for import testing. Everything here is FAKE: example.test domains (RFC 2606 reserved), the well-known demo TOTP secret, and the public Visa test PAN. No real credentials. Usage: python3 tools/lastpass-fixtures/gen.py # committed fixtures python3 tools/lastpass-fixtures/gen.py --large 3000 # + large-3000.csv (gitignored) python3 tools/lastpass-fixtures/gen.py --huge-note 2 # + huge-note-2mb.csv (gitignored) Output: tests/fixtures/lastpass/*.csv and expected.json (the oracle). expected.json semantics ----------------------- Each entry describes what CORRECT behaviour is, not what the code does today. `status` says how sure we are the current code meets it: - "baseline" : believed to pass today (regression guard) - "suspect" : believed to FAIL today; a failing test here is a real bug - "needs_decision" : correct behaviour is a product call; see `decision` `rows` counts are per-record (1-indexed, header excluded), matching the `ImportWarning.row` numbering in crates/relicario-core/src/import_lastpass.rs. """ import argparse import csv import io import json import os HEADER = ["url", "username", "password", "totp", "extra", "name", "grouping", "fav"] HEADER_LEGACY = ["url", "username", "password", "extra", "name", "grouping", "fav"] DEMO_TOTP = "JBSWY3DPEHPK3PXP" # RFC 6238 demo secret, universally used in docs OUT = os.path.join(os.path.dirname(__file__), "..", "..", "tests", "fixtures", "lastpass") def to_bytes(header, rows, lineterminator="\n", bom=False): buf = io.StringIO(newline="") w = csv.writer(buf, lineterminator=lineterminator, quoting=csv.QUOTE_MINIMAL) w.writerow(header) for r in rows: w.writerow(r) data = buf.getvalue().encode("utf-8") return (b"\xef\xbb\xbf" + data) if bom else data # kind: login | note | skip | login_warn (login_warn = imported WITH a warning) def row(kind, *cols): assert len(cols) == 8, cols return kind, list(cols) def summarize(rows): logins = sum(1 for k, _ in rows if k in ("login", "login_warn")) notes = sum(1 for k, _ in rows if k == "note") warn_rows = [i + 1 for i, (k, _) in enumerate(rows) if k in ("skip", "login_warn")] return {"logins": logins, "notes": notes, "warning_rows": warn_rows} FILES = {} # filename -> bytes EXPECTED = {} # filename -> oracle entry def add(name, data, description, status, expect, decision=None, suspects=None): FILES[name] = data entry = {"description": description, "status": status, "expect": expect} if decision: entry["decision"] = decision if suspects: entry["suspects"] = suspects EXPECTED[name] = entry def add_rows(name, rows, description, status="baseline", header=HEADER, **kw): data = to_bytes(header, [c for _, c in rows], **{k: kw.pop(k) for k in ("lineterminator", "bom") if k in kw}) s = summarize(rows) add(name, data, description, status, {"fatal": None, **s}, **kw) def build_committed(): # 01 — realistic happy path with the awkward-but-valid shapes real exports contain. basic = [ row("login", "https://example.test/login", "alice@example.test", 'p@ss,word"quoted"', "", "", "Example Login", "Personal", "0"), row("login", "https://mail.example.test", "alice", " spaced pass ", DEMO_TOTP, "recovery code: 1234\nsecond line", "Mail (TOTP)", "Work\\Email", "1"), row("note", "http://sn", "", "", "", 'Body of a note\nwith lines, commas, and "quotes"', "Plain Note", "Notes", "0"), row("login", "https://example.test/\u8def\u5f84", "us\u00e9r", "p\u00e4ssw\u00f6rd-\u5bc6\u7801-\U0001F511", "", "emoji note \U0001F389", "\u00dcn\u00efc\u00f6de \u00cdtem \U0001F510", "\u56fd\u9645", "0"), row("login", "https://example.test/a", "bob", '=HYPERLINK("http://evil.test")', "", "", "Formula Looking Password", "", "0"), row("login", "https://example.test/login", "carol", "different-password", "", "", "Example Login", "Personal", "0"), # duplicate title, no dedup row("note", "http://sn", "", "", "", " leading and trailing spaces kept in body ", "Whitespace Note", "", "0"), row("login", "http://192.168.1.1:8080/admin", "admin", "000123", "", "", "Router (leading zeros)", "Home", "0"), row("login", "https://example.test/long", "dave", "x" * 512, "", "", "Very Long Password", "", "0"), row("login", "https://example.test/pad", "erin", "pw", "", "", " Padded Title ", "", "0"), row("login", "https://example.test/fav", "frank", "pw", "", "", "Favorite Only", "", "1"), ] add_rows("01-basic.csv", basic, "Happy path: quoting, newlines in fields, unicode/emoji, nested group, favorite, TOTP, duplicate titles, padded title, long password.") # 02 — per-row problems. Import must NOT abort; each bad row yields exactly one warning. warn = [ row("skip", "https://x.test", "u", "p", "", "", "", "g", "0"), # 1 missing name row("skip", "https://x.test", "u", "", "", "", "No Password", "g", "0"), # 2 missing password row("login_warn", "not a url", "u", "p", "", "", "Bad URL", "", "0"), # 3 invalid url -> imported w/o url row("login_warn", "https://x.test", "u", "p", "!!notbase32!!", "", "Bad TOTP", "", "0"), # 4 row("login_warn", "example.test", "u", "p", "", "", "Scheme-less URL", "", "0"), # 5 row("note", "http://sn", "", "", "", "", "Empty Note Body", "", "0"), # 6 imported row("login", "https://x.test", "u", "p", "", "", "Good Row", "", "0"), # 7 ] # row 8: wrong field count (5 cols) -> csv error -> one warning, rest unaffected ragged = to_bytes(HEADER, [c for _, c in warn]) + b"https://x.test,u,p,,Short Row\n" + \ to_bytes(HEADER, [["https://x.test", "u", "p", "", "", "After Ragged", "", "0"]])[len(",".join(HEADER)) + 1:] s = summarize(warn) s["logins"] += 1 # the 'After Ragged' row imports s["warning_rows"] = s["warning_rows"] + [8] add("02-warnings.csv", ragged, "Mixed per-row problems incl. a ragged row; import must continue past each.", "baseline", {"fatal": None, **s}) # 03 — BOM (Excel / Notepad re-save). Correct behaviour: strip it and import. add_rows("03-bom.csv", [ row("login", "https://example.test", "u", "p", "", "", "After BOM 1", "", "0"), row("login", "https://example.test", "u2", "p2", "", "", "After BOM 2", "", "0"), row("note", "http://sn", "", "", "", "note body", "After BOM 3", "", "0"), ], "UTF-8 BOM before the header, as written by Excel/Notepad re-saves.", "suspect", bom=True, suspects="csv crate does not strip a BOM -> header[0] == '\\ufefful' -> ImportCsvHeader error") # 04 — legacy 7-column export (no totp column). legacy_rows = [ ["https://example.test", "u", "p", "legacy extra", "Legacy 1", "Old", "0"], ["http://sn", "", "", "legacy note body", "Legacy Note", "Old", "1"], ] add("04-legacy-7col.csv", to_bytes(HEADER_LEGACY, legacy_rows), "Pre-TOTP LastPass export: url,username,password,extra,name,grouping,fav.", "needs_decision", {"fatal": None, "logins": 1, "notes": 1, "warning_rows": []}, decision="Accept the legacy 7-col header (map columns by name) or reject with a message that says so? Recommend accept.", suspects="EXPECTED_HEADER is exact 8-col/order -> whole import rejected") # 05 — wrong format entirely (Bitwarden-style header). Must fail clearly, import nothing. add("05-wrong-format.csv", to_bytes(["folder", "favorite", "type", "name", "notes", "login_uri", "login_username", "login_password"], [["", "1", "login", "BW Item", "", "https://example.test", "u", "p"]]), "A different manager's export. Must fail with a clear, actionable message; nothing written.", "baseline", {"fatal": "header", "logins": 0, "notes": 0, "warning_rows": []}) # 06 — header only. add("06-header-only.csv", to_bytes(HEADER, []), "Valid header, zero rows. UI must say there is nothing to import and keep Import disabled.", "baseline", {"fatal": None, "logins": 0, "notes": 0, "warning_rows": []}) # 07 — CRLF everywhere, including inside a quoted field. crlf = [ row("login", "https://example.test", "u", "p", "", "line1\r\nline2", "CRLF Item 1", "", "0"), row("login", "https://example.test", "u2", "p2", "", "", "CRLF Item 2", "", "0"), row("note", "http://sn", "", "", "", "a\r\nb\r\nc", "CRLF Note", "", "0"), ] add_rows("07-crlf.csv", crlf, "Windows line endings, including CRLF inside quoted fields.", lineterminator="\r\n") # 08 — invalid UTF-8 (latin-1 'é' = 0xE9) in one row. Other rows must still import. good = to_bytes(HEADER, [["https://example.test", "u", "p", "", "", "Before Latin1", "", "0"]]) bad = b"https://example.test,u,p,,,Caf\xe9 Item,,0\n" after = to_bytes(HEADER, [["https://example.test", "u", "p", "", "", "After Latin1", "", "0"]]).split(b"\n", 1)[1] add("08-latin1.csv", good + bad + after, "One row is Latin-1, not UTF-8. Must not abort the whole import; the bad row warns (or decodes), the others import.", "needs_decision", {"fatal": None, "logins": 2, "notes": 0, "warning_rows": [2]}, decision="Warn-and-skip the non-UTF-8 row, or attempt a Windows-1252 fallback decode of the whole file? Recommend warn-and-skip, with the message naming the row.") # 09 — LastPass structured 'NoteType' notes (cards, banks, wifi...) arrive as http://sn secure notes. cc = ("NoteType:Credit Card\nLanguage:en-US\nName on Card:Alice Example\nType:Visa\n" "Number:4111111111111111\nSecurity Code:123\nStart Date:January,2020\n" "Expiration Date:January,2027\nNotes:fake test card") bank = ("NoteType:Bank Account\nLanguage:en-US\nBank Name:Example Bank\nAccount Type:Checking\n" "Routing Number:000000000\nAccount Number:0000000000\nSWIFT Code:\nIBAN Number:\nPin:0000\nBranch Address:\nBranch Phone:\nNotes:") wifi = "NoteType:Wi-Fi Password\nLanguage:en-US\nSSID:ExampleNet\nPassword:wifi-pass\nConnection Type:\nConnection Mode:\nAuthentication:WPA2\nEncryption:AES\nUse 802.1X:\nFIPS Mode:\nKey Type:\nProtected:\nIndex:\nNotes:" ssh = "NoteType:SSH Key\nLanguage:en-US\nBit Strength:2048\nFormat:RSA\nPassphrase:\nPrivate Key:-----BEGIN FAKE KEY-----\nAAAA\n-----END FAKE KEY-----\nPublic Key:ssh-rsa AAAA fake\nHostname:host.example.test\nDate:" add_rows("09-notetypes.csv", [ row("note", "http://sn", "", "", "", cc, "Visa (fake)", "Finance", "0"), row("note", "http://sn", "", "", "", bank, "Checking (fake)", "Finance", "0"), row("note", "http://sn", "", "", "", wifi, "Home WiFi", "Home", "0"), row("note", "http://sn", "", "", "", ssh, "Server key (fake)", "Servers", "0"), ], "LastPass structured note types. Today they import as raw secure notes.", "needs_decision", decision="Keep as raw secure notes (lossless, current) or map NoteType:Credit Card -> Card and SSH Key -> Key item types? Mapping is a feature, not a bug fix. Recommend: keep raw, log as roadmap item, but assert no data is dropped.") # 10 — hostile content. Must never execute/render as HTML; scheme must be safe. hostile = [ row("login", "https://example.test", "u", "p", "", '">', "", "grp", "0"), row("login_warn", "javascript:alert(document.domain)", "u", "p", "", "", "JS URL", "", "0"), row("login_warn", "data:text/html,", "u", "p", "", "", "Data URL", "", "0"), row("login", "https://example.test", "u", "p", "", "", "../../etc/passwd", "../..", "0"), row("login", "https://example.test", "u", "p", "", "", "RTL \u202eevil\u202c override", "", "0"), row("login", "https://example.test", "u", "p", "", "", "T" * 5000, "", "0"), row("note", "http://sn", "", "", "", "", "HTML Note", "", "0"), ] add_rows("10-hostile.csv", hostile, "XSS-shaped titles/groups/notes, javascript:/data: URLs, path-ish titles, bidi override, 5000-char title.", "needs_decision", decision="javascript:/data: URLs: reject with a warning (import login WITHOUT url), same as an invalid URL. Recommend yes — url::Url accepts any scheme today.", suspects="Url::parse accepts javascript:/data: so they are stored as the login URL; popup/vault render or open them") def build_large(n): rows = [] for i in range(1, n + 1): if i % 10 == 0: rows.append(["http://sn", "", "", "", f"note body {i}\nline two", f"Note {i:05d}", f"Group{i % 7}", "0"]) else: rows.append([f"https://site{i}.example.test/login", f"user{i}", f"pw-{i:05d}-" + "x" * 16, DEMO_TOTP if i % 25 == 0 else "", f"note {i}" if i % 5 == 0 else "", f"Login {i:05d}", f"Group{i % 7}", "1" if i % 50 == 0 else "0"]) return to_bytes(HEADER, rows) def build_huge_note(mb): body = ("A" * 1023 + "\n") * (mb * 1024) return to_bytes(HEADER, [["http://sn", "", "", "", body, f"Huge Note {mb}MB", "", "0"], ["https://example.test", "u", "p", "", "", "After Huge", "", "0"]]) def main(): ap = argparse.ArgumentParser() ap.add_argument("--large", type=int, metavar="N", help="also write large-N.csv (gitignored)") ap.add_argument("--huge-note", type=int, metavar="MB", help="also write huge-note-mb.csv (gitignored)") args = ap.parse_args() os.makedirs(OUT, exist_ok=True) build_committed() for name, data in FILES.items(): with open(os.path.join(OUT, name), "wb") as f: f.write(data) with open(os.path.join(OUT, "expected.json"), "w", encoding="utf-8") as f: json.dump(EXPECTED, f, indent=2, ensure_ascii=False, sort_keys=True) f.write("\n") if args.large: p = os.path.join(OUT, f"large-{args.large}.csv") open(p, "wb").write(build_large(args.large)) print("wrote", os.path.relpath(p)) if args.huge_note: p = os.path.join(OUT, f"huge-note-{args.huge_note}mb.csv") open(p, "wb").write(build_huge_note(args.huge_note)) print("wrote", os.path.relpath(p)) print(f"wrote {len(FILES)} fixtures + expected.json to {os.path.relpath(OUT)}") if __name__ == "__main__": main()