Files
baji-vc/scripts/package-character-test.py

236 lines
14 KiB
Python

#!/usr/bin/env python3
"""Build/verify one trusted persona debug profile with an explicit immutable media bundle.
No gateway mutations, voice selection, model calls or device installation.
Default profile can be built and verified separately without publishing a main APK.
"""
import argparse
import hashlib
import importlib.util
import json
from pathlib import Path
import re
import shutil
import subprocess
import struct
import tempfile
import urllib.request
import zipfile
ROOT = Path(__file__).resolve().parents[1]
TOOLS = Path('/home/ubuntu/android-build/sdk/build-tools/34.0.0')
CERT = 'b9608336bc1ed1de3269bb4594f9fe718daaa5439511c5187aa385d2b799dcf1'
BASELINE = ROOT/'artifacts/lan-voice-v0714-black-tulle-correct03-code33-arm64-debug.apk'
BASELINE_SHA = 'ba00023507e8f396f95e165f1aa744aba3a51d5072cbb8d5c2504a6159c75157'
spec = importlib.util.spec_from_file_location('character_assets', ROOT/'scripts/select-character-assets.py')
select = importlib.util.module_from_spec(spec)
spec.loader.exec_module(select)
require = select.require
def file_sha(p):
with Path(p).open('rb') as f:
return hashlib.file_digest(f, 'sha256').hexdigest()
def dex_float_fields(raw, descriptor='Lcom/gorios/lanvoice/BuildConfig;'):
"""Read encoded FLOAT bits: dexdump prints only six significant digits."""
def uleb(pos):
value=0
for shift in range(0,35,7):
byte=raw[pos];pos+=1;value|=(byte&127)<<shift
if byte<128:return value,pos
raise ValueError('invalid DEX uleb')
def uint(pos):return struct.unpack_from('<I',raw,pos)[0]
def string(index):
pos=uint(uint(60)+index*4);_,pos=uleb(pos)
return raw[pos:raw.index(b'\0',pos)].decode('utf-8')
def typename(index):return string(uint(uint(68)+index*4))
for i in range(uint(96)):
pos=uint(100)+i*32
if typename(uint(pos))!=descriptor:continue
data=uint(pos+24);values=uint(pos+28)
count,data=uleb(data)
for _ in range(3):_,data=uleb(data)
fields=[];field_index=0
for _ in range(count):
delta,data=uleb(data);_,data=uleb(data);field_index+=delta
fields.append(string(uint(uint(84)+field_index*8+4)))
size,values=uleb(values);floats={}
for name in fields[:size]:
header=raw[values];values+=1;kind=header&31;length=(header>>5)+1
if kind in (0x1e,0x1f):continue # null/boolean have no payload
require(kind in (0,2,3,4,6,16,17,23,24,25,26,27), 'unexpected BuildConfig DEX value')
payload=raw[values:values+length];values+=length
if kind==16:
require(length<=4,'invalid DEX float')
floats[name]=struct.unpack('<f',b'\0'*(4-length)+payload)[0]
return floats
raise ValueError('BuildConfig DEX class missing')
def flags(profile, version, media_bundle='black-correct03'):
media = select.catalog()['mediaBundles'][media_bundle]
pin = media['indexSha256']
cache_flags = [] if profile != 'liam-test-square540' else ['--project-cache-dir='+str(ROOT/'.runtime/gradle-project-cache'/profile/'square540-headchest')]
return cache_flags + ['-PcharacterProfile='+profile, '-PcharacterMediaBundle='+media_bundle,
'-PavatarUserNetworkActions='+str(media.get('networkActionsAllowed',False)).lower(),
'-PactionVersionCode='+str(version),
'-PnaturalManifestSha=0a3c4918ba746019cf1df885bec66e5858a8950997dac4f64e7d37094be64dad',
'-PemotionManifestSha='+pin] + ['-P'+name+'=true' for name in (
'avatarUserAssetCandidate', 'avatarActionCandidate',
'avatarNatural', 'avatarMouthCandidate', 'avatarFullActionCandidate', 'avatarPlaybackClockFix',
'avatarStartupFix', 'presenceCandidate', 'faceDiagnosticsFix', 'cameraCompatibilityFix',
'cameraDirectYuv', 'cameraPreviewStream', 'cameraProbeDiagnostic')]
def build_dir(profile):
return select.build_directory(profile)
def verify(apk, profile, version, media_bundle='black-correct03',frame_zoom=1,frame_center_y=.5):
catalog = select.catalog()
role = catalog['profiles'][profile]
framing = select.framing(profile, media_bundle)
if framing['id'] != 'legacy':
frame_zoom,frame_center_y=framing['zoom'],framing['centerY']
media = catalog['mediaBundles'][media_bundle]
selected = select.selection(ROOT/'app/src/main/assets', profile, emotion_sha=media['indexSha256'],
user_assets=True, mouth=True, startup=True, media_bundle=media_bundle)
require(file_sha(BASELINE) == BASELINE_SHA, 'code33 rollback drift')
with zipfile.ZipFile(BASELINE) as old, zipfile.ZipFile(apk) as new:
names = lambda z: {n for n in z.namelist() if n.startswith('assets/') and not n.endswith('/')}
require(names(new) == {'assets/'+n for n in selected['files']}, 'APK selection inventory mismatch')
if media_bundle == 'black-correct03':
require(names(new) == names(old), 'code33 inventory drift')
for name in names(new):
raw = new.read(name)
row = selected['files'][name[7:]]
require(len(raw) == row['bytes'] and select.digest(raw) == row['sha256'],
'APK media drift: '+name)
if media_bundle == 'black-correct03' or name in names(old):
require(raw == old.read(name), 'shared/retained code33 bytes drift: '+name)
if name.endswith('.mp4'):
require(new.getinfo(name).compress_type == zipfile.ZIP_STORED, 'video compression drift')
for name in ('startup_poster', 'startup_black_tulle_poster'):
n = 'res/drawable-nodpi-v4/'+name+'.png'
require(new.read(n) == old.read(n), 'poster resource drift')
poster_path='res/drawable-nodpi-v4/'+media['posterResource']+'.png'
require(new.read(poster_path)==new.read('assets/'+media['bootstrapRoot']+'poster.png'), 'selected poster mismatch')
# Read real DEX static values rather than trusting a generated Java file.
with tempfile.TemporaryDirectory() as folder:
dex_text = '';dex_floats={}
for name in new.namelist():
if re.fullmatch(r'classes\d*\.dex', name):
dex = Path(folder)/name
dex.write_bytes(new.read(name))
result = subprocess.check_output([str(TOOLS/'dexdump'), str(dex)]).decode('utf-8', errors='replace')
match = re.search(r"Class descriptor\s*:\s*'Lcom/gorios/lanvoice/BuildConfig;'([\s\S]*?)(?=\nClass #|\Z)", result)
if match:
dex_text = match[1];dex_floats=dex_float_fields(new.read(name))
break
require(dex_text, 'BuildConfig absent from actual DEX')
dex_values = dict(re.findall(r"name\s*:\s*'([^']+)'[^\n]*\n\s*type[^\n]*\n\s*access[^\n]*\n\s*value\s*:\s*([^\n]+)", dex_text))
expected = {'APPLICATION_ID': role['applicationId'], 'DIALOGUE_PERSONA': role['persona'],
'CHARACTER_PROFILE': profile, 'EMOTION_MANIFEST_SHA': media['indexSha256'],
'EMOTION_ASSET_ROOT': media['assetRoot'], 'STARTUP_ASSET_ROOT': media['bootstrapRoot'],
'STARTUP_MANIFEST_SHA': media['bootstrapSha256']}
if 'AVATAR_FRAMING_PRESET' in dex_values or framing['id']!='legacy':
expected['AVATAR_FRAMING_PRESET']=framing['id']
for field, value in expected.items():
require(dex_values.get(field) == '"'+value+'"', 'APK DEX mismatch: '+field)
for field, value in {'AVATAR_NETWORK_ACTIONS_ALLOWED': media.get('networkActionsAllowed',False), 'AVATAR_USER_ASSET_CANDIDATE': True,
'PERMISSION_CONNECTION_RETENTION': role['permissionConnectionRetention']}.items():
require(dex_values.get(field) == str(value).lower(), 'APK DEX boolean mismatch: '+field)
if 'WAITING_POSES_ENABLED' in dex_values or version>=40:
require(dex_values.get('WAITING_POSES_ENABLED') == str(media.get('waitingContract',False)).lower(), 'APK DEX waiting gate mismatch')
require(dex_values.get('VERSION_CODE') == str(version) and
dex_values.get('VERSION_NAME') == '"0.7.14'+role['versionSuffix']+'"', 'APK DEX version mismatch')
for field,value in [('AVATAR_FRAME_ZOOM',frame_zoom),('AVATAR_FRAME_CENTER_Y',frame_center_y)]:
if field in dex_values or frame_zoom!=1 or frame_center_y!=.5:
require(abs(dex_floats.get(field,float('nan'))-value)<.000001,'APK framing mismatch: '+field)
badge = subprocess.check_output([str(TOOLS/'aapt'), 'dump', 'badging', str(apk)], text=True)
version_name = '0.7.14'+role['versionSuffix']
for value in ("name='"+role['applicationId']+"'", f"versionCode='{version}'",
"versionName='"+version_name+"'", "sdkVersion:'26'", "targetSdkVersion:'34'",
"application-label:'"+role['appName']+"'"):
require(value in badge, 'APK badging: '+value)
require(re.search(r'^native-code: (.+)$', badge, re.M)[1].strip() == "'arm64-v8a'", 'APK ABI')
cert = subprocess.check_output([str(TOOLS/'apksigner'), 'verify', '--verbose', '--print-certs', str(apk)], text=True)
require(re.search(r'Signer #1 certificate SHA-256 digest: (\w+)', cert)[1] == CERT, 'debug certificate mismatch')
xml = subprocess.check_output([str(TOOLS/'aapt'), 'dump', 'xmltree', str(apk), 'AndroidManifest.xml'], text=True)
require('com.gorios.lanvoice.MainActivity' in xml and 'com.gorios.lanvoice.CameraDiagnosticsActivity' in xml,
'actual manifest class resolution')
require('sharedUserId' not in xml, 'shared UID would break private storage isolation')
authorities = re.findall(r'android:authorities[^=]*="([^"]+)"', xml)
require(authorities and all(a.startswith(role['applicationId']+'.') for a in authorities), 'provider authority isolation')
require('android:allowBackup' in xml and ('0xffffffff' if role['allowBackup'] else '0x0') in
re.search(r'android:allowBackup[^\n]*', xml)[0], 'backup mismatch')
return {'profile': profile, 'application_id': role['applicationId'], 'persona': role['persona'],
'version_name': version_name, 'version_code': version, 'certificate_sha256': CERT,
'index_sha256': media['indexSha256'], 'media_bundle':media_bundle, 'asset_files_verified':len(selected['files']),
'assets_unchanged': len(selected['files']) if media_bundle=='black-correct03' else None,
'network_actions_allowed':media.get('networkActionsAllowed',False),
'waiting_contract_enabled':media.get('waitingContract',False),
'framing_preset':framing['id'],'framing_zoom':frame_zoom,'framing_center_y':frame_center_y,
'poster_resources_unchanged': 2, 'provider_authorities': authorities,
'actual_dex_verified': True, 'device': 'not_run', 'gateway_changed': False}
def artifact_name(profile, version):
require(profile in ('lvbu-test', 'liam-test', 'liam-test-square540'), 'main publication outside this task')
return f"lan-voice-v0714-{profile}-code{version}-arm64-debug.apk"
def publish(apk, report, name=None):
name = name or artifact_name(report['profile'], report['version_code'])
require(re.fullmatch('[a-z0-9.-]+[.]apk',name),'artifact filename shape')
artifact = ROOT/'artifacts'/name
with artifact.open('xb') as out, apk.open('rb') as src:
shutil.copyfileobj(src, out)
sha = file_sha(artifact)
checksum = (sha+' '+name+'\n').encode()
with artifact.with_suffix('.apk.sha256').open('xb') as out:
out.write(checksum)
url = 'http://192.168.31.124:8080/'+name
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
with opener.open(url, timeout=30) as r:
require(r.status == 200 and select.digest(r.read()) == sha, 'HTTP APK bytes mismatch')
with opener.open(url+'.sha256', timeout=15) as r:
require(r.status == 200 and r.read() == checksum, 'HTTP checksum mismatch')
return {**report, 'url': url, 'sha256': sha, 'bytes': artifact.stat().st_size, 'http_bytes_verified': True}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--profile', choices=sorted(select.catalog()['profiles']), default='lvbu-test')
parser.add_argument('--version-code', type=int)
parser.add_argument('--media-bundle',choices=sorted(select.catalog()['mediaBundles']),default='black-correct03')
parser.add_argument('--build', action='store_true')
parser.add_argument('--publish', action='store_true')
parser.add_argument('--output', type=Path, required=True)
args = parser.parse_args()
minimum = max(select.catalog()['profiles'][args.profile].get('minimumVersionCode', 34),
select.catalog()['mediaBundles'][args.media_bundle].get('minimumVersionCode',0))
args.version_code = args.version_code if args.version_code is not None else minimum
require(args.version_code >= minimum, 'fresh character version required')
require(not args.publish or args.profile != 'main', 'main publication outside this task')
if args.publish:
require(not (ROOT/'artifacts'/artifact_name(args.profile, args.version_code)).exists(),
'published character version is immutable; choose a new code')
if args.build:
subprocess.run([str(ROOT/'scripts/build.sh'), ':app:assembleDebug', ':app:compileDebugAndroidTestKotlin',
*flags(args.profile, args.version_code, args.media_bundle)], check=True, cwd=ROOT)
apk = build_dir(args.profile)/'outputs/apk/debug/app-debug.apk'
report = verify(apk, args.profile, args.version_code, args.media_bundle)
if args.publish:
report = publish(apk, report)
args.output.parent.mkdir(parents=True, exist_ok=True)
with args.output.open('x') as out:
out.write(json.dumps(report, indent=2, ensure_ascii=False)+'\n')
print(json.dumps(report, indent=2, ensure_ascii=False))
if __name__ == '__main__':
main()