Signed-off-by: selikhov <selikhov@protei-lab.ru>
This commit is contained in:
selikhov committed 2026-10-04 18:07:21 +03:00
1 parent 52cd9e1425
commit 264f12ca9c
19 files changed
+901 -26

No files matched your search

+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env bash
# Build the release Flatpak in the same privileged image as GitHub Actions.
# Requires rootful Docker on a trusted machine. No CI cache/artifact API used.
# Usage: scripts/flatpak-build.sh [out-dir, default dist/flatpak]
set -euo pipefail
cd "$(dirname "$0")/.."
mkdir -p "${1:-dist/flatpak}"
out=$(cd "${1:-dist/flatpak}" && pwd)
tmp=$(mktemp -d "${RUNNER_TEMP:-${TMPDIR:-/tmp}}/voelin-flatpak.XXXXXX")
trap 'rm -rf "$tmp"' EXIT
mkdir "$tmp/source"
# Copy tracked working-tree files only: target/, secrets, and runner state
# must not become a Flatpak source or enter the privileged build container.
git ls-files -z | tar --null -T - -cf - | tar -C "$tmp/source" -xf -
docker run --rm --privileged \
--mount "type=bind,src=$tmp/source,dst=/src" \
--mount "type=bind,src=$out,dst=/out" \
--workdir /src \
ghcr.io/flathub-infra/flatpak-github-actions:freedesktop-25.08 \
bash -euo pipefail -c '
curl -sSfL -o /tmp/flatpak-cargo-generator.py \
https://raw.githubusercontent.com/flatpak/flatpak-builder-tools/41c20aa10819cdb2a4f3ca171758a96d1955c018/cargo/flatpak-cargo-generator.py
python3 -m venv /tmp/venv
/tmp/venv/bin/pip install --quiet "aiohttp>=3.9.5,<4" "tomlkit>=0.13.3,<1" "PyYAML>=6.0.2,<7"
/tmp/venv/bin/python /tmp/flatpak-cargo-generator.py Cargo.lock -o packaging/flatpak/cargo-sources.json
flatpak remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo
xvfb-run -a flatpak-builder --repo=/tmp/repo --state-dir=/tmp/state \
--disable-rofiles-fuse --install-deps-from=flathub --force-clean \
--default-branch=master --arch=x86_64 \
/tmp/build packaging/flatpak/io.github.faumaray.Voelin.yml
flatpak build-bundle --runtime-repo=https://flathub.org/repo/flathub.flatpakrepo \
--arch=x86_64 /tmp/repo /out/voelin.flatpak io.github.faumaray.Voelin master
'
test -s "$out/voelin.flatpak"
printf '%s\n' "$out/voelin.flatpak"
+162
View File
@@ -0,0 +1,162 @@
#!/usr/bin/env bash
# Upload verified packages to a draft only; publication is always manual.
set +x
set -euo pipefail
if (( $# > 1 )); then
echo "usage: $0 [asset-directory]" >&2
exit 1
fi
release_tmp=$(mktemp -d /tmp/gitea-release.XXXXXXXX)
trap 'rm -rf -- "$release_tmp"' EXIT
trap 'exit 130' INT
trap 'exit 143' HUP TERM
python3 - "${1:-dist/release}" "$release_tmp" <<'PY'
import hashlib
import json
import os
from pathlib import Path
import re
import subprocess
import sys
import tempfile
from urllib.parse import quote, urlsplit
def fail(message):
raise ValueError(message)
def positive_id(value):
if type(value) is not int or value <= 0:
fail("API returned an invalid id")
return value
def main():
token = os.environ.get("GITEA_RELEASE_TOKEN", "")
if not token or any(ord(c) < 33 or ord(c) > 126 for c in token):
fail("GITEA_RELEASE_TOKEN is missing or invalid")
server = os.environ.get("GITHUB_SERVER_URL", "")
parsed = urlsplit(server)
if (parsed.scheme != "https" or not parsed.hostname or parsed.username
or parsed.password or parsed.query or parsed.fragment
or any(c.isspace() for c in server)):
fail("GITHUB_SERVER_URL must be an HTTPS server URL without credentials or query")
repo = os.environ.get("GITHUB_REPOSITORY", "").split("/")
if len(repo) != 2 or any(not part or part in (".", "..") for part in repo):
fail("GITHUB_REPOSITORY must be owner/repo")
ref = os.environ.get("GITHUB_REF", "")
if not ref.startswith("refs/tags/v") or len(ref) <= len("refs/tags/v"):
fail("GITHUB_REF must be a v* tag")
tag = ref[len("refs/tags/"):]
sha = os.environ.get("GITHUB_SHA", "")
if not re.fullmatch(r"[0-9a-fA-F]{40}|[0-9a-fA-F]{64}", sha):
fail("GITHUB_SHA must be a full commit id")
directory = Path(sys.argv[1])
if directory.is_symlink() or not directory.is_dir():
fail("asset directory must be a non-symlink directory")
files = sorted(directory.iterdir())
if any(p.is_symlink() or not p.is_file() for p in files):
fail("asset directory must contain only regular non-symlink files")
names = {p.name for p in files}
if "SHA256SUMS" not in names or len(names) < 2:
fail("SHA256SUMS and at least one package are required")
# Exclude control characters and sha256sum's escaped filename syntax.
if any(any(ord(c) < 32 or c == "\\" for c in name) for name in names):
fail("unsupported control character or backslash in asset name")
expected = {}
for line in (directory / "SHA256SUMS").read_text().splitlines():
match = re.fullmatch(r"([0-9a-fA-F]{64}) [ *](.+)", line)
if not match or match[2] in expected:
fail("invalid or duplicate SHA256SUMS entry")
expected[match[2]] = match[1].lower()
if set(expected) != names - {"SHA256SUMS"}:
fail("SHA256SUMS must describe exactly all package files")
for name, digest in expected.items():
with (directory / name).open("rb") as package:
actual = hashlib.file_digest(package, "sha256").hexdigest()
if actual != digest:
fail("package checksum mismatch")
base = server.rstrip("/") + "/api/v1/repos/" + "/".join(quote(p, safe="") for p in repo) + "/releases"
# /tmp is outside the checkout/build context; mkdtemp and the header are private.
with tempfile.TemporaryDirectory(prefix="gitea-release-", dir=sys.argv[2]) as temp:
header = Path(temp) / "headers"
fd = os.open(header, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, "w") as output:
output.write("Authorization: token " + token + "\n")
environment = os.environ.copy()
environment.pop("GITEA_RELEASE_TOKEN", None)
not_found = object()
def diagnostic(text):
# Redact before truncation and again after stripping control characters.
text = text.replace(token, "[REDACTED]")
text = "".join(c for c in text if c.isprintable())
return text.replace(token, "[REDACTED]")[:512]
def request(method, url, *, payload=None, package=None, missing=False):
response = Path(temp) / "response"
args = ["curl", "--disable", "--silent", "--show-error", "--proto", "=https",
"--connect-timeout", "30", "--max-time", "1800",
"--request", method, "--header", "@" + str(header),
"--output", str(response), "--write-out", "%{http_code}", url]
if payload is not None:
body = Path(temp) / "request.json"
body.write_text(json.dumps(payload))
args += ["--header", "Content-Type: application/json", "--data-binary", "@" + str(body)]
if package is not None:
# Quoted curl form path protects commas/semicolons/quotes in paths.
path = str(package.resolve()).replace("\\", "\\\\").replace('"', '\\"')
args += ["--form", 'attachment=@"' + path + '"']
result = subprocess.run(args, capture_output=True, text=True, env=environment)
if result.returncode:
fail(f"Gitea API {method} transport failed (curl {result.returncode}): "
+ diagnostic(result.stderr))
if missing and result.stdout == "404":
return not_found
if not re.fullmatch(r"2[0-9]{2}", result.stdout):
message = ""
try:
with response.open() as output:
error = json.loads(output.read(8192))
if isinstance(error, dict) and isinstance(error.get("message"), str):
message = ": " + diagnostic(error["message"])
except (OSError, ValueError):
pass
fail(f"Gitea API {method} failed (HTTP {diagnostic(result.stdout)})" + message)
return json.loads(response.read_text()) if response.stat().st_size else None
release = request("GET", base + "/tags/" + quote(tag, safe=""), missing=True)
if release is not_found:
release = request("POST", base, payload={"tag_name": tag, "target_commitish": sha,
"name": tag, "draft": True, "prerelease": False,
"body": "Packages and SHA256 checksums. Review before publishing."})
if not isinstance(release, dict) or release.get("tag_name") != tag or release.get("draft") is not True:
fail("refusing to modify a published or mismatched release")
assets_url = base + "/" + str(positive_id(release.get("id"))) + "/assets"
assets = request("GET", assets_url)
if not isinstance(assets, list):
fail("API returned an invalid asset list")
for asset in assets:
if not isinstance(asset, dict) or not isinstance(asset.get("name"), str):
fail("API returned an invalid asset")
positive_id(asset.get("id"))
for package in files:
for asset in assets:
if asset["name"] == package.name:
request("DELETE", assets_url + "/" + str(asset["id"]))
uploaded = request("POST", assets_url + "?name=" + quote(package.name, safe=""), package=package)
if not isinstance(uploaded, dict):
fail("API returned an invalid uploaded asset")
positive_id(uploaded.get("id"))
print("Packages uploaded to draft release " + tag + "; publication remains manual.")
try:
main()
except (ValueError, OSError, KeyError, TypeError) as error:
print("gitea-release: " + str(error), file=sys.stderr)
sys.exit(1)
PY
+221
View File
@@ -0,0 +1,221 @@
#!/usr/bin/env python3
"""Offline regression tests of the real release script using a curl fixture."""
import hashlib
import json
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
SCRIPT = Path(__file__).with_name("gitea-release.sh").resolve()
FAKE_CURL = r'''#!/usr/bin/env python3
import json, os, pathlib, stat, sys
args = sys.argv[1:]
def option(name):
return args[args.index(name) + 1]
header = pathlib.Path(option('--header')[1:])
assert stat.S_IMODE(header.stat().st_mode) == 0o600
assert header.read_text() == 'Authorization: token fixture-secret\n'
assert 'GITEA_RELEASE_TOKEN' not in os.environ
assert not any('fixture-secret' in arg for arg in args)
assert '--location' not in args and '-L' not in args
assert args[0] == '--disable'
method = option('--request')
url = args[args.index('--write-out') + 2]
record = {'method': method, 'url': url, 'header': str(header)}
if '--data-binary' in args:
record['payload'] = json.loads(pathlib.Path(option('--data-binary')[1:]).read_text())
if '--form' in args:
record['form'] = option('--form')
with open(os.environ['SPY'], 'a') as spy:
spy.write(json.dumps(record) + '\n')
mode = os.environ.get('MODE', 'create')
if mode == 'transport-fail':
sys.stderr.write('curl: (60) TLS certificate failed: fixture-secret\n\x1b' + 'x' * 1000)
sys.exit(60)
status, body = '200', None
release = {'id': 7, 'tag_name': os.environ['GITHUB_REF'][10:], 'draft': mode != 'published'}
if mode == 'mismatched': release['tag_name'] = 'v-other'
if mode == 'invalid-release-id': release['id'] = True
if method == 'GET' and '/tags/' in url:
status, body = ('404', {}) if mode == 'create' else ('200', release)
if mode in ('null-lookup', 'empty-lookup'): body = None
if mode == 'http-error':
status, body = '403', {'message': 'Access denied: fixture-secret\n\x1b' + 'y' * 1000}
elif method == 'POST' and url.endswith('/releases'):
status, body = '201', release
elif method == 'GET' and url.endswith('/assets'):
body = [{'id': 9, 'name': 'package +#.zip'}, {'id': 10, 'name': 'unrelated.zip'}]
if mode == 'invalid-id': body[0]['id'] = '../bad'
elif method == 'DELETE':
status = '500' if mode == 'delete-fail' else '204'
elif method == 'POST' and '/assets?' in url:
status, body = ('500', {}) if mode == 'upload-fail' else ('201', {'id': 11})
else:
raise AssertionError(record)
pathlib.Path(option('--output')).write_text(json.dumps(body) if body is not None or mode == 'null-lookup' else '')
sys.stdout.write(status)
'''
class ReleaseTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.assets = self.root / "assets"
self.assets.mkdir()
self.package = self.assets / "package +#.zip"
self.package.write_bytes(b"package")
self.checksums()
self.bin = self.root / "bin"
self.bin.mkdir()
curl = self.bin / "curl"
curl.write_text(FAKE_CURL)
curl.chmod(0o755)
self.spy = self.root / "spy"
self.env = dict(os.environ, PATH=str(self.bin) + os.pathsep + os.environ['PATH'],
SPY=str(self.spy), MODE="create", GITEA_RELEASE_TOKEN="fixture-secret",
GITHUB_SERVER_URL="https://git.faumaray.ru", GITHUB_REPOSITORY="owner/repo",
GITHUB_REF="refs/tags/v1.0+test", GITHUB_SHA="a" * 40)
def checksums(self):
(self.assets / "SHA256SUMS").write_text(
hashlib.sha256(self.package.read_bytes()).hexdigest() + " " + self.package.name + "\n")
def run_script(self, success=True, pre_api=False):
result = subprocess.run(["bash", "-x", str(SCRIPT), str(self.assets)],
env=self.env, text=True, capture_output=True)
self.last_result = result
self.assertEqual(result.returncode == 0, success, result.stderr)
self.assertNotIn("fixture-secret", result.stdout + result.stderr)
calls = [json.loads(line) for line in self.spy.read_text().splitlines()] if self.spy.exists() else []
if pre_api:
self.assertEqual(calls, [])
for call in calls:
self.assertFalse(Path(call['header']).exists(), "credential file leaked")
self.assertNotEqual(call['method'], 'PATCH', "must never publish")
return calls
def test_create_draft_and_encoded_upload(self):
calls = self.run_script()
create = next(c for c in calls if 'payload' in c)
self.assertTrue(create['payload']['draft'])
self.assertEqual(create['payload']['target_commitish'], 'a' * 40)
self.assertTrue(calls[0]['url'].endswith('/tags/v1.0%2Btest'))
self.assertTrue(any(c['url'].endswith('?name=package%20%2B%23.zip') for c in calls))
self.assertEqual(len([c for c in calls if 'form' in c]), 2)
def test_invalid_successful_lookup_never_creates_release(self):
for mode in ('null-lookup', 'empty-lookup'):
with self.subTest(mode=mode):
self.spy.unlink(missing_ok=True)
self.env['MODE'] = mode
calls = self.run_script(False)
self.assertEqual([c['method'] for c in calls], ['GET'])
def test_transport_error_is_bounded_and_redacted(self):
self.env['MODE'] = 'transport-fail'
calls = self.run_script(False)
self.assertEqual([c['method'] for c in calls], ['GET'])
stderr = self.last_result.stderr
self.assertIn('GET transport failed (curl 60)', stderr)
self.assertIn('TLS certificate failed: [REDACTED]', stderr)
self.assertNotIn('\x1b', stderr)
self.assertLess(len(stderr), 650)
def test_http_error_is_bounded_and_redacted(self):
self.env['MODE'] = 'http-error'
calls = self.run_script(False)
self.assertEqual([c['method'] for c in calls], ['GET'])
stderr = self.last_result.stderr
self.assertIn('GET failed (HTTP 403)', stderr)
self.assertIn('Access denied: [REDACTED]', stderr)
self.assertNotIn('\x1b', stderr)
self.assertLess(len(stderr), 650)
def test_retry_replaces_only_matching_assets(self):
self.env['MODE'] = 'draft'
calls = self.run_script()
self.assertFalse(any('payload' in c for c in calls))
self.assertEqual([c['url'].split('/')[-1] for c in calls if c['method'] == 'DELETE'], ['9'])
def test_published_release_is_untouched(self):
self.env['MODE'] = 'published'
calls = self.run_script(False)
self.assertEqual([c['method'] for c in calls], ['GET'])
def test_mismatched_release_is_untouched(self):
self.env['MODE'] = 'mismatched'
calls = self.run_script(False)
self.assertEqual([c['method'] for c in calls], ['GET'])
def test_invalid_release_id_is_untouched(self):
self.env['MODE'] = 'invalid-release-id'
calls = self.run_script(False)
self.assertEqual([c['method'] for c in calls], ['GET'])
def test_form_path_and_url_encoding(self):
renamed = self.package.with_name('quote";,+#.zip')
self.package.rename(renamed)
self.package = renamed
self.checksums()
self.env['GITHUB_REF'] = 'refs/tags/v1/preview'
calls = self.run_script()
self.assertTrue(calls[0]['url'].endswith('/tags/v1%2Fpreview'))
upload = next(c for c in calls if c['url'].endswith('?name=quote%22%3B%2C%2B%23.zip'))
self.assertIn('quote\\";,+#.zip', upload['form'])
self.assertTrue(upload['form'].endswith('"'))
def test_invalid_environment_before_api(self):
for key, value in [('GITEA_RELEASE_TOKEN', ''), ('GITHUB_REF', 'refs/heads/main'),
('GITHUB_SERVER_URL', 'http://git.faumaray.ru'),
('GITHUB_SERVER_URL', 'https://user:pass@git.faumaray.ru'),
('GITHUB_SERVER_URL', 'https://git.faumaray.ru?query'),
('GITHUB_REPOSITORY', '../repo'), ('GITHUB_SHA', 'main')]:
with self.subTest(key=key, value=value):
old = self.env[key]
self.env[key] = value
self.run_script(False, pre_api=True)
self.env[key] = old
def test_checksum_failure_before_api(self):
self.package.write_bytes(b'corrupted')
self.run_script(False, pre_api=True)
def test_stale_file_before_api(self):
(self.assets / 'stale.zip').write_bytes(b'stale')
self.run_script(False, pre_api=True)
def test_directory_and_symlink_before_api(self):
extra = self.assets / 'extra'
extra.mkdir()
self.run_script(False, pre_api=True)
extra.rmdir()
extra.symlink_to(self.package)
self.run_script(False, pre_api=True)
def test_missing_manifest_before_api(self):
(self.assets / 'SHA256SUMS').unlink()
self.run_script(False, pre_api=True)
def test_upload_failure_stays_draft_and_cleans_token(self):
self.env['MODE'] = 'upload-fail'
calls = self.run_script(False)
self.assertEqual(len([c for c in calls if 'form' in c]), 1)
def test_delete_failure_stops_before_replacement(self):
self.env['MODE'] = 'delete-fail'
calls = self.run_script(False)
self.assertEqual(calls[-1]['method'], 'DELETE')
self.assertFalse(any('package%20' in c['url'] for c in calls))
def test_invalid_api_id_stops_before_mutation(self):
self.env['MODE'] = 'invalid-id'
calls = self.run_script(False)
self.assertTrue(all(c['method'] == 'GET' for c in calls))
if __name__ == '__main__':
unittest.main()