Skip to content

Commit 50a752f

Browse files
zaniebotzanieb
andauthored
Notarize macOS release binaries during dry-runs (#21494)
Without notarization, Gatekeeper does not trust the signature actually comes from the developer. Here, we add notarization on macOS, which takes a few minutes. The notarization process is in a Python script adopted from Codex's implementation. --------- Co-authored-by: Zanie Blue <[email protected]>
1 parent af8ba86 commit 50a752f

3 files changed

Lines changed: 330 additions & 1 deletion

File tree

‎.github/workflows/sign-release-binaries.yml‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ jobs:
122122
if-no-files-found: error
123123

124124
sign-macos:
125-
name: "sign macos binaries"
125+
name: "sign and notarize macos binaries"
126126
needs: prepare
127127
if: ${{ github.repository == 'astral-sh/uv' && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' }}
128128
runs-on: ubuntu-24.04
@@ -181,6 +181,13 @@ jobs:
181181
uv run scripts/sign-release-macos.py "./unsigned/$target" "./signed/$target"
182182
done < <(jq -r '.[].target' <<< "$TARGETS")
183183
184+
- name: "Notarize signed macOS executables"
185+
shell: bash
186+
env:
187+
AZURE_KEYVAULT_NAME: ${{ secrets.CODESIGN_AZURE_KEYVAULT_NAME }}
188+
APPLE_NOTARIZATION_AKV_KEY_NAME: ${{ secrets.CODESIGN_APPLE_NOTARIZATION_AKV_KEY_NAME }}
189+
run: uv run scripts/notarize-release-macos.py ./signed
190+
184191
- name: "Upload signed executable wheel members"
185192
id: upload
186193
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1

‎scripts/notarize-release-macos.py‎

Lines changed: 229 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,229 @@
1+
# /// script
2+
# requires-python = ">=3.12"
3+
# dependencies = ["boto3"]
4+
#
5+
# [tool.uv]
6+
# no-build = true
7+
# ///
8+
"""Submit signed macOS executables to Apple's notarization service.
9+
10+
Apple scans software for malware and signing issues. On acceptance, it publishes
11+
tickets that Gatekeeper can retrieve online when users run the binaries.
12+
Standalone executables cannot have tickets stapled to them, so uv relies on
13+
that online lookup even when the binaries are distributed in wheels or archives.
14+
15+
This script uploads all signed macOS targets and waits for Apple's result.
16+
It authenticates to the Notary API using an App Store Connect key in Azure Key
17+
Vault, which signs API tokens without exposing the private key.
18+
"""
19+
20+
import argparse
21+
import base64
22+
import hashlib
23+
import json
24+
import os
25+
import subprocess
26+
import sys
27+
import tempfile
28+
import time
29+
import urllib.error
30+
import urllib.request
31+
from dataclasses import dataclass
32+
from pathlib import Path
33+
from zipfile import ZIP_DEFLATED, ZipFile
34+
35+
import boto3
36+
from botocore.config import Config
37+
from botocore.exceptions import BotoCoreError, ClientError
38+
39+
NOTARY_URL = "https://appstoreconnect.apple.com/notary/v2/submissions"
40+
41+
42+
@dataclass(frozen=True, kw_only=True)
43+
class NotarizationKey:
44+
"""An App Store Connect key in Azure Key Vault."""
45+
46+
# Versioned Azure Key Vault URL used for signing. Azure CLI authenticates
47+
# requests using the workflow's existing Azure login.
48+
url: str
49+
key_id: str
50+
issuer: str
51+
52+
53+
def base64url(value: bytes) -> str:
54+
"""Encode a JWT component without padding."""
55+
return base64.urlsafe_b64encode(value).decode("ascii").rstrip("=")
56+
57+
58+
def azure_json(*arguments: str) -> dict:
59+
"""Run an Azure CLI request without printing key-vault details to CI logs."""
60+
try:
61+
result = subprocess.run(
62+
["az", *arguments, "--output", "json", "--only-show-errors"],
63+
check=True,
64+
capture_output=True,
65+
text=True,
66+
)
67+
except subprocess.CalledProcessError:
68+
raise RuntimeError("Azure Key Vault request failed") from None
69+
return json.loads(result.stdout)
70+
71+
72+
def notarization_key() -> NotarizationKey:
73+
"""Resolve the current key version and its Apple key and issuer IDs."""
74+
vault = os.environ["AZURE_KEYVAULT_NAME"]
75+
name = os.environ["APPLE_NOTARIZATION_AKV_KEY_NAME"]
76+
key = azure_json(
77+
"keyvault",
78+
"key",
79+
"show",
80+
"--vault-name",
81+
vault,
82+
"--name",
83+
name,
84+
"--query",
85+
'{url:key.kid,key_id:tags."apple-key-id",issuer:tags."apple-issuer-id"}',
86+
)
87+
return NotarizationKey(url=key["url"], key_id=key["key_id"], issuer=key["issuer"])
88+
89+
90+
def apple_token(key: NotarizationKey) -> str:
91+
"""Sign a short-lived Notary API token without exporting the Apple private key."""
92+
now = int(time.time())
93+
header = {"alg": "ES256", "kid": key.key_id, "typ": "JWT"}
94+
claims = {
95+
"iss": key.issuer,
96+
"iat": now,
97+
"exp": now + 15 * 60,
98+
"aud": "appstoreconnect-v1",
99+
"scope": ["/notary/v2"],
100+
}
101+
signing_input = ".".join(
102+
base64url(json.dumps(value, separators=(",", ":")).encode())
103+
for value in (header, claims)
104+
)
105+
signature = azure_json(
106+
"rest",
107+
"--method",
108+
"post",
109+
"--url",
110+
f"{key.url}/sign?api-version=7.4",
111+
"--resource",
112+
"https://vault.azure.net",
113+
"--headers",
114+
"Content-Type=application/json",
115+
"--body",
116+
json.dumps(
117+
{
118+
"alg": "ES256",
119+
"value": base64url(
120+
hashlib.sha256(signing_input.encode("ascii")).digest()
121+
),
122+
}
123+
),
124+
)
125+
if signature["kid"] != key.url:
126+
raise ValueError("Azure signed with an unexpected notarization key")
127+
if len(base64.urlsafe_b64decode(signature["value"] + "==")) != 64:
128+
raise ValueError("Azure returned an invalid ES256 signature")
129+
return f"{signing_input}.{signature['value']}"
130+
131+
132+
def apple_json(token: str, suffix: str = "", body: dict | None = None) -> dict:
133+
"""Send a JSON request to Apple's notary service."""
134+
request = urllib.request.Request(
135+
NOTARY_URL + suffix,
136+
data=json.dumps(body).encode() if body is not None else None,
137+
headers={
138+
"Authorization": f"Bearer {token}",
139+
"Content-Type": "application/json",
140+
},
141+
method="POST" if body is not None else "GET",
142+
)
143+
try:
144+
with urllib.request.urlopen(request, timeout=60) as response:
145+
return json.load(response)
146+
except urllib.error.HTTPError as error:
147+
raise RuntimeError(f"Apple Notary API returned HTTP {error.code}") from None
148+
149+
150+
def notarize(signed: Path) -> None:
151+
"""Submit all targets' signed binaries together and wait for Apple's acceptance."""
152+
key = notarization_key()
153+
with tempfile.TemporaryDirectory(dir=os.environ.get("RUNNER_TEMP")) as temporary:
154+
# Apple requires a supported container: ZIP, disk image, or signed flat
155+
# installer package. This ZIP is only for submission; distribution uses
156+
# the wheels and release archives assembled later.
157+
# https://developer.apple.com/documentation/security/customizing-the-notarization-workflow
158+
archive = Path(temporary) / "uv-notarization.zip"
159+
with ZipFile(archive, "w", compression=ZIP_DEFLATED) as output:
160+
for target in sorted(signed.iterdir()):
161+
for path in sorted(target.iterdir()):
162+
path.chmod(0o755)
163+
output.write(path, path.relative_to(signed))
164+
165+
# Include upload time in the budget so polling uses an unexpired token.
166+
deadline = time.monotonic() + 600
167+
token = apple_token(key)
168+
submission = apple_json(
169+
token,
170+
body={
171+
"submissionName": archive.name,
172+
"sha256": hashlib.sha256(archive.read_bytes()).hexdigest(),
173+
},
174+
)["data"]
175+
submission_id = submission["id"]
176+
upload = submission["attributes"]
177+
print(f"Uploading Apple notarization submission {submission_id}", flush=True)
178+
s3 = boto3.client(
179+
"s3",
180+
aws_access_key_id=upload["awsAccessKeyId"],
181+
aws_secret_access_key=upload["awsSecretAccessKey"],
182+
aws_session_token=upload["awsSessionToken"],
183+
config=Config(s3={"use_accelerate_endpoint": True}),
184+
)
185+
try:
186+
s3.upload_file(str(archive), upload["bucket"], upload["object"])
187+
except (BotoCoreError, ClientError):
188+
raise RuntimeError("Apple notarization upload failed") from None
189+
190+
while True:
191+
if time.monotonic() >= deadline:
192+
raise TimeoutError(f"Apple notarization timed out: {submission_id}")
193+
status = apple_json(token, f"/{submission_id}")["data"]["attributes"][
194+
"status"
195+
]
196+
if status != "In Progress":
197+
log_url = apple_json(token, f"/{submission_id}/logs")["data"][
198+
"attributes"
199+
]["developerLogUrl"]
200+
if not log_url.startswith("https://"):
201+
raise ValueError("Apple returned an invalid notarization log URL")
202+
with urllib.request.urlopen(log_url, timeout=60) as response:
203+
log = json.load(response)
204+
for issue in log.get("issues") or []:
205+
print(
206+
f"Apple notarization {issue['severity']}: "
207+
f"{issue['path']}: {issue['message']}",
208+
file=sys.stderr,
209+
)
210+
if status != "Accepted":
211+
raise ValueError(f"Apple notarization {status}: {submission_id}")
212+
print(f"Apple notarization accepted: {submission_id}")
213+
return
214+
time.sleep(10)
215+
216+
217+
def main() -> None:
218+
"""Notarize the signed executables from uv's protected release job."""
219+
parser = argparse.ArgumentParser(description=__doc__)
220+
parser.add_argument("signed", type=Path)
221+
args = parser.parse_args()
222+
try:
223+
notarize(args.signed)
224+
except (KeyError, OSError, ValueError, RuntimeError, TimeoutError) as error:
225+
parser.exit(1, f"{error}\n")
226+
227+
228+
if __name__ == "__main__":
229+
main()
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
version = 1
2+
revision = 3
3+
requires-python = ">=3.12"
4+
5+
[options]
6+
exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for backwards compatibility when using relative exclude-newer values.
7+
exclude-newer-span = "P7D"
8+
9+
[options.exclude-newer-package]
10+
astral-dev-toolchain-cargo-shear = "2026-08-27T04:00:00Z"
11+
astral-dev-toolchain-cargo-dist = "2026-08-28T04:00:00Z"
12+
13+
[manifest]
14+
requirements = [{ name = "boto3" }]
15+
16+
[[package]]
17+
name = "boto3"
18+
version = "1.43.83"
19+
source = { registry = "https://pypi.org/simple" }
20+
dependencies = [
21+
{ name = "botocore" },
22+
{ name = "jmespath" },
23+
{ name = "s3transfer" },
24+
]
25+
sdist = { url = "https://files.pythonhosted.org/packages/ec/30/96cf7d324e75cd2c349e2911ae2334d987fb8525d551495a2ef6758c26f3/boto3-1.43.83.tar.gz", hash = "sha256:6413d6e99f716af5d333a732db140e4b3359cac005a1271b11777b6d9ca82194", size = 112686, upload-time = "2026-08-28T19:35:52.273Z" }
26+
wheels = [
27+
{ url = "https://files.pythonhosted.org/packages/f2/4b/843f30dc77324778efa90c4169d503963668760b8d8abdf26a61bd090141/boto3-1.43.83-py3-none-any.whl", hash = "sha256:73a3564f737d4516625964eee709a498fa98ccee6aca929febad2b0b5fbeae1e", size = 140025, upload-time = "2026-08-28T19:35:49.228Z" },
28+
]
29+
30+
[[package]]
31+
name = "botocore"
32+
version = "1.43.83"
33+
source = { registry = "https://pypi.org/simple" }
34+
dependencies = [
35+
{ name = "jmespath" },
36+
{ name = "python-dateutil" },
37+
{ name = "urllib3" },
38+
]
39+
sdist = { url = "https://files.pythonhosted.org/packages/ed/6f/cf16418004c832e6eb9abc6905fa323a3bf96a76ca7f2e97858801a4103e/botocore-1.43.83.tar.gz", hash = "sha256:d9389b3b74400c34219965a2fb858c1d48744718865ee0496fd03bd5b21b943f", size = 16010078, upload-time = "2026-08-28T19:35:46.211Z" }
40+
wheels = [
41+
{ url = "https://files.pythonhosted.org/packages/98/50/332d6713fa09b05ff0882f5d194569fa70d1c8735aca9829b1286fef32ba/botocore-1.43.83-py3-none-any.whl", hash = "sha256:bf75a6cf587c22d968e43e79fe122c39f82deafbe9c3422bc5d3e80b6210fc98", size = 15704489, upload-time = "2026-08-28T19:35:40.603Z" },
42+
]
43+
44+
[[package]]
45+
name = "jmespath"
46+
version = "1.1.0"
47+
source = { registry = "https://pypi.org/simple" }
48+
sdist = { url = "https://files.pythonhosted.org/packages/d3/59/322338183ecda247fb5d1763a6cbe46eff7222eaeebafd9fa65d4bf5cb11/jmespath-1.1.0.tar.gz", hash = "sha256:472c87d80f36026ae83c6ddd0f1d05d4e510134ed462851fd5f754c8c3cbb88d", size = 27377, upload-time = "2026-01-22T16:35:26.279Z" }
49+
wheels = [
50+
{ url = "https://files.pythonhosted.org/packages/14/2f/967ba146e6d58cf6a652da73885f52fc68001525b4197effc174321d70b4/jmespath-1.1.0-py3-none-any.whl", hash = "sha256:a5663118de4908c91729bea0acadca56526eb2698e83de10cd116ae0f4e97c64", size = 20419, upload-time = "2026-01-22T16:35:24.919Z" },
51+
]
52+
53+
[[package]]
54+
name = "python-dateutil"
55+
version = "2.9.0.post0"
56+
source = { registry = "https://pypi.org/simple" }
57+
dependencies = [
58+
{ name = "six" },
59+
]
60+
sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" }
61+
wheels = [
62+
{ url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" },
63+
]
64+
65+
[[package]]
66+
name = "s3transfer"
67+
version = "0.19.2"
68+
source = { registry = "https://pypi.org/simple" }
69+
dependencies = [
70+
{ name = "botocore" },
71+
]
72+
sdist = { url = "https://files.pythonhosted.org/packages/76/43/35e4d8aa320bffe8287fe8f65f578fa2d2db0a64212f0e710dce58267854/s3transfer-0.19.2.tar.gz", hash = "sha256:ba0309fd86be3c27dbf78cdd813c13c5e1df16e5874b99d2535ebbdfb9892993", size = 165592, upload-time = "2026-07-22T19:30:44.432Z" }
73+
wheels = [
74+
{ url = "https://files.pythonhosted.org/packages/bc/e7/5c595c75e9f41a44f30e526eda465ea0b4eec93470e074e4a111b253f13a/s3transfer-0.19.2-py3-none-any.whl", hash = "sha256:d8168eccca828cbb2cd573675333f3bddd254313a9c42494b84c76b539e8ba25", size = 90216, upload-time = "2026-07-22T19:30:43.251Z" },
75+
]
76+
77+
[[package]]
78+
name = "six"
79+
version = "1.17.0"
80+
source = { registry = "https://pypi.org/simple" }
81+
sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" }
82+
wheels = [
83+
{ url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" },
84+
]
85+
86+
[[package]]
87+
name = "urllib3"
88+
version = "2.7.0"
89+
source = { registry = "https://pypi.org/simple" }
90+
sdist = { url = "https://files.pythonhosted.org/packages/53/0c/06f8b233b8fd13b9e5ee11424ef85419ba0d8ba0b3138bf360be2ff56953/urllib3-2.7.0.tar.gz", hash = "sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c", size = 433602, upload-time = "2026-05-07T16:13:18.596Z" }
91+
wheels = [
92+
{ url = "https://files.pythonhosted.org/packages/7f/3e/5db95bcf282c52709639744ca2a8b149baccf648e39c8cc87553df9eae0c/urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897", size = 131087, upload-time = "2026-05-07T16:13:17.151Z" },
93+
]

0 commit comments

Comments
 (0)