feat(#1084): Play upload tool, standard library only, tests first
tools/play/play_release.py sends a signed release bundle to Play's closed testing track (External) or production through the Android Publisher edits API. A read-only tracks command lists every track for A3. Before any change it checks the bundle certificate against the release-signed.yml pin, the bundle version code against the tag's pubspec, the tag against the pubspec version, the notes length, and that the code is higher than anything Play holds unless Play already holds this exact bundle. It never removes another release, stops on a different version mid rollout, on a narrowing request and on a release shared with another version, and a re-run at the same rollout changes nothing. A failed run deletes its edit. 32 tests, run in the analyze check. Each of 17 guards was removed in turn and every removal failed a test. The parser reads codes 66, 67 and 68 and the pinned certificate from the three real release bundles. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>docs/1086-a3-result
parent
f84605f29e
commit
63e5fcb62e
@ -0,0 +1,495 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Send a signed Offband release bundle to a Google Play track (#1053, #1084).
|
||||
|
||||
Standard library only. Two commands:
|
||||
|
||||
tracks Read-only: list every track and its releases. Changes nothing.
|
||||
publish Check the bundle, then put this release on External (closed
|
||||
testing) or production at the rollout asked for.
|
||||
|
||||
The access token comes from the PLAY_ACCESS_TOKEN environment variable and is
|
||||
never printed. Every check that can't tell what is true stops the run (PLAN.md
|
||||
section 6); nothing is guessed. A failed run deletes its uncommitted edit, so
|
||||
Play is left as it was.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
PACKAGE = "app.offband.meshcore"
|
||||
|
||||
# The same pin as release-signed.yml's two certificate checks. A test keeps
|
||||
# them identical.
|
||||
EXPECTED_CERT_SHA256 = (
|
||||
"e7da8cd5bf22ac3eda7cb954b8b120a18b6c4382d1b6e6fdd204ddedddaf5488"
|
||||
)
|
||||
|
||||
# Play's API names for the two targets. A3 reads the real names live.
|
||||
TRACKS = {"external": "alpha", "production": "production"}
|
||||
ROLLOUTS = ("draft", "10", "25", "50", "100")
|
||||
NOTES_MAX = 500
|
||||
NOTES_LANGUAGE = "en-US"
|
||||
|
||||
API = "https://androidpublisher.googleapis.com/androidpublisher/v3/applications"
|
||||
UPLOAD = (
|
||||
"https://androidpublisher.googleapis.com/upload/androidpublisher/v3/applications"
|
||||
)
|
||||
|
||||
|
||||
class Stop(Exception):
|
||||
"""A check failed or couldn't tell. The run ends and changes nothing."""
|
||||
|
||||
|
||||
# --- Bundle reading ----------------------------------------------------------
|
||||
|
||||
|
||||
def _der(data: bytes, pos: int) -> tuple[int, int, int]:
|
||||
"""Reads one DER header at pos. Returns (tag, content start, content end)."""
|
||||
if pos + 2 > len(data):
|
||||
raise Stop("signature block is truncated")
|
||||
tag = data[pos]
|
||||
length = data[pos + 1]
|
||||
pos += 2
|
||||
if length & 0x80:
|
||||
count = length & 0x7F
|
||||
if count == 0 or count > 4 or pos + count > len(data):
|
||||
raise Stop("signature block has an unreadable length")
|
||||
length = int.from_bytes(data[pos : pos + count], "big")
|
||||
pos += count
|
||||
end = pos + length
|
||||
if end > len(data):
|
||||
raise Stop("signature block is truncated")
|
||||
return tag, pos, end
|
||||
|
||||
|
||||
def _children(data: bytes, start: int, end: int) -> list[tuple[int, int, int, int]]:
|
||||
"""Each child TLV as (tag, header start, content start, content end)."""
|
||||
out = []
|
||||
pos = start
|
||||
while pos < end:
|
||||
tag, body, stop = _der(data, pos)
|
||||
out.append((tag, pos, body, stop))
|
||||
pos = stop
|
||||
return out
|
||||
|
||||
|
||||
def signer_certificate(block: bytes) -> bytes:
|
||||
"""The first certificate in a PKCS#7 SignedData block, as DER bytes.
|
||||
|
||||
ContentInfo { contentType, [0] SignedData { version, digestAlgorithms,
|
||||
encapContentInfo, [0] certificates, ... } }. keytool's SHA-256 is the
|
||||
digest of exactly these bytes.
|
||||
"""
|
||||
tag, body, end = _der(block, 0)
|
||||
if tag != 0x30:
|
||||
raise Stop("signature block is not a PKCS#7 structure")
|
||||
info = _children(block, body, end)
|
||||
if len(info) < 2 or info[1][0] != 0xA0:
|
||||
raise Stop("signature block has no signed content")
|
||||
_, _, inner, inner_end = info[1]
|
||||
tag, body, end = _der(block, inner)
|
||||
if tag != 0x30:
|
||||
raise Stop("signature block's signed content is malformed")
|
||||
for tag, _, cert_body, cert_end in _children(block, body, end):
|
||||
if tag == 0xA0:
|
||||
certs = _children(block, cert_body, cert_end)
|
||||
if not certs:
|
||||
break
|
||||
_, head, _, stop = certs[0]
|
||||
return block[head:stop]
|
||||
raise Stop("signature block carries no certificate")
|
||||
|
||||
|
||||
def certificate_sha256(aab: zipfile.ZipFile) -> str:
|
||||
blocks = [
|
||||
n
|
||||
for n in aab.namelist()
|
||||
if re.fullmatch(r"META-INF/[^/]+\.(RSA|EC|DSA)", n, re.IGNORECASE)
|
||||
]
|
||||
if len(blocks) != 1:
|
||||
raise Stop(f"bundle has {len(blocks)} signature blocks, expected 1")
|
||||
cert = signer_certificate(aab.read(blocks[0]))
|
||||
return hashlib.sha256(cert).hexdigest()
|
||||
|
||||
|
||||
def _varint(data: bytes, pos: int) -> tuple[int, int]:
|
||||
value = shift = 0
|
||||
while True:
|
||||
if pos >= len(data):
|
||||
raise Stop("bundle manifest is truncated")
|
||||
byte = data[pos]
|
||||
pos += 1
|
||||
value |= (byte & 0x7F) << shift
|
||||
if not byte & 0x80:
|
||||
return value, pos
|
||||
shift += 7
|
||||
if shift > 63:
|
||||
raise Stop("bundle manifest has an unreadable number")
|
||||
|
||||
|
||||
def _fields(data: bytes) -> list[tuple[int, int, object]]:
|
||||
"""Protobuf fields as (number, wire type, int or bytes)."""
|
||||
out = []
|
||||
pos = 0
|
||||
while pos < len(data):
|
||||
key, pos = _varint(data, pos)
|
||||
number, wire = key >> 3, key & 7
|
||||
if wire == 0:
|
||||
value, pos = _varint(data, pos)
|
||||
elif wire == 2:
|
||||
size, pos = _varint(data, pos)
|
||||
if pos + size > len(data):
|
||||
raise Stop("bundle manifest is truncated")
|
||||
value, pos = data[pos : pos + size], pos + size
|
||||
elif wire == 5:
|
||||
value, pos = data[pos : pos + 4], pos + 4
|
||||
elif wire == 1:
|
||||
value, pos = data[pos : pos + 8], pos + 8
|
||||
else:
|
||||
raise Stop("bundle manifest has an unreadable field")
|
||||
out.append((number, wire, value))
|
||||
return out
|
||||
|
||||
|
||||
def manifest_version_code(manifest: bytes) -> int:
|
||||
"""android:versionCode from a bundle's protobuf AndroidManifest.xml.
|
||||
|
||||
aapt2's XmlNode: element = 1. XmlElement: name = 3, attribute = 4.
|
||||
XmlAttribute: name = 2, value = 3, compiled_item = 6. Item: prim = 7.
|
||||
Primitive: int_decimal_value = 6.
|
||||
"""
|
||||
element = next((v for n, w, v in _fields(manifest) if n == 1 and w == 2), None)
|
||||
if element is None:
|
||||
raise Stop("bundle manifest has no root element")
|
||||
fields = _fields(element)
|
||||
name = next((v for n, w, v in fields if n == 3 and w == 2), b"")
|
||||
if name != b"manifest":
|
||||
raise Stop("bundle manifest's root is not <manifest>")
|
||||
for n, w, attribute in fields:
|
||||
if n != 4 or w != 2:
|
||||
continue
|
||||
parts = _fields(attribute)
|
||||
if next((v for n, w, v in parts if n == 2 and w == 2), b"") != b"versionCode":
|
||||
continue
|
||||
for n, w, item in parts:
|
||||
if n == 6 and w == 2:
|
||||
for n2, w2, prim in _fields(item):
|
||||
if n2 == 7 and w2 == 2:
|
||||
for n3, w3, value in _fields(prim):
|
||||
if n3 == 6 and w3 == 0:
|
||||
return value
|
||||
text = next((v for n, w, v in parts if n == 3 and w == 2), b"")
|
||||
if text.isdigit():
|
||||
return int(text)
|
||||
raise Stop("bundle manifest's versionCode is unreadable")
|
||||
raise Stop("bundle manifest has no versionCode")
|
||||
|
||||
|
||||
def read_bundle(path: Path) -> dict:
|
||||
if not path.is_file():
|
||||
raise Stop(f"no bundle at {path}")
|
||||
try:
|
||||
with zipfile.ZipFile(path) as aab:
|
||||
cert = certificate_sha256(aab)
|
||||
try:
|
||||
manifest = aab.read("base/manifest/AndroidManifest.xml")
|
||||
except KeyError:
|
||||
raise Stop("bundle has no base/manifest/AndroidManifest.xml")
|
||||
code = manifest_version_code(manifest)
|
||||
except zipfile.BadZipFile:
|
||||
raise Stop(f"{path} is not a bundle")
|
||||
return {
|
||||
"cert_sha256": cert,
|
||||
"version_code": code,
|
||||
"sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
|
||||
}
|
||||
|
||||
|
||||
# --- Release facts from the tag ----------------------------------------------
|
||||
|
||||
|
||||
def pubspec_version(pubspec: Path) -> tuple[str, int]:
|
||||
match = re.search(
|
||||
r"^version:\s*(\d+\.\d+\.\d+)\+(\d+)\s*$", pubspec.read_text("utf-8"), re.M
|
||||
)
|
||||
if not match:
|
||||
raise Stop(f"{pubspec} has no version of the form X.Y.Z+N")
|
||||
return match.group(1), int(match.group(2))
|
||||
|
||||
|
||||
def check_tag(tag: str, version: str) -> None:
|
||||
if tag != f"v{version}" and not tag.startswith(f"v{version}-"):
|
||||
raise Stop(f"tag {tag} is not a release of pubspec version {version}")
|
||||
|
||||
|
||||
def read_notes(notes_dir: Path, version: str) -> str:
|
||||
path = notes_dir / f"{version}.txt"
|
||||
if not path.is_file():
|
||||
raise Stop(f"release notes {path} are missing")
|
||||
text = path.read_text("utf-8").strip()
|
||||
if not text:
|
||||
raise Stop(f"release notes {path} are empty")
|
||||
if len(text) > NOTES_MAX:
|
||||
raise Stop(f"release notes {path} are {len(text)} characters, over {NOTES_MAX}")
|
||||
return text
|
||||
|
||||
|
||||
def check_bundle(bundle: dict, version_code: int) -> None:
|
||||
if bundle["cert_sha256"] != EXPECTED_CERT_SHA256:
|
||||
raise Stop(
|
||||
f"bundle certificate {bundle['cert_sha256']} is not the release key"
|
||||
)
|
||||
if bundle["version_code"] != version_code:
|
||||
raise Stop(
|
||||
f"bundle version code {bundle['version_code']} differs from the "
|
||||
f"tag's pubspec, {version_code}"
|
||||
)
|
||||
|
||||
|
||||
# --- Track rules --------------------------------------------------------------
|
||||
|
||||
|
||||
def wanted_release(rollout: str, target: str) -> dict:
|
||||
if rollout not in ROLLOUTS:
|
||||
raise Stop(f"rollout {rollout} is not one of {', '.join(ROLLOUTS)}")
|
||||
if target == "external" and rollout not in ("draft", "100"):
|
||||
raise Stop("External goes to its whole tester list: use draft or 100")
|
||||
if rollout == "draft":
|
||||
return {"status": "draft"}
|
||||
if rollout == "100":
|
||||
return {"status": "completed"}
|
||||
return {"status": "inProgress", "userFraction": int(rollout) / 100}
|
||||
|
||||
|
||||
def reach(release: dict) -> float:
|
||||
"""How widely a release is served: draft 0, a fraction, completed 1."""
|
||||
status = release.get("status")
|
||||
if status == "draft":
|
||||
return 0.0
|
||||
if status == "completed":
|
||||
return 1.0
|
||||
if status == "inProgress":
|
||||
return float(release.get("userFraction", 0))
|
||||
raise Stop(f"release status {status} can't be compared; change it in Console")
|
||||
|
||||
|
||||
def plan_track(track: dict, version_code: int, wanted: dict) -> list | None:
|
||||
"""The track's new release list, or None when it already serves this.
|
||||
|
||||
Never removes another release. Stops when a different version is mid
|
||||
rollout, or when the request would narrow what the track already serves.
|
||||
"""
|
||||
code = str(version_code)
|
||||
releases = track.get("releases", [])
|
||||
ours = [r for r in releases if code in r.get("versionCodes", [])]
|
||||
others = [r for r in releases if code not in r.get("versionCodes", [])]
|
||||
for release in others:
|
||||
if release.get("status") in ("inProgress", "halted"):
|
||||
raise Stop(
|
||||
f"version {', '.join(release.get('versionCodes', []))} is mid "
|
||||
f"rollout on {track.get('track')}: finish or halt it in Console"
|
||||
)
|
||||
if ours:
|
||||
if len(ours) > 1:
|
||||
raise Stop(f"{track.get('track')} lists version {code} twice")
|
||||
if ours[0].get("versionCodes") != [code]:
|
||||
raise Stop(
|
||||
f"{track.get('track')} serves version {code} in one release with "
|
||||
f"{', '.join(ours[0].get('versionCodes', []))}: change it in Console"
|
||||
)
|
||||
current, asked = reach(ours[0]), reach(wanted)
|
||||
if current == asked and ours[0].get("status") == wanted["status"]:
|
||||
return None
|
||||
if current > asked:
|
||||
raise Stop(
|
||||
f"{track.get('track')} already serves version {code} wider than "
|
||||
"asked: narrowing or halting is done in Console"
|
||||
)
|
||||
return others + [wanted]
|
||||
|
||||
|
||||
# --- Play API -----------------------------------------------------------------
|
||||
|
||||
|
||||
class Play:
|
||||
"""Android Publisher edits, over urllib. Tests replace `send`."""
|
||||
|
||||
def __init__(self, token: str, package: str = PACKAGE):
|
||||
self.token = token
|
||||
self.package = package
|
||||
|
||||
def send(self, method, url, body=None, content_type="application/json"):
|
||||
request = urllib.request.Request(url, data=body, method=method)
|
||||
request.add_header("Authorization", f"Bearer {self.token}")
|
||||
if body is not None:
|
||||
request.add_header("Content-Type", content_type)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=600) as response:
|
||||
raw = response.read()
|
||||
except urllib.error.HTTPError as error:
|
||||
detail = error.read().decode("utf-8", "replace")
|
||||
try:
|
||||
detail = json.loads(detail)["error"]["message"]
|
||||
except (ValueError, KeyError, TypeError):
|
||||
pass
|
||||
raise Stop(f"Play refused {method} ({error.code}): {detail}")
|
||||
except urllib.error.URLError as error:
|
||||
raise Stop(f"Play unreachable: {error.reason}")
|
||||
return json.loads(raw) if raw else {}
|
||||
|
||||
def _edit(self, edit_id: str = "") -> str:
|
||||
base = f"{API}/{self.package}/edits"
|
||||
return f"{base}/{edit_id}" if edit_id else base
|
||||
|
||||
def open_edit(self) -> str:
|
||||
return self.send("POST", self._edit(), b"{}")["id"]
|
||||
|
||||
def delete_edit(self, edit_id: str) -> None:
|
||||
self.send("DELETE", self._edit(edit_id))
|
||||
|
||||
def tracks(self, edit_id: str) -> list:
|
||||
return self.send("GET", f"{self._edit(edit_id)}/tracks").get("tracks", [])
|
||||
|
||||
def bundles(self, edit_id: str) -> list:
|
||||
return self.send("GET", f"{self._edit(edit_id)}/bundles").get("bundles", [])
|
||||
|
||||
def upload(self, edit_id: str, aab: Path) -> dict:
|
||||
url = f"{UPLOAD}/{self.package}/edits/{edit_id}/bundles?uploadType=media"
|
||||
return self.send("POST", url, aab.read_bytes(), "application/octet-stream")
|
||||
|
||||
def set_track(self, edit_id: str, track: str, releases: list) -> None:
|
||||
body = json.dumps({"track": track, "releases": releases}).encode()
|
||||
self.send("PUT", f"{self._edit(edit_id)}/tracks/{track}", body)
|
||||
|
||||
def commit(self, edit_id: str) -> None:
|
||||
self.send("POST", f"{self._edit(edit_id)}:commit")
|
||||
|
||||
|
||||
def highest_code(tracks: list, bundles: list) -> int:
|
||||
codes = [int(b["versionCode"]) for b in bundles if "versionCode" in b]
|
||||
for track in tracks:
|
||||
for release in track.get("releases", []):
|
||||
codes += [int(c) for c in release.get("versionCodes", [])]
|
||||
return max(codes, default=0)
|
||||
|
||||
|
||||
def list_tracks(play: Play, out=print) -> None:
|
||||
edit = play.open_edit()
|
||||
try:
|
||||
for track in play.tracks(edit):
|
||||
out(f"track {track.get('track')}")
|
||||
for release in track.get("releases", []):
|
||||
fraction = release.get("userFraction")
|
||||
extra = f" at {fraction:.0%}" if fraction is not None else ""
|
||||
codes = ", ".join(release.get("versionCodes", [])) or "none"
|
||||
out(
|
||||
f" {release.get('name', '(unnamed)')}: versions {codes}, "
|
||||
f"{release.get('status')}{extra}"
|
||||
)
|
||||
finally:
|
||||
play.delete_edit(edit)
|
||||
|
||||
|
||||
def publish(play: Play, aab: Path, pubspec: Path, notes_dir: Path, tag: str,
|
||||
target: str, rollout: str, out=print) -> str:
|
||||
if target not in TRACKS:
|
||||
raise Stop(f"target {target} is not external or production")
|
||||
wanted = wanted_release(rollout, target)
|
||||
version, version_code = pubspec_version(pubspec)
|
||||
check_tag(tag, version)
|
||||
notes = read_notes(notes_dir, version)
|
||||
bundle = read_bundle(aab)
|
||||
check_bundle(bundle, version_code)
|
||||
wanted.update(
|
||||
name=f"{version_code} ({version})",
|
||||
versionCodes=[str(version_code)],
|
||||
releaseNotes=[{"language": NOTES_LANGUAGE, "text": notes}],
|
||||
)
|
||||
track_name = TRACKS[target]
|
||||
|
||||
edit = play.open_edit()
|
||||
committed = False
|
||||
try:
|
||||
tracks = play.tracks(edit)
|
||||
bundles = play.bundles(edit)
|
||||
held = [b for b in bundles if str(b.get("versionCode")) == str(version_code)]
|
||||
if held and held[0].get("sha256", "").lower() != bundle["sha256"]:
|
||||
raise Stop(
|
||||
f"Play already holds a different bundle as version {version_code}"
|
||||
)
|
||||
if not held and version_code <= highest_code(tracks, bundles):
|
||||
raise Stop(
|
||||
f"version {version_code} is not higher than Play's highest, "
|
||||
f"{highest_code(tracks, bundles)}"
|
||||
)
|
||||
current = next((t for t in tracks if t.get("track") == track_name), None)
|
||||
if current is None:
|
||||
raise Stop(f"Play has no track named {track_name}")
|
||||
releases = plan_track(current, version_code, wanted)
|
||||
if releases is None:
|
||||
out(f"{track_name} already serves {wanted['name']} as asked; nothing changed")
|
||||
return "unchanged"
|
||||
if held:
|
||||
out(f"Play already holds version {version_code}; not uploading again")
|
||||
else:
|
||||
uploaded = play.upload(edit, aab)
|
||||
if str(uploaded.get("versionCode")) != str(version_code):
|
||||
raise Stop(
|
||||
f"Play read the upload as version {uploaded.get('versionCode')}"
|
||||
)
|
||||
out(f"uploaded version {version_code}")
|
||||
play.set_track(edit, track_name, releases)
|
||||
play.commit(edit)
|
||||
committed = True
|
||||
out(f"{wanted['name']} is on {track_name}: {rollout}")
|
||||
return "published"
|
||||
finally:
|
||||
if not committed:
|
||||
try:
|
||||
play.delete_edit(edit)
|
||||
except Stop:
|
||||
pass
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
commands = parser.add_subparsers(dest="command", required=True)
|
||||
commands.add_parser("tracks", help="list Play's tracks, read-only")
|
||||
send = commands.add_parser("publish", help="put this release on a track")
|
||||
send.add_argument("--aab", type=Path, required=True)
|
||||
send.add_argument("--tag", required=True)
|
||||
send.add_argument("--target", choices=sorted(TRACKS), required=True)
|
||||
send.add_argument("--rollout", choices=ROLLOUTS, required=True)
|
||||
send.add_argument("--pubspec", type=Path, default=Path("pubspec.yaml"))
|
||||
send.add_argument("--notes-dir", type=Path, default=Path("play"))
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
token = os.environ.get("PLAY_ACCESS_TOKEN", "")
|
||||
if not token:
|
||||
print("stop: PLAY_ACCESS_TOKEN is not set", file=sys.stderr)
|
||||
return 1
|
||||
play = Play(token)
|
||||
try:
|
||||
if args.command == "tracks":
|
||||
list_tracks(play)
|
||||
else:
|
||||
publish(play, args.aab, args.pubspec, args.notes_dir, args.tag,
|
||||
args.target, args.rollout)
|
||||
except Stop as stop:
|
||||
print(f"stop: {stop}", file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@ -0,0 +1,411 @@
|
||||
"""Tests for play_release.py (#1084). Run: python -m unittest discover -s tools/play
|
||||
|
||||
Each refusal in PLAN.md section 6 that the tool owns has a test here. The
|
||||
workflow-level rows (identity condition, tag on main, release asset present,
|
||||
provenance) belong to play-publish.yml and are tested there (#1087, #1088).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import hashlib
|
||||
import io
|
||||
import re
|
||||
import tempfile
|
||||
import unittest
|
||||
import zipfile
|
||||
from contextlib import redirect_stderr
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
import play_release as p
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
# --- Fixture builders ---------------------------------------------------------
|
||||
|
||||
|
||||
def der(tag: int, body: bytes) -> bytes:
|
||||
n = len(body)
|
||||
if n < 0x80:
|
||||
return bytes([tag, n]) + body
|
||||
size = n.to_bytes((n.bit_length() + 7) // 8, "big")
|
||||
return bytes([tag, 0x80 | len(size)]) + size + body
|
||||
|
||||
|
||||
def pkcs7(cert: bytes) -> bytes:
|
||||
signed = der(
|
||||
0x30,
|
||||
der(0x02, b"\x01")
|
||||
+ der(0x31, b"")
|
||||
+ der(0x30, der(0x06, b"\x2a\x86\x48\x86\xf7\x0d\x01\x07\x01"))
|
||||
+ der(0xA0, cert)
|
||||
+ der(0x31, b""),
|
||||
)
|
||||
return der(0x30, der(0x06, b"\x2a\x86\x48\x86\xf7\x0d\x01\x07\x02") + der(0xA0, signed))
|
||||
|
||||
|
||||
def fake_cert(seed: bytes) -> bytes:
|
||||
return der(0x30, der(0x30, der(0x04, seed * 40)) + der(0x30, b""))
|
||||
|
||||
|
||||
def varint(n: int) -> bytes:
|
||||
out = bytearray()
|
||||
while True:
|
||||
byte = n & 0x7F
|
||||
n >>= 7
|
||||
out.append(byte | (0x80 if n else 0))
|
||||
if not n:
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def field(number: int, value) -> bytes:
|
||||
if isinstance(value, int):
|
||||
return varint(number << 3) + varint(value)
|
||||
return varint(number << 3 | 2) + varint(len(value)) + value
|
||||
|
||||
|
||||
def manifest(code: int | None, compiled: bool = True) -> bytes:
|
||||
attrs = field(4, field(2, b"package") + field(3, b"app.offband.meshcore"))
|
||||
if code is not None:
|
||||
attr = field(1, b"http://schemas.android.com/apk/res/android")
|
||||
attr += field(2, b"versionCode") + field(3, str(code).encode())
|
||||
if compiled:
|
||||
attr += field(6, field(7, field(6, code)))
|
||||
attrs += field(4, attr)
|
||||
return field(1, field(3, b"manifest") + attrs)
|
||||
|
||||
|
||||
CERT = fake_cert(b"release")
|
||||
DEBUG_CERT = fake_cert(b"debug")
|
||||
PIN = hashlib.sha256(CERT).hexdigest()
|
||||
|
||||
|
||||
def write_aab(path: Path, code: int = 69, cert: bytes = CERT) -> Path:
|
||||
with zipfile.ZipFile(path, "w") as z:
|
||||
z.writestr("base/manifest/AndroidManifest.xml", manifest(code))
|
||||
z.writestr("META-INF/MESHCORE.RSA", pkcs7(cert))
|
||||
z.writestr("base/dex/classes.dex", b"dex")
|
||||
return path
|
||||
|
||||
|
||||
# --- Fake Play ----------------------------------------------------------------
|
||||
|
||||
|
||||
class FakePlay(p.Play):
|
||||
"""An in-memory Play: edits stage changes, commit applies them."""
|
||||
|
||||
def __init__(self, tracks=None, bundles=None):
|
||||
super().__init__("token")
|
||||
self.live_tracks = tracks if tracks is not None else [
|
||||
{"track": "alpha", "releases": []},
|
||||
{"track": "production", "releases": [
|
||||
{"name": "68 (1.7.0)", "versionCodes": ["68"], "status": "completed"}
|
||||
]},
|
||||
]
|
||||
self.live_bundles = bundles if bundles is not None else [
|
||||
{"versionCode": 68, "sha256": "aa" * 32}
|
||||
]
|
||||
self.calls = []
|
||||
self.edits = {}
|
||||
self.fail = {}
|
||||
self.upload_code = None
|
||||
|
||||
def _maybe_fail(self, what):
|
||||
if what in self.fail:
|
||||
raise p.Stop(self.fail[what])
|
||||
|
||||
def open_edit(self):
|
||||
self.calls.append("open")
|
||||
edit = f"e{len(self.edits) + 1}"
|
||||
self.edits[edit] = {
|
||||
"tracks": copy.deepcopy(self.live_tracks),
|
||||
"bundles": copy.deepcopy(self.live_bundles),
|
||||
"state": "open",
|
||||
}
|
||||
return edit
|
||||
|
||||
def delete_edit(self, edit):
|
||||
self.calls.append("delete")
|
||||
self.edits[edit]["state"] = "deleted"
|
||||
|
||||
def tracks(self, edit):
|
||||
self.calls.append("tracks")
|
||||
self._maybe_fail("tracks")
|
||||
return copy.deepcopy(self.edits[edit]["tracks"])
|
||||
|
||||
def bundles(self, edit):
|
||||
self.calls.append("bundles")
|
||||
return copy.deepcopy(self.edits[edit]["bundles"])
|
||||
|
||||
def upload(self, edit, aab):
|
||||
self.calls.append("upload")
|
||||
bundle = p.read_bundle(aab)
|
||||
code = self.upload_code or bundle["version_code"]
|
||||
self.edits[edit]["bundles"].append({"versionCode": code, "sha256": bundle["sha256"]})
|
||||
return {"versionCode": code, "sha256": bundle["sha256"]}
|
||||
|
||||
def set_track(self, edit, track, releases):
|
||||
self.calls.append(f"set {track}")
|
||||
for t in self.edits[edit]["tracks"]:
|
||||
if t["track"] == track:
|
||||
t["releases"] = copy.deepcopy(releases)
|
||||
|
||||
def commit(self, edit):
|
||||
self.calls.append("commit")
|
||||
self._maybe_fail("commit")
|
||||
self.live_tracks = self.edits[edit]["tracks"]
|
||||
self.live_bundles = self.edits[edit]["bundles"]
|
||||
self.edits[edit]["state"] = "committed"
|
||||
|
||||
def track(self, name):
|
||||
return next(t for t in self.live_tracks if t["track"] == name)
|
||||
|
||||
|
||||
# --- Tests --------------------------------------------------------------------
|
||||
|
||||
|
||||
class Base(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.dir = Path(tempfile.mkdtemp())
|
||||
self.pin = mock.patch.object(p, "EXPECTED_CERT_SHA256", PIN)
|
||||
self.pin.start()
|
||||
self.addCleanup(self.pin.stop)
|
||||
self.pubspec = self.dir / "pubspec.yaml"
|
||||
self.pubspec.write_text("name: x\nversion: 1.8.0+69\n", "utf-8")
|
||||
self.notes = self.dir / "play"
|
||||
self.notes.mkdir()
|
||||
(self.notes / "1.8.0.txt").write_text("Fixes and improvements.\n", "utf-8")
|
||||
self.aab = write_aab(self.dir / "app-release.aab")
|
||||
self.play = FakePlay()
|
||||
|
||||
def run_publish(self, target="external", rollout="draft", tag="v1.8.0"):
|
||||
return p.publish(self.play, self.aab, self.pubspec, self.notes, tag,
|
||||
target, rollout, out=lambda *_: None)
|
||||
|
||||
def assertStops(self, pattern, **kwargs):
|
||||
with self.assertRaisesRegex(p.Stop, pattern):
|
||||
self.run_publish(**kwargs)
|
||||
|
||||
def assertNothingCommitted(self):
|
||||
self.assertNotIn("commit", self.play.calls)
|
||||
for edit in self.play.edits.values():
|
||||
self.assertEqual(edit["state"], "deleted")
|
||||
|
||||
|
||||
class BundleReading(Base):
|
||||
def test_reads_version_code_and_certificate(self):
|
||||
bundle = p.read_bundle(self.aab)
|
||||
self.assertEqual(bundle["version_code"], 69)
|
||||
self.assertEqual(bundle["cert_sha256"], PIN)
|
||||
|
||||
def test_reads_an_uncompiled_version_code(self):
|
||||
self.assertEqual(p.manifest_version_code(manifest(70, compiled=False)), 70)
|
||||
|
||||
def test_no_version_code_stops(self):
|
||||
with self.assertRaisesRegex(p.Stop, "no versionCode"):
|
||||
p.manifest_version_code(manifest(None))
|
||||
|
||||
def test_long_certificate_lengths_parse(self):
|
||||
big = fake_cert(b"x" * 50)
|
||||
self.assertEqual(p.signer_certificate(pkcs7(big)), big)
|
||||
|
||||
def test_pin_matches_release_signed_workflow(self):
|
||||
workflow = (REPO / ".github/workflows/release-signed.yml").read_text("utf-8")
|
||||
pins = re.findall(r"EXPECTED_SHA256:\s*([0-9a-f]{64})", workflow)
|
||||
self.assertEqual(len(pins), 2)
|
||||
self.pin.stop()
|
||||
try:
|
||||
self.assertEqual(set(pins), {p.EXPECTED_CERT_SHA256})
|
||||
finally:
|
||||
self.pin.start()
|
||||
|
||||
|
||||
class Refusals(Base):
|
||||
"""PLAN.md section 6, the rows the tool owns."""
|
||||
|
||||
def test_missing_token_stops(self):
|
||||
with mock.patch.dict("os.environ", {}, clear=True), redirect_stderr(io.StringIO()) as err:
|
||||
self.assertEqual(p.main(["tracks"]), 1)
|
||||
self.assertIn("PLAY_ACCESS_TOKEN", err.getvalue())
|
||||
|
||||
def test_missing_bundle_stops(self):
|
||||
self.aab.unlink()
|
||||
self.assertStops("no bundle")
|
||||
self.assertEqual(self.play.calls, [])
|
||||
|
||||
def test_debug_or_other_certificate_stops(self):
|
||||
write_aab(self.aab, cert=DEBUG_CERT)
|
||||
self.assertStops("not the release key")
|
||||
self.assertEqual(self.play.calls, [])
|
||||
|
||||
def test_version_code_differs_from_pubspec_stops(self):
|
||||
write_aab(self.aab, code=70)
|
||||
self.assertStops("differs from the tag's pubspec")
|
||||
self.assertEqual(self.play.calls, [])
|
||||
|
||||
def test_tag_not_of_this_version_stops(self):
|
||||
self.assertStops("not a release of pubspec version", tag="v1.7.9")
|
||||
|
||||
def test_rc_tag_of_this_version_is_accepted(self):
|
||||
self.assertEqual(self.run_publish(tag="v1.8.0-rc.1"), "published")
|
||||
|
||||
def test_tracks_unreadable_stops(self):
|
||||
self.play.fail["tracks"] = "Play refused GET (500): backend"
|
||||
self.assertStops("backend")
|
||||
self.assertNothingCommitted()
|
||||
|
||||
def test_code_not_higher_than_play_stops(self):
|
||||
self.play.live_bundles.append({"versionCode": 69, "sha256": "bb" * 32})
|
||||
self.assertStops("different bundle")
|
||||
self.play = FakePlay(bundles=[{"versionCode": 70, "sha256": "cc" * 32}])
|
||||
self.assertStops("not higher than Play's highest, 70")
|
||||
self.assertNothingCommitted()
|
||||
|
||||
def test_code_on_a_track_counts_toward_highest(self):
|
||||
self.play.track("alpha")["releases"] = [
|
||||
{"versionCodes": ["75"], "status": "completed"}
|
||||
]
|
||||
self.assertStops("not higher than Play's highest, 75")
|
||||
|
||||
def test_notes_missing_empty_or_long_stop(self):
|
||||
path = self.notes / "1.8.0.txt"
|
||||
path.write_text(" \n", "utf-8")
|
||||
self.assertStops("are empty")
|
||||
path.write_text("x" * 501, "utf-8")
|
||||
self.assertStops("501 characters, over 500")
|
||||
path.unlink()
|
||||
self.assertStops("are missing")
|
||||
self.assertEqual(self.play.calls, [])
|
||||
|
||||
def test_notes_at_the_limit_pass(self):
|
||||
(self.notes / "1.8.0.txt").write_text("x" * 500 + "\n", "utf-8")
|
||||
self.assertEqual(self.run_publish(), "published")
|
||||
|
||||
def test_external_with_a_percentage_stops(self):
|
||||
for rollout in ("10", "25", "50"):
|
||||
self.assertStops("whole tester list", rollout=rollout)
|
||||
self.assertEqual(self.play.calls, [])
|
||||
|
||||
def test_narrowing_stops(self):
|
||||
self.run_publish(target="production", rollout="50")
|
||||
self.assertStops("narrowing or halting is done in Console",
|
||||
target="production", rollout="25")
|
||||
self.assertStops("narrowing", target="production", rollout="draft")
|
||||
|
||||
def test_other_version_mid_rollout_stops(self):
|
||||
for status in ("inProgress", "halted"):
|
||||
self.play = FakePlay()
|
||||
self.play.track("production")["releases"].append(
|
||||
{"versionCodes": ["67"], "status": status, "userFraction": 0.2}
|
||||
)
|
||||
self.assertStops("67 is mid rollout", target="production", rollout="10")
|
||||
self.assertNothingCommitted()
|
||||
|
||||
def test_release_shared_with_another_version_stops(self):
|
||||
self.play.track("production")["releases"].append(
|
||||
{"versionCodes": ["67", "69"], "status": "draft"}
|
||||
)
|
||||
self.play.live_bundles.append({"versionCode": 69, "sha256": p.read_bundle(self.aab)["sha256"]})
|
||||
self.assertStops("in one release with 67, 69", target="production", rollout="100")
|
||||
self.assertNothingCommitted()
|
||||
|
||||
def test_unknown_status_of_this_release_stops(self):
|
||||
self.play.track("alpha")["releases"] = [
|
||||
{"versionCodes": ["69"], "status": "statusUnspecified"}
|
||||
]
|
||||
self.play.live_bundles.append({"versionCode": 69, "sha256": p.read_bundle(self.aab)["sha256"]})
|
||||
self.assertStops("can't be compared")
|
||||
self.assertNothingCommitted()
|
||||
|
||||
def test_review_refusal_stops_without_retry(self):
|
||||
self.play.fail["commit"] = (
|
||||
"Play refused POST (400): Changes cannot be sent for review automatically"
|
||||
)
|
||||
self.assertStops("cannot be sent for review")
|
||||
self.assertEqual(self.play.calls.count("commit"), 1)
|
||||
self.assertEqual(self.play.edits["e1"]["state"], "deleted")
|
||||
self.assertEqual(self.play.track("alpha")["releases"], [])
|
||||
|
||||
def test_upload_read_as_another_version_stops(self):
|
||||
self.play.upload_code = 71
|
||||
self.assertStops("read the upload as version 71")
|
||||
self.assertNothingCommitted()
|
||||
|
||||
def test_missing_track_stops(self):
|
||||
self.play = FakePlay(tracks=[{"track": "production", "releases": []}])
|
||||
self.assertStops("no track named alpha")
|
||||
|
||||
|
||||
class Publishing(Base):
|
||||
def test_external_draft_uploads_and_commits(self):
|
||||
self.assertEqual(self.run_publish(), "published")
|
||||
self.assertEqual(self.play.calls.count("upload"), 1)
|
||||
[release] = self.play.track("alpha")["releases"]
|
||||
self.assertEqual(release["status"], "draft")
|
||||
self.assertEqual(release["versionCodes"], ["69"])
|
||||
self.assertEqual(release["name"], "69 (1.8.0)")
|
||||
self.assertEqual(release["releaseNotes"],
|
||||
[{"language": "en-US", "text": "Fixes and improvements."}])
|
||||
|
||||
def test_external_100_is_completed(self):
|
||||
self.run_publish(rollout="100")
|
||||
self.assertEqual(self.play.track("alpha")["releases"][0]["status"], "completed")
|
||||
|
||||
def test_production_staged_keeps_the_serving_release(self):
|
||||
self.run_publish(target="production", rollout="10")
|
||||
releases = self.play.track("production")["releases"]
|
||||
self.assertEqual([r["versionCodes"] for r in releases], [["68"], ["69"]])
|
||||
self.assertEqual(releases[1]["status"], "inProgress")
|
||||
self.assertEqual(releases[1]["userFraction"], 0.1)
|
||||
|
||||
def test_promote_reuses_the_bundle(self):
|
||||
self.run_publish(target="external", rollout="100")
|
||||
self.run_publish(target="production", rollout="25")
|
||||
self.assertEqual(self.play.calls.count("upload"), 1)
|
||||
self.assertEqual(self.play.track("production")["releases"][1]["userFraction"], 0.25)
|
||||
self.assertEqual(self.play.track("alpha")["releases"][0]["versionCodes"], ["69"])
|
||||
|
||||
def test_widening_a_rollout(self):
|
||||
self.run_publish(target="production", rollout="10")
|
||||
self.run_publish(target="production", rollout="100")
|
||||
releases = self.play.track("production")["releases"]
|
||||
self.assertEqual(releases[-1]["status"], "completed")
|
||||
self.assertEqual(len([r for r in releases if "69" in r["versionCodes"]]), 1)
|
||||
|
||||
def test_rerun_at_the_same_rollout_changes_nothing(self):
|
||||
self.run_publish(target="production", rollout="25")
|
||||
before = copy.deepcopy(self.play.live_tracks)
|
||||
calls = len(self.play.calls)
|
||||
self.assertEqual(self.run_publish(target="production", rollout="25"), "unchanged")
|
||||
new = self.play.calls[calls:]
|
||||
self.assertNotIn("upload", new)
|
||||
self.assertNotIn("commit", new)
|
||||
self.assertEqual(new[-1], "delete")
|
||||
self.assertEqual(self.play.live_tracks, before)
|
||||
|
||||
def test_another_draft_on_the_track_is_kept(self):
|
||||
self.play.track("alpha")["releases"] = [
|
||||
{"versionCodes": ["60"], "status": "draft"}
|
||||
]
|
||||
self.run_publish(rollout="100")
|
||||
codes = [r["versionCodes"] for r in self.play.track("alpha")["releases"]]
|
||||
self.assertEqual(codes, [["60"], ["69"]])
|
||||
|
||||
|
||||
class TrackListing(Base):
|
||||
def test_lists_and_changes_nothing(self):
|
||||
lines = []
|
||||
self.play.track("production")["releases"].append(
|
||||
{"name": "69 (1.8.0)", "versionCodes": ["69"], "status": "inProgress",
|
||||
"userFraction": 0.1}
|
||||
)
|
||||
p.list_tracks(self.play, out=lines.append)
|
||||
self.assertEqual(self.play.calls, ["open", "tracks", "delete"])
|
||||
self.assertIn("track production", lines)
|
||||
self.assertIn(" 69 (1.8.0): versions 69, inProgress at 10%", lines)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Loading…
Reference in new issue