Skip to content

Commit 23dc1bd

Browse files
authored
ci: automate Apache release candidate staging (#8347)
* ci: automate Apache release candidate staging * ci: harden release candidate staging * ci: verify trusted release branch identity * ci: require reviewer approval for release environment * ci: close release packaging review gaps
1 parent 169fc03 commit 23dc1bd

10 files changed

Lines changed: 1015 additions & 11 deletions

File tree

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
#!/usr/bin/env python3
2+
# Licensed to the Apache Software Foundation (ASF) under one or more
3+
# contributor license agreements. See the NOTICE file distributed with
4+
# this work for additional information regarding copyright ownership.
5+
# The ASF licenses this file to You under the Apache License, Version 2.0
6+
# (the "License"); you may not use this file except in compliance with
7+
# the License. You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
17+
"""Check the actual Maven archives, not merely the source legal files."""
18+
19+
import argparse
20+
import hashlib
21+
import json
22+
from pathlib import Path, PurePosixPath
23+
import re
24+
import xml.etree.ElementTree as ET
25+
import zipfile
26+
27+
28+
SHADED_ARTIFACTS = (
29+
"shenyu-admin-listener-apollo",
30+
"shenyu-registry-apollo",
31+
"shenyu-spring-boot-starter-sync-data-apollo",
32+
)
33+
34+
35+
def check_jar(path, notice):
36+
with zipfile.ZipFile(path) as jar:
37+
names = jar.namelist()
38+
for name in ("META-INF/LICENSE", "META-INF/NOTICE"):
39+
if names.count(name) != 1:
40+
raise ValueError(f"{path}: expected exactly one {name}")
41+
license_text = jar.read("META-INF/LICENSE").decode("utf-8")
42+
notice_text = jar.read("META-INF/NOTICE").decode("utf-8")
43+
if not all(term in license_text for term in ("Apache License", "Version 2.0", "TERMS AND CONDITIONS")):
44+
raise ValueError(f"{path}: missing project Apache 2.0 license")
45+
if notice.strip() not in notice_text:
46+
raise ValueError(f"{path}: missing project NOTICE attribution")
47+
if "static/index.html" in names:
48+
for name in ("META-INF/licenses/LICENSE-dashboard.txt", "META-INF/licenses/NOTICE-dashboard.txt"):
49+
if name not in names or not jar.read(name).strip():
50+
raise ValueError(f"{path}: bundled dashboard is missing {name}")
51+
if any(path.name.startswith(artifact + "-") for artifact in SHADED_ARTIFACTS) and not path.name.endswith(("-sources.jar", "-javadoc.jar")):
52+
for name in ("META-INF/LICENSE-shaded-dependencies.txt", "META-INF/NOTICE-shaded-dependencies.txt"):
53+
if name not in names:
54+
raise ValueError(f"{path}: missing shaded dependency terms: {name}")
55+
return {"archive": path.name, "project_license": True, "project_notice": True,
56+
"sha512": hashlib.sha512(path.read_bytes()).hexdigest()}
57+
58+
59+
def check_source(path, root):
60+
with zipfile.ZipFile(path) as archive:
61+
names = archive.namelist()
62+
prefix = names[0].split("/")[0] + "/"
63+
for relative in ("LICENSE", "NOTICE", "RELEASE-NOTES.md"):
64+
if archive.read(prefix + relative) != (root / relative).read_bytes():
65+
raise ValueError(f"{path}: source {relative} differs from the release commit")
66+
static = "shenyu-admin/src/main/resources/static/"
67+
html = archive.read(prefix + static + "index.html").decode("utf-8")
68+
references = re.findall(r'(?:src|href)=[\"\']([^\"\']+\.(?:js|css))(?:\?[^\"\']*)?[\"\']', html)
69+
if not references:
70+
raise ValueError(f"{path}: no dashboard JS/CSS references")
71+
for reference in references:
72+
if "://" in reference or reference.startswith("//"):
73+
raise ValueError(f"{path}: unexpected remote dashboard asset: {reference}")
74+
relative = static + reference.removeprefix("./").lstrip("/")
75+
if archive.read(prefix + relative) != (root / relative).read_bytes():
76+
raise ValueError(f"{path}: dashboard asset differs: {reference}")
77+
for name in names:
78+
relative = name.removeprefix(prefix)
79+
parts = PurePosixPath(relative).parts
80+
if "target" in parts or ".git" in parts or relative.startswith("actions/") or relative.endswith((".jar", ".class", ".war")):
81+
raise ValueError(f"{path}: unintended source archive entry: {relative}")
82+
return {"archive": path.name, "project_legal_files": True, "dashboard_assets": references}
83+
84+
85+
def main():
86+
parser = argparse.ArgumentParser(description=__doc__)
87+
parser.add_argument("--repository", type=Path, required=True)
88+
parser.add_argument("--root", type=Path, default=Path.cwd())
89+
args = parser.parse_args()
90+
root = args.root
91+
pom = ET.parse(root / "pom.xml").getroot()
92+
version = pom.findtext("{http://maven.apache.org/POM/4.0.0}version")
93+
repository = args.repository
94+
notice = (root / "NOTICE").read_text()
95+
jars = sorted(repository.glob(f"*/{version}/*.jar"))
96+
if not jars:
97+
raise ValueError(f"No candidate JARs in {repository}")
98+
results = [check_jar(path, notice) for path in jars]
99+
for path in jars:
100+
if not path.name.endswith(("-sources.jar", "-javadoc.jar")):
101+
for classifier in ("sources", "javadoc"):
102+
if not path.with_name(path.stem + f"-{classifier}.jar").exists():
103+
raise ValueError(f"{path}: missing {classifier} attachment")
104+
sources = list(repository.glob(f"*/{version}/*-src.zip")) + list(repository.glob(f"shenyu/{version}/*-source-release.zip"))
105+
if len(sources) != 2:
106+
raise ValueError(f"Expected both source archives, found {len(sources)}")
107+
report = {"version": version, "jars": results, "sources": [check_source(p, root) for p in sources]}
108+
output = root / "target/release-audit"
109+
output.mkdir(parents=True, exist_ok=True)
110+
(output / "project-artifacts.json").write_text(json.dumps(report, indent=2) + "\n")
111+
print(f"Verified project LICENSE/NOTICE in all {len(jars)} Maven JARs and dashboard resources in both source archives")
112+
113+
114+
if __name__ == "__main__":
115+
main()
Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
#!/usr/bin/env python3
2+
# Licensed to the Apache Software Foundation (ASF) under one or more
3+
# contributor license agreements. See the NOTICE file distributed with
4+
# this work for additional information regarding copyright ownership.
5+
# The ASF licenses this file to You under the Apache License, Version 2.0
6+
# (the "License"); you may not use this file except in compliance with
7+
# the License. You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
17+
"""Collect legal resources from the exact assembled distribution JARs."""
18+
19+
import argparse
20+
import hashlib
21+
import io
22+
import json
23+
from pathlib import Path, PurePosixPath
24+
import re
25+
import tarfile
26+
import xml.etree.ElementTree as ET
27+
import zipfile
28+
29+
30+
LEGAL_NAME = re.compile(r"^(license|notice|copyright|copying)(?:[._-].*)?$", re.I)
31+
TEXT_SUFFIXES = {"", ".txt", ".text", ".md", ".html", ".htm", ".rst", ".adoc"}
32+
# Version-specific regressions: names alone cannot establish the applicable license.
33+
LICENSE_DECLARATIONS = {
34+
"jersey-client-3.1.11.jar": ("jersey-client 3.1.11", "EPL 2.0"),
35+
"jersey-common-3.1.11.jar": ("jersey-common 3.1.11", "EPL 2.0"),
36+
"jersey-hk2-3.1.11.jar": ("jersey-hk2 3.1.11", "EPL 2.0"),
37+
"jersey-apache-connector-3.1.11.jar": ("jersey-apache-connector 3.1.11", "EPL 2.0"),
38+
"aspectjweaver-1.9.25.1.jar": ("aspectjweaver 1.9.25.1", "EPL-2.0 AND BSD-3-Clause AND Apache-1.1"),
39+
"osgi-resource-locator-1.0.3.jar": ("osgi-resource-locator 1.0.3", "EPL 2.0 OR GPL 2.0 with Classpath Exception"),
40+
"jakarta.annotation-api-2.1.1.jar": ("jakarta.annotation-api 2.1.1", "EPL 2.0 OR GPL 2.0 with Classpath Exception"),
41+
"lettuce-core-6.6.0.RELEASE.jar": ("lettuce-core 6.6.0.RELEASE", "MIT"),
42+
"jcl-over-slf4j-2.0.17.jar": ("jcl-over-slf4j 2.0.17", "Apache 2.0"),
43+
}
44+
45+
46+
def collect(archive):
47+
jars = []
48+
texts = {}
49+
documents = []
50+
index = ""
51+
with tarfile.open(archive, "r:gz") as distribution:
52+
for member in distribution:
53+
path = PurePosixPath(member.name)
54+
if member.isfile() and ((len(path.parts) == 2 and path.name in {"LICENSE", "NOTICE"})
55+
or (len(path.parts) > 2 and path.parts[1] == "licenses")):
56+
with distribution.extractfile(member) as document:
57+
text = document.read().decode("utf-8-sig", errors="replace").replace("\r\n", "\n")
58+
documents.append(text)
59+
if len(path.parts) == 2 and path.name == "LICENSE":
60+
index = text
61+
if not member.isfile() or path.parent.name != "lib" or path.suffix != ".jar":
62+
continue
63+
if path.name.startswith("shenyu-"):
64+
continue
65+
resources = []
66+
coordinates = []
67+
pom_licenses = []
68+
with distribution.extractfile(member) as jar_stream:
69+
with zipfile.ZipFile(io.BytesIO(jar_stream.read())) as jar:
70+
for entry in sorted(jar.namelist()):
71+
resource = PurePosixPath(entry)
72+
if entry.startswith("META-INF/maven/") and entry.endswith("/pom.properties"):
73+
properties = {}
74+
for line in jar.read(entry).decode("utf-8").splitlines():
75+
key, separator, value = line.partition("=")
76+
if separator and key in {"groupId", "artifactId", "version"}:
77+
properties[key] = value.strip()
78+
if len(properties) == 3:
79+
coordinates.append(properties)
80+
if entry.startswith("META-INF/maven/") and entry.endswith("/pom.xml"):
81+
pom = ET.fromstring(jar.read(entry))
82+
for license_element in pom.findall("{*}licenses/{*}license"):
83+
pom_licenses.append({"pom": entry, "name": license_element.findtext("{*}name"),
84+
"url": license_element.findtext("{*}url")})
85+
legal_path = LEGAL_NAME.fullmatch(resource.name) or re.search(
86+
r"\.(?:license|notice)(?:\.|$)", resource.name, re.I) or any(
87+
part.lower() in {"license", "licenses"} for part in resource.parts[:-1])
88+
if not legal_path or resource.suffix.lower() not in TEXT_SUFFIXES:
89+
continue
90+
# Legal resources are read in place; archive paths are never extracted.
91+
data = jar.read(entry)
92+
try:
93+
text = data.decode("utf-8-sig")
94+
except UnicodeDecodeError:
95+
text = data.decode("latin-1")
96+
text = text.replace("\r\n", "\n").strip()
97+
if not text:
98+
continue
99+
digest = hashlib.sha256(text.encode("utf-8")).hexdigest()
100+
texts[digest] = text
101+
resources.append({
102+
"path": entry,
103+
"kind": "notice" if re.search(r"(^|[._-])notice([._-]|$)", resource.name, re.I) else "license",
104+
"sha256": digest,
105+
})
106+
jars.append({"name": path.name, "coordinates": coordinates, "resources": resources,
107+
"embedded_pom_licenses": pom_licenses})
108+
if not jars:
109+
raise ValueError(f"No third-party library JARs found in {archive}")
110+
legal_documents = "\n".join(documents)
111+
missing = [jar["name"] + " / " + resource["path"] for jar in jars for resource in jar["resources"]
112+
if texts[resource["sha256"]] not in legal_documents]
113+
for jar in jars:
114+
if jar["name"] not in LICENSE_DECLARATIONS:
115+
continue
116+
component, expected = LICENSE_DECLARATIONS[jar["name"]]
117+
declarations = [line for line in index.splitlines() if line.strip().startswith(component + ":")]
118+
if len(declarations) != 1 or expected not in declarations[0]:
119+
missing.append(f"{jar['name']}: expected one component declaration with {expected}")
120+
return {"archive": archive.name, "jars": sorted(jars, key=lambda item: item["name"]), "texts": texts,
121+
"missing_legal_resources": missing}
122+
123+
124+
def main():
125+
parser = argparse.ArgumentParser(description=__doc__)
126+
parser.add_argument("--check", action="store_true", help="Require bundled legal documents to reproduce JAR legal resources")
127+
args = parser.parse_args()
128+
output = Path("target/release-audit")
129+
output.mkdir(parents=True, exist_ok=True)
130+
missing = []
131+
for component in ("admin", "bootstrap"):
132+
archives = list(Path(f"shenyu-dist/shenyu-{component}-dist/target").glob(f"apache-shenyu-*-{component}-bin.tar.gz"))
133+
if len(archives) != 1:
134+
raise ValueError(f"Expected one {component} distribution, found {len(archives)}")
135+
report = collect(archives[0])
136+
(output / f"{component}-legal.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
137+
print(f"{component}: {len(report['jars'])} third-party JARs, {len(report['texts'])} distinct legal texts")
138+
missing.extend(component + ": " + resource for resource in report["missing_legal_resources"])
139+
if args.check and missing:
140+
raise ValueError("Legal resources missing from distribution documents:\n" + "\n".join(missing))
141+
142+
143+
if __name__ == "__main__":
144+
main()

0 commit comments

Comments
 (0)