signal-bot/signal_bot/media_strip.py
Krzysztof kuhy Rudnicki aefffb2fd9
Some checks are pending
CI / check (push) Waiting to run
feat: add a photo to the album from the chat, tagged, stripped and verified
Send a photo captioned "!add_photo alfa wakacje" in one of the album's own
groups and it lands in the pack tagged with both, retrievable through !alfa
and the new !losowe immediately -- no restart, and no tagger session on the PC.
A label matching nobody becomes a custom tag, and !losowe is the only door to
one, which is what keeps a live swap a *data* swap: it can never register a
trigger or widen a command's groups.

No typed label travels. Labels become pseudonym keys in a new registry
arg_resolver, at the dispatcher, before the line that logs the command name --
so no handler, journal entry, command_uses row or reply body ever holds a word
somebody typed. The reply is counts and pseudonyms: "dodano · p1: 4 · t1: 1".

Stripping is exiftool with a *positive* check on the output, never an exit
code. ffmpeg was tried first and fails silently on photos: given a JPEG with a
real APP1 Exif segment it returned a byte-identical file, GPS intact, exit 0.
The surviving-tag allowlist is per tag *name* rather than per group, because
measurement showed a group-level "must be empty" rule rejects every format
except JPEG -- a valid PNG always reports its IHDR, an MP4 some fifty QuickTime
tags that are the container itself. Codec configuration (CompressorName,
VendorID, the HEVC parameter set) is on the list by decision: CompressorName
lives in the avc1 sample description and exiftool cannot write it at all, so
the alternative was refusing every video and every iPhone HEIC. Location and
identity tags are still refused, and the e2e run re-reads the stored files to
prove a QuickTime geotag did not survive.

.webm and .svg stay on the format allowlist and are stored *unstripped*:
exiftool 13.55 can write neither, and its SVG reader does not even surface
<metadata>. That is a deliberate, documented hole, not an oversight.

Two things this had to defuse along the way:
- personal_data_sources now reads custom.json, so "!add_photo kot <photo>"
  would have outlawed the word "kot" and refused every future commit, fixable
  only by hand-editing an album the committer cannot see. Minting now refuses
  a word that is already a command, and the gate subtracts the repo's own
  alias vocabulary from custom labels only -- curated people.json names are
  never excused.
- signal_bot/external.py is now the single subprocess site in the repository,
  so ruff's S603 needs exactly one scoped per-file-ignore instead of one per
  module that shells out. A test asserts nothing else imports subprocess.

A failed add changes nothing: media and the three manifests are written, the
album is reloaded, and only a load that succeeds is published; a load that
fails rolls all four back and keeps serving the pack that was already working,
without raising -- Restart=always would turn a ConfigError into a loop.

977 tests, 100% branch coverage, no omits and no suppressions. scripts/e2e.sh
gains 8 scenarios driven against the real exiftool on media generated at run
time, and asserts the invariants a reply cannot: that a refused upload is not
stored, that a message with no attachment leaves custom.json byte-identical,
and that signal-cli's own copy of every ingested attachment is gone.

Closes TODO-add-photo.md.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JqqE22jp94B1ypwxppdr1o
2026-08-31 11:20:00 +02:00

137 lines
5.7 KiB
Python

# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Removing metadata from an upload, and *proving* it is gone.
The gate is a positive check on the output, never an exit code, because an
exit code is exactly what lied the first time. ``ffmpeg -map_metadata -1 -c
copy`` was tested against a JPEG carrying a real APP1 Exif segment and
produced a byte-identical file -- 292 bytes in, 292 bytes out, GPS marker
still there -- and exited 0. ``-c copy`` hands the compressed frame through
as an opaque packet, and a JPEG's Exif lives inside it. Do not reintroduce
ffmpeg here.
So: strip with exiftool, then read the result back and require every
surviving tag to be structural (media_tags). A metadata atom nobody
anticipated shows up as a tag that is not on the allowlist, and the upload is
refused rather than stored.
Temp files go in /tmp, which the unit makes per-service with PrivateTmp=true.
Staging beside ``media/`` would let a crash mid-strip leave an unstripped
original inside the album permanently, where nothing in pack_load would ever
flag it.
The ``Stripper`` protocol is the seam: unit tests inject a fake so they never
shell out, and ``scripts/e2e.sh`` runs the real one against generated media.
"""
from __future__ import annotations
import logging
import re
import shutil
import tempfile
from pathlib import Path
from typing import TYPE_CHECKING, Final, Protocol
from signal_bot.external import run
from signal_bot.media_tags import is_allowed
if TYPE_CHECKING:
from signal_bot.media_sniff import MediaKind
logger = logging.getLogger(__name__)
EXIFTOOL: Final = "exiftool"
# How long either exiftool call may take. A phone video is a few tens of
# megabytes and exiftool rewrites the container, not the frames.
TIMEOUT_SECONDS: Final = 60
# "[Group] TagName : value", which is what -G0 -s prints.
_TAG_LINE: Final = re.compile(r"^\[(\w+)\]\s+(\S+)\s*:\s?(.*)$")
class Stripper(Protocol):
"""Removes metadata from one upload, or refuses it."""
def strip(self, payload: bytes, kind: MediaKind) -> bytes | None:
"""Return the cleaned file, or None when it cannot be proven clean."""
class ExiftoolStripper:
"""The real stripper: exiftool 13.55, plus a positive post-check."""
def __init__(self, executable: str | None = None) -> None:
"""Locate exiftool once, by absolute path.
Args:
executable: Override for the binary, used by the e2e script.
"""
self._exiftool = executable or shutil.which(EXIFTOOL)
def strip(self, payload: bytes, kind: MediaKind) -> bytes | None:
"""Strip one upload and verify the result, or refuse it.
Args:
payload: The file exactly as it arrived.
kind: What the sniffer decided it is.
Returns:
The cleaned bytes, or None when the strip failed or the output
still carries a tag that is not structural.
"""
if not kind.strippable:
# kuhy's decision of 2026-08-31: .webm and .svg stay on the
# allowlist even though exiftool 13.55 can write neither, so they
# are stored exactly as they arrived, metadata included. Flagged
# at the time and recorded in DOCS-photo-pack.md.
logger.warning("storing %s unstripped: exiftool cannot write it", kind.suffix)
return payload
if self._exiftool is None:
logger.error("exiftool is not installed; refusing to store %s", kind.suffix)
return None
with tempfile.TemporaryDirectory(prefix="signal-bot-strip-") as workspace:
return self._run(Path(workspace), payload, kind)
def _run(self, workspace: Path, payload: bytes, kind: MediaKind) -> bytes | None:
"""Do the strip inside a temp directory that is removed either way."""
source = workspace / f"in{kind.suffix}"
destination = workspace / f"out{kind.suffix}"
source.write_bytes(payload)
# Never --overwrite_original: writing in place would leave a partial
# file where the original was if exiftool died halfway.
if not self._exiftool_ok(["-all=", "-o", str(destination), str(source)]):
return None
if not destination.is_file():
logger.warning("exiftool produced no output for %s", kind.suffix)
return None
report = self._exiftool_output(["-G0", "-s", "-all", str(destination)])
if report is None or not self._verify(report, kind):
return None
return destination.read_bytes()
def _verify(self, report: str, kind: MediaKind) -> bool:
"""True when every tag the stripped file still reports is structural."""
for line in report.splitlines():
match = _TAG_LINE.match(line)
if match is None:
continue
group, tag, value = match.group(1), match.group(2), match.group(3)
if not is_allowed(group, tag, value):
# The tag name, never its value: the value is the metadata.
logger.warning("refusing %s: %s:%s survived the strip", kind.suffix, group, tag)
return False
return True
def _exiftool_ok(self, arguments: list[str]) -> bool:
"""Run exiftool for its effect, reporting whether it succeeded."""
return self._exiftool_output(arguments) is not None
def _exiftool_output(self, arguments: list[str]) -> str | None:
"""Run exiftool and return its stdout, or None if it failed at all.
Every subprocess in this repository goes through signal_bot.external;
see that module for why there is exactly one.
"""
result = run([str(self._exiftool), *arguments], timeout=TIMEOUT_SECONDS)
return result.stdout if result.ok else None