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
92 changes: 92 additions & 0 deletions .github/web-build/test_production_verification.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
"""Exercise the deployed-site verification over HTTP with temporary release files."""

import functools
import http.server
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import textwrap
import threading
import unittest
import zipfile


WORKFLOW = Path(__file__).resolve().parents[1] / "workflows/website-deploy.yml"
VERSION = "0.0.25"
SOURCE = "a" * 40
NOTEBOOK_PAGES = (
"html/_node.toml",
"cmgfm/_node.toml",
"html/00-start/welcome/index.html",
"cmgfm/00-start/welcome/index.md",
)


class QuietHandler(http.server.SimpleHTTPRequestHandler):
def log_message(self, *_args):
pass


def write_site(root):
demo = root / "demo"
demo.mkdir(parents=True)
identity = json.dumps({"source_sha": SOURCE, "version": VERSION})
(root / "release-identity.json").write_text(identity, encoding="utf-8")
(demo / "index.html").write_text('<script src="./notecraft-aa.wasm"></script>', encoding="utf-8")
(demo / "notecraft-aa.wasm").write_bytes(b"\0asm" + VERSION.encode())
with zipfile.ZipFile(demo / "welcome-notebook.zip", "w") as archive:
for name in NOTEBOOK_PAGES:
archive.writestr(zipfile.ZipInfo(name), f"Welcome to NoteCraft (Ver {VERSION})")


class ProductionVerification(unittest.TestCase):
def test_exact_source_and_bytes_are_required(self):
script = WORKFLOW.read_text(encoding="utf-8").split("python3 - <<'PY'\n", 1)[1]
verifier = textwrap.dedent(script.rsplit("\n PY", 1)[0])
with tempfile.TemporaryDirectory() as temp:
workspace = Path(temp)
live = workspace / "live"
write_site(workspace / "website")
write_site(live)
handler = functools.partial(QuietHandler, directory=live)
with http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler) as server:
worker = threading.Thread(target=server.serve_forever)
worker.start()
try:
base = f"http://127.0.0.1:{server.server_port}"
verifier = verifier.replace("https://notecraft.cloud", base)
verifier = verifier.replace("range(1, 13)", "range(1, 2)").replace("time.sleep(10)", "time.sleep(0)")
env = dict(os.environ, GITHUB_WORKSPACE=str(workspace), NOTECRAFT_VERSION=VERSION, VERIFY_QUERY=SOURCE)
self.verify(verifier, env)
changes = (
("release-identity.json", json.dumps({"source_sha": "b" * 40, "version": VERSION}).encode(), "source commit"),
("demo/notecraft-aa.wasm", b"\0asm different bytes " + VERSION.encode(), "live WASM digest"),
("demo/welcome-notebook.zip", b"different bytes", "notebook digest"),
)
for relative, replacement, error in changes:
with self.subTest(relative=relative):
file = live / relative
original = file.read_bytes()
file.write_bytes(replacement)
try:
self.verify(verifier, env, error)
finally:
file.write_bytes(original)
finally:
server.shutdown()
worker.join()

def verify(self, verifier, env, error=None):
run = subprocess.run([sys.executable, "-c", verifier], env=env, capture_output=True, text=True, timeout=15)
if error is None:
self.assertEqual(run.returncode, 0, run.stderr)
else:
self.assertEqual(run.returncode, 1, run.stderr)
self.assertIn(error, run.stderr)


if __name__ == "__main__":
unittest.main()
59 changes: 52 additions & 7 deletions .github/workflows/website-deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,38 @@ jobs:
test -f "$GITHUB_WORKSPACE/website/index.html"
test -f "$GITHUB_WORKSPACE/website/demo/index.html"
test -f "$GITHUB_WORKSPACE/website/demo/welcome-notebook.zip"
jq -e --arg sha "$SOURCE_SHA" --arg version "$NOTECRAFT_VERSION" \
'.source_sha == $sha and .version == $version' "$GITHUB_WORKSPACE/website/release-identity.json" > /dev/null

- uses: Azure/static-web-apps-deploy@v1
- name: Require a current production deployment
env:
GH_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
SOURCE_SHA: ${{ inputs.source-sha }}
run: |
set -euo pipefail
current="$RUNNER_TEMP/deployed-release-identity.json"
url="https://notecraft.cloud/release-identity.json?deploy-check=$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT"
code=$(curl --silent --show-error --retry 2 --max-time 20 -H 'Cache-Control: no-cache' \
--output "$current" --write-out '%{http_code}' "$url")
case "$code" in
404) echo "Production has no deployment identity yet."; exit 0 ;;
200) ;;
*) echo "::error::Cannot verify the current production deployment (HTTP $code)."; exit 1 ;;
esac
deployed=$(jq -er '.source_sha | strings | select(test("^[0-9a-f]{40}$"))' "$current")
if [[ "$deployed" == "$SOURCE_SHA" ]]; then
echo "Redeploying the same source commit."
exit 0
fi
# The live commit is the comparison head. It must be behind the candidate.
relation=$(gh api "repos/$REPO/compare/$SOURCE_SHA...$deployed?per_page=1" --jq .status)
if [[ "$relation" != behind ]]; then
echo "::error::Production already serves $deployed. Refusing candidate $SOURCE_SHA ($relation)."
exit 1
fi

- uses: Azure/static-web-apps-deploy@1a947af9992250f3bc2e68ad0754c0b0c11566c9 # v1
with:
azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN }}
repo_token: ${{ github.token }}
Expand All @@ -71,13 +101,16 @@ jobs:
output_location: ""
skip_app_build: true

