From e4fb4f309f9257498af678c3ae37d22039081b15 Mon Sep 17 00:00:00 2001 From: Anya Tokugawa Date: Fri, 6 Nov 2026 02:21:28 +0900 Subject: [PATCH] Prepare independent CLI builds and immutable Gitea release assets --- .dockerignore | 7 ++++ .gitea/workflows/release.yml | 59 ++++++++++++++++++++++++++++ .gitignore | 7 ++++ DISTRIBUTION.md | 40 +++++++++++++++++++ Dockerfile.release | 11 ++++++ README.md | 8 ++-- THIRD_PARTY.md | 9 +++++ VERSION | 1 + WINDOWS-TODO.md | 18 +++++++++ pages | 4 +- requirements-build.txt | 2 + test_distribution.py | 46 ++++++++++++++++++++++ tools/build.py | 65 +++++++++++++++++++++++++++++++ tools/publish.py | 75 ++++++++++++++++++++++++++++++++++++ tools/smoke_binary.py | 48 +++++++++++++++++++++++ 15 files changed, 396 insertions(+), 4 deletions(-) create mode 100644 .dockerignore create mode 100644 .gitea/workflows/release.yml create mode 100644 .gitignore create mode 100644 DISTRIBUTION.md create mode 100644 Dockerfile.release create mode 100644 THIRD_PARTY.md create mode 100644 VERSION create mode 100644 WINDOWS-TODO.md create mode 100644 requirements-build.txt create mode 100644 test_distribution.py create mode 100644 tools/build.py create mode 100644 tools/publish.py create mode 100644 tools/smoke_binary.py diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..096a769 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,7 @@ +.git +.venv +__pycache__ +build +dist +release +*.spec diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml new file mode 100644 index 0000000..e36310a --- /dev/null +++ b/.gitea/workflows/release.yml @@ -0,0 +1,59 @@ +name: Test and release pages-cli +on: + push: + branches: [main] + tags: ['v*'] + workflow_dispatch: +jobs: + linux: + runs-on: ${{ vars.IMAGE_RUNNER_LABEL || 'ubuntu-latest' }} + container: + image: docker.gitea.com/runner-images:ubuntu-latest@sha256:fd911d7417bfbf0f454530e447da95b58001e1df41bbc5e1a8dd35d432575aae + env: + PATH: /opt/acttoolcache/node/24.19.0/x64/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin + steps: + - uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + ref: ${{ github.sha }} + persist-credentials: false + - name: Build native Linux amd64 artifacts and test + env: + SOURCE_REVISION: ${{ github.sha }} + run: docker buildx build --platform linux/amd64 --build-arg SOURCE_REVISION="$SOURCE_REVISION" --file Dockerfile.release --output type=local,dest=release . + - name: Publish release assets + if: startsWith(github.ref, 'refs/tags/v') + env: + GITEA_TOKEN: ${{ secrets.CLI_RELEASE_TOKEN || github.token }} + GITEA_SERVER_URL: ${{ github.server_url }} + GITEA_REPOSITORY: ${{ github.repository }} + GITEA_REF: ${{ github.ref }} + GITEA_SHA: ${{ github.sha }} + run: python3 tools/publish.py + macos: + needs: linux + if: vars.CLI_MACOS_ENABLED == 'true' + runs-on: ${{ vars.CLI_MACOS_RUNNER_LABEL || 'pages-cli-macos' }} + steps: + - uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + ref: ${{ github.sha }} + persist-credentials: false + - name: Native macOS build + env: + SOURCE_REVISION: ${{ github.sha }} + run: | + python3 -m venv .venv + . .venv/bin/activate + python -m pip install -r requirements-build.txt + python -m unittest test_pages test_productivity test_distribution + python tools/build.py + python tools/smoke_binary.py dist/pages + - name: Publish release assets + if: startsWith(github.ref, 'refs/tags/v') + env: + GITEA_TOKEN: ${{ secrets.CLI_RELEASE_TOKEN || github.token }} + GITEA_SERVER_URL: ${{ github.server_url }} + GITEA_REPOSITORY: ${{ github.repository }} + GITEA_REF: ${{ github.ref }} + GITEA_SHA: ${{ github.sha }} + run: .venv/bin/python tools/publish.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e44035b --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +__pycache__/ +*.pyc +.venv/ +build/ +dist/ +release/ +*.spec diff --git a/DISTRIBUTION.md b/DISTRIBUTION.md new file mode 100644 index 0000000..4ee5b82 --- /dev/null +++ b/DISTRIBUTION.md @@ -0,0 +1,40 @@ +# CLIのダウンロードと配布 + +配布先はGiteaの `anya/pages-cli` のReleases。CLIはサーバーとは独立したSemVerで、最初の独立配布版はv0.1.0。対応APIがあるサーバーが必要で、タスク・連絡先を含む利用ではPagesWiki v0.6.0以降を基準とする。ユーザーの設定やセッションは既存のまま利用できる。 + +## 対象OS + +| 対象 | 配布状態と条件 | +| --- | --- | +| Linux/amd64 | ELF単体とtar.gz。glibc 2.36以降(Debian 12、Ubuntu 24.04等)。Python同梱。Alpine/muslは対象外 | +| macOS | Unixソース対応。配布バイナリはmacOS runner接続後にネイティブビルド・実機検証する。署名・公証は別途必要 | +| Windows/amd64 | 配布準備の対象。fcntl、readline、所有者・0600権限検証のWindows移植とネイティブ検証が必要。未対応exeは公開しない | + +rpm/debは初期配布の必須条件にせず、LinuxはELFを提供する。PyInstallerはクロスコンパイラではないため、macOS/WindowsバイナリをLinux上で作ったとみなさない。[公式説明](https://www.pyinstaller.org/en/stable/) + +## インストール + +Releases画面からOSに合うtar.gzと `*-SHA256SUMS` をダウンロードする。非公開リポジトリではGiteaへのログインが必要。資格情報をコマンドライン引数や公開URLに埋め込まない。 + +```sh +# ダウンロード先で実行。手元にあるファイルをチェックする。 +sha256sum --ignore-missing -c pages-cli-v0.1.0-linux-amd64-SHA256SUMS +tar -xzf pages-cli-v0.1.0-linux-amd64.tar.gz +mkdir -p ~/.local/bin +install -m 755 pages ~/.local/bin/pages +pages --version +``` + +SHA-256はダウンロード内容の整合確認であり、配布者の暗号学的署名ではない。ELF単体を取得した場合も同じSHA256SUMSで確認し、実行権限を付ける。設定・ログイン手順は[README](README.md)を参照。`PAGER`・`EDITOR`、TLS用のOS信頼ストアは利用環境側に必要で、バイナリはOSのlibcなどへ動的リンクする。 + +## ビルドとリリース + +LinuxのCIはGitea Actionsでテスト後、Dockerfile.releaseからPython同梱ELFを作り、versionとhelpを起動確認する。`VERSION` とソースのVERSIONは一致必須。ビルドメタデータ、ソース版、tar.gz、実行ファイル、SHA256SUMSを出力する。ソース版に設定・トークン・ユーザーデータは含めない。 + +mainへのpushはテスト・ビルドのみ。`vX.Y.Z` タグのpushは同じ処理に加えてGitea Releaseへ添付し、全ファイルの転送後にdraftを解除する。同じ名前の既存添付はハッシュが一致する場合だけ再利用し、相違があれば停止する。公開タグは付け替えない。 + +既存runnerにはdocker/buildxとGiteaへのHTTPS接続が必要。公開にはジョブのtokenを使用し、権限不足の場合だけこのリポジトリに限定した `CLI_RELEASE_TOKEN` を設定する。サーバーリポジトリのPATやDocker資格情報をコピーしない。 + +macOSは `CLI_MACOS_ENABLED=true` と `CLI_MACOS_RUNNER_LABEL` を設定した場合のみ起動する。runnerにはPython 3とgitが必要で、タグcheckout後に同じbuild.pyを実行する。Macの最低OS、CPU、署名・公証は実際のrunnerと検証結果に合わせて公開時に明記する。Windowsは安全な資格情報保存の移植が済むまでジョブを有効化しない。 + +サーバーリポジトリ側の旧pages-cliは結合テスト用スナップショット。CLIの新規実装・配布はこのリポジトリで行い、サーバーの結合テスト用コピーはレビューしたリビジョンに明示的に更新する。 diff --git a/Dockerfile.release b/Dockerfile.release new file mode 100644 index 0000000..00c0de4 --- /dev/null +++ b/Dockerfile.release @@ -0,0 +1,11 @@ +FROM python:3.11-slim-bookworm@sha256:a83ba18aef0f865b1a4a611c2cf460fe446f2795673bbb9fe43be570439e3b39 AS build +RUN apt-get update && apt-get install -y --no-install-recommends binutils ca-certificates && rm -rf /var/lib/apt/lists/* +WORKDIR /src +ARG SOURCE_REVISION +ENV SOURCE_REVISION=$SOURCE_REVISION +COPY requirements-build.txt . +RUN pip install --no-cache-dir -r requirements-build.txt +COPY . . +RUN python -m unittest test_pages test_productivity test_distribution && python tools/build.py && python tools/smoke_binary.py dist/pages +FROM scratch AS artifacts +COPY --from=build /src/release/ / diff --git a/README.md b/README.md index 84224c0..01029db 100644 --- a/README.md +++ b/README.md @@ -7,12 +7,14 @@ DBに直接アクセスする `data/pageswiki-cli` とは独立したHTTPクラ ## はじめる -Python 3.9以降、Linux/macOS等のUnix系環境を使用します。外部Pythonパッケージは不要です。 -リポジトリ内では `./pages-cli/pages` で実行できます。PATHへ配置する場合: +独立リポジトリは `https://git.anya.jp/anya/pages-cli` です。リリースのダウンロード方法とOS別の対応状況は [配布ガイド](DISTRIBUTION.md) を参照してください。 + +ソース版はPython 3.9以降、Linux/macOS等のUnix系環境を使用します。外部Pythonパッケージは不要です。Linux配布バイナリはPythonの別途インストール不要です。 +リポジトリ内では `./pages` で実行できます。ソース版をPATHへ配置する場合: ```sh mkdir -p ~/.local/bin -install -m 755 pages-cli/pages ~/.local/bin/pages +install -m 755 pages ~/.local/bin/pages # ~/.local/bin をPATHに含めてください。 ``` diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md new file mode 100644 index 0000000..c1ac38f --- /dev/null +++ b/THIRD_PARTY.md @@ -0,0 +1,9 @@ +# バンドルに含む第三者ソフトウェア + +CLIのソース版はPython標準ライブラリのみを使う。実行ファイル版にはCPython、PyInstallerのbootloader、Pythonが利用する共有ライブラリを含む。これらの権利は各権利者に帰属する。PyInstallerのbootloaderにはアプリケーション配布に関する例外がある。 + +- CPython: https://docs.python.org/3/license.html +- PyInstaller: https://pyinstaller.org/en/stable/license.html +- OpenSSL: https://www.openssl.org/source/license.html + +tar.gzにはビルド環境のPythonとPyInstallerのライセンスを `licenses/` に収録する。ソースの公開範囲とオープンソースライセンスの付与は別であり、この切り出しでは元の独自コードに新しいライセンスを付与しない。 diff --git a/VERSION b/VERSION new file mode 100644 index 0000000..6e8bf73 --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +0.1.0 diff --git a/WINDOWS-TODO.md b/WINDOWS-TODO.md new file mode 100644 index 0000000..240014c --- /dev/null +++ b/WINDOWS-TODO.md @@ -0,0 +1,18 @@ +# Windows amd64ネイティブ対応 + +Windows版exeの公開は以下の実装とWindows runnerでの検証が完了するまで保留する。Unix専用の検査を単に無効化してビルドを通すことはしない。 + +## 必須の移植 + +- `fcntl.flock` をWindowsの排他ロックへ置き換える。設定→セッションのロック順序、二重起動時の拒否、プロセス終了時の解除を維持する。 +- `getuid` と0700/0600検証に代わり、現在ユーザーのSIDとDACLを検証する。新規ディレクトリ・一時ファイルは最初から制限付きDACLで作り、既存の広い権限は黙って受け入れない。junction/reparse pointとシンボリックリンクも拒否する。 +- atomic replace、`fsync`、ロックファイルの作成、編集中原稿のリカバリーをWindowsで確認する。Bearerを一時的にも他ユーザーから読める場所へ書かない。 +- `readline` がない環境の対話シェルを用意する。履歴はメモリ内のみとし、秘密情報を永続化しない。 +- `$EDITOR`、`$PAGER` の既定値と、スペースを含むWindows実行ファイルパスの引数処理を実装する。`shell=True` に置き換えない。 +- UTF-8、CRLF、コンソール入力と非表示パスワード入力、ブラウザ起動を確認する。 + +## 配布ゲート + +Windows/amd64のnative runnerで全単体テストと実exeのconfigure・ログイン・OIDC・タスク操作・対話シェル・二重起動・不正ACL拒否を検証する。成功後にbuild.pyのWindows拒否を解除し、zip・exe・メタデータ・SHA256SUMSを出力する。コード署名とSmartScreenの扱いは別途決定する。 + +macOSについても実runnerで最低OSとCPUを確認する。macOS/Windowsで取得した結果をLinuxによる疑似テストだけで代替しない。 diff --git a/pages b/pages index b3c5a2f..1714e6e 100755 --- a/pages +++ b/pages @@ -28,6 +28,7 @@ import urllib.parse as url import urllib.request as http import webbrowser +VERSION = '0.1.0' class Failure(Exception): def __init__(self, message, status=0, payload=None): @@ -81,7 +82,7 @@ class Client: def request(self, route, method='GET', data=None, form=None, limit=4 << 20, etag=None, content_type=None): if not route.startswith('/') or route.startswith('//'): raise Failure('Invalid API route.') - headers = {'Accept': 'application/json', 'User-Agent': 'pages-cli/0.1'} + headers = {'Accept': 'application/json', 'User-Agent': 'pages-cli/' + VERSION} if etag is not None: headers['If-Match'] = etag if self.token: @@ -739,6 +740,7 @@ def shell(client, profile): def main(argv=None): parser = argparse.ArgumentParser(prog='pages', description=__doc__, epilog='Commands: configure, login, logout, status, shell, ls, cd, pwd, cat, view, get, put, edit, search, open, task, contacts. Use pages COMMAND --help.') + parser.add_argument('--version', action='version', version='pages-cli ' + VERSION) parser.add_argument('--profile', help='Use another configured connection for this invocation') parser.add_argument('--lang', help='auto or an exact language tag for this invocation') parser.add_argument('command', nargs='?', default='shell') diff --git a/requirements-build.txt b/requirements-build.txt new file mode 100644 index 0000000..919b5f5 --- /dev/null +++ b/requirements-build.txt @@ -0,0 +1,2 @@ +# Build tool only; the source client uses the Python standard library. +pyinstaller==6.22.0 diff --git a/test_distribution.py b/test_distribution.py new file mode 100644 index 0000000..70e70e8 --- /dev/null +++ b/test_distribution.py @@ -0,0 +1,46 @@ +import contextlib +import io +import os +from pathlib import Path +import runpy +import tempfile +import unittest +from unittest.mock import patch +import urllib.request +from tools.publish import SameOriginRedirect, main + +class DistributionTests(unittest.TestCase): + def test_version_matches(self): + module=runpy.run_path(str(Path(__file__).with_name('pages'))) + self.assertEqual(module['VERSION'],Path('VERSION').read_text().strip()) + output=io.StringIO() + with contextlib.redirect_stdout(output),self.assertRaises(SystemExit) as exited:module['main'](['--version']) + self.assertEqual(exited.exception.code,0) + self.assertIn(module['VERSION'],output.getvalue()) + + def test_credential_redirect_is_same_origin_only(self): + redirect=SameOriginRedirect() + req=urllib.request.Request('https://git.anya.jp/asset',headers={'Authorization':'token synthetic'}) + for url in ['https://other.invalid/asset','http://git.anya.jp/asset']: + with self.assertRaises(RuntimeError):redirect.redirect_request(req,None,302,'',{},url) + new=redirect.redirect_request(req,None,302,'',{},'https://git.anya.jp/attachment') + self.assertEqual(new.get_header('Authorization'),'token synthetic') + + def test_publisher_rejects_wrong_tag_before_network(self): + env={'GITEA_SERVER_URL':'https://git.anya.jp','GITEA_REPOSITORY':'anya/pages-cli','GITEA_TOKEN':'synthetic','GITEA_REF':'refs/tags/v9.9.9'} + with patch.dict(os.environ,env),patch('urllib.request.build_opener') as network,self.assertRaises(SystemExit):main() + network.assert_not_called() + + def test_publisher_rejects_tampered_artifacts(self): + cwd=Path.cwd() + with tempfile.TemporaryDirectory() as root: + try: + os.chdir(root);Path('VERSION').write_text('0.1.0');Path('release').mkdir() + Path('release/asset').write_bytes(b'bad') + Path('release/test-SHA256SUMS').write_text('0'*64+' asset\n') + env={'GITEA_SERVER_URL':'https://git.anya.jp','GITEA_REPOSITORY':'anya/pages-cli','GITEA_TOKEN':'synthetic','GITEA_REF':'refs/tags/v0.1.0','GITEA_SHA':'a'*40} + with patch.dict(os.environ,env),patch('subprocess.check_output',return_value='a'*40),patch('urllib.request.build_opener') as opener,self.assertRaises(SystemExit):main() + opener.return_value.open.assert_not_called() + finally:os.chdir(cwd) + +if __name__=='__main__':unittest.main() diff --git a/tools/build.py b/tools/build.py new file mode 100644 index 0000000..c1c91cf --- /dev/null +++ b/tools/build.py @@ -0,0 +1,65 @@ +"""Build native CLI artifacts. Invoke on each target OS; never cross-label.""" +import hashlib +import importlib.metadata +import json +import os +from pathlib import Path +import platform +import re +import shutil +import subprocess +import sysconfig +import tarfile + +ROOT = Path(__file__).resolve().parent.parent + +def main(): + os.chdir(ROOT) + version = (ROOT / 'VERSION').read_text().strip() + if not re.fullmatch(r'0|[1-9][0-9]*', version.split('.')[0]) or not re.fullmatch(r'(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)', version): + raise SystemExit('VERSION must be a stable SemVer version') + if f"VERSION = '{version}'" not in (ROOT / 'pages').read_text(): + raise SystemExit('VERSION and pages disagree') + system = platform.system().lower() + arch = {'x86_64':'amd64','AMD64':'amd64','arm64':'arm64','aarch64':'arm64'}.get(platform.machine()) + if system not in ('linux','darwin') or arch not in ('amd64','arm64'): + raise SystemExit('Native Windows credential/locking port is not yet validated; no unsupported binary will be published') + subprocess.run(['python','-m','PyInstaller','--clean','--noconfirm','--onefile','--name','pages','pages'],check=True) + binary = ROOT / 'dist/pages' + output = subprocess.check_output([str(binary),'--version'],text=True).strip() + if output != 'pages-cli '+version: raise SystemExit('Binary version mismatch') + subprocess.run([str(binary),'task','--help'],check=True,stdout=subprocess.DEVNULL) + subprocess.run([str(binary),'contacts','--help'],check=True,stdout=subprocess.DEVNULL) + release=ROOT/'release' + if release.exists():shutil.rmtree(release) + release.mkdir() + target=f'{system}-{arch}' + name=f'pages-cli-v{version}-{target}' + with tarfile.open(release/(name+'.tar.gz'),'w:gz') as tar: + tar.add(binary,arcname='pages') + for path in ('README.md','DISTRIBUTION.md','THIRD_PARTY.md','VERSION'): + tar.add(ROOT/path,arcname=path) + python_license=Path(sysconfig.get_path('stdlib'))/'LICENSE.txt' + if not python_license.is_file():raise SystemExit('Missing Python license') + tar.add(python_license,arcname='licenses/Python-LICENSE.txt') + dist=importlib.metadata.distribution('pyinstaller') + found=False + for path in dist.files or []: + if 'COPYING' in str(path) or 'LICENSE' in str(path): + candidate=Path(dist.locate_file(path)) + if candidate.is_file():tar.add(candidate,arcname='licenses/PyInstaller/'+str(path));found=True + if not found:raise SystemExit('Missing PyInstaller license') + for copyright_file in Path('/usr/share/doc').glob('*/copyright'): + tar.add(copyright_file,arcname='licenses/system/'+copyright_file.parent.name+'/copyright') + shutil.copy2(binary,release/(name+('.elf' if system=='linux' else ''))) + # The source script remains available to Python users independently of the bundle. + shutil.copy2(ROOT/'pages',release/f'pages-v{version}.py') + metadata={'version':version,'target':target,'python':platform.python_version(),'libc':platform.libc_ver(),'source_revision':os.environ.get('SOURCE_REVISION','')} + (release/(name+'.json')).write_text(json.dumps(metadata,indent=2)+'\n') + hashes=[] + for path in sorted(release.iterdir()): + if path.name.endswith('SHA256SUMS'): continue + hashes.append(hashlib.sha256(path.read_bytes()).hexdigest()+' '+path.name) + (release/(name+'-SHA256SUMS')).write_text('\n'.join(hashes)+'\n') + +if __name__=='__main__':main() diff --git a/tools/publish.py b/tools/publish.py new file mode 100644 index 0000000..0016d68 --- /dev/null +++ b/tools/publish.py @@ -0,0 +1,75 @@ +"""Publish verified assets using the repository-scoped Gitea Actions token.""" +import hashlib +import json +import os +from pathlib import Path +import re +import subprocess +import urllib.error +import urllib.parse +import urllib.request +import uuid + +class SameOriginRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self,req,fp,code,msg,headers,newurl): + if urllib.parse.urlsplit(newurl)[:2] != urllib.parse.urlsplit(req.full_url)[:2]: + raise RuntimeError('Refusing cross-origin release download') + return super().redirect_request(req,fp,code,msg,headers,newurl) + +def main(): + base=os.environ['GITEA_SERVER_URL'].rstrip('/') + if base!='https://git.anya.jp':raise SystemExit('Unexpected Gitea host') + repo=os.environ['GITEA_REPOSITORY'] + if repo!='anya/pages-cli':raise SystemExit('Unexpected repository') + token=os.environ['GITEA_TOKEN'] + if not token:raise SystemExit('Missing repository release token') + version=Path('VERSION').read_text().strip() + tag='v'+version + if os.environ['GITEA_REF']!='refs/tags/'+tag:raise SystemExit('Tag does not match VERSION') + revision=subprocess.check_output(['git','rev-parse','HEAD'],text=True).strip() + expected=os.environ['GITEA_SHA'] + if revision!=expected:raise SystemExit('Checkout revision mismatch') + opener=urllib.request.build_opener(SameOriginRedirect()) + def raw(path,method='GET',body=None,ctype='application/json'): + req=urllib.request.Request(base+path,data=body,method=method,headers={'Authorization':'token '+token,'Content-Type':ctype}) + with opener.open(req,timeout=90) as r:return r.read() + def api(path,method='GET',body=None): + value=raw('/api/v1/repos/'+repo+path,method,None if body is None else json.dumps(body).encode()) + return json.loads(value) if value else {} + files=sorted(p for p in Path('release').iterdir() if p.is_file()) + manifests=[p for p in files if p.name.endswith('-SHA256SUMS')] + if len(manifests)!=1:raise SystemExit('Expected one target checksum manifest') + listed=set() + for line in manifests[0].read_text().splitlines(): + digest,name=line.split(' ',1) + if not re.fullmatch(r'[a-zA-Z0-9_.-]+',name):raise SystemExit('Invalid asset name') + path=Path('release')/name + if hashlib.sha256(path.read_bytes()).hexdigest()!=digest:raise SystemExit('Asset checksum mismatch') + listed.add(name) + if {p.name for p in files} != listed|{manifests[0].name}:raise SystemExit('Unlisted release assets') + metadata=json.loads(next(p for p in files if p.suffix=='.json').read_text()) + if metadata['source_revision']!=revision or metadata['version']!=version:raise SystemExit('Artifact provenance mismatch') + try:release=api('/releases/tags/'+tag) + except urllib.error.HTTPError as e: + if e.code!=404:raise + release=api('/releases','POST',{'tag_name':tag,'target_commitish':revision,'name':'pages-cli '+tag,'draft':True,'prerelease':False,'body':'Standalone PagesWiki CLI. Download the archive and its SHA256SUMS. See DISTRIBUTION.md for platform support and compatibility. macOS/Windows binaries are available only after their native builds have been validated.'}) + rid=release['id'] + assets={a['name']:a for a in api(f'/releases/{rid}/assets')} + for path in files: + content=path.read_bytes() + if path.name in assets: + download=urllib.parse.urlsplit(assets[path.name]['browser_download_url']) + if download[:2]!=urllib.parse.urlsplit(base)[:2]:raise SystemExit('Unexpected asset download host') + existing=raw(download.path+('?' + download.query if download.query else '')) + if hashlib.sha256(existing).digest()!=hashlib.sha256(content).digest():raise SystemExit('Refusing to replace existing release asset: '+path.name) + print('Unchanged:',path.name);continue + boundary='pages-cli-'+uuid.uuid4().hex + body=(f'--{boundary}\r\nContent-Disposition: form-data; name="attachment"; filename="{path.name}"\r\nContent-Type: application/octet-stream\r\n\r\n'.encode()+content+f'\r\n--{boundary}--\r\n'.encode()) + raw('/api/v1/repos/'+repo+f'/releases/{rid}/assets?name='+urllib.parse.quote(path.name),'POST',body,'multipart/form-data; boundary='+boundary) + print('Uploaded:',path.name) + if release['draft']:api(f'/releases/{rid}','PATCH',{'draft':False}) + print('Release:',base+'/'+repo+'/releases/tag/'+tag) + +if __name__=='__main__': + try:main() + except urllib.error.HTTPError as e:raise SystemExit('Gitea release API returned HTTP '+str(e.code)) diff --git a/tools/smoke_binary.py b/tools/smoke_binary.py new file mode 100644 index 0000000..1f9e5fc --- /dev/null +++ b/tools/smoke_binary.py @@ -0,0 +1,48 @@ +"""Exercise the actual packaged executable against a synthetic loopback API.""" +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +binary=str(Path(sys.argv[1]).resolve()) +token='synthetic_session_'+('x'*40) +seen=[] +class Handler(BaseHTTPRequestHandler): + def log_message(self,*args):pass + def do_POST(self): + self.rfile.read(int(self.headers.get('Content-Length',0))) + if self.path=='/_/auth/login': self.reply({'access_token':token,'token_type':'Bearer','expires_in':3600}) + elif self.path=='/_/auth/logout':self.reply({}) + else:self.send_error(404) + def do_GET(self): + if self.headers.get('Authorization')!='Bearer '+token:self.send_error(401);return + seen.append(self.path) + self.reply({'items':[{'uuid':'synthetic-task','title':'Packaged CLI task','status':'todo'}]}) + def reply(self,value): + self.send_response(200);self.send_header('Content-Type','application/json');self.end_headers();self.wfile.write(json.dumps(value).encode()) + +server=ThreadingHTTPServer(('127.0.0.1',0),Handler) +thread=threading.Thread(target=server.serve_forever,daemon=True);thread.start() +try: + with tempfile.TemporaryDirectory() as root: + env={**os.environ,'XDG_CONFIG_HOME':root} + def run(*args,stdin='',success=True): + p=subprocess.run([binary,*args],input=stdin,text=True,capture_output=True,env=env,timeout=15) + if token in p.stdout+p.stderr:raise AssertionError('Credential leaked') + if (p.returncode==0)!=success:raise AssertionError('Packaged command failed: '+str(args)+' '+p.stderr) + return p.stdout + run('configure','--origin',f'http://127.0.0.1:{server.server_port}','--username','synthetic') + run('login',stdin='synthetic-password\n') + if 'Packaged CLI task' not in run('task','list'):raise AssertionError('Task missing') + run('shell',stdin='pwd\nexit\n') + profile=Path(root)/'pages-cli/sessions/default.json' + if profile.stat().st_mode&0o077:raise AssertionError('Credential permissions') + profile.chmod(0o644);run('task','list',success=False);profile.chmod(0o600) + run('logout') + if not seen:raise AssertionError('No HTTP request') + print('Packaged CLI: configure/login/task-list/permissions/logout passed') +finally:server.shutdown();server.server_close();thread.join()