#!/usr/bin/env python3 """Build/test the pinned Messenger bridge (mautrix-meta's Facebook connector) with Xessenger's single-owner patch, with photos picked together going as one Messenger message (and a message holding several read as one album), with rooms made only for threads active within thread_backfill.days_limit (recent-chats.patch), a Messenger thread's info asked for on request answered as errors.ErrUnsupported (it comes only with thread sync; a history move then uses what the bridge holds: chat-info-unsupported.patch), the device-list patch to its whatsmeow, and with its account keys stored sealed with the bridge's key when XESSENGER_SEAL_KEY_FILE is set (mautrix-seal.patch, whatsmeow-seal.patch).""" import argparse import json import os from pathlib import Path import shutil import subprocess import tempfile ROOT = Path(__file__).resolve().parent def run(args, **kwargs): return subprocess.run(args, check=True, text=True, **kwargs) def writable(directory): for path in [directory, *directory.rglob('*')]: path.chmod(path.stat().st_mode | 0o200) def patch_dependency(source_dir, path, patches): """Build with a copy of the dependency version the bridge pins (go.sum checks the download), patched. The copy lives in the source tree and the replace is relative, so the binary records no temporary directory.""" module = json.loads(run(['go', 'mod', 'download', '-json', path], cwd=source_dir, capture_output=True).stdout) target = source_dir / '.xessenger' / path.rsplit('/', 1)[-1] shutil.copytree(module['Dir'], target) writable(target) for patch in patches: run(['patch', '--batch', '--fuzz=0', '-p1', '-i', str(ROOT / patch)], cwd=target) run(['go', 'mod', 'edit', '-replace='+path+'=./'+target.relative_to(source_dir).as_posix()], cwd=source_dir) def use_seal(source_dir): """The seal package in seal/, the same in every bridge, which the patched mautrix-go and whatsmeow import.""" shutil.copytree(ROOT / 'seal', source_dir / '.xessenger' / 'seal') run(['go', 'mod', 'edit', '-require=xessenger.local/seal@v0.0.0', '-replace=xessenger.local/seal=./.xessenger/seal'], cwd=source_dir) def use_bridgekit(source_dir, command): """services/bridgekit, Xessenger's extension every bridge runs with (QA-289), installed in main.go (bridgekit.patch): taken from the repository, or in Docker from the bridgekit build context the Dockerfile copies to XESSENGER_BRIDGEKIT. Looked up only here: the --warm layer has neither.""" bridgekit = Path(os.environ.get('XESSENGER_BRIDGEKIT') or ROOT.parents[2] / 'services' / 'bridgekit') shutil.copytree(bridgekit, source_dir / '.xessenger' / 'bridgekit', ignore=shutil.ignore_patterns('*_test.go', 'testdata')) run(['go', 'mod', 'edit', '-require=xessenger/bridgekit@v0.0.0', '-replace=xessenger/bridgekit=./.xessenger/bridgekit'], cwd=source_dir) run(['patch', '--batch', '--fuzz=0', '-p1', '-i', str(ROOT / 'bridgekit.patch')], cwd=source_dir) # The patch must change the command this script builds, or the bridge would run without the extension. if 'bridgekit.Install(' not in (source_dir / command / 'main.go').read_text(): raise RuntimeError(f'bridgekit.patch does not install bridgekit in {command}') def build(output=None, test=False, warm=False): lock = json.loads((ROOT / 'upstream.json').read_text()) source = json.loads(run(['go', 'mod', 'download', '-json', lock['Path']+'@'+lock['Version']], capture_output=True).stdout) if any(source.get(k) != v for k, v in lock.items()): raise RuntimeError('Upstream module does not match the pinned checksums') with tempfile.TemporaryDirectory(prefix='xessenger-facebook-') as temp: source_dir = Path(temp) / 'source' shutil.copytree(source['Dir'], source_dir) writable(source_dir) env = dict(os.environ, CGO_ENABLED='1') # Every build runs with -trimpath: Go keys its build cache on the package directory otherwise, and this one # is new each time. --warm compiles the unpatched upstream into that cache for the image's next layer, with # mautrix-go and whatsmeow taken from copies as below, so only what the patches touch compiles again. if warm: patch_dependency(source_dir, 'maunium.net/go/mautrix', []) patch_dependency(source_dir, 'go.mau.fi/whatsmeow', []) run(['go', 'build', '-trimpath', '-tags', 'goolm', '-o', os.devnull, './cmd/mautrix-meta'], cwd=source_dir, env=env) return for patch in ['single-owner.patch', 'album.patch', 'recent-chats.patch', 'chat-info-unsupported.patch']: run(['patch', '--batch', '--fuzz=0', '-p1', '-i', str(ROOT / patch)], cwd=source_dir) # Encrypted Messenger chats are sent by whatsmeow, a dependency, which also keeps their device keys. The login's # secrets are sealed in mautrix-go and the device keys in whatsmeow. use_seal(source_dir) patch_dependency(source_dir, 'maunium.net/go/mautrix', ['mautrix-seal.patch', 'mautrix-device-keys.patch']) patch_dependency(source_dir, 'go.mau.fi/whatsmeow', ['whatsmeow-device-list.patch', 'whatsmeow-seal.patch']) shutil.copy(ROOT / 'seal_test.go', source_dir / 'pkg/metaid/xessenger_seal_test.go') use_bridgekit(source_dir, 'cmd/mautrix-meta') if test: run(['go', 'test', '-trimpath', '-tags', 'goolm', './pkg/connector', './pkg/msgconv', './pkg/metaid'], cwd=source_dir, env=env) # One package at a time: with XESSENGER_SEAL_TEST_POSTGRES both empty the same database. run(['go', 'test', '-p', '1', '-trimpath', '-tags', 'goolm', '-run', 'Xessenger', 'maunium.net/go/mautrix/bridgev2/database', 'maunium.net/go/mautrix/crypto/xessengertest', 'go.mau.fi/whatsmeow/store/sqlstore'], cwd=source_dir, env=env) run(['go', 'build', '-trimpath', '-tags', 'goolm', '-o', os.devnull, './cmd/mautrix-meta'], cwd=source_dir, env=env) if output: output = Path(output).resolve() output.parent.mkdir(parents=True, exist_ok=True) run(['go', 'build', '-trimpath', '-tags', 'goolm', '-ldflags', '-X main.Tag=v0.2609.0-xessenger-device-list', '-o', str(output), './cmd/mautrix-meta'], cwd=source_dir, env=env) if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--output') parser.add_argument('--test', action='store_true') parser.add_argument('--warm', action='store_true', help='only compile the unpatched upstream into the Go build cache') args = parser.parse_args() if args.warm and (args.output or args.test): parser.error('--warm runs alone') if not args.output and not args.test and not args.warm: parser.error('Choose --test and/or --output, or --warm') build(args.output, args.test, args.warm)