From 33a79d2a9d9a6a471416393747ba2199e6aa1dfa Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:42:06 -0500 Subject: [PATCH] feat(#1217): owner tool to list, pull, decrypt and unpack uploads tools/logs/offband_logs.py: keygen makes the owner key pair once and refuses to overwrite it (#1216); list shows intake issues not yet labeled seen; pull finds the stored object named on the intake issue, downloads it over the Cloudflare API, decrypts it, unpacks it into debug_logs/OB-XXXXX/ and only then labels the issue seen and comments. A wrong key, an altered byte or a zip member pointing outside the folder fails before anything is written or marked. Tests open the same Python-reference vectors the Dart encoder matches, and run in the required analyze job. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/flutter_dart.yml | 7 + tools/logs/conftest.py | 4 + tools/logs/offband_logs.py | 248 +++++++++++++++++++++++++++++ tools/logs/test_offband_logs.py | 148 +++++++++++++++++ 4 files changed, 407 insertions(+) create mode 100644 tools/logs/conftest.py create mode 100644 tools/logs/offband_logs.py create mode 100644 tools/logs/test_offband_logs.py diff --git a/.github/workflows/flutter_dart.yml b/.github/workflows/flutter_dart.yml index 3b868325..c0f5e490 100644 --- a/.github/workflows/flutter_dart.yml +++ b/.github/workflows/flutter_dart.yml @@ -81,6 +81,13 @@ jobs: if: needs.classify.outputs.docs_only != 'true' run: python3 -m unittest discover -s tools/play -v + - name: Log pull tool tests (#1195) + if: needs.classify.outputs.docs_only != 'true' + run: | + python3 -m venv "$RUNNER_TEMP/logs-venv" + "$RUNNER_TEMP/logs-venv/bin/pip" install --quiet cryptography==46.0.7 pytest==9.0.2 + "$RUNNER_TEMP/logs-venv/bin/python" -m pytest tools/logs -q + - name: Set up Flutter if: needs.classify.outputs.docs_only != 'true' uses: subosito/flutter-action@v2 diff --git a/tools/logs/conftest.py b/tools/logs/conftest.py new file mode 100644 index 00000000..4b039907 --- /dev/null +++ b/tools/logs/conftest.py @@ -0,0 +1,4 @@ +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) diff --git a/tools/logs/offband_logs.py b/tools/logs/offband_logs.py new file mode 100644 index 00000000..c3ffe0ea --- /dev/null +++ b/tools/logs/offband_logs.py @@ -0,0 +1,248 @@ +"""Pull, decrypt and unpack Send to Offband uploads (#1195). + + python tools/logs/offband_logs.py keygen + python tools/logs/offband_logs.py list + python tools/logs/offband_logs.py pull OB-XXXXX + +keygen makes the owner's key pair once. The private key goes to +~/.secrets/offband-log-key and into Bitwarden; without it no upload can ever be +read. The public key goes into the app. + +list shows uploads not pulled yet. pull downloads an upload, decrypts it, +unpacks it into debug_logs/OB-XXXXX/, labels its intake issue `seen` (which +starts the 30-day deletion clock) and comments there. If anything fails before +the files are written, nothing is marked seen. + +Needs CLOUDFLARE_API_TOKEN with R2 read, the `gh` CLI signed in with access to +OffbandMesh/log-intake, and Python's `cryptography` package. +""" +import argparse +import hashlib +import io +import json +import os +import re +import subprocess +import sys +import urllib.request +import zipfile +from datetime import datetime, timezone +from pathlib import Path + +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric.x25519 import ( + X25519PrivateKey, + X25519PublicKey, +) +from cryptography.hazmat.primitives.ciphers.aead import AESGCM +from cryptography.hazmat.primitives.kdf.hkdf import HKDF + +MAGIC = b"OBLG" +VERSION = 1 +HEADER_LENGTH = 53 +TAG_LENGTH = 16 +INFO = b"offband-log-v1" + +INTAKE_REPO = "OffbandMesh/log-intake" +BUCKET = "offband-log-intake" +SEEN_LABEL = "seen" +KEY_PATH = Path.home() / ".secrets" / "offband-log-key" +OUT_ROOT = Path(__file__).resolve().parents[2] / "debug_logs" +CODE = re.compile(r"^OB-[23456789ABCDEFGHJKMNPQRSTUVWXYZ]{5}$") +OBJECT = re.compile(r"`(uploads/(OB-[23456789ABCDEFGHJKMNPQRSTUVWXYZ]{5})-[0-9a-f-]{36}\.bin)`") + + +class WrongKey(Exception): + pass + + +def key_id(public: bytes) -> bytes: + return hashlib.sha256(public).digest()[:4] + + +def public_bytes(private: X25519PrivateKey) -> bytes: + return private.public_key().public_bytes( + serialization.Encoding.Raw, serialization.PublicFormat.Raw + ) + + +def open_envelope(blob: bytes, private: X25519PrivateKey) -> bytes: + """The zipped package inside an upload. Raises on anything not sealed to + this key or altered since: a wrong key id, a bad header, a failed tag.""" + if len(blob) < HEADER_LENGTH + TAG_LENGTH: + raise ValueError(f"upload is {len(blob)} bytes, too short to be an envelope") + header = blob[:HEADER_LENGTH] + if header[:4] != MAGIC or header[4] != VERSION: + raise ValueError("upload does not start with the OBLG version 1 header") + recipient = public_bytes(private) + if header[5:9] != key_id(recipient): + raise WrongKey( + f"upload was sealed for key id {header[5:9].hex()}, this key is {key_id(recipient).hex()}" + ) + ephemeral = header[9:41] + shared = private.exchange(X25519PublicKey.from_public_bytes(ephemeral)) + key = HKDF( + algorithm=hashes.SHA256(), length=32, salt=ephemeral + recipient, info=INFO + ).derive(shared) + return AESGCM(key).decrypt(header[41:53], blob[HEADER_LENGTH:], header) + + +def unpack(package: bytes, dest: Path) -> list: + """Write every member of [package] under [dest]. A member that would land + outside [dest] is refused before anything is written.""" + root = dest.resolve() + with zipfile.ZipFile(io.BytesIO(package)) as zf: + members = [m for m in zf.infolist() if not m.is_dir()] + for m in members: + target = (root / m.filename).resolve() + if root != target and root not in target.parents: + raise ValueError(f"package member {m.filename!r} points outside {dest}") + written = [] + for m in members: + target = root / m.filename + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(zf.read(m)) + written.append(m.filename) + return written + + +def free_dir(root: Path, code: str) -> Path: + candidate = root / code + n = 2 + while candidate.exists(): + candidate = root / f"{code}-{n}" + n += 1 + return candidate + + +def load_key(path: Path = KEY_PATH) -> X25519PrivateKey: + if not path.exists(): + raise SystemExit(f"No private key at {path}. Restore it from Bitwarden, or run keygen once.") + return X25519PrivateKey.from_private_bytes(bytes.fromhex(path.read_text().strip())) + + +def keygen(path: Path = KEY_PATH, out=sys.stdout) -> bytes: + if path.exists(): + raise SystemExit(f"{path} already exists. Refusing to overwrite the only key that reads past uploads.") + private = X25519PrivateKey.generate() + raw = private.private_bytes( + serialization.Encoding.Raw, + serialization.PrivateFormat.Raw, + serialization.NoEncryption(), + ) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(raw.hex() + "\n") + try: + os.chmod(path, 0o600) + except OSError: + pass + public = public_bytes(private) + print(f"Private key written to {path}", file=out) + print("Store it in Bitwarden now. Without it no upload can ever be read.", file=out) + print(f"Public key: {public.hex()}", file=out) + print(f"Key id: {key_id(public).hex()}", file=out) + return public + + +# --- GitHub and Cloudflare -------------------------------------------------- + + +def gh(*args: str) -> str: + return subprocess.run( + ["gh", *args], check=True, capture_output=True, text=True, encoding="utf-8" + ).stdout + + +def cf_get(path: str) -> bytes: + token = os.environ.get("CLOUDFLARE_API_TOKEN") + if not token: + raise SystemExit("CLOUDFLARE_API_TOKEN is not set.") + req = urllib.request.Request( + f"https://api.cloudflare.com/client/v4{path}", + headers={"Authorization": f"Bearer {token}"}, + ) + with urllib.request.urlopen(req, timeout=120) as res: + return res.read() + + +def download(object_key: str) -> bytes: + accounts = json.loads(cf_get("/accounts"))["result"] + if len(accounts) != 1: + raise SystemExit(f"Expected one Cloudflare account, found {len(accounts)}.") + quoted = urllib.request.quote(object_key, safe="") + return cf_get(f"/accounts/{accounts[0]['id']}/r2/buckets/{BUCKET}/objects/{quoted}") + + +def intake_issues(state: str, search: str = "") -> list: + args = ["issue", "list", "--repo", INTAKE_REPO, "--state", state, "--limit", "200", + "--json", "number,title,body,labels,createdAt"] + if search: + args += ["--search", search] + return json.loads(gh(*args)) + + +def mark_seen(number: int, note: str) -> None: + gh("label", "create", SEEN_LABEL, "--repo", INTAKE_REPO, "--force", + "--description", "Pulled by the owner; deleted 30 days later") + gh("issue", "edit", str(number), "--repo", INTAKE_REPO, "--add-label", SEEN_LABEL) + gh("issue", "comment", str(number), "--repo", INTAKE_REPO, "--body", note) + + +# --- Commands --------------------------------------------------------------- + + +def unseen(issues: list) -> list: + return [i for i in issues if SEEN_LABEL not in {label["name"] for label in i["labels"]}] + + +def pull(code: str, *, key=None, issues=None, fetch=download, seen=mark_seen, + out_root: Path = OUT_ROOT, out=sys.stdout) -> list: + if not CODE.match(code): + raise SystemExit(f"{code!r} is not a reference code like OB-7K2QX.") + key = key or load_key() + issues = issues if issues is not None else intake_issues("all", f"{code} in:title") + targets = [] + for issue in issues: + if not issue["title"].startswith(code): + continue + for object_key, object_code in OBJECT.findall(issue["body"] or ""): + if object_code == code: + targets.append((issue["number"], object_key)) + if not targets: + raise SystemExit(f"No intake issue names a stored upload for {code}.") + + pulled = [] + for number, object_key in targets: + package = open_envelope(fetch(object_key), key) + dest = free_dir(out_root, code) + files = unpack(package, dest) + when = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC") + seen(number, f"Pulled and decrypted {when}: {len(files)} files. Deleted 30 days from now.") + print(f"#{number}: {len(files)} files in {dest}", file=out) + pulled.append(dest) + return pulled + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + sub = parser.add_subparsers(dest="command", required=True) + sub.add_parser("keygen", help="make the owner key pair, once") + sub.add_parser("list", help="uploads not pulled yet") + p = sub.add_parser("pull", help="download, decrypt and unpack one upload") + p.add_argument("code") + args = parser.parse_args(argv) + + if args.command == "keygen": + keygen() + elif args.command == "list": + waiting = unseen(intake_issues("open")) + for issue in waiting: + print(f"#{issue['number']} {issue['createdAt'][:16]} {issue['title']}") + print(f"{len(waiting)} upload(s) not pulled yet.") + else: + pull(args.code) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/logs/test_offband_logs.py b/tools/logs/test_offband_logs.py new file mode 100644 index 00000000..b55359eb --- /dev/null +++ b/tools/logs/test_offband_logs.py @@ -0,0 +1,148 @@ +import io +import json +import zipfile +from pathlib import Path + +import pytest +from cryptography.exceptions import InvalidTag +from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey + +import offband_logs as ol + +VECTORS = json.loads( + (Path(__file__).resolve().parents[2] / "test" / "fixtures" / "log_envelope_vectors.json").read_text() +)["vectors"] + + +def key_of(vector): + return X25519PrivateKey.from_private_bytes(bytes.fromhex(vector["recipientPrivate"])) + + +def zipped(files): + buf = io.BytesIO() + with zipfile.ZipFile(buf, "w") as zf: + for name, data in files.items(): + zf.writestr(name, data) + return buf.getvalue() + + +def test_opens_every_envelope_the_dart_app_makes(): + assert len(VECTORS) == 3 + for v in VECTORS: + assert ol.open_envelope(bytes.fromhex(v["envelope"]), key_of(v)) == bytes.fromhex(v["plaintext"]) + + +def test_refuses_an_altered_upload(): + v = VECTORS[0] + blob = bytearray(bytes.fromhex(v["envelope"])) + blob[-1] ^= 1 + with pytest.raises(InvalidTag): + ol.open_envelope(bytes(blob), key_of(v)) + header = bytearray(bytes.fromhex(v["envelope"])) + header[45] ^= 1 + with pytest.raises(InvalidTag): + ol.open_envelope(bytes(header), key_of(v)) + + +def test_names_the_key_an_upload_was_sealed_for(): + with pytest.raises(ol.WrongKey, match="key id"): + ol.open_envelope(bytes.fromhex(VECTORS[0]["envelope"]), key_of(VECTORS[1])) + + +@pytest.mark.parametrize("blob", [b"", b"PK\x03\x04" + bytes(80), b"OBLG\x02" + bytes(80)]) +def test_refuses_what_is_not_an_envelope(blob): + with pytest.raises(ValueError): + ol.open_envelope(blob, key_of(VECTORS[0])) + + +def test_unpack_refuses_a_member_outside_the_folder(tmp_path): + with pytest.raises(ValueError, match="outside"): + ol.unpack(zipped({"ok.log": b"1", "../escape.txt": b"2"}), tmp_path / "OB-AAAAA") + assert not (tmp_path / "escape.txt").exists() + assert not (tmp_path / "OB-AAAAA" / "ok.log").exists() + + +def test_keygen_writes_once_and_never_overwrites(tmp_path): + path = tmp_path / ".secrets" / "offband-log-key" + out = io.StringIO() + public = ol.keygen(path, out=out) + assert ol.public_bytes(ol.load_key(path)) == public + assert public.hex() in out.getvalue() + assert "Bitwarden" in out.getvalue() + before = path.read_text() + with pytest.raises(SystemExit, match="Refusing"): + ol.keygen(path, out=io.StringIO()) + assert path.read_text() == before + + +def sealed_package(tmp_path): + """A real envelope around a real zip, sealed with the Python reference.""" + import make_envelope_vectors as ref + + owner = X25519PrivateKey.generate() + package = zipped({"manifest.json": b"{}", "offband.log": b"line\n", "traces/anr-1.txt": b"t"}) + blob = ref.seal(package, ol.public_bytes(owner), X25519PrivateKey.generate(), bytes(12)) + return owner, blob + + +ISSUE = { + "number": 7, + "title": "OB-7K2QX: android 1.8.0", + "body": "Stored as `uploads/OB-7K2QX-1b4e28ba-2fa1-11d2-883f-0016d3cca427.bin`", + "labels": [], +} + + +def test_pull_unpacks_and_then_marks_seen(tmp_path): + owner, blob = sealed_package(tmp_path) + fetched, marked = [], [] + dests = ol.pull( + "OB-7K2QX", + key=owner, + issues=[ISSUE, {**ISSUE, "number": 8, "title": "OB-99999: other"}], + fetch=lambda k: fetched.append(k) or blob, + seen=lambda n, note: marked.append((n, note)), + out_root=tmp_path, + out=io.StringIO(), + ) + assert fetched == ["uploads/OB-7K2QX-1b4e28ba-2fa1-11d2-883f-0016d3cca427.bin"] + assert dests == [tmp_path / "OB-7K2QX"] + assert (tmp_path / "OB-7K2QX" / "traces" / "anr-1.txt").read_bytes() == b"t" + assert [n for n, _ in marked] == [7] + assert "30 days" in marked[0][1] + + +def test_a_failed_decrypt_marks_nothing_and_writes_nothing(tmp_path): + _, blob = sealed_package(tmp_path) + marked = [] + with pytest.raises(ol.WrongKey): + ol.pull( + "OB-7K2QX", + key=X25519PrivateKey.generate(), + issues=[ISSUE], + fetch=lambda k: blob, + seen=lambda n, note: marked.append(n), + out_root=tmp_path, + out=io.StringIO(), + ) + assert marked == [] + assert list(tmp_path.iterdir()) == [] + + +def test_a_second_pull_does_not_overwrite_the_first(tmp_path): + owner, blob = sealed_package(tmp_path) + kwargs = dict(key=owner, issues=[ISSUE], fetch=lambda k: blob, + seen=lambda n, note: None, out_root=tmp_path, out=io.StringIO()) + ol.pull("OB-7K2QX", **kwargs) + assert ol.pull("OB-7K2QX", **kwargs) == [tmp_path / "OB-7K2QX-2"] + + +def test_list_leaves_out_uploads_already_seen(): + issues = [ISSUE, {**ISSUE, "number": 9, "labels": [{"name": "seen"}]}] + assert [i["number"] for i in ol.unseen(issues)] == [7] + + +@pytest.mark.parametrize("code", ["OB-0O1IL", "ob-7k2qx", "OB-7K2Q", "7K2QX"]) +def test_refuses_a_malformed_code(code): + with pytest.raises(SystemExit): + ol.pull(code, key=X25519PrivateKey.generate(), issues=[])