diff --git a/changes/3209.md b/changes/3209.md new file mode 100644 index 000000000..f24d41a04 --- /dev/null +++ b/changes/3209.md @@ -0,0 +1,3 @@ +kind: added + +On synthetic fixtures, `install download --early` adds an opt-in `early` channel that authenticates through `gh` for `openwizpro/WizPro` prereleases and follows the newest early or public release by semver. diff --git a/docs/install.md b/docs/install.md index 6da8581db..85b15ea38 100644 --- a/docs/install.md +++ b/docs/install.md @@ -41,6 +41,15 @@ The agent runs each command itself and reads its JSON. `` is the install f Then it proves the build: `/current/openwiz --build-identity` prints the version (`0.1.1`) and the source commit. The `openwiz` program lives there, not on your `PATH`: typing `openwiz` alone says "command not found". + **Early builds (OpenWiz Pro, opt-in):** with no extra flag, `install download` reads only public releases from `openwizdev/OpenWiz` and installs on the `packaged` channel. OpenWiz Pro members can opt into the `early` channel by passing `--early` to `install download`: + + ```sh + python3 -I "$openwiz"/tools/install/install download --early --target --dir + python3 -I "$openwiz"/tools/install/install install --assets --target --root + ``` + + `download --early` uses your existing `gh` login (without storing or logging any token) to check prereleases tagged `v-rc.` in the private `openwizpro/WizPro` repository alongside public releases, picks whichever is newer by semver, and verifies `SHA256SUMS`, the manifest and the archive the same way. Installing writes `{"schema":"openwiz.update-channel.v1","channel":"early"}` to `/channel.json`, and later updates follow the newest early or public release by semver so you are never left behind a public release. If `gh` is missing or not logged in, it refuses and tells you to run `gh auth login`; if your account does not have access to `openwizpro/WizPro` (HTTP 404), it refuses and links to [openwiz.dev/pro](https://openwiz.dev/pro/). `install remove` removes an `early` `channel.json` the same as `packaged`. + 3. **Setup and logins.** Nothing opens in a browser by itself: the agent reads each connection with one check, run from the installed build, and reruns it after each change. ```sh diff --git a/tools/install/install b/tools/install/install index daa863688..c8df13cc3 100755 --- a/tools/install/install +++ b/tools/install/install @@ -21,14 +21,16 @@ DESCRIPTION = """OpenWiz's install entry (#1109): the commands the install skill Reads this machine only: Python, the supported target, free disk space, on Linux the glibc version (from ldd --version; 2.34 or later), and whether room-cli, gh and git are on PATH. It runs none of those three. - install download --target TARGET --dir PRIVATE_DIR [--version vX.Y.Z] + install download --target TARGET --dir PRIVATE_DIR [--version vX.Y.Z] [--early] Fetches a release's checksum file, manifest and archive from github.com/openwizdev/OpenWiz/releases into a new private folder, within their declared sizes, and checks the manifest against the checksum. Without --version it takes the latest release; when latest is a 404 (the newest release is a pre-release), the newest tag in the releases feed. + With --early it also checks prereleases tagged v-rc. from + openwizpro/WizPro through gh and picks whichever is newer by semver. A refusal names the failure, such as "release asset 404 at URL". - install install --assets PRIVATE_DIR --target TARGET --root ROOT [--state-root STATE] + install install --assets PRIVATE_DIR --target TARGET --root ROOT [--state-root STATE] [--early] Installs those downloaded files with the verified offline installer (install.py, contracts/install.v1.md) and selects the build only when every file matched. A refusal keeps the last good build selected. A @@ -83,6 +85,7 @@ TOOLS = (('room-cli', 'Optional: CloudRoom is needed only if you pick it as the ('gh', 'Install the GitHub CLI and run gh auth login.'), ('git', 'Install git.')) ARCHIVE_NAME = re.compile(r'openwiz-0\.[0-9]+\.[0-9]+-[a-z0-9_]+-[a-z0-9_-]+\.tar\.gz') +EARLY_ARCHIVE_NAME = re.compile(r'openwiz-0\.[0-9]+\.[0-9]+(?:-rc\.[0-9]+)?-[a-z0-9_]+-[a-z0-9_-]+\.tar\.gz') class Usage(Exception): @@ -159,16 +162,27 @@ def write_private(path, data): handle.write(data) -def download(target, folder, fetch, version=None): +def download(target, folder, fetch, version=None, early=False, which=shutil.which): name = 'openwiz-' + target - sums, raw, manifest, _ = pull.published(target, fetch, version) - installer.require(ARCHIVE_NAME.fullmatch(manifest['archive']), 'invalid published archive name') - prefix = pull.BASE + 'download/v' + manifest['version'] + '/' - archive = fetch(prefix + manifest['archive'], manifest['archive_bytes']) + if early: + found, origin, asset_fetch = pull.published_early(target, fetch=fetch, version=version, which=which) + sums, raw, manifest, _ = found + installer.require(EARLY_ARCHIVE_NAME.fullmatch(manifest['archive']), 'invalid published archive name') + prefix = '' if origin == 'early' else pull.BASE + 'download/v' + manifest['version'] + '/' + location = (pull.PRO_REPO + '/v' + manifest['version'] + '/' + manifest['archive'] + if origin == 'early' else prefix + manifest['archive']) + else: + origin = 'public' + asset_fetch = fetch + sums, raw, manifest, _ = pull.published(target, fetch, version) + installer.require(ARCHIVE_NAME.fullmatch(manifest['archive']), 'invalid published archive name') + prefix = pull.BASE + 'download/v' + manifest['version'] + '/' + location = prefix + manifest['archive'] + archive = asset_fetch(prefix + manifest['archive'], manifest['archive_bytes']) installer.require(len(archive) == manifest['archive_bytes'], 'incomplete archive download') installer.require(installer.sha(archive) == manifest['archive_sha256'], 'archive checksum mismatch at ' - + prefix + manifest['archive']) - listed = release_sums(fetch(prefix + 'SHA256SUMS', 64 * 1024)) + + location) + listed = release_sums(asset_fetch(prefix + 'SHA256SUMS', 64 * 1024)) for file, data in (('openwiz-%s-%s.manifest.json' % (manifest['version'], target), raw), (manifest['archive'], archive)): installer.require(file in listed, 'SHA256SUMS does not list ' + file) @@ -177,9 +191,15 @@ def download(target, folder, fetch, version=None): write_private(folder / (name + '.sha256'), sums) write_private(folder / (name + '.manifest.json'), raw) write_private(folder / manifest['archive'], archive) - return {'schema': 'openwiz.download.v1', 'outcome': 'downloaded', 'version': manifest['version'], - 'source': manifest['source'], 'target': target, 'dir': str(folder), - 'reason': 'Downloaded and checked every file against its published checksums; nothing is installed yet.'} + if early: + write_private(folder / 'channel.json', installer.CHANNELS['early']) + result = {'schema': 'openwiz.download.v1', 'outcome': 'downloaded', 'version': manifest['version'], + 'source': manifest['source'], 'target': target, 'dir': str(folder), + 'reason': 'Downloaded and checked every file against its published checksums; nothing is installed yet.'} + if early: + result['channel'] = 'early' + result['origin'] = origin + return result def release_sums(data): @@ -191,10 +211,12 @@ def release_sums(data): return listed -def release_version(value): - match = re.fullmatch(r'v?(0\.[0-9]+\.[0-9]+)', value) +def release_version(value, early=False): + pattern = r'v?(0\.[0-9]+\.[0-9]+(?:-rc\.[0-9]+)?)' if early else r'v?(0\.[0-9]+\.[0-9]+)' + match = re.fullmatch(pattern, value) if not match: - raise argparse.ArgumentTypeError('expected a release tag such as v0.1.0') + raise Usage('argument --version: expected a release tag such as ' + + ('v0.1.0-rc.1' if early else 'v0.1.0')) return match[1] @@ -223,20 +245,31 @@ def prepare_parent(root): 'an install parent folder is a link or not yours') -def install(assets, target, root, state_root): +def install(assets, target, root, state_root, early=False): assets = Path(assets) installer.require(target in installer.TARGETS, 'unsupported package target') name = 'openwiz-' + target installer.private(assets) + channel_file = assets / 'channel.json' + if channel_file.exists() or channel_file.is_symlink(): + installer.private(channel_file, False) + raw_channel = channel_file.read_bytes() + installer.require(raw_channel in installer.CHANNELS.values(), 'invalid downloaded channel metadata') + downloaded_channel = 'early' if raw_channel == installer.CHANNELS['early'] else 'packaged' + else: + downloaded_channel = 'packaged' + channel = 'early' if early else downloaded_channel sums = (assets / (name + '.sha256')).read_bytes() match = re.fullmatch(rb'([0-9a-f]{64}) ' + re.escape((name + '.manifest.json').encode()) + rb'\n', sums) installer.require(match, 'invalid published manifest checksum') manifest_file = assets / (name + '.manifest.json') - manifest = installer.manifest_at(manifest_file, match[1].decode('ascii'), target)[0] - installer.require(ARCHIVE_NAME.fullmatch(manifest['archive']), 'invalid published archive name') + manifest = installer.manifest_at(manifest_file, match[1].decode('ascii'), target, + allow_prerelease=(channel == 'early'))[0] + archive_re = EARLY_ARCHIVE_NAME if channel == 'early' else ARCHIVE_NAME + installer.require(archive_re.fullmatch(manifest['archive']), 'invalid published archive name') prepare_parent(root) result = installer.install(manifest_file, assets / manifest['archive'], match[1].decode('ascii'), - Path(root), target, state_root=state_root) + Path(root), target, state_root=state_root, channel=channel) program, path, state = link_state(root) where = 'openwiz is at %s' % program return dict(result, outcome='installed', openwiz=str(program), next=( @@ -306,9 +339,14 @@ def selected(root, state_root=None): installer.require(value['source'] == build.name, 'the selected build is not its own source') installer.verify_installed(build, assets, raw) channel = root / 'channel.json' - known = (channel.exists() and not channel.is_symlink() - and channel.read_bytes() == b'{"schema":"openwiz.update-channel.v1","channel":"packaged"}\n') - return build, state, value, ('packaged' if known else 'unknown') + channel_name = 'unknown' + if channel.exists() and not channel.is_symlink(): + raw_channel = channel.read_bytes() + for cname, expected in installer.CHANNELS.items(): + if raw_channel == expected: + channel_name = cname + break + return build, state, value, channel_name def status(root, state_root): @@ -409,7 +447,7 @@ def remove_unlocked(root, state, state_root, yes, home, codex_home, made=None): delete = [path for path, kind in ((link, stat.S_ISLNK), (root / 'install.lock', stat.S_ISREG)) if owned(path, kind)] channel = root / 'channel.json' - if owned(channel, stat.S_ISREG) and channel.read_bytes() == CHANNEL: + if owned(channel, stat.S_ISREG) and channel.read_bytes() in installer.CHANNELS.values(): delete.append(channel) delete += [root / 'skills' / name for name in marked_skills(root / 'skills')] delete += [builds / name for name in installer.entries(builds) if verified_build(builds / name)] @@ -460,12 +498,14 @@ def main(argv=None, fetch=pull.fetch_bytes, host=None, stdout=None): d = commands.add_parser('download') d.add_argument('--target', required=True) d.add_argument('--dir', required=True) - d.add_argument('--version', type=release_version) + d.add_argument('--version') + d.add_argument('--early', action='store_true') i = commands.add_parser('install') i.add_argument('--assets', required=True) i.add_argument('--target', required=True) i.add_argument('--root', required=True) i.add_argument('--state-root') + i.add_argument('--early', action='store_true') n = commands.add_parser('link') n.add_argument('--root', required=True) n.add_argument('--state-root') @@ -482,6 +522,8 @@ def main(argv=None, fetch=pull.fetch_bytes, host=None, stdout=None): k.add_argument('--state-root') try: args = parser.parse_args(sys.argv[1:] if argv is None else argv) + if args.command == 'download' and args.version is not None: + args.version = release_version(args.version, early=args.early) except Usage as usage: print(json.dumps({'schema': 'openwiz.install-error.v1', 'outcome': 'usage', 'reason': str(usage)}), file=out) return 2 @@ -494,9 +536,9 @@ def main(argv=None, fetch=pull.fetch_bytes, host=None, stdout=None): return None value, code = preflight(host or (platform.system(), platform.machine()), shutil.which, disk) elif args.command == 'download': - value, code = download(args.target, args.dir, fetch, args.version), 0 + value, code = download(args.target, args.dir, fetch, args.version, early=args.early), 0 elif args.command == 'install': - value, code = install(args.assets, args.target, args.root, args.state_root), 0 + value, code = install(args.assets, args.target, args.root, args.state_root, early=args.early), 0 elif args.command == 'skills': build, _, manifest, _ = selected(args.root, args.state_root) value, code = harness.install_skills(build, manifest, args.root, Path.home(), diff --git a/tools/install/install.py b/tools/install/install.py index f17b65c5a..d72d6419d 100644 --- a/tools/install/install.py +++ b/tools/install/install.py @@ -20,6 +20,12 @@ """ TARGETS = ('aarch64-apple-darwin', 'x86_64-apple-darwin', 'x86_64-unknown-linux-gnu') +VERSION_RE = re.compile(r'0\.[0-9]+\.[0-9]+') +EARLY_VERSION_RE = re.compile(r'0\.[0-9]+\.[0-9]+(?:-rc\.[0-9]+)?') +CHANNELS = { + 'packaged': b'{"schema":"openwiz.update-channel.v1","channel":"packaged"}\n', + 'early': b'{"schema":"openwiz.update-channel.v1","channel":"early"}\n', +} PROGRAMS = {'openwiz'} REQUIRED = PROGRAMS | {'runtime/openwiz-build.txt', 'runtime/install.py', 'runtime/pull.py', 'runtime/skills/setup/SKILL.md', 'runtime/skills/grill/SKILL.md', @@ -77,13 +83,14 @@ def safe(path, legacy=False): return path -def manifest_at(path, checksum, target, selected=False): +def manifest_at(path, checksum, target, selected=False, allow_prerelease=False): data = path.read_bytes() require(len(data) <= 4 * 1024 * 1024 and sha(data) == checksum, 'manifest checksum mismatch') value = json.loads(data, object_pairs_hook=unique) shape(value, 'schema version source target setup_api archive archive_sha256 archive_bytes assets') require(value['schema'] == 'openwiz.install.v1', 'unsupported manifest schema') - require(isinstance(value['version'], str) and re.fullmatch(r'0\.[0-9]+\.[0-9]+', value['version']), 'invalid version') + version_re = EARLY_VERSION_RE if (allow_prerelease or selected) else VERSION_RE + require(isinstance(value['version'], str) and version_re.fullmatch(value['version']), 'invalid version') require(digest(value['source'], 40), 'invalid source identity') require(target in TARGETS and value['target'] == target, 'unsupported or mismatched target') require(type(value['setup_api']) is int and value['setup_api'] == 1, 'incompatible setup API') @@ -258,9 +265,11 @@ def activate_link(build, root): def install(manifest, archive, manifest_sha256, root, target, state_root=None, - free_bytes=lambda path: shutil.disk_usage(path).free, activate=activate_link, stage_only=False): + free_bytes=lambda path: shutil.disk_usage(path).free, activate=activate_link, stage_only=False, + channel='packaged'): + require(channel in CHANNELS, 'unsupported update channel') manifest, archive, root = Path(manifest), Path(archive), Path(root) - value, assets, raw = manifest_at(manifest, manifest_sha256, target) + value, assets, raw = manifest_at(manifest, manifest_sha256, target, allow_prerelease=(channel == 'early')) require(archive.stat().st_size == value['archive_bytes'], 'archive size mismatch') hasher = hashlib.sha256() with archive.open('rb') as stream: @@ -291,12 +300,12 @@ def install(manifest, archive, manifest_sha256, root, target, state_root=None, require(selected.is_absolute() and selected.parent == builds and digest(selected.name, 40), 'foreign current selection') if selected != builds / value['source']: private(selected) - channel = root / 'channel.json' - require(channel.exists() or not link.is_symlink(), 'source installation requires an explicit channel migration') - channel_bytes = b'{"schema":"openwiz.update-channel.v1","channel":"packaged"}\n' - if channel.exists() or channel.is_symlink(): - private(channel, False) - require(channel.read_bytes() == channel_bytes, 'existing update channel requires explicit migration') + channel_file = root / 'channel.json' + require(channel_file.exists() or not link.is_symlink(), 'source installation requires an explicit channel migration') + channel_bytes = CHANNELS[channel] + if channel_file.exists() or channel_file.is_symlink(): + private(channel_file, False) + require(channel_file.read_bytes() == channel_bytes, 'existing update channel requires explicit migration') build = builds / value['source'] with tarfile.open(archive, 'r:gz') as tar: members = [] @@ -363,8 +372,8 @@ def install(manifest, archive, manifest_sha256, root, target, state_root=None, os.chmod(build, stat.S_IMODE(damaged_meta.st_mode)) raise if not stage_only: - if not channel.exists(): - write(channel, channel_bytes) + if not channel_file.exists(): + write(channel_file, channel_bytes) sync(root) activate(build, root) return {'schema': 'openwiz.install-result.v1', 'version': value['version'], 'source': value['source'], @@ -378,6 +387,7 @@ def main(): parser.add_argument('--' + flag, required=True) parser.add_argument('--state-root') parser.add_argument('--stage-only', action='store_true') + parser.add_argument('--channel', choices=tuple(CHANNELS), default='packaged') args = vars(parser.parse_args()) try: result = install(**args) diff --git a/tools/install/pull.py b/tools/install/pull.py index 533eebc26..20843c23a 100644 --- a/tools/install/pull.py +++ b/tools/install/pull.py @@ -4,6 +4,8 @@ import json from pathlib import Path import re +import shutil +import subprocess import sys import tempfile import urllib.error @@ -12,13 +14,19 @@ sys.dont_write_bytecode = True sys.path.insert(0, str(Path(__file__).resolve().parent)) -from install import Refused, TARGETS, install, manifest_at, private, require, sha, unique +from install import (CHANNELS, EARLY_VERSION_RE, Refused, TARGETS, VERSION_RE, + install, manifest_at, private, require, sha, unique) DESCRIPTION = """Fixed published-release transport. No source checkout, build, push or shell.""" BASE = 'https://github.com/openwizdev/OpenWiz/releases/' FEED = 'https://github.com/openwizdev/OpenWiz/releases.atom' TAG_LINK = re.compile(r'href="https://github\.com/openwizdev/OpenWiz/releases/tag/v(0\.[0-9]+\.[0-9]+)"') +PRO_REPO = 'openwizpro/WizPro' +PRO_URL = 'https://openwiz.dev/pro/' +RC_TAG_RE = re.compile(r'^v(0\.[0-9]+\.[0-9]+-rc\.[0-9]+)$') +SEMVER_RE = re.compile(r'^(0)\.([0-9]+)\.([0-9]+)(?:-rc\.([0-9]+))?$') +ASSET_NAME_RE = re.compile(r'^[A-Za-z0-9][A-Za-z0-9_.-]*$') class NotFound(Refused): @@ -52,11 +60,107 @@ def fetch_bytes(url, limit): return data -def load(raw, checksum, target, selected=False): +def semver_key(version): + match = SEMVER_RE.fullmatch(version) + require(match, 'invalid release version') + major, minor, patch = int(match[1]), int(match[2]), int(match[3]) + return (major, minor, patch, 1, 0) if match[4] is None else (major, minor, patch, 0, int(match[4])) + + +def is_prerelease(version): + return '-rc.' in version + + +def read_channel(root): + channel = Path(root) / 'channel.json' + if not channel.exists() and not channel.is_symlink(): + return None + private(channel, False) + raw = channel.read_bytes() + for name, expected in CHANNELS.items(): + if raw == expected: + return name + raise Refused('unknown update channel') + + +def gh_binary(which=shutil.which): + path = which('gh') + require(path, "early builds require the GitHub CLI (gh); install gh and run 'gh auth login'") + return path + + +def gh_auth_check(gh_bin): + try: + proc = subprocess.run([gh_bin, 'auth', 'token'], stdin=subprocess.DEVNULL, capture_output=True, + text=True, timeout=15) + except (OSError, subprocess.SubprocessError): + raise Refused("GitHub CLI (gh) is not logged in; run 'gh auth login' to sign in") from None + logged_in = proc.returncode == 0 and bool(proc.stdout.strip()) + require(logged_in, "GitHub CLI (gh) is not logged in; run 'gh auth login' to sign in") + + +def _refuse_gh_error(proc, fallback): + text = (proc.stderr or '') + '\n' + (proc.stdout or '') + lower = text.lower() + if '404' in text or 'not found' in lower: + raise NotFound(f'no access to {PRO_REPO} (HTTP 404); early builds need OpenWiz Pro: {PRO_URL}') + if '401' in text or 'bad credentials' in lower or 'not logged in' in lower or 'gh auth login' in lower: + raise Refused("GitHub CLI (gh) is not logged in; run 'gh auth login' to sign in") + raise Refused(fallback) + + +def pro_releases(gh_bin): + gh_auth_check(gh_bin) + try: + proc = subprocess.run([gh_bin, 'api', f'repos/{PRO_REPO}/releases'], stdin=subprocess.DEVNULL, + capture_output=True, text=True, timeout=60) + except (OSError, subprocess.SubprocessError): + raise Refused(f'could not read early releases from {PRO_REPO}') from None + if proc.returncode != 0: + _refuse_gh_error(proc, f'could not read early releases from {PRO_REPO}') + try: + entries = json.loads(proc.stdout) + except ValueError: + raise Refused(f'invalid release listing from {PRO_REPO}') from None + require(isinstance(entries, list), f'invalid release listing from {PRO_REPO}') + versions = [] + for item in entries: + if not isinstance(item, dict) or item.get('draft') or item.get('prerelease') is not True: + continue + tag = item.get('tag_name') + match = RC_TAG_RE.fullmatch(tag) if isinstance(tag, str) else None + if match: + versions.append(match[1]) + return versions + + +def fetch_pro_asset(tag, filename, limit, gh_bin): + require(RC_TAG_RE.fullmatch(tag), 'invalid early release tag') + require(ASSET_NAME_RE.fullmatch(filename), 'invalid release asset name') + with tempfile.TemporaryDirectory(prefix='openwiz-early-') as temporary: + dest = Path(temporary) / filename + try: + proc = subprocess.run( + [gh_bin, 'release', 'download', tag, '--repo', PRO_REPO, '--pattern', filename, '--output', str(dest)], + stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=120) + except (OSError, subprocess.SubprocessError): + raise Refused(f'early release download failed for {filename} in {PRO_REPO}') from None + if proc.returncode != 0: + _refuse_gh_error(proc, f'early release download failed for {filename} in {PRO_REPO}') + require(dest.is_file() and not dest.is_symlink(), f'missing downloaded asset {filename}') + require(dest.stat().st_size <= limit, f'artifact exceeds its declared byte bound at {PRO_REPO}/{tag}/{filename}') + return dest.read_bytes() + + +def pro_fetcher(tag, gh_bin): + return lambda name, limit: fetch_pro_asset(tag, name, limit, gh_bin) + + +def load(raw, checksum, target, selected=False, allow_prerelease=False): with tempfile.TemporaryDirectory(prefix='openwiz-package-manifest-') as temporary: file = Path(temporary) / 'manifest.json' file.write_bytes(raw) - return manifest_at(file, checksum, target, selected)[0] + return manifest_at(file, checksum, target, selected, allow_prerelease=allow_prerelease)[0] def published(target, fetch=fetch_bytes, version=None): @@ -74,27 +178,70 @@ def published(target, fetch=fetch_bytes, version=None): return found -def manifest_from(prefix, target, fetch): +def published_early(target, fetch=fetch_bytes, version=None, which=shutil.which): + require(target in TARGETS, 'unsupported package target') + gh_bin = gh_binary(which) + rc_versions = pro_releases(gh_bin) + if version is not None: + if is_prerelease(version): + tag = 'v' + version + require(RC_TAG_RE.fullmatch(tag), 'invalid release version') + require(version in rc_versions, f'early release {tag} not found in {PRO_REPO}') + early_fetch = pro_fetcher(tag, gh_bin) + found = manifest_from('', target, early_fetch, allow_prerelease=True) + require(found[2]['version'] == version, 'published version does not match its tag ' + tag) + return found, 'early', early_fetch + return published(target, fetch, version), 'public', fetch + best_early = max(rc_versions, key=semver_key) if rc_versions else None + try: + public_found = published(target, fetch) + except NotFound: + if best_early is None: + raise + public_found = None + if best_early is not None and (public_found is None or semver_key(best_early) > semver_key(public_found[2]['version'])): + tag = 'v' + best_early + early_fetch = pro_fetcher(tag, gh_bin) + found = manifest_from('', target, early_fetch, allow_prerelease=True) + require(found[2]['version'] == best_early, 'published version does not match its tag ' + tag) + return found, 'early', early_fetch + require(public_found is not None, f'no published or early release found for {target}') + return public_found, 'public', fetch + + +def manifest_from(prefix, target, fetch, allow_prerelease=False): name = 'openwiz-' + target sums = fetch(prefix + name + '.sha256', 256) match = re.fullmatch(rb'([0-9a-f]{64}) ' + re.escape((name + '.manifest.json').encode()) + rb'\n', sums) require(match, 'invalid published manifest checksum') checksum = match[1].decode('ascii') raw = fetch(prefix + name + '.manifest.json', 4 * 1024 * 1024) - return sums, raw, load(raw, checksum, target), checksum + return sums, raw, load(raw, checksum, target, allow_prerelease=allow_prerelease), checksum -def discover(target, fetch=fetch_bytes): +def discover(target, fetch=fetch_bytes, channel=None, root=None, which=shutil.which): + if channel is None: + channel = (read_channel(root) or 'packaged') if root else 'packaged' + require(channel in CHANNELS, 'unsupported update channel') + if channel == 'early': + found, origin, _ = published_early(target, fetch=fetch, which=which) + manifest, checksum = found[2:] + return {'schema': 'openwiz.package-candidate.v1', 'version': manifest['version'], + 'source': manifest['source'], 'target': target, 'manifest_sha256': checksum, + 'channel': 'early', 'origin': origin} manifest, checksum = published(target, fetch)[2:] return {'schema': 'openwiz.package-candidate.v1', 'version': manifest['version'], 'source': manifest['source'], 'target': target, 'manifest_sha256': checksum} -def stage(target, version, source, checksum, root, state_root, fetch=fetch_bytes): - require(target in TARGETS and re.fullmatch(r'0\.[0-9]+\.[0-9]+', version), 'invalid version/target') +def stage(target, version, source, checksum, root, state_root, fetch=fetch_bytes, which=shutil.which): root, state_root = Path(root), Path(state_root) private(root) private(state_root / 'service') + root_channel = read_channel(root) or 'packaged' + is_early = root_channel == 'early' + version_re = EARLY_VERSION_RE if is_early else VERSION_RE + require(target in TARGETS and version_re.fullmatch(version), 'invalid version/target') current = root / 'current' require(current.is_symlink(), 'missing packaged current selection') selected = current.readlink() @@ -103,15 +250,22 @@ def stage(target, version, source, checksum, root, state_root, fetch=fetch_bytes private(selected / 'install-manifest.json', False) old_raw = (selected / 'install-manifest.json').read_bytes() old = load(old_raw, sha(old_raw), target, selected=True) - require(tuple(map(int, version.split('.'))) > tuple(map(int, old['version'].split('.'))), 'published version must advance') + require(semver_key(version) > semver_key(old['version']), 'published version must advance') name = f'openwiz-{version}-{target}.manifest.json' - prefix = BASE + 'download/v' + version + '/' - raw = fetch(prefix + name, 4 * 1024 * 1024) - manifest = load(raw, checksum, target) + if is_early and is_prerelease(version): + gh_bin = gh_binary(which) + gh_auth_check(gh_bin) + asset_fetch = pro_fetcher('v' + version, gh_bin) + prefix = '' + else: + asset_fetch = fetch + prefix = BASE + 'download/v' + version + '/' + raw = asset_fetch(prefix + name, 4 * 1024 * 1024) + manifest = load(raw, checksum, target, allow_prerelease=is_early) require(manifest['version'] == version and manifest['source'] == source, 'published identity changed') - bundle = fetch(prefix + manifest['archive'], manifest['archive_bytes']) + bundle = asset_fetch(prefix + manifest['archive'], manifest['archive_bytes']) listed = {} - for line in fetch(prefix + 'SHA256SUMS', 64 * 1024).decode('ascii', 'replace').splitlines(): + for line in asset_fetch(prefix + 'SHA256SUMS', 64 * 1024).decode('ascii', 'replace').splitlines(): match = re.fullmatch(r'([0-9a-f]{64}) ([A-Za-z0-9_.-]+)', line) require(match and match[2] not in listed, 'invalid SHA256SUMS line') listed[match[2]] = match[1] @@ -126,7 +280,8 @@ def stage(target, version, source, checksum, root, state_root, fetch=fetch_bytes manifest_file.chmod(0o600) archive.write_bytes(bundle) archive.chmod(0o600) - return install(manifest_file, archive, checksum, root, target, state_root=state_root, stage_only=True) + return install(manifest_file, archive, checksum, root, target, state_root=state_root, stage_only=True, + channel=root_channel) def main(): @@ -134,6 +289,8 @@ def main(): commands = parser.add_subparsers(dest='action', required=True) discover_parser = commands.add_parser('discover') discover_parser.add_argument('target', choices=TARGETS) + discover_parser.add_argument('--channel', choices=tuple(CHANNELS)) + discover_parser.add_argument('--root') stage_parser = commands.add_parser('stage') for key in ('target', 'version', 'source', 'checksum', 'root', 'state_root'): stage_parser.add_argument(key) diff --git a/tools/install/test_pull.py b/tools/install/test_pull.py index 1b4c62ac7..fc1c27942 100644 --- a/tools/install/test_pull.py +++ b/tools/install/test_pull.py @@ -1,6 +1,7 @@ #!/usr/bin/env python3 import importlib.util import json +import os import re from pathlib import Path import subprocess @@ -12,10 +13,64 @@ HERE = Path(__file__).resolve().parent PREFIX = 'https://github.com/openwizdev/OpenWiz/releases/download/v0.0.99/' +FAKE_GH = '''#!/usr/bin/env python3 +import json, os, shutil, sys +from pathlib import Path + +cfg = json.loads(Path(os.environ['FAKE_PRO_GH']).read_text()) +args = sys.argv[1:] +if cfg.get('log'): + with open(cfg['log'], 'a') as f: + f.write(json.dumps(args) + '\\n') +if args[:2] == ['auth', 'token']: + if not cfg.get('logged_in', True): + print('not logged into any GitHub hosts; run gh auth login', file=sys.stderr) + sys.exit(1) + print(cfg.get('token', 'gho_synthetic_token_never_logged')) + sys.exit(0) +if args[:2] == ['api', 'repos/openwizpro/WizPro/releases']: + code = cfg.get('status', 200) + if code == 404: + print('gh: Not Found (HTTP 404)', file=sys.stderr) + sys.exit(1) + if code == 401: + print('gh: Bad credentials (HTTP 401)', file=sys.stderr) + sys.exit(1) + print(json.dumps(cfg.get('releases', []))) + sys.exit(0) +if args[:2] == ['release', 'download']: + tag = args[2] + repo = args[args.index('--repo') + 1] + pattern = args[args.index('--pattern') + 1] + output = args[args.index('--output') + 1] + if repo != 'openwizpro/WizPro' or cfg.get('status', 200) == 404: + print('gh: Not Found (HTTP 404)', file=sys.stderr) + sys.exit(1) + src = Path(cfg['assets']) / tag / pattern + if not src.is_file(): + print('gh: release asset not found (HTTP 404)', file=sys.stderr) + sys.exit(1) + shutil.copyfile(src, output) + sys.exit(0) +print('unexpected fake gh call: ' + ' '.join(args), file=sys.stderr) +sys.exit(2) +''' + + +def write_fake_gh(base, cfg): + bin_dir = base / 'fake-gh-bin' + bin_dir.mkdir(exist_ok=True) + gh = bin_dir / 'gh' + gh.write_text(FAKE_GH) + gh.chmod(0o700) + cfg_path = base / 'fake-pro-gh.json' + cfg_path.write_text(json.dumps(cfg)) + return str(gh), str(cfg_path) + -def release_sums(raw, archive, target=fixture.TARGETS[2]): - return ('%s openwiz-0.0.99-%s.manifest.json\n%s bundle.tar.gz\n' - % (fixture.sha(raw), target, fixture.sha(archive))).encode() +def release_sums(raw, archive, target=fixture.TARGETS[2], version='0.0.99', archive_name='bundle.tar.gz'): + return ('%s openwiz-%s-%s.manifest.json\n%s %s\n' + % (fixture.sha(raw), version, target, fixture.sha(archive), archive_name)).encode() class Pull(unittest.TestCase): @@ -216,6 +271,140 @@ def status(): code, value = status() self.assertEqual((code, value.get('source'), value.get('version')), (0, '2' * 40, '0.0.99'), value) + def test_early_channel_follows_newest_semver_across_pro_and_public_and_refuses_rollback(self): + spec = importlib.util.spec_from_file_location('pull', Path(__file__).with_name('pull.py')) + pull = importlib.util.module_from_spec(spec) + spec.loader.exec_module(pull) + f = fixture.Install() + f.setUp() + self.addCleanup(f.doCleanups) + target = fixture.TARGETS[2] + assets_root = f.base / 'pro-assets' + + def populate_pro(version, source): + b = f.bundle(version=version, source=source) + raw, arch = b[0].read_bytes(), b[1].read_bytes() + tag_dir = assets_root / ('v' + version) + tag_dir.mkdir(parents=True, exist_ok=True) + (tag_dir / f'openwiz-{target}.sha256').write_bytes( + f'{fixture.sha(raw)} openwiz-{target}.manifest.json\n'.encode()) + (tag_dir / f'openwiz-{target}.manifest.json').write_bytes(raw) + (tag_dir / f'openwiz-{version}-{target}.manifest.json').write_bytes(raw) + (tag_dir / 'bundle.tar.gz').write_bytes(arch) + (tag_dir / 'SHA256SUMS').write_bytes(release_sums(raw, arch, target, version)) + return b, raw, arch + + rc1, raw_rc1, _ = populate_pro('0.1.2-rc.1', '1' * 40) + rc2, raw_rc2, _ = populate_pro('0.1.2-rc.2', '2' * 40) + rc3, raw_rc3, _ = populate_pro('0.1.3-rc.1', '4' * 40) + pub_old = f.bundle(version='0.1.1', source='a' * 40) + pub_new = f.bundle(version='0.1.2', source='3' * 40) + current_pub = {'bundle': pub_old, 'version': '0.1.1'} + + def pub_fetch(url, limit): + b = current_pub['bundle'] + raw, arch = b[0].read_bytes(), b[1].read_bytes() + if url.endswith('.sha256'): + return f'{fixture.sha(raw)} openwiz-{target}.manifest.json\n'.encode() + if url.endswith('.manifest.json'): + return raw + if url.endswith('.tar.gz'): + return arch + if url.endswith('SHA256SUMS'): + return release_sums(raw, arch, target, current_pub['version']) + raise pull.NotFound('404 at ' + url) + + cfg = { + 'logged_in': True, 'status': 200, 'assets': str(assets_root), + 'releases': [ + {'tag_name': 'v0.1.2-rc.1', 'prerelease': True, 'draft': False}, + {'tag_name': 'v0.1.2-rc.2', 'prerelease': True, 'draft': False}, + {'tag_name': 'v0.1.3-rc.1', 'prerelease': True, 'draft': True}, + {'tag_name': 'v0.1.3', 'prerelease': False, 'draft': False}, + ], + } + gh_path, cfg_path = write_fake_gh(f.base, cfg) + old_env = os.environ.get('FAKE_PRO_GH') + os.environ['FAKE_PRO_GH'] = cfg_path + self.addCleanup(lambda: os.environ.pop('FAKE_PRO_GH', None) if old_env is None + else os.environ.__setitem__('FAKE_PRO_GH', old_env)) + which = lambda name: gh_path if name == 'gh' else None + + res = subprocess.run([sys.executable, str(HERE / 'install.py'), '--manifest', str(rc1[0]), + '--archive', str(rc1[1]), '--manifest-sha256', fixture.sha(raw_rc1), + '--root', str(f.root), '--target', target, '--channel', 'early'], + capture_output=True, text=True) + self.assertEqual(res.returncode, 0, res.stdout + res.stderr) + self.assertEqual((f.root / 'channel.json').read_text(), + '{"schema":"openwiz.update-channel.v1","channel":"early"}\n') + + cand = pull.discover(target, fetch=pub_fetch, root=f.root, which=which) + self.assertEqual((cand['version'], cand['channel'], cand['origin']), ('0.1.2-rc.2', 'early', 'early')) + staged = pull.stage(target, cand['version'], cand['source'], cand['manifest_sha256'], + f.root, f.root / 'state', fetch=pub_fetch, which=which) + self.assertEqual((staged['version'], staged['activated']), ('0.1.2-rc.2', False)) + subprocess.run([sys.executable, str(HERE / 'install.py'), '--manifest', str(rc2[0]), + '--archive', str(rc2[1]), '--manifest-sha256', fixture.sha(raw_rc2), + '--root', str(f.root), '--target', target, '--channel', 'early'], + check=True, capture_output=True) + + current_pub.update(bundle=pub_new, version='0.1.2') + cand = pull.discover(target, fetch=pub_fetch, root=f.root, which=which) + self.assertEqual((cand['version'], cand['channel'], cand['origin']), ('0.1.2', 'early', 'public')) + staged = pull.stage(target, cand['version'], cand['source'], cand['manifest_sha256'], + f.root, f.root / 'state', fetch=pub_fetch, which=which) + self.assertEqual((staged['version'], staged['activated']), ('0.1.2', False)) + subprocess.run([sys.executable, str(HERE / 'install.py'), '--manifest', str(pub_new[0]), + '--archive', str(pub_new[1]), '--manifest-sha256', fixture.sha(pub_new[0].read_bytes()), + '--root', str(f.root), '--target', target, '--channel', 'early'], + check=True, capture_output=True) + self.assertEqual((f.root / 'channel.json').read_text(), + '{"schema":"openwiz.update-channel.v1","channel":"early"}\n') + + with self.assertRaisesRegex(pull.Refused, 'published version must advance'): + pull.stage(target, '0.1.2-rc.2', '2' * 40, fixture.sha(raw_rc2), + f.root, f.root / 'state', fetch=pub_fetch, which=which) + + cfg['releases'].append({'tag_name': 'v0.1.3-rc.1', 'prerelease': True, 'draft': False}) + Path(cfg_path).write_text(json.dumps(cfg)) + cand = pull.discover(target, fetch=pub_fetch, root=f.root, which=which) + self.assertEqual((cand['version'], cand['origin']), ('0.1.3-rc.1', 'early')) + staged = pull.stage(target, cand['version'], cand['source'], cand['manifest_sha256'], + f.root, f.root / 'state', fetch=pub_fetch, which=which) + self.assertEqual((staged['version'], staged['source']), ('0.1.3-rc.1', '4' * 40)) + + def test_early_channel_refusals_for_missing_gh_logged_out_and_no_pro_access(self): + spec = importlib.util.spec_from_file_location('pull', Path(__file__).with_name('pull.py')) + pull = importlib.util.module_from_spec(spec) + spec.loader.exec_module(pull) + f = fixture.Install() + f.setUp() + self.addCleanup(f.doCleanups) + target = fixture.TARGETS[2] + fail_fetch = lambda url, limit: self.fail('must not fetch public before Pro auth/access check: ' + url) + + with self.assertRaisesRegex(pull.Refused, 'gh auth login'): + pull.discover(target, fetch=fail_fetch, channel='early', which=lambda _: None) + + gh_path, cfg_path = write_fake_gh(f.base, {'logged_in': False, 'token': 'gho_synthetic_secret_123'}) + old_env = os.environ.get('FAKE_PRO_GH') + os.environ['FAKE_PRO_GH'] = cfg_path + self.addCleanup(lambda: os.environ.pop('FAKE_PRO_GH', None) if old_env is None + else os.environ.__setitem__('FAKE_PRO_GH', old_env)) + which = lambda name: gh_path if name == 'gh' else None + + with self.assertRaises(pull.Refused) as ctx: + pull.discover(target, fetch=fail_fetch, channel='early', which=which) + self.assertIn('gh auth login', str(ctx.exception)) + self.assertNotIn('gho_synthetic_secret_123', str(ctx.exception)) + + Path(cfg_path).write_text(json.dumps({'logged_in': True, 'status': 404, 'token': 'gho_synthetic_secret_123'})) + with self.assertRaises(pull.Refused) as ctx: + pull.discover(target, fetch=fail_fetch, channel='early', which=which) + self.assertIn('OpenWiz Pro', str(ctx.exception)) + self.assertIn('https://openwiz.dev/pro/', str(ctx.exception)) + self.assertNotIn('gho_synthetic_secret_123', str(ctx.exception)) + if __name__ == '__main__': unittest.main() diff --git a/tools/install/tests/installer/test_installer.py b/tools/install/tests/installer/test_installer.py index 024b6a1fe..b8d08d0f6 100644 --- a/tools/install/tests/installer/test_installer.py +++ b/tools/install/tests/installer/test_installer.py @@ -17,6 +17,7 @@ INSTALL = Path(__file__).resolve().parents[2] sys.path.insert(0, str(INSTALL)) import test_install +import test_pull import pull spec = importlib.util.spec_from_loader('install_entry', SourceFileLoader('install_entry', str(INSTALL / 'install'))) @@ -378,5 +379,116 @@ def test_link_never_replaces_the_users_own_openwiz(self): self.assertEqual(code, 5) +class EarlyChannel(Installer): + def publish_pro(self, assets_root, version, source='1' * 40, tamper_sums=False): + archive_name = f'openwiz-{version}-{TARGET}.tar.gz' + manifest, archive, _ = self.bundle(version=version, source=source, + mutate=lambda m: m.update(archive=archive_name)) + raw, data = manifest.read_bytes(), archive.read_bytes() + tag_dir = assets_root / ('v' + version) + tag_dir.mkdir(parents=True, exist_ok=True) + (tag_dir / (NAME + '.sha256')).write_bytes( + f'{test_install.sha(raw)} {NAME}.manifest.json\n'.encode()) + (tag_dir / (NAME + '.manifest.json')).write_bytes(raw) + (tag_dir / archive_name).write_bytes(data) + sums = (f'{test_install.sha(raw)} openwiz-{version}-{TARGET}.manifest.json\n' + f'{"0" * 64 if tamper_sums else test_install.sha(data)} {archive_name}\n') + (tag_dir / 'SHA256SUMS').write_bytes(sums.encode()) + return archive_name + + def setup_fake_gh(self, cfg): + gh_path, cfg_path = test_pull.write_fake_gh(self.base, cfg) + old_env = os.environ.get('FAKE_PRO_GH') + os.environ['FAKE_PRO_GH'] = cfg_path + self.addCleanup(lambda: os.environ.pop('FAKE_PRO_GH', None) if old_env is None + else os.environ.__setitem__('FAKE_PRO_GH', old_env)) + os.environ['PATH'] = str(Path(gh_path).parent) + os.pathsep + '/usr/bin:/bin' + return cfg_path + + def test_early_download_install_status_public_supersede_and_remove(self): + assets_root = self.base / 'pro-assets' + archive_rc = self.publish_pro(assets_root, '0.1.2-rc.1', source='a' * 40) + self.publish('v0.1.0', '0.1.0') + self.feed('v0.1.0') + cfg_path = self.setup_fake_gh({ + 'logged_in': True, 'status': 200, 'assets': str(assets_root), + 'releases': [{'tag_name': 'v0.1.2-rc.1', 'prerelease': True, 'draft': False}], + }) + dl = self.base / 'dl-early' + code, value = self.run_entry('download', '--early', '--target', TARGET, '--dir', str(dl)) + self.assertEqual((code, value['outcome'], value['version'], value['channel'], value['origin']), + (0, 'downloaded', '0.1.2-rc.1', 'early', 'early'), value) + self.assertEqual(sorted(p.name for p in dl.iterdir()), + sorted([NAME + '.sha256', NAME + '.manifest.json', archive_rc, 'channel.json'])) + + code, value = self.run_entry('install', '--assets', str(dl), '--target', TARGET, '--root', str(self.root)) + self.assertEqual((code, value['outcome'], value['version']), (0, 'installed', '0.1.2-rc.1'), value) + self.assertEqual((self.root / 'channel.json').read_text(), + '{"schema":"openwiz.update-channel.v1","channel":"early"}\n') + code, value = self.run_entry('status', '--root', str(self.root)) + self.assertEqual((code, value['outcome'], value['version'], value['channel']), + (0, 'installed', '0.1.2-rc.1', 'early'), value) + + pub_archive = f'openwiz-0.1.2-{TARGET}.tar.gz' + manifest, archive, _ = self.bundle(version='0.1.2', source='b' * 40, + mutate=lambda m: m.update(archive=pub_archive)) + raw, data = manifest.read_bytes(), archive.read_bytes() + prefix = '/openwizdev/OpenWiz/releases/download/v0.1.2/' + sums = f'{test_install.sha(raw)} openwiz-0.1.2-{TARGET}.manifest.json\n{test_install.sha(data)} {pub_archive}\n' + Host.routes.update({ + prefix + NAME + '.sha256': f'{test_install.sha(raw)} {NAME}.manifest.json\n'.encode(), + prefix + NAME + '.manifest.json': raw, prefix + pub_archive: data, prefix + 'SHA256SUMS': sums.encode(), + }) + self.feed('v0.1.0', 'v0.1.2') + dl_pub = self.base / 'dl-early-pub' + code, value = self.run_entry('download', '--early', '--target', TARGET, '--dir', str(dl_pub)) + self.assertEqual((code, value['version'], value['channel'], value['origin']), + (0, '0.1.2', 'early', 'public'), value) + code, value = self.run_entry('install', '--assets', str(dl_pub), '--target', TARGET, '--root', str(self.root)) + self.assertEqual((code, value['version']), (0, '0.1.2'), value) + self.assertEqual(self.run_entry('status', '--root', str(self.root))[1]['channel'], 'early') + + code, value = self.run_entry('remove', '--root', str(self.root)) + self.assertEqual((code, value['outcome']), (0, 'preview'), value) + self.assertIn(str(self.root / 'channel.json'), value['delete']) + code, value = self.run_entry('remove', '--root', str(self.root), '--yes') + self.assertEqual((code, value['outcome']), (0, 'removed'), value) + self.assertFalse(self.root.exists()) + + self.publish_pro(assets_root, '0.1.3-rc.1', source='c' * 40, tamper_sums=True) + Path(cfg_path).write_text(json.dumps({ + 'logged_in': True, 'status': 200, 'assets': str(assets_root), + 'releases': [{'tag_name': 'v0.1.3-rc.1', 'prerelease': True, 'draft': False}], + })) + bad_dl = self.base / 'dl-bad-early' + code, value = self.run_entry('download', '--early', '--target', TARGET, '--dir', str(bad_dl)) + self.assertEqual((code, value['outcome']), (5, 'refused'), value) + self.assertIn('SHA256SUMS does not match', value['reason']) + self.assertFalse(bad_dl.exists()) + + def test_early_download_refusals_and_default_unchanged(self): + code, _ = self.run_entry('download', '--target', TARGET, '--dir', str(self.base / 'dl-rc'), + '--version', 'v0.1.2-rc.1') + self.assertEqual(code, 2) + + empty_bin = self.base / 'empty-bin' + empty_bin.mkdir() + os.environ['PATH'] = str(empty_bin) + code, value = self.run_entry('download', '--early', '--target', TARGET, '--dir', str(self.base / 'dl-nogh')) + self.assertEqual((code, value['outcome']), (5, 'refused'), value) + self.assertIn('gh auth login', value['reason']) + + cfg_path = self.setup_fake_gh({'logged_in': False}) + code, value = self.run_entry('download', '--early', '--target', TARGET, '--dir', str(self.base / 'dl-out')) + self.assertEqual((code, value['outcome']), (5, 'refused'), value) + self.assertIn('gh auth login', value['reason']) + + Path(cfg_path).write_text(json.dumps({'logged_in': True, 'status': 404})) + code, value = self.run_entry('download', '--early', '--target', TARGET, '--dir', str(self.base / 'dl-404')) + self.assertEqual((code, value['outcome']), (5, 'refused'), value) + self.assertIn('OpenWiz Pro', value['reason']) + self.assertIn('https://openwiz.dev/pro/', value['reason']) + + if __name__ == '__main__': unittest.main()