gnodet commented on code in PR #24573: URL: https://github.com/apache/camel/pull/24573#discussion_r3557893284
########## tooling/maven/camel-package-maven-plugin/src/main/java/org/apache/camel/maven/packaging/UpdateSecurityAdvisoriesMojo.java: ########## @@ -0,0 +1,292 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.maven.packaging; + +import java.io.File; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.file.Path; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.TreeSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.inject.Inject; + +import org.apache.camel.tooling.model.JsonMapper; +import org.apache.camel.tooling.model.SecurityAdvisoryModel; +import org.apache.camel.util.json.JsonArray; +import org.apache.camel.util.json.JsonObject; +import org.apache.camel.util.json.Jsoner; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.plugins.annotations.LifecyclePhase; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.project.MavenProjectHelper; +import org.codehaus.plexus.build.BuildContext; +import org.snakeyaml.engine.v2.api.Load; +import org.snakeyaml.engine.v2.api.LoadSettings; + +/** + * Syncs the published Apache Camel CVE security advisories (the sources behind + * <a href="https://camel.apache.org/security/">camel.apache.org/security</a>, maintained as Markdown files with YAML + * front matter in the camel-website git repository) into a JSON file shipped with camel-catalog, the same way the known + * releases are synced by {@code update-camel-releases}. + */ +@Mojo(name = "update-security-advisories", threadSafe = true, defaultPhase = LifecyclePhase.GENERATE_RESOURCES) +public class UpdateSecurityAdvisoriesMojo extends AbstractGeneratorMojo { + + private static final String GIT_SECURITY_URL + = "https://api.github.com/repos/apache/camel-website/contents/content/security"; + private static final String WEBSITE_BASE_URL = "https://camel.apache.org"; + + private static final Pattern ADVISORY_FILE = Pattern.compile("CVE-\\d{4}-\\d{4,}\\.md"); + private static final Pattern COMPONENT_TOKEN = Pattern.compile("camel-[a-z0-9]+(?:-[a-z0-9]+)*"); + private static final Pattern CVE_ID = Pattern.compile("CVE-(\\d{4})-(\\d+)"); + + /** + * The output directory for the generated catalog advisories file + */ + @Parameter(defaultValue = "${project.basedir}/src/generated/resources/org/apache/camel/catalog/advisories") + protected File outDir; + + @Inject + public UpdateSecurityAdvisoriesMojo(MavenProjectHelper projectHelper, BuildContext buildContext) { + super(projectHelper, buildContext); + } + + @Override + public void execute() throws MojoExecutionException, MojoFailureException { + if (outDir == null) { + outDir = new File(project.getBasedir(), "src/generated/resources"); + } + + try { + getLog().info("Updating Camel security advisories from camel-website"); + List<String> links = fetchAdvisoryLinks(); + List<SecurityAdvisoryModel> advisories = processAdvisories(links); + advisories.sort(Comparator.comparingLong(UpdateSecurityAdvisoriesMojo::cveOrdinal)); + getLog().info("Found " + advisories.size() + " published security advisories"); + + JsonArray arr = new JsonArray(); + for (SecurityAdvisoryModel advisory : advisories) { + arr.add(JsonMapper.asJsonObject(advisory)); + } + String json = Jsoner.serialize(arr); + json = Jsoner.prettyPrint(json, 4); + + Path path = outDir.toPath(); + updateResource(path, "camel-security-advisories.json", json); + addResourceDirectory(path); + } catch (Exception e) { + throw new MojoExecutionException(e); + } + } + + private List<SecurityAdvisoryModel> processAdvisories(List<String> urls) throws Exception { + List<SecurityAdvisoryModel> answer = new ArrayList<>(); + + try (CloseableHttpClient hc = new CloseableHttpClient()) { + for (String url : urls) { + HttpResponse<String> res + = hc.send(HttpRequest.newBuilder(new URI(url)).timeout(Duration.ofSeconds(20)).build(), + HttpResponse.BodyHandlers.ofString()); + + if (res.statusCode() == 200) { + SecurityAdvisoryModel model = parseAdvisory(res.body()); + if (model != null) { + answer.add(model); + } + } + } + } + + return answer; + } + + /** + * Parse one advisory Markdown file (YAML front matter). Returns {@code null} for drafts, non-advisory pages and + * files without parseable front matter, so only published advisories are included. + */ + static SecurityAdvisoryModel parseAdvisory(String content) { + Map<String, Object> frontMatter = frontMatter(content); + if (frontMatter == null) { + return null; + } + if (!"security-advisory".equals(str(frontMatter.get("type")))) { + return null; + } + Object draft = frontMatter.get("draft"); + if (Boolean.TRUE.equals(draft) || "true".equalsIgnoreCase(str(draft))) { + return null; + } + String cve = str(frontMatter.get("cve")); + if (cve == null || cve.isBlank()) { + return null; + } + + SecurityAdvisoryModel model = new SecurityAdvisoryModel(); + model.setCve(cve.trim()); + model.setDate(trimmed(frontMatter.get("date"))); + String severity = str(frontMatter.get("severity")); + if (severity != null) { + model.setSeverity(severity.trim().toUpperCase(Locale.ROOT)); + } + model.setSummary(trimmed(frontMatter.get("summary"))); + model.setAffected(trimmed(frontMatter.get("affected"))); + model.setFixed(trimmed(frontMatter.get("fixed"))); + model.setMitigation(trimmed(frontMatter.get("mitigation"))); + + String url = str(frontMatter.get("url")); + if (url == null || url.isBlank()) { + url = "/security/" + model.getCve() + ".html"; + } + if (url.startsWith("/")) { + url = WEBSITE_BASE_URL + url; + } + model.setUrl(url.trim()); + + model.setComponents(extractComponents(str(frontMatter.get("title")), model.getSummary(), + str(frontMatter.get("description")), model.getMitigation())); + return model; + } + + @SuppressWarnings("unchecked") + static Map<String, Object> frontMatter(String content) { + if (content == null) { + return null; + } + String trimmedContent = content.stripLeading(); + if (!trimmedContent.startsWith("---")) { + return null; + } + int start = trimmedContent.indexOf('\n'); + if (start < 0) { + return null; + } + int end = trimmedContent.indexOf("\n---", start); + if (end < 0) { + return null; + } + String yaml = trimmedContent.substring(start + 1, end); + try { + Object parsed = new Load(LoadSettings.builder().build()).loadFromString(yaml); + return parsed instanceof Map ? (Map<String, Object>) parsed : null; + } catch (Exception e) { + return null; + } + } + + /** + * The Camel components named by the advisory text, as {@code camel-*} tokens (best-effort: some older advisories do + * not name components at all). + */ + static List<String> extractComponents(String... texts) { + TreeSet<String> found = new TreeSet<>(); + for (String text : texts) { + if (text == null) { + continue; + } + Matcher matcher = COMPONENT_TOKEN.matcher(text.toLowerCase(Locale.ROOT)); + while (matcher.find()) { + found.add(matcher.group()); + } + } + return new ArrayList<>(found); + } + + private List<String> fetchAdvisoryLinks() throws Exception { + List<String> answer = new ArrayList<>(); + + // use JDK http client to call github api + try (CloseableHttpClient hc = new CloseableHttpClient()) { + HttpResponse<String> res = hc.send( + HttpRequest.newBuilder(new URI(GIT_SECURITY_URL)).timeout(Duration.ofSeconds(20)).build(), + HttpResponse.BodyHandlers.ofString()); + + // follow redirect + if (res.statusCode() == 302) { + String loc = res.headers().firstValue("location").orElse(null); + if (loc != null) { + res = hc.send(HttpRequest.newBuilder(new URI(loc)).timeout(Duration.ofSeconds(20)).build(), + HttpResponse.BodyHandlers.ofString()); + } + } + + if (res.statusCode() == 200) { + JsonArray root = (JsonArray) Jsoner.deserialize(res.body()); + for (Object o : root) { + JsonObject jo = (JsonObject) o; + String name = jo.getString("name"); + if (name != null && ADVISORY_FILE.matcher(name).matches()) { + String url = jo.getString("download_url"); + if (url != null) { + answer.add(url); + } Review Comment: The `COMPONENT_TOKEN` regex `camel-[a-z0-9]+(?:-[a-z0-9]+)*` extracts false-positive component names from advisory text. The generated `camel-security-advisories.json` contains bogus components including: - **JIRA issue IDs**: `camel-10894`, `camel-12444`, `camel-23200`, `camel-23212`, `camel-23372`, `camel-23506` — extracted from prose like `CAMEL-12444` in mitigation URLs - **Generic English words**: `camel-internal` (×10), `camel-prefixed` (×13), `camel-specific`, `camel-side`, `camel-namespace` — extracted from phrases like "Camel-namespace filter" and "camel-internal headers" For example, CVE-2018-8027 has components `["camel-10894", "camel-12444"]` which are JIRA ticket IDs, not actual Camel component artifacts. Consider: 1. Adding a negative lookahead to filter JIRA IDs: `camel-(?!\d+\b)[a-z][a-z0-9]+(?:-[a-z0-9]+)*` 2. Validating extracted tokens against the catalog's known artifact IDs 3. Adding a denylist for known false positives (`camel-internal`, `camel-prefixed`, etc.) Option 1 alone fixes the JIRA IDs but not the English words. Option 2 would be the most comprehensive. ```suggestion private static final Pattern COMPONENT_TOKEN = Pattern.compile("camel-(?!\\d+\\b)[a-z][a-z0-9]+(?:-[a-z0-9]+)*"); ``` -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
