forked from theupdateframework/python-tuf
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathverify_release
More file actions
Latest commit
executable file
·248 lines (200 loc) · 8.68 KB
/
Copy pathverify_release
File metadata and controls
executable file
·248 lines (200 loc) · 8.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
#!/usr/bin/env python
# Copyright 2022, TUF contributors
# SPDX-License-Identifier: MIT OR Apache-2.0
"""verify_release - verify that published release matches a locally built one
Builds a release from current commit and verifies that the release artifacts
on GitHub and PyPI match the built release artifacts.
"""
importargparse
importjson
importos
importsubprocess
importsys
fromfilecmpimportcmp
fromtempfileimportTemporaryDirectory
try:
importbuildas_# type: ignore
importrequests
exceptImportError:
print("Error: verify_release requires modules 'requests' and 'build':")
print(" pip install requests build")
sys.exit(1)
# Project variables
# Note that only these project artifacts are supported:
# [f"{PYPI_PROJECT}-{VER}-none-any.whl", f"{PYPI_PROJECT}-{VER}.tar.gz"]
GITHUB_ORG="theupdateframework"
GITHUB_PROJECT="python-tuf"
PYPI_PROJECT="tuf"
HTTP_TIMEOUT=5
defbuild(build_dir: str) ->str:
"""Build release locally. Return version as string"""
orig_dir=os.path.dirname(os.path.abspath(__file__))
withTemporaryDirectory() assrc_dir:
# fresh git clone: this prevents uncommitted files from affecting build
git_cmd= ["git", "clone", "--quiet", orig_dir, src_dir]
subprocess.run(git_cmd, stdout=subprocess.DEVNULL, check=True)
build_cmd= ["python3", "-m", "build", "--outdir", build_dir, src_dir]
subprocess.run(build_cmd, stdout=subprocess.DEVNULL, check=True)
build_version=None
forfilenameinos.listdir(build_dir):
prefix, postfix=f"{PYPI_PROJECT}-", ".tar.gz"
iffilename.startswith(prefix) andfilename.endswith(postfix):
build_version=filename[len(prefix) : -len(postfix)]
assertbuild_version
returnbuild_version
defget_git_version() ->str:
"""Return version string from git describe"""
cmd= ["git", "describe"]
process=subprocess.run(cmd, text=True, capture_output=True, check=True)
assertprocess.stdout.startswith("v") andprocess.stdout.endswith("\n")
returnprocess.stdout[1:-1]
defget_github_version() ->str:
"""Return version string of latest GitHub release"""
release_json=f"https://api.github.com/repos/{GITHUB_ORG}/{GITHUB_PROJECT}/releases/latest"
releases=json.loads(
requests.get(release_json, timeout=HTTP_TIMEOUT).content
)
returnreleases["tag_name"][1:]
defget_pypi_pip_version() ->str:
"""Return latest version string available on PyPI according to pip"""
# pip can't tell us what the newest available version is... So we download
# newest tarball and figure out the version from the filename
withTemporaryDirectory() aspypi_dir:
cmd= ["pip", "download", "--no-deps", "--dest", pypi_dir]
source_download=cmd+ ["--no-binary", PYPI_PROJECT, PYPI_PROJECT]
subprocess.run(source_download, stdout=subprocess.DEVNULL, check=True)
forfilenameinos.listdir(pypi_dir):
prefix, postfix=f"{PYPI_PROJECT}-", ".tar.gz"
iffilename.startswith(prefix) andfilename.endswith(postfix):
returnfilename[len(prefix) : -len(postfix)]
assertFalse
defverify_github_release(version: str, compare_dir: str) ->bool:
"""Verify that given GitHub version artifacts match expected artifacts"""
base_url= (
f"https://github.com/{GITHUB_ORG}/{GITHUB_PROJECT}/releases/download"
)
tar=f"{PYPI_PROJECT}-{version}.tar.gz"
wheel=f"{PYPI_PROJECT}-{version}-py3-none-any.whl"
withTemporaryDirectory() asgithub_dir:
forfilenamein [tar, wheel]:
url=f"{base_url}/v{version}/{filename}"
response=requests.get(url, stream=True, timeout=HTTP_TIMEOUT)
withopen(os.path.join(github_dir, filename), "wb") asf:
fordatainresponse.iter_content():
f.write(data)
returncmp(
os.path.join(github_dir, tar),
os.path.join(compare_dir, tar),
shallow=False,
) andcmp(
os.path.join(github_dir, wheel),
os.path.join(compare_dir, wheel),
shallow=False,
)
defverify_pypi_release(version: str, compare_dir: str) ->bool:
"""Verify that given PyPI version artifacts match expected artifacts"""
tar=f"{PYPI_PROJECT}-{version}.tar.gz"
wheel=f"{PYPI_PROJECT}-{version}-py3-none-any.whl"
withTemporaryDirectory() aspypi_dir:
cmd= ["pip", "download", "--no-deps", "--dest", pypi_dir]
target=f"{PYPI_PROJECT}=={version}"
binary_download=cmd+ [target]
source_download=cmd+ ["--no-binary", PYPI_PROJECT, target]
subprocess.run(binary_download, stdout=subprocess.DEVNULL, check=True)
subprocess.run(source_download, stdout=subprocess.DEVNULL, check=True)
returncmp(
os.path.join(pypi_dir, wheel),
os.path.join(compare_dir, wheel),
shallow=False,
) andcmp(
os.path.join(pypi_dir, tar),
os.path.join(compare_dir, tar),
shallow=False,
)
defsign_release_artifacts(
version: str, build_dir: str, key_id: str=None
) ->None:
"""Sign built release artifacts with gpg and write signature files to cwd"""
sdist=f"{PYPI_PROJECT}-{version}.tar.gz"
wheel=f"{PYPI_PROJECT}-{version}-py3-none-any.whl"
cmd= ["gpg", "--detach-sign", "--armor"]
ifkey_idisnotNone:
cmd+= ["--local-user", key_id]
forfilenamein [sdist, wheel]:
artifact_path=os.path.join(build_dir, filename)
signature_path=f"{filename}.asc"
subprocess.run(
cmd+ ["--output", signature_path, artifact_path], check=True
)
assertos.path.exists(signature_path)
deffinished(s: str) ->None:
# clear line
sys.stdout.write("\033[K")
print(f"* {s}")
defprogress(s: str) ->None:
# clear line
sys.stdout.write("\033[K")
# carriage return but no newline: next print will overwrite this one
print(f" {s}...", end="\r", flush=True)
defmain() ->int:
parser=argparse.ArgumentParser()
parser.add_argument(
"--skip-pypi",
action="store_true",
dest="skip_pypi",
help="Skip PyPI release check.",
)
parser.add_argument(
"--sign",
nargs="?",
const=True,
metavar="<key id>",
dest="sign",
help="Sign release artifacts with 'gpg'. If no <key id> is passed, the default "
"signing key is used. Resulting '*.asc' files are written to CWD.",
)
args=parser.parse_args()
success=True
withTemporaryDirectory() asbuild_dir:
progress("Building release")
build_version=build(build_dir)
finished(f"Built release {build_version}")
git_version=get_git_version()
assertgit_version.startswith(build_version)
ifgit_version!=build_version:
finished(f"WARNING: Git describes version as {git_version}")
progress("Checking GitHub latest version")
github_version=get_github_version()
ifgithub_version!=build_version:
finished(f"WARNING: GitHub latest version is {github_version}")
ifnotargs.skip_pypi:
progress("Checking PyPI latest version")
pypi_version=get_pypi_pip_version()
ifpypi_version!=build_version:
finished(f"WARNING: PyPI latest version is {pypi_version}")
progress("Downloading release from PyPI")
ifnotverify_pypi_release(build_version, build_dir):
# This is expected while build is not reproducible
finished("ERROR: PyPI artifacts do not match built release")
success=False
else:
finished("PyPI artifacts match the built release")
progress("Downloading release from GitHub")
ifnotverify_github_release(build_version, build_dir):
# This is expected while build is not reproducible
finished("ERROR: GitHub artifacts do not match built release")
success=False
else:
finished("GitHub artifacts match the built release")
# NOTE: 'gpg' might prompt for password or ask if it should override files...
ifargs.sign:
progress("Signing built release with gpg")
ifsuccess:
key_id=args.signifargs.signisnotTrueelseNone
sign_release_artifacts(build_version, build_dir, key_id)
finished("Created signatures in cwd (see '*.asc' files)")
else:
finished("WARNING: Skipped signing of non-matching artifacts")
return0ifsuccesselse1
if__name__=="__main__":
sys.exit(main())