Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .github/workflows/hosted-install.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ jobs:
# Digests from the v0.1.7 assets published by Release run 41123276320.
ARCHIVE_SHA256: fb13dbd429c1e61f9fb6d8974e3b17792f65b5882e4623a37a335590e000fe13
CHECKSUMS_SHA256: c5b9c6ebb2cf7729fefe29ee3137655e757a01685501374afbd3da094ac614c6
# Reviewed installer: proofline 0421e803, apps/marketing/public/cli/install.sh.
INSTALLER_SHA256: da5e9d49eaa193a9f98d002b799c7b432129ac1f9c746295abf19ca1f613f567
steps:
- run: |
Expand Down
4 changes: 1 addition & 3 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,7 @@ jobs:
test "$(find artifacts -name '*.tar.gz' | wc -l)" -eq 5
(cd artifacts && LC_ALL=C sha256sum proofline-*.tar.gz > SHA256SUMS)
printf '%s\n' "$VERSION" > artifacts/latest
# Creating the draft reserves the GitHub version atomically.
gh release create "v$VERSION" --repo "$GITHUB_REPOSITORY" --target "$GITHUB_SHA" --draft --title "Proofline $VERSION" --generate-notes
python3 scripts/github-assets.py "$VERSION" artifacts
- uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2
with:
subject-path: artifacts/*.tar.gz
Expand All @@ -118,7 +117,6 @@ jobs:
VERSION: ${{ needs.version.outputs.version }}
GH_TOKEN: ${{ github.token }}
run: |
gh release upload "v$VERSION" artifacts/* --repo "$GITHUB_REPOSITORY"
gh release edit "v$VERSION" --repo "$GITHUB_REPOSITORY" --draft=false --latest
for archive in artifacts/*.tar.gz; do
name=$(basename "$archive")
Expand Down
52 changes: 52 additions & 0 deletions scripts/github-assets.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
"""Reserve the version on GitHub and verify or upload each checked release asset."""

import hashlib
import json
import os
import re
import subprocess
import sys
from pathlib import Path


def gh(*args):
return subprocess.check_output(["gh", *args, "--repo", os.environ["GITHUB_REPOSITORY"]], text=True)


def stage(version, directory):
if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", version):
raise ValueError("invalid CLI version")
tag = f"v{version}"
commit = os.environ["GITHUB_SHA"]
# Create first so a concurrent publisher cannot claim the same version.
# A failed create can also mean this run already reserved the release.
subprocess.run(
["gh", "release", "create", tag, "--repo", os.environ["GITHUB_REPOSITORY"],
"--target", commit, "--draft", "--title", f"Proofline {version}", "--notes", f"Proofline CLI {version}."],
check=False, capture_output=True,
)

def read():
release = json.loads(gh("release", "view", tag, "--json", "targetCommitish,assets,isDraft"))
if release["targetCommitish"] != commit:
raise ValueError("GitHub release belongs to a different commit")
return release

release = read()
existing = {asset["name"]: asset["digest"] for asset in release["assets"]}
expected = {
path.name: "sha256:" + hashlib.sha256(path.read_bytes()).hexdigest()
for path in directory.iterdir()
}
if any(expected.get(name) != digest for name, digest in existing.items()):
raise ValueError("GitHub release has an unexpected asset")
for name in sorted(expected.keys() - existing.keys()):
if not release["isDraft"]:
raise ValueError("published GitHub release is missing an asset")
gh("release", "upload", tag, str(directory / name))
if {asset["name"]: asset["digest"] for asset in read()["assets"]} != expected:
raise ValueError("GitHub release asset verification failed")


if __name__ == "__main__":
stage(sys.argv[1], Path(sys.argv[2]))
92 changes: 55 additions & 37 deletions scripts/publish-r2.sh
Original file line number Diff line number Diff line change
Expand Up @@ -30,54 +30,72 @@ for target in $targets; do
done
cmp -s "$temporary/SHA256SUMS" "$dist/SHA256SUMS" || refuse 'SHA256SUMS does not match the five release archives'

origin="https://$CLOUDFLARE_ACCOUNT_ID.r2.cloudflarestorage.com/proofline-cli-releases"
signed() {
printf 'user = "%s:%s"\n' "$access_key" "$secret_key" |
curl --config - --aws-sigv4 'aws:amz:auto:s3' --proto '=https' --tlsv1.2 \
--silent --show-error --connect-timeout 15 --max-time 120 "$@"
}

# Read from the bucket. The installer's edge cache may still hold an older pointer.
read_key() {
signed --dump-header "$temporary/headers" --output "$temporary/remote" \
--write-out '%{http_code}' "$origin/$1"
}

put() {
local key=$1 source=$2 content_type=$3 cache_control=$4 condition=${5:-} digest
local key=$1 source=$2 content_type=$3 cache_control=$4 condition=$5 digest
digest=$(sha256sum "$source" | cut -d ' ' -f 1)
# Object Read & Write tokens support the S3 API only. curl signs the exact
# payload and metadata; credentials stay out of command arguments and logs.
printf 'user = "%s:%s"\n' "$access_key" "$secret_key" |
curl --config - --aws-sigv4 'aws:amz:auto:s3' \
--proto '=https' --tlsv1.2 --fail --silent --show-error \
--connect-timeout 15 --max-time 120 --retry 2 \
--request PUT --upload-file "$source" \
--header "Content-Type: $content_type" \
--header "Cache-Control: $cache_control" \
--header "x-amz-content-sha256: $digest" \
--header "If-None-Match: $condition" \
"https://$CLOUDFLARE_ACCOUNT_ID.r2.cloudflarestorage.com/proofline-cli-releases/$key"
signed --fail --output /dev/null --request PUT --upload-file "$source" \
--header "Content-Type: $content_type" --header "Cache-Control: $cache_control" \
--header "x-amz-content-sha256: $digest" --header "$condition" "$origin/$key"
}

# Old releases predate R2 reservations. Refuse those too, and never replace
# latest with an older version. An unavailable origin is not an empty registry.
status=$(curl --proto '=https' --tlsv1.2 --silent --show-error --location \
--connect-timeout 15 --max-time 30 --output "$temporary/probe" --write-out '%{http_code}' \
"https://proofline.sh/cli/download/$version/SHA256SUMS")
[ "$status" = 404 ] || refuse "version $version is already published or its status is unavailable ($status)"
status=$(curl --proto '=https' --tlsv1.2 --silent --show-error --location \
--connect-timeout 15 --max-time 30 --output "$temporary/latest" --write-out '%{http_code}' \
'https://proofline.sh/cli/latest')
immutable() {
local key=$1 source=$2 content_type=$3 status
status=$(read_key "$key")
case "$status" in
200) cmp -s "$source" "$temporary/remote" || refuse "existing content differs for $key" ;;
404) put "$key" "$source" "$content_type" 'public, max-age=31536000, immutable' 'If-None-Match: *' ;;
*) refuse "could not read $key ($status)" ;;
esac
}

latest=''
status=$(read_key latest)
case "$status" in
200)
latest=$(cat "$temporary/latest")
latest=$(cat "$temporary/remote")
[[ "$latest" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || refuse 'latest is not a version'
[ "$latest" != "$version" ] && [ "$(printf '%s\n%s\n' "$latest" "$version" | sort -V | tail -1)" = "$version" ] \
|| refuse "$version is not newer than $latest"
[ "$(printf '%s\n%s\n' "$latest" "$version" | sort -V | tail -1)" = "$version" ] || refuse "latest is newer than $version"
etag=$(awk 'tolower($1) == "etag:" {gsub(/\r/, "", $2); print $2}' "$temporary/headers")
[[ "$etag" =~ ^\"[a-fA-F0-9-]+\"$ ]] || refuse 'latest has no usable entity tag'
condition="If-Match: $etag"
;;
404) ;;
404) condition='If-None-Match: *' ;;
*) refuse "could not read latest ($status)" ;;
esac

# Reserve the version before any release object is written. A failed upload
# retains the claim, so another run cannot overwrite a partial publication.
printf '{"version":"%s","commit":"%s"}\n' "$version" "${GITHUB_SHA:?missing release commit}" > "$temporary/reservation.json"
put "$version/RELEASE.json" "$temporary/reservation.json" application/json 'public, max-age=31536000, immutable' '*'
immutable='public, max-age=31536000, immutable'
[[ "${GITHUB_SHA:-}" =~ ^[0-9a-f]{40}$ ]] || refuse 'missing release commit'
printf '{"version":"%s","commit":"%s"}\n' "$version" "$GITHUB_SHA" > "$temporary/reservation.json"
status=$(read_key "$version/RELEASE.json")
case "$status" in
200) cmp -s "$temporary/reservation.json" "$temporary/remote" || refuse 'version reserved for a different commit' ;;
404)
status=$(read_key "$version/SHA256SUMS")
[ "$status" = 404 ] && [ "$latest" != "$version" ] || refuse 'version is already published or unavailable'
put "$version/RELEASE.json" "$temporary/reservation.json" application/json 'public, max-age=31536000, immutable' 'If-None-Match: *'
;;
*) refuse "could not read version reservation ($status)" ;;
esac

for target in $targets; do
archive="proofline-$target.tar.gz"
put "$version/$archive" "$dist/$archive" application/gzip "$immutable"
immutable "$version/$archive" "$dist/$archive" application/gzip
done
put "$version/SHA256SUMS" "$dist/SHA256SUMS" 'text/plain; charset=utf-8' "$immutable"
# Installers see the version only after all six release objects exist.
printf '%s\n' "$version" > "$temporary/latest"
put latest "$temporary/latest" 'text/plain; charset=utf-8' 'public, max-age=60'
printf 'cli publish: uploaded CLI %s\n' "$version"
immutable "$version/SHA256SUMS" "$dist/SHA256SUMS" 'text/plain; charset=utf-8'
if [ "$latest" != "$version" ]; then
printf '%s\n' "$version" > "$temporary/latest"
put latest "$temporary/latest" 'text/plain; charset=utf-8' 'public, max-age=60' "$condition"
fi
printf 'cli publish: verified CLI %s\n' "$version"
32 changes: 25 additions & 7 deletions scripts/test_publish_r2.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,17 @@ def setUpClass(cls):

class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
code = cls.probe_status if self.path.endswith("SHA256SUMS") else 200
body = cls.latest.encode() if self.path == "/cli/latest" else b""
body = cls.objects.get(self.path)
if body is not None:
code = 200
elif self.path.endswith("/latest"):
code, body = 200, cls.latest.encode()
else:
code = cls.probe_status if self.path.endswith("/SHA256SUMS") else 404
body = b""
self.send_response(code)
self.send_header("Content-Length", str(len(body)))
self.send_header("ETag", '"' + hashlib.sha256(body).hexdigest() + '"')
self.end_headers()
self.wfile.write(body)

Expand All @@ -55,7 +62,7 @@ def do_PUT(self):
if self.headers.get("If-None-Match") == "*" and self.path in cls.objects:
status = 412
if status == 200:
cls.objects.add(self.path)
cls.objects[self.path] = body
self.send_response(status)
self.send_header("Content-Length", "0")
self.end_headers()
Expand Down Expand Up @@ -92,7 +99,7 @@ def tearDownClass(cls):
def setUp(self):
type(self).requests = []
type(self).reject = None
type(self).objects = set()
type(self).objects = {}
type(self).probe_status = 404
type(self).latest = "0.0.9"
self.dist = self.base / self._testMethodName
Expand Down Expand Up @@ -157,6 +164,18 @@ def test_upload_refusal_keeps_latest_absent(self):
self.assertNotEqual(self.run_publish().returncode, 0)
self.assertEqual(len(self.requests), 3)
self.assertFalse(any(path.endswith("/latest") for path, _, _ in self.requests))
already_uploaded = set(self.objects)
self.requests.clear()
type(self).reject = None
result = self.run_publish()
self.assertEqual(result.returncode, 0, result.stderr)
self.assertFalse(already_uploaded.intersection(path for path, _, _ in self.requests))
self.requests.clear()
self.assertEqual(self.run_publish().returncode, 0)
self.assertEqual(self.requests, [])
self.objects[f"/proofline-cli-releases/0.1.0/proofline-{TARGETS[0]}.tar.gz"] = b"changed"
self.assertNotEqual(self.run_publish().returncode, 0)
self.assertEqual(self.requests, [])

def test_checksum_mismatch_writes_nothing(self):
(self.dist / f"proofline-{TARGETS[-1]}.tar.gz").write_bytes(b"damaged")
Expand All @@ -177,10 +196,9 @@ def test_existing_or_unavailable_release_and_version_regression_refuse(self):
self.assertEqual(self.requests, [])

def test_reserved_version_cannot_overwrite_partial_release(self):
type(self).objects.add("/proofline-cli-releases/0.1.0/RELEASE.json")
self.objects["/proofline-cli-releases/0.1.0/RELEASE.json"] = b"other commit"
self.assertNotEqual(self.run_publish().returncode, 0)
self.assertEqual(len(self.requests), 1)
self.assertEqual(self.requests[0][1]["If-None-Match"], "*")
self.assertEqual(self.requests, [])

def test_invalid_credentials_and_version_write_nothing(self):
self.env["CLI_RELEASE_R2_CREDENTIALS"] = json.dumps({"access_key_id": "invalid", "secret_access_key": SECRET})
Expand Down
Loading