- name: Verify deployed production demo version
- name: Verify production source, WASM and notebook bytes
env:
NOTECRAFT_VERSION: ${{ inputs.version }}
VERIFY_QUERY: ${{ inputs.source-sha }}
run: |
python3 - <<'PY'
import hashlib
import json
import os
from pathlib import Path
import re
import sys
import time
Expand All @@ -89,23 +122,35 @@ jobs:

base = "https://notecraft.cloud/demo/"
version = os.environ["NOTECRAFT_VERSION"].encode()
query = "?release-check=" + os.environ["VERIFY_QUERY"]
source = os.environ["VERIFY_QUERY"]
query = "?release-check=" + source
site = Path(os.environ["GITHUB_WORKSPACE"]) / "website"
expected_notebook = hashlib.sha256((site / "demo" / "welcome-notebook.zip").read_bytes()).digest()
last_error = "no attempt made"
for attempt in range(1, 13):
try:
with urlopen(urljoin(base, "../release-identity.json") + query, timeout=30) as response:
identity = json.load(response)
if identity != {"source_sha": source, "version": version.decode()}:
raise RuntimeError(f"live site does not report source commit {source}")
with urlopen(base + query, timeout=30) as response:
html = response.read().decode("utf-8")
match = re.search(r"['\"](\./[^'\"]+\.wasm)['\"]", html)
match = re.search(r"['\"](\./[A-Za-z0-9_.-]+\.wasm)['\"]", html)
if not match:
raise RuntimeError("deployed demo index does not reference a WASM file")
wasm_url = urljoin(base, match.group(1)) + query
with urlopen(wasm_url, timeout=60) as response:
wasm = response.read()
built_wasm = site / "demo" / match.group(1)[2:]
if not built_wasm.is_file() or hashlib.sha256(wasm).digest() != hashlib.sha256(built_wasm.read_bytes()).digest():
raise RuntimeError("live WASM digest does not match the uploaded site")
if version not in wasm:
last_error = f"live WASM does not contain NoteCraft {version.decode()}"
raise RuntimeError(last_error)
with urlopen(base + "welcome-notebook.zip" + query, timeout=60) as response:
archive_bytes = response.read()
if hashlib.sha256(archive_bytes).digest() != expected_notebook:
raise RuntimeError("live Welcome notebook digest does not match the uploaded site")
with zipfile.ZipFile(BytesIO(archive_bytes)) as notebook:
html = notebook.read("html/00-start/welcome/index.html").decode("utf-8")
cmgfm = notebook.read("cmgfm/00-start/welcome/index.md").decode("utf-8")
Expand All @@ -120,11 +165,11 @@ jobs:
)):
last_error = "live Welcome notebook must contain both generated formats"
raise RuntimeError(last_error)
print(f"Live demo at {wasm_url} and both Welcome notebook formats embed NoteCraft {version.decode()}")
print(f"Live demo at {wasm_url} and both Welcome notebook formats match {source} (NoteCraft {version.decode()})")
sys.exit(0)
except (URLError, TimeoutError, RuntimeError, zipfile.BadZipFile, KeyError, UnicodeDecodeError) as error:
except (URLError, TimeoutError, RuntimeError, zipfile.BadZipFile, KeyError, ValueError) as error:
last_error = str(error)
if attempt < 12:
time.sleep(10)
sys.exit(f"Live demo version verification failed after {attempt} attempts: {last_error}")
sys.exit(f"Live demo verification failed after {attempt} attempts: {last_error}")
PY
4 changes: 4 additions & 0 deletions .github/workflows/website-pipeline.yml
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ jobs:
- name: Build the demo from source (no external build service)
run: |
set -eu
python3 .github/web-build/test_production_verification.py
python3 .github/web-build/apply-web-diff.py . .github/web-build/web.diff
python3 .github/web-build/apply-web-patches.py . .github/web-build/patches.yaml
# The tab-close policy is platform-neutral and tested with real files on the host.
Expand Down Expand Up @@ -195,6 +196,9 @@ jobs:
set -euo pipefail
staging="$RUNNER_TEMP/website-artifact"
mkdir -p "$staging"
printf '%s\n' "$SOURCE_SHA" | grep -Eq '^[0-9a-f]{40}$'
jq -n --arg source_sha "$SOURCE_SHA" --arg version "$NOTECRAFT_VERSION" \
'{source_sha: $source_sha, version: $version}' > website/release-identity.json
tar -C website -cf "$staging/site.tar" .
printf '%s\n' "$SOURCE_SHA" > "$staging/source-sha.txt"
printf '%s\n' "$NOTECRAFT_VERSION" > "$staging/version.txt"
Expand Down
7 changes: 5 additions & 2 deletions docs/releasing.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,8 +128,11 @@ pick, such as a minor version.
Android signing below), then install it on a clean emulator or device before publishing.
5. The Release run deploys the website from the release commit once the draft is created.
It publishes the browser app and the separately version-checked Welcome notebook archive from
`docs/demo/DemoNotebook`. Its production check verifies both the served WASM and notebook
payload. Open the demo in a clean browser session and confirm it opens the official Welcome
`docs/demo/DemoNotebook`. The production deploy shares one concurrency group with the
nightly. It checks the deployed source identity before upload and refuses an older or
divergent candidate. After upload it checks the live source commit and the exact WASM and
notebook digests against the verified site archive. Open the demo in a clean browser
session and confirm it opens the official Welcome
notebook. If the website job fails, rerun it before signoff.
6. Review the draft's complete asset list and rendered notes, then test each platform package on a
clean target. Publish the draft only after the owner approves.
Expand Down
Loading