This is an automated email from the ASF dual-hosted git repository.
davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
The following commit(s) were added to refs/heads/main by this push:
new fe0221680b89 CAMEL-27344: camel-jbang - camel dependency audit
--osv-database and the TUI check with the offline OSV database, so no
coordinates leave the machine (#30557)
fe0221680b89 is described below
commit fe0221680b89609eeee47540e00394a6a3ff7ebe
Author: Claus Ibsen <[email protected]>
AuthorDate: Sat Nov 21 20:16:05 2026 +0100
CAMEL-27344: camel-jbang - camel dependency audit --osv-database and the
TUI check with the offline OSV database, so no coordinates leave the machine
(#30557)
camel dependency audit --osv-database (and --osv-database-url for a mirror
or a ZIP on disk) checks the dependencies against the export of all Maven
vulnerabilities of OSV.dev, matched locally, so no coordinates leave the
machine. The export is cached in ~/.camel/osv and refreshed once a day with
If-Modified-Since; a broken download never replaces a good copy. OsvClient and
OsvDatabase implement VulnerabilitySource, used by CveAudit. The TUI has an OSV
Database setting (camel.tui.osvD [...]
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Claus Ibsen <[email protected]>
---
.../org/apache/camel/catalog/cve/CveAudit.java | 5 +-
.../org/apache/camel/catalog/cve/OsvClient.java | 11 +-
.../org/apache/camel/catalog/cve/OsvDatabase.java | 355 +++++++++++++++++++++
.../camel/catalog/cve/VulnerabilitySource.java | 38 +++
.../apache/camel/catalog/cve/OsvDatabaseTest.java | 222 +++++++++++++
.../modules/ROOT/pages/camel-jbang-projects.adoc | 37 ++-
.../ROOT/pages/camel-jbang-tui-observe.adoc | 7 +
.../ROOT/pages/camel-jbang-tui-settings.adoc | 6 +
.../camel-jbang-dependency-audit.adoc | 3 +
.../META-INF/camel-jbang-commands-metadata.json | 2 +-
.../dsl/jbang/core/commands/DependencyAudit.java | 98 +++++-
.../camel/dsl/jbang/core/common/OsvProxy.java | 20 +-
.../jbang/core/commands/DependencyAuditTest.java | 58 ++++
.../src/test/resources/golden/cli-help.txt | 23 +-
.../dsl/jbang/core/commands/tui/CveAuditTab.java | 20 +-
.../dsl/jbang/core/commands/tui/SettingsPopup.java | 31 +-
.../dsl/jbang/core/commands/tui/TuiSettings.java | 62 +++-
.../src/main/resources/tui/help/cve-audit.md | 11 +
.../core/commands/tui/SettingsPopupRenderTest.java | 4 +-
.../jbang/core/commands/tui/TuiSettingsTest.java | 25 ++
20 files changed, 988 insertions(+), 50 deletions(-)
diff --git
a/catalog/camel-catalog-cve/src/main/java/org/apache/camel/catalog/cve/CveAudit.java
b/catalog/camel-catalog-cve/src/main/java/org/apache/camel/catalog/cve/CveAudit.java
index 561f8f9156ff..d2ef19619949 100644
---
a/catalog/camel-catalog-cve/src/main/java/org/apache/camel/catalog/cve/CveAudit.java
+++
b/catalog/camel-catalog-cve/src/main/java/org/apache/camel/catalog/cve/CveAudit.java
@@ -58,11 +58,12 @@ public final class CveAudit {
* JAR files
* @param endpointComponents the components of the endpoints of the
routes; null when not known (no usage)
* @param catalog the catalog with the Camel advisories and the
components
- * @param osv the OSV.dev client; null to check the Camel
advisories only
+ * @param osv the OSV.dev API client or the offline OSV
database; null to check the Camel advisories
+ * only
*/
public static Result audit(
List<Dependency> deps, Map<String, Path> jars, Set<String>
declared, Map<String, String> fallbackVia,
- Collection<String> endpointComponents, CamelCatalog catalog,
OsvClient osv) {
+ Collection<String> endpointComponents, CamelCatalog catalog,
VulnerabilitySource osv) {
Map<String, List<OsvClient.Vulnerability>> vulnMap = osv != null ?
osv.queryBatch(deps) : Map.of();
String osvError = osv != null ? osv.lastError() : null;
diff --git
a/catalog/camel-catalog-cve/src/main/java/org/apache/camel/catalog/cve/OsvClient.java
b/catalog/camel-catalog-cve/src/main/java/org/apache/camel/catalog/cve/OsvClient.java
index 1dfea6ae9aa4..289712a2356a 100644
---
a/catalog/camel-catalog-cve/src/main/java/org/apache/camel/catalog/cve/OsvClient.java
+++
b/catalog/camel-catalog-cve/src/main/java/org/apache/camel/catalog/cve/OsvClient.java
@@ -39,7 +39,7 @@ import org.apache.maven.artifact.versioning.ComparableVersion;
* maintains a global in-memory cache keyed by Maven GAV coordinates so
results persist across tab visits and
* integration switches.
*/
-public class OsvClient {
+public class OsvClient implements VulnerabilitySource {
/** The OSV.dev API, to look up the proxy to reach it through. */
public static final String API_URL = "https://api.osv.dev/";
@@ -131,6 +131,7 @@ public class OsvClient {
*
* @return map from GAV string (groupId:artifactId:version) to list of
vulnerabilities
*/
+ @Override
public Map<String, List<Vulnerability>> queryBatch(List<Dependency>
entries) {
Map<String, List<Vulnerability>> result = new HashMap<>();
List<Dependency> uncached = new ArrayList<>();
@@ -303,6 +304,7 @@ public class OsvClient {
}
/** Why the last query got no answer from OSV.dev, so its JARs are not
checked; null when it got one. */
+ @Override
public String lastError() {
return lastError;
}
@@ -320,7 +322,8 @@ public class OsvClient {
}
}
- private Vulnerability parseVuln(JsonObject vuln) {
+ /** A vulnerability of its OSV JSON, as the API and the OSV database
export write it; null without an id. */
+ static Vulnerability parseVuln(JsonObject vuln) {
String id = getString(vuln, "id");
if (id == null) {
return null;
@@ -382,7 +385,7 @@ public class OsvClient {
return result;
}
- private List<String> extractFixedVersions(JsonObject vuln) {
+ private static List<String> extractFixedVersions(JsonObject vuln) {
JsonArray affected = (JsonArray) vuln.get("affected");
if (affected == null) {
return Collections.emptyList();
@@ -484,7 +487,7 @@ public class OsvClient {
return "MEDIUM";
}
- private List<String> extractAliases(JsonObject vuln) {
+ private static List<String> extractAliases(JsonObject vuln) {
JsonArray aliases = (JsonArray) vuln.get("aliases");
if (aliases == null || aliases.isEmpty()) {
return Collections.emptyList();
diff --git
a/catalog/camel-catalog-cve/src/main/java/org/apache/camel/catalog/cve/OsvDatabase.java
b/catalog/camel-catalog-cve/src/main/java/org/apache/camel/catalog/cve/OsvDatabase.java
new file mode 100644
index 000000000000..e67b45adcae3
--- /dev/null
+++
b/catalog/camel-catalog-cve/src/main/java/org/apache/camel/catalog/cve/OsvDatabase.java
@@ -0,0 +1,355 @@
+/*
+ * 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.catalog.cve;
+
+import java.io.IOException;
+import java.net.ProxySelector;
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.AtomicMoveNotSupportedException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.nio.file.attribute.FileTime;
+import java.security.MessageDigest;
+import java.time.Duration;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HexFormat;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+import java.util.zip.ZipInputStream;
+
+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.artifact.versioning.ComparableVersion;
+
+/**
+ * The offline OSV database (CAMEL-27344): the export of all the Maven
vulnerabilities of OSV.dev, one ZIP file updated
+ * every day, matched locally, so no coordinates of the project leave the
machine. The ZIP comes from
+ * {@link #DEFAULT_URL}, from a mirror of it (such as a raw repository of
Nexus or a generic remote of Artifactory), or
+ * from a file; a downloaded one is cached and refreshed once a day.
+ */
+public final class OsvDatabase implements VulnerabilitySource {
+
+ /** The export of the Maven vulnerabilities of OSV.dev. */
+ public static final String DEFAULT_URL =
"https://osv-vulnerabilities.storage.googleapis.com/Maven/all.zip";
+
+ /** How long a downloaded database is used before it is downloaded again.
*/
+ public static final Duration DEFAULT_MAX_AGE = Duration.ofDays(1);
+
+ // an entry is a few KB; a larger one is not an OSV entry
+ private static final long MAX_ENTRY_SIZE = 16 * 1024 * 1024;
+
+ private final String location;
+ private final Path file;
+ private final Instant updated;
+ private final String warning;
+ private volatile String lastError;
+
+ private OsvDatabase(String location, Path file, Instant updated, String
warning, String error) {
+ this.location = location;
+ this.file = file;
+ this.updated = updated;
+ this.warning = warning;
+ this.lastError = error;
+ }
+
+ /** The database of a ZIP file on disk. */
+ public static OsvDatabase of(Path zip) {
+ return new OsvDatabase(zip.toString(), zip, modified(zip), null, null);
+ }
+
+ /**
+ * The database of a URL or a file: a URL is downloaded into the cache
directory, and downloaded again when the
+ * cached copy is older than {@code maxAge} (with {@code
If-Modified-Since}, so an unchanged one is not); a stale
+ * copy is kept when the download fails. Never fails: without a database,
{@link #lastError()} says why and no JAR
+ * is checked.
+ *
+ * @param location the URL of the ZIP ({@link #DEFAULT_URL} when null), a
{@code file:} URL or a path
+ * @param cacheDir where a downloaded ZIP is kept
+ * @param maxAge how long a downloaded ZIP is used
+ * @param proxy the proxy to download through; null for the proxy
settings of the JVM
+ */
+ public static OsvDatabase open(String location, Path cacheDir, Duration
maxAge, HttpProxy proxy) {
+ String where = location != null && !location.isBlank() ?
location.trim() : DEFAULT_URL;
+ if (!where.startsWith("http://") && !where.startsWith("https://")) {
+ Path zip = where.startsWith("file:") ? Path.of(URI.create(where))
: Path.of(where);
+ if (!Files.isRegularFile(zip)) {
+ return new OsvDatabase(where, null, null, null, "The OSV
database " + zip + " does not exist");
+ }
+ return new OsvDatabase(where, zip, modified(zip), null, null);
+ }
+ Path cached = cacheDir.resolve(cacheName(where));
+ if (Files.isRegularFile(cached) && age(cached).compareTo(maxAge) < 0) {
+ return new OsvDatabase(where, cached, modified(cached), null,
null);
+ }
+ try {
+ download(where, cached, proxy);
+ return new OsvDatabase(where, cached, modified(cached), null,
null);
+ } catch (Exception e) {
+ if (e instanceof InterruptedException) {
+ Thread.currentThread().interrupt();
+ }
+ String reason = "The OSV database could not be downloaded from " +
where
+ + (proxy != null ? " through the proxy " + proxy :
"") + ": "
+ + (e.getMessage() != null ? e.getMessage() :
e.getClass().getSimpleName());
+ if (Files.isRegularFile(cached)) {
+ return new OsvDatabase(
+ where, cached, modified(cached), reason + "; the copy
of " + modified(cached)
+ + " is used",
+ null);
+ }
+ return new OsvDatabase(where, null, null, null, reason);
+ }
+ }
+
+ /** Where the database comes from: its URL or file. */
+ public String location() {
+ return location;
+ }
+
+ /** The ZIP file of the database; null when there is none. */
+ public Path file() {
+ return file;
+ }
+
+ /** When the ZIP file was last updated; null when there is none. */
+ public Instant updated() {
+ return updated;
+ }
+
+ /** Why an older copy of the database is used, as the download failed;
null when it is up to date. */
+ public String warning() {
+ return warning;
+ }
+
+ @Override
+ public String lastError() {
+ return lastError;
+ }
+
+ /**
+ * Matches the JARs against the database: a JAR is affected when its
version is one of the affected versions of an
+ * entry for its {@code groupId:artifactId}, or in one of its affected
ranges. Withdrawn entries are left out.
+ */
+ @Override
+ public Map<String, List<OsvClient.Vulnerability>>
queryBatch(List<Dependency> entries) {
+ Map<String, List<Dependency>> byPackage = new HashMap<>();
+ for (Dependency d : entries) {
+ if (d.groupId() != null && d.version() != null) {
+ byPackage.computeIfAbsent(d.groupId() + ":" + d.artifactId(),
k -> new ArrayList<>()).add(d);
+ }
+ }
+ Map<String, List<OsvClient.Vulnerability>> result = new
LinkedHashMap<>();
+ if (file == null) {
+ return result;
+ }
+ try {
+ Map<String, List<Affected>> affected = read(file,
byPackage.keySet());
+ for (Map.Entry<String, List<Dependency>> e : byPackage.entrySet())
{
+ List<Affected> candidates = affected.getOrDefault(e.getKey(),
List.of());
+ for (Dependency d : e.getValue()) {
+ List<OsvClient.Vulnerability> vulns = new ArrayList<>();
+ for (Affected a : candidates) {
+ if (a.affects(e.getKey(), d.version()) &&
!vulns.contains(a.vulnerability())) {
+ vulns.add(a.vulnerability());
+ }
+ }
+ result.put(d.gav(), vulns);
+ }
+ }
+ lastError = null;
+ } catch (IOException e) {
+ lastError = "The OSV database " + file + " could not be read: " +
e.getMessage();
+ result.clear();
+ }
+ return result;
+ }
+
+ /** An entry of the database for one package: the vulnerability, and the
versions it lists as affected. */
+ record Affected(OsvClient.Vulnerability vulnerability, List<String>
versions) {
+
+ boolean affects(String packageName, String version) {
+ if (versions.contains(version)) {
+ return true;
+ }
+ ComparableVersion v = new ComparableVersion(version);
+ for (OsvClient.AffectedRange r : vulnerability.ranges()) {
+ if (!r.packageName().equals(packageName)) {
+ continue;
+ }
+ if (r.introduced() != null && v.compareTo(new
ComparableVersion(r.introduced())) < 0) {
+ continue;
+ }
+ if (r.fixed() != null) {
+ if (v.compareTo(new ComparableVersion(r.fixed())) < 0) {
+ return true;
+ }
+ } else if (r.lastAffected() != null) {
+ if (v.compareTo(new ComparableVersion(r.lastAffected()))
<= 0) {
+ return true;
+ }
+ } else {
+ // no fix yet
+ return true;
+ }
+ }
+ return false;
+ }
+ }
+
+ /** The entries of the ZIP for the given packages, by package. */
+ static Map<String, List<Affected>> read(Path zip, Set<String> packages)
throws IOException {
+ Map<String, List<Affected>> answer = new HashMap<>();
+ try (ZipInputStream in = new
ZipInputStream(Files.newInputStream(zip))) {
+ for (ZipEntry entry = in.getNextEntry(); entry != null; entry =
in.getNextEntry()) {
+ if (entry.isDirectory() || !entry.getName().endsWith(".json"))
{
+ continue;
+ }
+ byte[] data = in.readNBytes((int) MAX_ENTRY_SIZE + 1);
+ if (data.length > MAX_ENTRY_SIZE) {
+ continue;
+ }
+ JsonObject json;
+ try {
+ json = (JsonObject) Jsoner.deserialize(new String(data,
StandardCharsets.UTF_8));
+ } catch (Exception e) {
+ // not an OSV entry
+ continue;
+ }
+ if (json.get("withdrawn") != null) {
+ continue;
+ }
+ index(json, packages, answer);
+ }
+ }
+ return answer;
+ }
+
+ private static void index(JsonObject json, Set<String> packages,
Map<String, List<Affected>> answer) {
+ JsonArray affected = (JsonArray) json.get("affected");
+ if (affected == null) {
+ return;
+ }
+ OsvClient.Vulnerability vuln = null;
+ for (Object o : affected) {
+ JsonObject aff = (JsonObject) o;
+ JsonObject pkg = (JsonObject) aff.get("package");
+ Object name = pkg != null ? pkg.get("name") : null;
+ if (name == null || !packages.contains(name.toString()) ||
!"Maven".equals(pkg.get("ecosystem"))) {
+ continue;
+ }
+ if (vuln == null) {
+ vuln = OsvClient.parseVuln(json);
+ if (vuln == null) {
+ return;
+ }
+ }
+ List<String> versions = new ArrayList<>();
+ JsonArray list = (JsonArray) aff.get("versions");
+ if (list != null) {
+ list.forEach(v -> versions.add(String.valueOf(v)));
+ }
+ answer.computeIfAbsent(name.toString(), k -> new
ArrayList<>()).add(new Affected(vuln, versions));
+ }
+ }
+
+ private static void download(String url, Path target, HttpProxy proxy)
throws IOException, InterruptedException {
+ HttpClient.Builder builder = HttpClient.newBuilder()
+ .connectTimeout(Duration.ofSeconds(10))
+ .followRedirects(HttpClient.Redirect.NORMAL)
+ .proxy(proxy != null ? proxy.selector() :
ProxySelector.getDefault());
+ if (proxy != null && proxy.authenticator() != null) {
+ HttpProxy.allowBasicTunneling();
+ builder.authenticator(proxy.authenticator());
+ }
+ HttpRequest.Builder request = HttpRequest.newBuilder()
+ .uri(URI.create(url))
+ .timeout(Duration.ofMinutes(5))
+ .GET();
+ Instant since = Files.isRegularFile(target) ? modified(target) : null;
+ if (since != null) {
+ request.header("If-Modified-Since",
+
DateTimeFormatter.RFC_1123_DATE_TIME.format(since.atOffset(ZoneOffset.UTC)));
+ }
+ Files.createDirectories(target.getParent());
+ Path tmp = Files.createTempFile(target.getParent(),
target.getFileName().toString(), ".tmp");
+ try {
+ HttpResponse<Path> response = builder.build().send(request.build(),
+ HttpResponse.BodyHandlers.ofFile(tmp));
+ if (response.statusCode() == 304) {
+ // unchanged: used for another day
+ Files.setLastModifiedTime(target,
FileTime.from(Instant.now()));
+ return;
+ }
+ if (response.statusCode() == 407) {
+ throw new IOException("the proxy needs a username and password
(HTTP status 407)");
+ }
+ if (response.statusCode() != 200) {
+ throw new IOException("HTTP status " + response.statusCode());
+ }
+ // a broken download does not replace a good copy
+ try (ZipFile ignored = new ZipFile(tmp.toFile())) {
+ // a ZIP
+ } catch (IOException e) {
+ throw new IOException("not a ZIP file", e);
+ }
+ try {
+ Files.move(tmp, target, StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.ATOMIC_MOVE);
+ } catch (AtomicMoveNotSupportedException e) {
+ Files.move(tmp, target, StandardCopyOption.REPLACE_EXISTING);
+ }
+ } finally {
+ Files.deleteIfExists(tmp);
+ }
+ }
+
+ // one cached file per URL
+ static String cacheName(String url) {
+ try {
+ byte[] hash =
MessageDigest.getInstance("SHA-256").digest(url.getBytes(StandardCharsets.UTF_8));
+ return "osv-" + HexFormat.of().formatHex(hash, 0, 8) + ".zip";
+ } catch (Exception e) {
+ return "osv-" + Integer.toHexString(url.hashCode()) + ".zip";
+ }
+ }
+
+ private static Instant modified(Path file) {
+ try {
+ return Files.getLastModifiedTime(file).toInstant();
+ } catch (IOException e) {
+ return null;
+ }
+ }
+
+ private static Duration age(Path file) {
+ Instant m = modified(file);
+ return m != null ? Duration.between(m, Instant.now()) :
Duration.ofDays(36500);
+ }
+}
diff --git
a/catalog/camel-catalog-cve/src/main/java/org/apache/camel/catalog/cve/VulnerabilitySource.java
b/catalog/camel-catalog-cve/src/main/java/org/apache/camel/catalog/cve/VulnerabilitySource.java
new file mode 100644
index 000000000000..c57afdc6e015
--- /dev/null
+++
b/catalog/camel-catalog-cve/src/main/java/org/apache/camel/catalog/cve/VulnerabilitySource.java
@@ -0,0 +1,38 @@
+/*
+ * 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.catalog.cve;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Where the vulnerabilities of the JARs come from: the OSV.dev API ({@link
OsvClient}), or the offline OSV database
+ * ({@link OsvDatabase}).
+ */
+public interface VulnerabilitySource {
+
+ /**
+ * The vulnerabilities of the JARs.
+ *
+ * @return the vulnerabilities by GAV ({@code
groupId:artifactId:version}); a JAR that could not be checked has no
+ * entry
+ */
+ Map<String, List<OsvClient.Vulnerability>> queryBatch(List<Dependency>
entries);
+
+ /** Why the last query got no answer, so its JARs are not checked; null
when it got one. */
+ String lastError();
+}
diff --git
a/catalog/camel-catalog-cve/src/test/java/org/apache/camel/catalog/cve/OsvDatabaseTest.java
b/catalog/camel-catalog-cve/src/test/java/org/apache/camel/catalog/cve/OsvDatabaseTest.java
new file mode 100644
index 000000000000..78238fd717ea
--- /dev/null
+++
b/catalog/camel-catalog-cve/src/test/java/org/apache/camel/catalog/cve/OsvDatabaseTest.java
@@ -0,0 +1,222 @@
+/*
+ * 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.catalog.cve;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.FileTime;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+import com.sun.net.httpserver.HttpServer;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * CAMEL-27344: the offline OSV database, matched locally, downloaded from a
mirror and cached.
+ */
+class OsvDatabaseTest {
+
+ // commons-text 1.5 up to 1.10.0, as OSV writes CVE-2022-42889
+ private static final String TEXT
+ = """
+ {"id": "GHSA-599f-7c49-w659", "aliases":
["CVE-2022-42889"], "summary": "Arbitrary code execution in Apache Commons
Text",
+ "database_specific": {"severity": "CRITICAL"},
+ "affected": [{"package": {"name":
"org.apache.commons:commons-text", "ecosystem": "Maven"},
+ "ranges": [{"type": "ECOSYSTEM", "events":
[{"introduced": "1.5"}, {"fixed": "1.10.0"}]}]}]}
+ """;
+ // only the affected versions are listed
+ private static final String LISTED = """
+ {"id": "GHSA-list-only", "summary": "Listed versions",
+ "affected": [{"package": {"name": "org.example:listed",
"ecosystem": "Maven"}, "versions": ["2.0-beta1"]}]}
+ """;
+ // up to the last affected version, with no fix
+ private static final String LAST = """
+ {"id": "GHSA-last-affected", "summary": "No fix",
+ "affected": [{"package": {"name": "org.example:last",
"ecosystem": "Maven"},
+ "ranges": [{"type": "ECOSYSTEM", "events": [{"introduced":
"0"}, {"last_affected": "3.2"}]}]}]}
+ """;
+ private static final String WITHDRAWN = """
+ {"id": "GHSA-withdrawn", "withdrawn": "2024-01-01T00:00:00Z",
+ "affected": [{"package": {"name": "org.example:last",
"ecosystem": "Maven"},
+ "ranges": [{"type": "ECOSYSTEM", "events": [{"introduced":
"0"}]}]}]}
+ """;
+ // the same name in another ecosystem
+ private static final String NPM = """
+ {"id": "GHSA-npm", "affected": [{"package": {"name":
"org.example:last", "ecosystem": "npm"},
+ "ranges": [{"type": "ECOSYSTEM", "events": [{"introduced":
"0"}]}]}]}
+ """;
+
+ @TempDir
+ Path dir;
+
+ private HttpServer server;
+ private final List<String> requests = new CopyOnWriteArrayList<>();
+
+ @AfterEach
+ void stopServer() {
+ if (server != null) {
+ server.stop(0);
+ }
+ }
+
+ @Test
+ void matchesTheRangesAndTheListedVersions() throws Exception {
+ OsvDatabase db = OsvDatabase.of(zip(dir.resolve("all.zip")));
+
+ Map<String, List<OsvClient.Vulnerability>> result =
db.queryBatch(List.of(
+ new Dependency("org.apache.commons", "commons-text", "1.9"),
+ new Dependency("org.apache.commons", "commons-text", "1.10.0"),
+ new Dependency("org.apache.commons", "commons-text", "1.4"),
+ new Dependency("org.example", "listed", "2.0-beta1"),
+ new Dependency("org.example", "listed", "2.0"),
+ new Dependency("org.example", "last", "3.2"),
+ new Dependency("org.example", "last", "3.2.1"),
+ new Dependency("org.example", "unknown", "1.0")));
+
+ assertThat(ids(result,
"org.apache.commons:commons-text:1.9")).containsExactly("GHSA-599f-7c49-w659");
+
assertThat(result.get("org.apache.commons:commons-text:1.9").get(0).aliases()).containsExactly("CVE-2022-42889");
+
assertThat(result.get("org.apache.commons:commons-text:1.9").get(0).severity()).isEqualTo("CRITICAL");
+ // fixed, and before the range
+ assertThat(ids(result,
"org.apache.commons:commons-text:1.10.0")).isEmpty();
+ assertThat(ids(result,
"org.apache.commons:commons-text:1.4")).isEmpty();
+ assertThat(ids(result,
"org.example:listed:2.0-beta1")).containsExactly("GHSA-list-only");
+ assertThat(ids(result, "org.example:listed:2.0")).isEmpty();
+ // up to the last affected one; the withdrawn entry and the npm
package are left out
+ assertThat(ids(result,
"org.example:last:3.2")).containsExactly("GHSA-last-affected");
+ assertThat(ids(result, "org.example:last:3.2.1")).isEmpty();
+ // checked, with no vulnerability
+ assertThat(result).containsEntry("org.example:unknown:1.0", List.of());
+ assertThat(db.lastError()).isNull();
+ }
+
+ @Test
+ void aMissingFileIsAnError() {
+ OsvDatabase db = OsvDatabase.open(dir.resolve("none.zip").toString(),
dir, Duration.ofDays(1), null);
+
+ assertThat(db.queryBatch(List.of(new Dependency("org.yaml",
"snakeyaml", "1.33")))).isEmpty();
+ assertThat(db.lastError()).contains("does not exist");
+ }
+
+ @Test
+ void downloadsOnceADayFromAMirror() throws Exception {
+ byte[] zip = Files.readAllBytes(zip(dir.resolve("served.zip")));
+ String url = serve(zip, false);
+ Path cache = dir.resolve("cache");
+
+ OsvDatabase first = OsvDatabase.open(url, cache, Duration.ofDays(1),
null);
+ assertThat(first.lastError()).isNull();
+ assertThat(first.file()).exists().hasParent(cache);
+ assertThat(ids(first.queryBatch(List.of(new
Dependency("org.apache.commons", "commons-text", "1.9"))),
+
"org.apache.commons:commons-text:1.9")).containsExactly("GHSA-599f-7c49-w659");
+
+ // the cached copy, without a request
+ OsvDatabase second = OsvDatabase.open(url, cache, Duration.ofDays(1),
null);
+ assertThat(second.file()).isEqualTo(first.file());
+ assertThat(requests).hasSize(1);
+
+ // a day later: asked again with If-Modified-Since
+ Files.setLastModifiedTime(first.file(),
FileTime.from(Instant.now().minus(Duration.ofDays(2))));
+ OsvDatabase third = OsvDatabase.open(url, cache, Duration.ofDays(1),
null);
+ assertThat(third.lastError()).isNull();
+ assertThat(requests).hasSize(2);
+ assertThat(requests.get(1)).isNotEmpty();
+ }
+
+ @Test
+ void keepsTheOldCopyWhenTheDownloadFails() throws Exception {
+ byte[] zip = Files.readAllBytes(zip(dir.resolve("served.zip")));
+ String url = serve(zip, false);
+ Path cache = dir.resolve("cache");
+ Path cached = OsvDatabase.open(url, cache, Duration.ofDays(1),
null).file();
+ server.stop(0);
+ // a broken mirror: not a ZIP
+ url =
serve("<html>maintenance</html>".getBytes(StandardCharsets.UTF_8), true);
+ Path stale = cache.resolve(OsvDatabase.cacheName(url));
+ Files.copy(cached, stale);
+ Files.setLastModifiedTime(stale,
FileTime.from(Instant.now().minus(Duration.ofDays(2))));
+
+ OsvDatabase db = OsvDatabase.open(url, cache, Duration.ofDays(1),
null);
+
+ assertThat(db.lastError()).isNull();
+ assertThat(db.warning()).contains("could not be
downloaded").contains("not a ZIP file").contains("is used");
+ assertThat(db.file()).isEqualTo(stale);
+ assertThat(ids(db.queryBatch(List.of(new
Dependency("org.apache.commons", "commons-text", "1.9"))),
+
"org.apache.commons:commons-text:1.9")).containsExactly("GHSA-599f-7c49-w659");
+ }
+
+ @Test
+ void noDatabaseWithoutDownload() throws Exception {
+ String url =
serve("<html>maintenance</html>".getBytes(StandardCharsets.UTF_8), true);
+
+ OsvDatabase db = OsvDatabase.open(url, dir.resolve("cache"),
Duration.ofDays(1), null);
+
+ assertThat(db.file()).isNull();
+ assertThat(db.lastError()).contains("could not be downloaded from " +
url);
+ assertThat(db.queryBatch(List.of(new Dependency("org.yaml",
"snakeyaml", "1.33")))).isEmpty();
+ }
+
+ private String serve(byte[] body, boolean always) throws IOException {
+ server = HttpServer.create(new
InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
+ server.createContext("/osv/Maven/all.zip", exchange -> {
+ String since =
exchange.getRequestHeaders().getFirst("If-Modified-Since");
+ requests.add(since != null ? since : "");
+ if (since != null && !always) {
+ exchange.sendResponseHeaders(304, -1);
+ } else {
+ exchange.sendResponseHeaders(200, body.length);
+ try (OutputStream out = exchange.getResponseBody()) {
+ out.write(body);
+ }
+ }
+ exchange.close();
+ });
+ server.start();
+ return "http://127.0.0.1:" + server.getAddress().getPort() +
"/osv/Maven/all.zip";
+ }
+
+ private static Path zip(Path file) throws IOException {
+ ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+ try (ZipOutputStream out = new ZipOutputStream(bytes)) {
+ String[] entries = { TEXT, LISTED, LAST, WITHDRAWN, NPM };
+ for (int i = 0; i < entries.length; i++) {
+ out.putNextEntry(new ZipEntry("entry-" + i + ".json"));
+ out.write(entries[i].getBytes(StandardCharsets.UTF_8));
+ out.closeEntry();
+ }
+ }
+ return Files.write(file, bytes.toByteArray());
+ }
+
+ private static List<String> ids(Map<String, List<OsvClient.Vulnerability>>
result, String gav) {
+ return result.getOrDefault(gav,
List.of()).stream().map(OsvClient.Vulnerability::id).toList();
+ }
+}
diff --git a/docs/user-manual/modules/ROOT/pages/camel-jbang-projects.adoc
b/docs/user-manual/modules/ROOT/pages/camel-jbang-projects.adoc
index 98f4b2690c46..c0623e49e64b 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-jbang-projects.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-jbang-projects.adoc
@@ -264,12 +264,45 @@ The options:
* `--json` prints one JSON document, for a script or an AI agent.
`vulnerabilities` counts the ones listed (`--severity`),
`totalVulnerabilities` all of them, and `failed` is `true` when the command
exits with 1.
* `--offline` checks only the Apache Camel security advisories, without
OSV.dev.
+* `--osv-database` checks with the offline OSV database instead of the OSV.dev
API, see below.
The command exits with 1 when it finds a vulnerability of the `--fail-on`
severity or worse (default `low`: any), so a
-CI job fails; `--fail-on=none` always exits with 0. The CVE Audit screen of
the xref:camel-jbang-tui.adoc[Camel TUI]
+CI job fails; `--fail-on=none` always exits with 0. When OSV.dev (or the OSV
database) cannot be used, the command
+warns and checks the Apache Camel security advisories only; with
`--fail-on-error` it exits with 1 then, so a CI job
+does not pass without the check. The CVE Audit screen of the
xref:camel-jbang-tui.adoc[Camel TUI]
shows the same for a running integration, and explains a vulnerability with AI.
-The command reaches OSV.dev through a proxy, which is taken from, in order:
+=== The offline OSV database
+
+By default, the command sends the coordinates (`groupId:artifactId:version`)
of every dependency to the OSV.dev API,
+including those of the internal libraries of a company. With `--osv-database`
it does not: it downloads the export of
+all the Maven vulnerabilities of OSV.dev (one ZIP file of about 10 MB, updated
every day by OSV.dev) and matches the
+versions locally, so no coordinates leave the machine:
+
+[source,bash]
+----
+camel dependency audit --osv-database
+----
+
+The ZIP is kept in `~/.camel/osv` and downloaded again once a day, and only
when it changed (`If-Modified-Since`).
+When the download fails, the copy of the day before is used, with a warning.
+
+A build machine without internet access can download the ZIP from the
repository manager of the company: a raw
+repository of Nexus or a generic remote repository of Artifactory that proxies
+`https://osv-vulnerabilities.storage.googleapis.com/Maven/all.zip`, or a file
on disk:
+
+[source,bash]
+----
+camel dependency audit
--osv-database-url=https://nexus.corp.com/repository/osv/Maven/all.zip
+camel dependency audit --osv-database-url=/opt/osv/all.zip
+----
+
+The offline database and the OSV.dev API give the same vulnerabilities:
OSV.dev matches the versions with the same
+data.
+
+=== Proxy
+
+The command reaches OSV.dev (or the URL of `--osv-database-url`) through a
proxy, which is taken from, in order:
. the active proxy of the Maven settings: `~/.m2/settings.xml`, or the file of
`--maven-settings`, with its username,
its password (encrypted with `settings-security.xml` or not) and its
`nonProxyHosts`;
diff --git a/docs/user-manual/modules/ROOT/pages/camel-jbang-tui-observe.adoc
b/docs/user-manual/modules/ROOT/pages/camel-jbang-tui-observe.adoc
index be6d9ac30a79..4a010356afe9 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-jbang-tui-observe.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-jbang-tui-observe.adoc
@@ -477,6 +477,13 @@ fixes all of them, which is what to upgrade. Press `/` to
filter the rows by CVE
of the chain. Results are cached globally -- switching integrations that share
JARs is instant. When OSV.dev cannot
be reached, the title says so and only the Camel advisories were checked;
press `r` to scan again.
+By default the coordinates of the JARs are sent to the OSV.dev API. With *OSV
Database* in the
+xref:camel-jbang-tui-settings.adoc[Settings] set to `default`, the tab uses
the offline OSV database instead, as
+`camel dependency audit --osv-database` does: the export of all the Maven
vulnerabilities of OSV.dev, downloaded once a
+day into `~/.camel/osv` and matched locally, so no coordinates leave the
machine. The title then says
+`offline OSV database, updated <date>`. A URL downloads the export from a
mirror, such as the repository manager of
+the company, and a path reads a ZIP file on disk.
+
=== Kafka
The Kafka tab (under More > Data) provides a dedicated view for Kafka
consumers and their connectivity
diff --git a/docs/user-manual/modules/ROOT/pages/camel-jbang-tui-settings.adoc
b/docs/user-manual/modules/ROOT/pages/camel-jbang-tui-settings.adoc
index 7659e6910d3b..0f74097ed283 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-jbang-tui-settings.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-jbang-tui-settings.adoc
@@ -229,6 +229,12 @@ what you change lasts for that session only, so your own
settings are left as th
| Port of the proxy host.
| `8080`
+| OSV Database | `camel.tui.osvDatabase`
+| Where the xref:camel-jbang-tui-observe.adoc#_cve_audit[CVE Audit] gets the
vulnerabilities from. Empty for the
+ OSV.dev API; `default` for the offline OSV database (the export of OSV.dev,
downloaded once a day and matched
+ locally, so no coordinates leave the machine); a URL to download that export
from a mirror; or a ZIP file on disk.
+|
+
| Shell History | `camel.tui.shell.history`
| How many commands the embedded shell remembers (see <<_input_history,Input
history>>).
| `100`
diff --git
a/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-dependency-audit.adoc
b/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-dependency-audit.adoc
index 14d042083cd0..c461e0a04c50 100644
---
a/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-dependency-audit.adoc
+++
b/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-dependency-audit.adoc
@@ -33,6 +33,7 @@ camel dependency audit [options]
| `--dry-run` | Preview export without writing files | false | boolean
| `--exclude` | Exclude files by name or pattern | | List
| `--fail-on` | Exits 1 when a vulnerability at or above this severity is
found: critical, high, medium, low or none | low | String
+| `--fail-on-error` | Exits 1 when the dependencies could not be checked with
OSV.dev or the OSV database (not reachable, no database), instead of checking
the Apache Camel security advisories only | | boolean
| `--fresh` | Make sure we use fresh (i.e. non-cached) resources | false |
boolean
| `--gav` | The Maven group:artifact:version | | String
| `--groovy-pre-compiled` | Whether to include pre-compiled Groovy classes in
the export (only supported with runtime=camel-main) | false | boolean
@@ -58,6 +59,8 @@ camel dependency audit [options]
| `--observe` | Enable observability services | false | boolean
| `--offline` | Checks the Apache Camel security advisories of the catalog
only, without OSV.dev | | boolean
| `--open-api` | Adds an OpenAPI spec from the given file (json or yaml file)
| | String
+| `--osv-database` | Checks with the offline OSV database instead of the
OSV.dev API: the export of all the Maven vulnerabilities of OSV.dev, downloaded
once a day and matched locally, so no coordinates of the project leave the
machine | | boolean
+| `--osv-database-url` | Where the offline OSV database is downloaded from,
such as a mirror on the repository manager of the company, or a ZIP file on
disk (default:
\https://osv-vulnerabilities.storage.googleapis.com/Maven/all.zip). Implies
--osv-database | | String
| `--output` | Output format (gav, maven, jbang) | gav | String
| `--package-name` | For Java source files should they have the given package
name. By default the package name is computed from the Maven GAV. Use false to
turn off and not include package name in the Java source files. | | String
| `--package-scan-jars` | Whether to automatic package scan JARs for custom
Spring or Quarkus beans making them available for Camel CLI | false | boolean
diff --git
a/dsl/camel-jbang/camel-jbang-core/src/generated/resources/META-INF/camel-jbang-commands-metadata.json
b/dsl/camel-jbang/camel-jbang-core/src/generated/resources/META-INF/camel-jbang-commands-metadata.json
index ef2a7878e6f7..a94faa0006c7 100644
---
a/dsl/camel-jbang/camel-jbang-core/src/generated/resources/META-INF/camel-jbang-commands-metadata.json
+++
b/dsl/camel-jbang/camel-jbang-core/src/generated/resources/META-INF/camel-jbang-commands-metadata.json
@@ -6,7 +6,7 @@
{ "name": "completion", "fullName": "completion", "description": "Generate
completion script for bash\/zsh", "sourceClass":
"org.apache.camel.dsl.jbang.core.commands.Complete", "options": [ { "names":
"-h,--help", "description": "Display this help and exit", "javaType":
"boolean", "type": "boolean" } ] },
{ "name": "config", "fullName": "config", "description": "Get and set user
configuration values", "sourceClass":
"org.apache.camel.dsl.jbang.core.commands.config.ConfigCommand", "options": [ {
"names": "-h,--help", "description": "Display this help and exit", "javaType":
"boolean", "type": "boolean" } ], "subcommands": [ { "name": "get", "fullName":
"config get", "description": "Display user configuration value", "sourceClass":
"org.apache.camel.dsl.jbang.core.commands.config.ConfigG [...]
{ "name": "debug", "fullName": "debug", "description": "Debug local Camel
integration", "sourceClass": "org.apache.camel.dsl.jbang.core.commands.Debug",
"options": [ { "names": "--ago", "description": "Use ago instead of yyyy-MM-dd
HH:mm:ss in timestamp.", "javaType": "boolean", "type": "boolean" }, { "names":
"--background", "description": "Run in the background", "defaultValue":
"false", "javaType": "boolean", "type": "boolean" }, { "names":
"--background-wait", "description": "How [...]
- { "name": "dependency", "fullName": "dependency", "description": "Displays
all Camel dependencies required to run", "sourceClass":
"org.apache.camel.dsl.jbang.core.commands.DependencyCommand", "options": [ {
"names": "-h,--help", "description": "Display this help and exit", "javaType":
"boolean", "type": "boolean" } ], "subcommands": [ { "name": "audit",
"fullName": "dependency audit", "description": "Checks the dependencies for
known vulnerabilities (CVEs) with OSV.dev and the Apach [...]
+ { "name": "dependency", "fullName": "dependency", "description": "Displays
all Camel dependencies required to run", "sourceClass":
"org.apache.camel.dsl.jbang.core.commands.DependencyCommand", "options": [ {
"names": "-h,--help", "description": "Display this help and exit", "javaType":
"boolean", "type": "boolean" } ], "subcommands": [ { "name": "audit",
"fullName": "dependency audit", "description": "Checks the dependencies for
known vulnerabilities (CVEs) with OSV.dev and the Apach [...]
{ "name": "dev", "fullName": "dev", "description": "Run in dev mode with
live reload", "sourceClass": "org.apache.camel.dsl.jbang.core.commands.Dev",
"options": [ { "names": "--background", "description": "Run in the background",
"defaultValue": "false", "javaType": "boolean", "type": "boolean" }, { "names":
"--background-wait", "description": "How long to wait for the integration in
the background to start, before returning, in millis or as a duration such as
2m (true waits 60 secon [...]
{ "name": "dirty", "fullName": "dirty", "description": "Check if there are
dirty files from previous Camel runs that did not terminate gracefully",
"sourceClass": "org.apache.camel.dsl.jbang.core.commands.process.Dirty",
"options": [ { "names": "--clean", "description": "Clean dirty files which are
no longer in use, and the logs of the previous runs of the integrations (camel
log --previous)", "defaultValue": "false", "javaType": "boolean", "type":
"boolean" }, { "names": "-h,--help" [...]
{ "name": "doc", "fullName": "doc", "description": "Shows documentation
for kamelet, component, EIP, and other Camel resources", "sourceClass":
"org.apache.camel.dsl.jbang.core.commands.catalog.CatalogDoc", "options": [ {
"names": "--camel-version", "description": "To use a different Camel version
than the default version", "javaType": "java.lang.String", "type": "string" },
{ "names": "--download", "description": "Whether to allow automatic downloading
JAR dependencies (over the int [...]
diff --git
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/DependencyAudit.java
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/DependencyAudit.java
index 2e3131103903..286af1f95b26 100644
---
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/DependencyAudit.java
+++
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/DependencyAudit.java
@@ -43,6 +43,8 @@ import org.apache.camel.catalog.cve.CvssScore;
import org.apache.camel.catalog.cve.Dependency;
import org.apache.camel.catalog.cve.HttpProxy;
import org.apache.camel.catalog.cve.OsvClient;
+import org.apache.camel.catalog.cve.OsvDatabase;
+import org.apache.camel.catalog.cve.VulnerabilitySource;
import org.apache.camel.dsl.jbang.core.commands.ai.RouteComponents;
import org.apache.camel.dsl.jbang.core.common.ActionClient;
import org.apache.camel.dsl.jbang.core.common.CliException;
@@ -50,6 +52,7 @@ import org.apache.camel.dsl.jbang.core.common.CliExitCode;
import org.apache.camel.dsl.jbang.core.common.JsonOutput;
import org.apache.camel.dsl.jbang.core.common.OsvProxy;
import org.apache.camel.dsl.jbang.core.common.ProcessFinder;
+import org.apache.camel.dsl.jbang.run.common.CamelHome;
import org.apache.camel.tooling.maven.MavenArtifact;
import org.apache.camel.tooling.maven.MavenDownloaderImpl;
import org.apache.camel.tooling.maven.MavenGav;
@@ -65,13 +68,16 @@ import org.apache.camel.util.json.JsonObject;
description = "Checks the dependencies for known
vulnerabilities (CVEs) with OSV.dev and the Apache Camel security advisories",
generateHelp = true,
footer = {
- "Exits 1 when a vulnerability at or above --fail-on
is found (default: any), so a CI job fails.",
+ "Exits 1 when a vulnerability at or above --fail-on
is found (default: any), so a CI job fails,",
+ "and with --fail-on-error also when OSV.dev or the
OSV database could not be used.",
"",
"Examples:",
" camel dependency audit",
" camel dependency audit --by-artifact",
" camel dependency audit --integration=my-app",
" camel dependency audit --severity=high
--fail-on=critical",
+ " camel dependency audit --osv-database
--fail-on-error",
+ " camel dependency audit
--osv-database-url=https://nexus.corp.com/repository/osv/Maven/all.zip",
" camel dependency audit --json" })
public class DependencyAudit extends DependencyList {
@@ -100,8 +106,25 @@ public class DependencyAudit extends DependencyList {
description = "Checks the Apache Camel security advisories of the
catalog only, without OSV.dev")
boolean offline;
+ @Option(name = "fail-on-error", hasValue = false,
+ description = "Exits 1 when the dependencies could not be checked
with OSV.dev or the OSV database (not reachable, no database),"
+ + " instead of checking the Apache Camel security
advisories only")
+ boolean failOnError;
+
+ @Option(name = "osv-database", hasValue = false,
+ description = "Checks with the offline OSV database instead of the
OSV.dev API: the export of all the Maven vulnerabilities of OSV.dev,"
+ + " downloaded once a day and matched locally, so no
coordinates of the project leave the machine")
+ boolean osvDatabase;
+
+ @Option(name = "osv-database-url",
+ description = "Where the offline OSV database is downloaded from,
such as a mirror on the repository manager of the company,"
+ + " or a ZIP file on disk (default: " +
OsvDatabase.DEFAULT_URL + "). Implies --osv-database")
+ String osvDatabaseUrl;
+
// the direct dependencies of the project, as DependencyList finds them
private final List<MavenGav> directDeps = new ArrayList<>();
+ // the offline OSV database, when it is used
+ private OsvDatabase database;
@Override
public Integer doCall() throws Exception {
@@ -143,14 +166,14 @@ public class DependencyAudit extends DependencyList {
}
List<Dependency> deps = new ArrayList<>();
Map<String, Path> jars = new HashMap<>();
- HttpProxy proxy = null;
+ VulnerabilitySource source = null;
if (!gavs.isEmpty()) {
boolean snapshot = gavs.stream().anyMatch(g ->
g.contains("SNAPSHOT"));
try (MavenDownloaderImpl downloader = new MavenDownloaderImpl()) {
downloader.setMavenSettingsLocation(mavenSettings);
downloader.setMavenSettingsSecurityLocation(mavenSettingsSecurity);
downloader.build();
- proxy = offline ? null : OsvProxy.resolve(downloader,
System.getenv());
+ source = vulnerabilitySource(downloader);
for (MavenArtifact ma : downloader.resolveArtifacts(gavs,
Set.of(), true, snapshot)) {
MavenGav g = ma.getGav();
if (g.getVersion() == null || skipArtifact(g.getGroupId(),
g.getArtifactId(), g.getVersion())) {
@@ -163,12 +186,12 @@ public class DependencyAudit extends DependencyList {
}
}
}
- if (proxy == null && !offline) {
- proxy = OsvProxy.resolve(mavenSettings, mavenSettingsSecurity,
System.getenv());
+ if (source == null) {
+ source = vulnerabilitySource(null);
}
CamelCatalog catalog = new DefaultCamelCatalog();
return report("project", deps, CveAudit.audit(deps, jars, declared,
Map.of(), routeComponents(catalog),
- catalog, offline ? null : new OsvClient(proxy)));
+ catalog, source));
}
/** The classpath of a running integration, and the components of its
endpoints. */
@@ -196,8 +219,29 @@ public class DependencyAudit extends DependencyList {
String name = process.name() != null && !process.name().contains(" ")
? process.name() + " (" + process.pid() + ")" :
String.valueOf(process.pid());
return report("integration " + name, deps, CveAudit.audit(deps, jars,
declaredDependencies(process.status()),
- Map.of(), endpointComponents(process.status()), catalog,
- offline ? null : new OsvClient(OsvProxy.resolve(mavenSettings,
mavenSettingsSecurity, System.getenv()))));
+ Map.of(), endpointComponents(process.status()), catalog,
vulnerabilitySource(null)));
+ }
+
+ /**
+ * Where the vulnerabilities come from: the offline OSV database
(--osv-database), the OSV.dev API, or none
+ * (--offline). The proxy comes from the Maven settings of the downloader
(null to read them), else HTTPS_PROXY.
+ */
+ VulnerabilitySource vulnerabilitySource(MavenDownloaderImpl downloader) {
+ if (offline) {
+ return null;
+ }
+ Map<String, String> env = System.getenv();
+ if (osvDatabase || osvDatabaseUrl != null) {
+ String url = osvDatabaseUrl != null && !osvDatabaseUrl.isBlank() ?
osvDatabaseUrl : OsvDatabase.DEFAULT_URL;
+ HttpProxy proxy = !url.startsWith("http://") &&
!url.startsWith("https://") ? null
+ : downloader != null ? OsvProxy.resolve(downloader, env,
url)
+ : OsvProxy.resolve(mavenSettings, mavenSettingsSecurity,
env, url);
+ database = OsvDatabase.open(url,
CamelHome.getCamelDir().resolve("osv"), OsvDatabase.DEFAULT_MAX_AGE, proxy);
+ return database;
+ }
+ return new OsvClient(
+ downloader != null
+ ? OsvProxy.resolve(downloader, env) :
OsvProxy.resolve(mavenSettings, mavenSettingsSecurity, env));
}
/** The components the routes of the project files use; null when there
are no route files. */
@@ -298,21 +342,24 @@ public class DependencyAudit extends DependencyList {
if (result.osvError() != null) {
outPrinter().printWarn(result.osvError() + ": only the Apache
Camel security advisories were checked");
}
+ if (database != null && database.warning() != null) {
+ outPrinter().printWarn(database.warning());
+ }
String below = notListed > 0 ? " (" + notListed + " more below
--severity=" + severity + ")" : "";
if (findings.isEmpty()) {
outPrinter().println((notListed > 0
? "No vulnerabilities of " + severity + " severity or
worse in "
: "No known vulnerabilities in ")
+ deps.size() + " dependencies of the " +
source
- + (offline ? " (Apache Camel security
advisories only)" : "") + below);
+ + (offline ? " (Apache Camel security
advisories only)" : "") + databaseNote() + below);
} else {
outPrinter().println(byArtifact ? artifactTable(artifacts) :
findingTable(findings));
outPrinter().println();
outPrinter().println(findings.size() + " vulnerabilities in "
+ artifacts.size() + " of " + deps.size()
- + " dependencies of the " + source +
counts(findings) + below);
+ + " dependencies of the " + source +
counts(findings) + databaseNote() + below);
}
}
- return failed(result.findings()) ? CliExitCode.FAILURE :
CliExitCode.OK;
+ return failed(result) ? CliExitCode.FAILURE : CliExitCode.OK;
}
/**
@@ -330,13 +377,24 @@ public class DependencyAudit extends DependencyList {
doc.put("vulnerableArtifacts", artifacts.size());
doc.put("severity", severity);
doc.put("failOn", failOn);
- doc.put("failed", failed(result.findings()));
+ doc.put("failed", failed(result));
if (result.osvError() != null) {
doc.put("osvError", result.osvError());
}
if (offline) {
doc.put("offline", true);
}
+ if (database != null) {
+ JsonObject db = new JsonObject();
+ db.put("location", database.location());
+ if (database.updated() != null) {
+ db.put("updated", database.updated().toString());
+ }
+ if (database.warning() != null) {
+ db.put("warning", database.warning());
+ }
+ doc.put("osvDatabase", db);
+ }
JsonArray rows = new JsonArray();
if (byArtifact) {
artifacts.forEach(a -> rows.add(a.toJson()));
@@ -348,6 +406,22 @@ public class DependencyAudit extends DependencyList {
return doc;
}
+ // which offline OSV database was used, such as " (offline OSV database,
updated 2026-11-20)"
+ private String databaseNote() {
+ if (database == null || database.updated() == null) {
+ return "";
+ }
+ return " (offline OSV database, updated " +
database.updated().toString().substring(0, 10) + ")";
+ }
+
+ /**
+ * Whether the command exits with 1: a vulnerability at or above
--fail-on, or (--fail-on-error) the JARs could not
+ * be checked with OSV.dev or the OSV database.
+ */
+ boolean failed(CveAudit.Result result) {
+ return failed(result.findings()) || (failOnError && result.osvError()
!= null);
+ }
+
/** Whether a vulnerability at or above --fail-on was found (of all of
them, not only those listed). */
boolean failed(List<CveFinding> findings) {
int level = LEVELS.indexOf(failOn);
diff --git
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/OsvProxy.java
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/OsvProxy.java
index 2cd5a9ee8e4c..427b62408235 100644
---
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/OsvProxy.java
+++
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/OsvProxy.java
@@ -34,9 +34,17 @@ public final class OsvProxy {
private OsvProxy() {
}
- /** The proxy, from the Maven settings of a built downloader, else from
the environment. */
+ /** The proxy to OSV.dev, from the Maven settings of a built downloader,
else from the environment. */
public static HttpProxy resolve(MavenDownloaderImpl downloader,
Map<String, String> env) {
- MavenProxy maven = downloader != null ?
downloader.proxyFor(OsvClient.API_URL) : null;
+ return resolve(downloader, env, OsvClient.API_URL);
+ }
+
+ /**
+ * The proxy to the given URL (such as the one of the offline OSV
database), from the Maven settings of a built
+ * downloader, else from the environment.
+ */
+ public static HttpProxy resolve(MavenDownloaderImpl downloader,
Map<String, String> env, String url) {
+ MavenProxy maven = downloader != null ? downloader.proxyFor(url) :
null;
if (maven != null) {
// with the nonProxyHosts: the TUI fetches other URLs (the
documentation) through the same proxy
return new HttpProxy(
@@ -51,11 +59,17 @@ public final class OsvProxy {
* the environment. Only the settings are read: nothing is downloaded.
*/
public static HttpProxy resolve(String mavenSettings, String
mavenSettingsSecurity, Map<String, String> env) {
+ return resolve(mavenSettings, mavenSettingsSecurity, env,
OsvClient.API_URL);
+ }
+
+ /** The proxy to the given URL, from the given Maven settings, else from
the environment. */
+ public static HttpProxy resolve(
+ String mavenSettings, String mavenSettingsSecurity, Map<String,
String> env, String url) {
try (MavenDownloaderImpl downloader = new MavenDownloaderImpl()) {
downloader.setMavenSettingsLocation(mavenSettings);
downloader.setMavenSettingsSecurityLocation(mavenSettingsSecurity);
downloader.build();
- return resolve(downloader, env);
+ return resolve(downloader, env, url);
} catch (Exception e) {
// unreadable settings: as without them
return HttpProxy.fromEnvironment(env);
diff --git
a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/DependencyAuditTest.java
b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/DependencyAuditTest.java
index f77c0f97cd25..55248c8a3483 100644
---
a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/DependencyAuditTest.java
+++
b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/DependencyAuditTest.java
@@ -16,20 +16,32 @@
*/
package org.apache.camel.dsl.jbang.core.commands;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
import org.apache.camel.catalog.cve.CveAudit;
import org.apache.camel.catalog.cve.CveFinding;
import org.apache.camel.catalog.cve.CveScan;
+import org.apache.camel.catalog.cve.Dependency;
+import org.apache.camel.catalog.cve.OsvDatabase;
+import org.apache.camel.catalog.cve.VulnerabilitySource;
import org.apache.camel.dsl.jbang.core.common.CliException;
import org.apache.camel.util.json.JsonObject;
import org.apache.camel.util.json.Jsoner;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.assertj.core.api.InstanceOfAssertFactories.LIST;
/**
* CAMEL-27340: camel dependency audit, the parts that need no network or
running integration.
@@ -85,6 +97,21 @@ class DependencyAuditTest {
assertThat(audit.jsonReport("project", 5, result, List.of(),
List.of()).getBoolean("failed")).isFalse();
}
+ @Test
+ void failOnErrorWhenOsvCouldNotBeUsed() {
+ CveAudit.Result unchecked = new CveAudit.Result(List.of(), List.of(),
"OSV.dev could not be reached: timeout");
+ DependencyAudit audit = new DependencyAudit();
+ audit.failOn = "low";
+
+ // only the Camel advisories were checked: a warning, not a failure
+ assertThat(audit.failed(unchecked)).isFalse();
+
+ audit.failOnError = true;
+ assertThat(audit.failed(unchecked)).isTrue();
+ assertThat(audit.jsonReport("project", 3, unchecked, List.of(),
List.of()).getBoolean("failed")).isTrue();
+ assertThat(audit.failed(new CveAudit.Result(List.of(), List.of(),
null))).isFalse();
+ }
+
@Test
void aSeverityOptionMustBeALevel() {
DependencyAudit.checkLevel("--severity", "HIGH", false);
@@ -135,4 +162,35 @@ class DependencyAuditTest {
assertThat(DependencyAudit.classpathOf(reply)).containsExactly("/r/a.jar",
"/r/b.jar", "/r/commons-text-1.9.jar");
assertThat(DependencyAudit.classpathOf(null)).isEmpty();
}
+
+ @Test
+ void theOfflineOsvDatabaseOfAFile(@TempDir Path dir) throws IOException {
+ // CAMEL-27344: a ZIP on disk, as a mirror of the OSV export
+ Path zip = dir.resolve("all.zip");
+ try (OutputStream file = Files.newOutputStream(zip); ZipOutputStream
out = new ZipOutputStream(file)) {
+ out.putNextEntry(new ZipEntry("GHSA-599f-7c49-w659.json"));
+ out.write("""
+ {"id": "GHSA-599f-7c49-w659", "aliases":
["CVE-2022-42889"], "summary": "Arbitrary code execution",
+ "affected": [{"package": {"name":
"org.apache.commons:commons-text", "ecosystem": "Maven"},
+ "ranges": [{"type": "ECOSYSTEM", "events":
[{"introduced": "1.5"}, {"fixed": "1.10.0"}]}]}]}
+ """.getBytes(StandardCharsets.UTF_8));
+ out.closeEntry();
+ }
+ DependencyAudit audit = new DependencyAudit();
+ audit.osvDatabaseUrl = zip.toString();
+
+ VulnerabilitySource source = audit.vulnerabilitySource(null);
+
+ assertThat(source).isInstanceOf(OsvDatabase.class);
+ assertThat(source.queryBatch(List.of(new
Dependency("org.apache.commons", "commons-text", "1.9"))))
+
.extractingByKey("org.apache.commons:commons-text:1.9").asInstanceOf(LIST).hasSize(1);
+ CveAudit.Result result = new CveAudit.Result(List.of(), List.of(),
null);
+ JsonObject db = (JsonObject) audit.jsonReport("project", 1, result,
List.of(), List.of()).get("osvDatabase");
+ assertThat(db.getString("location")).isEqualTo(zip.toString());
+ assertThat(db.getString("updated")).isNotBlank();
+
+ // --offline wins
+ audit.offline = true;
+ assertThat(audit.vulnerabilitySource(null)).isNull();
+ }
}
diff --git
a/dsl/camel-jbang/camel-jbang-core/src/test/resources/golden/cli-help.txt
b/dsl/camel-jbang/camel-jbang-core/src/test/resources/golden/cli-help.txt
index 31b5c0027959..dc09df9b96c1 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/test/resources/golden/cli-help.txt
+++ b/dsl/camel-jbang/camel-jbang-core/src/test/resources/golden/cli-help.txt
@@ -2404,6 +2404,8 @@ Apache Camel security advisories
Usage: camel dependency audit [-hy] [--integration=<integration>]
[--by-artifact] [--json] [--severity=<severity>]
[--fail-on=<fail-on>] [--offline]
+ [--fail-on-error] [--osv-database]
+ [--osv-database-url=<osv-database-url>]
[--output=<output>] [--dep=<dep>]
[--runtime=<runtime>] [--name=<name>]
[--port=<port>]
@@ -2459,6 +2461,21 @@ Options:
Default: low
--offline Checks the Apache Camel security advisories of the
catalog only, without OSV.dev
+ --fail-on-error Exits 1 when the dependencies could not be checked
+ with OSV.dev or the OSV database (not reachable, no
+ database), instead of checking the Apache Camel
+ security advisories only
+ --osv-database Checks with the offline OSV database instead of the
+ OSV.dev API: the export of all the Maven
+ vulnerabilities of OSV.dev, downloaded once a day
+ and matched locally, so no coordinates of the
+ project leave the machine
+ --osv-database-url=<osv-database-url>
+ Where the offline OSV database is downloaded from,
+ such as a mirror on the repository manager of the
+ company, or a ZIP file on disk (default:
+
https://osv-vulnerabilities.storage.googleapis.com/Maven/all.zip).
+ Implies --osv-database
--output=<output> Output format (gav, maven, jbang)
Default: gav
--dep, --dependency=<dep>
@@ -2622,13 +2639,17 @@ Options:
specified then what was last run will be exported.
Exits 1 when a vulnerability at or above --fail-on is found (default: any), so
a
-CI job fails.
+CI job fails,
+and with --fail-on-error also when OSV.dev or the OSV database could not be
+used.
Examples:
camel dependency audit
camel dependency audit --by-artifact
camel dependency audit --integration=my-app
camel dependency audit --severity=high --fail-on=critical
+ camel dependency audit --osv-database --fail-on-error
+ camel dependency audit
--osv-database-url=https://nexus.corp.com/repository/osv/Maven/all.zip
camel dependency audit --json
== camel dependency copy --help
diff --git
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/CveAuditTab.java
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/CveAuditTab.java
index 053bb12db682..d33a54a25ae6 100644
---
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/CveAuditTab.java
+++
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/CveAuditTab.java
@@ -54,6 +54,8 @@ import org.apache.camel.catalog.cve.CveScan;
import org.apache.camel.catalog.cve.CvssScore;
import org.apache.camel.catalog.cve.Dependency;
import org.apache.camel.catalog.cve.OsvClient;
+import org.apache.camel.catalog.cve.OsvDatabase;
+import org.apache.camel.catalog.cve.VulnerabilitySource;
import org.apache.camel.util.json.JsonArray;
import org.apache.camel.util.json.JsonObject;
@@ -79,6 +81,8 @@ class CveAuditTab extends AbstractTableTab {
private volatile String errorMessage;
// the JARs were not checked against OSV.dev (it could not be reached):
only the Camel advisories were
private volatile String osvError;
+ // which offline OSV database the last scan used, such as "offline OSV
database, updated 2026-11-20"; null for the API
+ private volatile String sourceNote;
private volatile boolean dataLoaded;
private int scannedCount;
@@ -480,6 +484,8 @@ class CveAuditTab extends AbstractTableTab {
}
if (osvError != null) {
sb.append(" - OSV.dev not checked");
+ } else if (sourceNote != null) {
+ sb.append(" - ").append(sourceNote);
}
sb.append(" ");
return sb.toString();
@@ -595,13 +601,23 @@ class CveAuditTab extends AbstractTableTab {
IntegrationInfo current = ctx.findSelectedIntegration();
List<Dependency> deps = allDeps.stream()
.map(d -> new Dependency(d.groupId(), d.artifactId(),
d.version())).toList();
+ // the source and the proxy are looked up for each scan, so a change
in the settings applies without a restart
+ VulnerabilitySource source = TuiSettings.vulnerabilitySource();
+ sourceNote = source instanceof OsvDatabase db ? databaseNote(db) :
null;
CveAudit.Result result = CveAudit.audit(deps, jars,
declaredDependencies(info), fallbackVia,
endpointComponents(current != null ? current : info),
ProjectOverviewAssist.catalog(),
- // the proxy is looked up for each scan, so a change in the
settings applies without a restart
- new OsvClient(TuiSettings.httpProxy()));
+ source);
applyResult(deps, result.findings(), null, result.osvError());
}
+ static String databaseNote(OsvDatabase db) {
+ if (db.updated() == null) {
+ return null;
+ }
+ return "offline OSV database, updated " +
db.updated().toString().substring(0, 10)
+ + (db.warning() != null ? " (the download failed)" : "");
+ }
+
/** The {@code groupId:artifactId} of the dependencies the project
declares. */
private static Set<String> declaredDependencies(IntegrationInfo info) {
Set<String> declared = new HashSet<>();
diff --git
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/SettingsPopup.java
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/SettingsPopup.java
index 4b746d7a0a26..86cacc4dcc19 100644
---
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/SettingsPopup.java
+++
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/SettingsPopup.java
@@ -59,15 +59,16 @@ class SettingsPopup {
static final int ROW_FOLDER = 11;
static final int ROW_PROXY_HOST = 12;
static final int ROW_PROXY_PORT = 13;
- static final int ROW_SHELL_HISTORY = 14;
- static final int ROW_AI_PROVIDER = 15;
- static final int ROW_AI_MODEL = 16;
- static final int ROW_AI_URL = 17;
- static final int ROW_AI_TOOLS = 18;
- static final int ROW_AI_OVERVIEW = 19;
- static final int ROW_AI_PROMPT_HISTORY = 20;
- static final int ROW_AI_ACP_COMMAND = 21;
- static final int ROW_COUNT = 22;
+ static final int ROW_OSV_DATABASE = 14;
+ static final int ROW_SHELL_HISTORY = 15;
+ static final int ROW_AI_PROVIDER = 16;
+ static final int ROW_AI_MODEL = 17;
+ static final int ROW_AI_URL = 18;
+ static final int ROW_AI_TOOLS = 19;
+ static final int ROW_AI_OVERVIEW = 20;
+ static final int ROW_AI_PROMPT_HISTORY = 21;
+ static final int ROW_AI_ACP_COMMAND = 22;
+ static final int ROW_COUNT = 23;
/**
* Separator lines drawn between the row groups, after the Select Tab,
Panel Theme, Default Folder and Shell History
* rows.
@@ -125,6 +126,7 @@ class SettingsPopup {
private TextInputState folderInput;
private TextInputState proxyHostInput;
private TextInputState proxyPortInput;
+ private TextInputState osvDatabaseInput;
private TextInputState shellHistoryInput;
private TextInputState aiModelInput;
private TextInputState aiUrlInput;
@@ -209,6 +211,7 @@ class SettingsPopup {
folderInput = new TextInputState(settings.getDefaultFolder() != null ?
settings.getDefaultFolder() : "");
proxyHostInput = new TextInputState(settings.getProxyHost() != null ?
settings.getProxyHost() : "");
proxyPortInput = new TextInputState(settings.getProxyPort() != null ?
settings.getProxyPort() : "");
+ osvDatabaseInput = new TextInputState(settings.getOsvDatabase() !=
null ? settings.getOsvDatabase() : "");
shellHistoryInput = new TextInputState(settings.getShellHistory() !=
null ? settings.getShellHistory() : "");
String currentProvider = settings.getAiProvider() != null ?
settings.getAiProvider() : "auto";
int providerIdx = AI_PROVIDERS.indexOf(currentProvider);
@@ -331,6 +334,10 @@ class SettingsPopup {
handleTextInput(ke, proxyPortInput);
return true;
}
+ if (selectedRow == ROW_OSV_DATABASE) {
+ handleTextInput(ke, osvDatabaseInput);
+ return true;
+ }
if (selectedRow == ROW_SHELL_HISTORY) {
handleTextInput(ke, shellHistoryInput);
return true;
@@ -421,6 +428,7 @@ class SettingsPopup {
settings.setDefaultFolder(stripControlChars(folderInput.text().trim()));
settings.setProxyHost(stripControlChars(proxyHostInput.text().trim()));
settings.setProxyPort(stripControlChars(proxyPortInput.text().trim()));
+
settings.setOsvDatabase(stripControlChars(osvDatabaseInput.text().trim()));
settings.setShellHistory(stripControlChars(shellHistoryInput.text().trim()));
settings.setAiProvider(AI_PROVIDERS.get(aiProviderIndex));
settings.setAiModel(stripControlChars(aiModelInput.text().trim()));
@@ -555,6 +563,11 @@ class SettingsPopup {
selectedRow == ROW_PROXY_PORT, "(8080)");
rowY++;
+ renderLabel(frame, innerX, rowY, labelW, "OSV Database:", selectedRow
== ROW_OSV_DATABASE);
+ renderTextInput(frame, innerX + labelW, rowY, fieldW, osvDatabaseInput,
+ selectedRow == ROW_OSV_DATABASE, "(OSV.dev API) default, a URL
or a file");
+ rowY++;
+
renderLabel(frame, innerX, rowY, labelW, "Shell History:", selectedRow
== ROW_SHELL_HISTORY);
renderTextInput(frame, innerX + labelW, rowY, fieldW,
shellHistoryInput,
selectedRow == ROW_SHELL_HISTORY, "(100)");
diff --git
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiSettings.java
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiSettings.java
index 976602d5e6a8..486662201d22 100644
---
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiSettings.java
+++
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiSettings.java
@@ -16,8 +16,16 @@
*/
package org.apache.camel.dsl.jbang.core.commands.tui;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.ConcurrentHashMap;
+
import org.apache.camel.catalog.cve.HttpProxy;
+import org.apache.camel.catalog.cve.OsvClient;
+import org.apache.camel.catalog.cve.OsvDatabase;
+import org.apache.camel.catalog.cve.VulnerabilitySource;
import org.apache.camel.dsl.jbang.core.common.OsvProxy;
+import org.apache.camel.dsl.jbang.run.common.CamelHome;
/**
* User-facing preferences for the Camel TUI, persisted under {@code
camel.tui.*} keys in the CLI user configuration
@@ -44,6 +52,7 @@ final class TuiSettings {
static final String PROP_AI_ACP_COMMAND = "camel.tui.ai.acp.command";
static final String PROP_PROXY_HOST = "camel.tui.proxyHost";
static final String PROP_PROXY_PORT = "camel.tui.proxyPort";
+ static final String PROP_OSV_DATABASE = "camel.tui.osvDatabase";
static final String PROP_SHELL_HISTORY = "camel.tui.shell.history";
static final String PROP_AI_PROMPT_HISTORY = "camel.tui.ai.promptHistory";
static final String PROP_CONFIRM_ACTIONS = "camel.tui.confirmActions";
@@ -61,6 +70,7 @@ final class TuiSettings {
private String defaultFolder;
private String proxyHost;
private String proxyPort;
+ private String osvDatabase;
private String aiProvider;
private String aiModel;
private String aiUrl;
@@ -140,6 +150,15 @@ final class TuiSettings {
this.proxyPort = proxyPort;
}
+ /** The offline OSV database of the CVE Audit screen: {@code default}, a
URL or a file; null for the OSV.dev API. */
+ String getOsvDatabase() {
+ return osvDatabase;
+ }
+
+ void setOsvDatabase(String osvDatabase) {
+ this.osvDatabase = osvDatabase;
+ }
+
String getAiProvider() {
return aiProvider;
}
@@ -309,6 +328,7 @@ final class TuiSettings {
settings.defaultFolder =
trimToNull(TuiUserConfig.read(PROP_DEFAULT_FOLDER));
settings.proxyHost =
trimToNull(TuiUserConfig.read(PROP_PROXY_HOST));
settings.proxyPort =
trimToNull(TuiUserConfig.read(PROP_PROXY_PORT));
+ settings.osvDatabase =
trimToNull(TuiUserConfig.read(PROP_OSV_DATABASE));
settings.aiProvider =
trimToNull(TuiUserConfig.read(PROP_AI_PROVIDER));
settings.aiModel = trimToNull(TuiUserConfig.read(PROP_AI_MODEL));
settings.aiUrl = trimToNull(TuiUserConfig.read(PROP_AI_URL));
@@ -344,6 +364,7 @@ final class TuiSettings {
TuiUserConfig.write(PROP_DEFAULT_FOLDER, defaultFolder);
TuiUserConfig.write(PROP_PROXY_HOST, proxyHost);
TuiUserConfig.write(PROP_PROXY_PORT, proxyPort);
+ TuiUserConfig.write(PROP_OSV_DATABASE, osvDatabase);
TuiUserConfig.write(PROP_AI_PROVIDER, aiProvider);
TuiUserConfig.write(PROP_AI_MODEL, aiModel);
TuiUserConfig.write(PROP_AI_URL, aiUrl);
@@ -363,16 +384,22 @@ final class TuiSettings {
}
}
- // the proxy of the Maven settings or of HTTPS_PROXY, looked up once:
reading the settings builds a resolver session
- private static HttpProxy fallbackProxy;
- private static boolean fallbackResolved;
+ // the proxy of the Maven settings or of HTTPS_PROXY by URL, looked up
once: reading the settings builds a resolver
+ // session; Optional as the map takes no null
+ private static final Map<String, Optional<HttpProxy>> FALLBACK_PROXIES =
new ConcurrentHashMap<>();
+
+ /** The proxy to reach OSV.dev through, see {@link #httpProxy(String)}. */
+ static HttpProxy httpProxy() {
+ return httpProxy(OsvClient.API_URL);
+ }
/**
- * The proxy to reach the internet through (OSV.dev of the CVE Audit
screen, the documentation): the Proxy Host and
- * Proxy Port of the settings, else the active proxy of the Maven settings
({@code ~/.m2/settings.xml}, with its
- * username and password), else {@code HTTPS_PROXY}; null for the proxy
settings of the JVM.
+ * The proxy to reach a URL through (OSV.dev and the offline OSV database
of the CVE Audit screen, the
+ * documentation): the Proxy Host and Proxy Port of the settings, else the
active proxy of the Maven settings
+ * ({@code ~/.m2/settings.xml}, with its username, password and
nonProxyHosts), else {@code HTTPS_PROXY}; null for
+ * the proxy settings of the JVM.
*/
- static HttpProxy httpProxy() {
+ static HttpProxy httpProxy(String url) {
TuiSettings s = load();
String host = s.getProxyHost();
if (host != null && !host.isEmpty()) {
@@ -387,15 +414,24 @@ final class TuiSettings {
}
return new HttpProxy(host, port);
}
- return fallbackProxy();
+ return FALLBACK_PROXIES
+ .computeIfAbsent(url, u ->
Optional.ofNullable(OsvProxy.resolve(null, null, System.getenv(), u)))
+ .orElse(null);
}
- private static synchronized HttpProxy fallbackProxy() {
- if (!fallbackResolved) {
- fallbackProxy = OsvProxy.resolve(null, null, System.getenv());
- fallbackResolved = true;
+ /**
+ * Where the CVE Audit screen gets the vulnerabilities from: the offline
OSV database of the OSV Database setting
+ * ({@code default} or {@code true} for the export of OSV.dev, else a URL
or a file), cached in {@code ~/.camel/osv}
+ * as {@code camel dependency audit --osv-database} does, else the OSV.dev
API.
+ */
+ static VulnerabilitySource vulnerabilitySource() {
+ String db = load().getOsvDatabase();
+ if (db == null || db.isBlank()) {
+ return new OsvClient(httpProxy());
}
- return fallbackProxy;
+ String url = "default".equalsIgnoreCase(db) ||
"true".equalsIgnoreCase(db) ? OsvDatabase.DEFAULT_URL : db;
+ HttpProxy proxy = url.startsWith("http://") ||
url.startsWith("https://") ? httpProxy(url) : null;
+ return OsvDatabase.open(url, CamelHome.getCamelDir().resolve("osv"),
OsvDatabase.DEFAULT_MAX_AGE, proxy);
}
private static String trimToNull(String value) {
diff --git
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/resources/tui/help/cve-audit.md
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/resources/tui/help/cve-audit.md
index 30ed17846039..d8f4c7b326b1 100644
---
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/resources/tui/help/cve-audit.md
+++
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/resources/tui/help/cve-audit.md
@@ -63,6 +63,17 @@ also benefit from the cache. Press `r` to force a rescan.
When
OSV.dev cannot be reached, the title says so and only the Camel
advisories were checked: press `r` to try again.
+## Offline OSV Database
+
+By default the coordinates of the JARs are sent to the OSV.dev API.
+With **OSV Database** in Settings (F2 > Settings...) set to `default`,
+the tab uses the export of all the Maven vulnerabilities of OSV.dev
+instead, downloaded once a day into `~/.camel/osv` and matched
+locally, so no coordinates leave the machine; the title says
+`offline OSV database, updated <date>`. Set it to a URL to download
+the export from a mirror (such as the repository manager of the
+company), or to a ZIP file on disk. Leave it empty for the API.
+
## Explain with AI
Press `Shift+F8` on a vulnerability to ask the AI about it, or on an
diff --git
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/SettingsPopupRenderTest.java
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/SettingsPopupRenderTest.java
index 4d48d90828e7..b60e5e6093e7 100644
---
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/SettingsPopupRenderTest.java
+++
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/SettingsPopupRenderTest.java
@@ -72,7 +72,8 @@ class SettingsPopupRenderTest {
new TabRegistry.TabEntry("🩺", "Health", "health", "7", 6,
-1)));
popup.open();
- Rect area = new Rect(0, 0, 80, 30);
+ // tall enough for all the rows without scrolling
+ Rect area = new Rect(0, 0, 80, 32);
Buffer buffer = Buffer.empty(area);
Frame frame = Frame.forTesting(buffer);
popup.render(frame, area);
@@ -85,6 +86,7 @@ class SettingsPopupRenderTest {
assertTrue(rendered.contains("Rate per"), "the Rate per row should be
shown");
assertTrue(rendered.contains("Panel Theme"), "the Panel Theme row
should be shown");
assertTrue(rendered.contains("Default Folder"), "the Default Folder
row should be shown");
+ assertTrue(rendered.contains("OSV Database"), "the OSV Database row
should be shown");
assertTrue(rendered.contains("AI Provider"), "the AI Provider row
should be shown");
assertTrue(rendered.contains("AI Model"), "the AI Model row should be
shown");
assertTrue(rendered.contains("AI Base URL"), "the AI Base URL row
should be shown");
diff --git
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiSettingsTest.java
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiSettingsTest.java
index 4089d53e3b39..bb9038082873 100644
---
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiSettingsTest.java
+++
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiSettingsTest.java
@@ -16,9 +16,13 @@
*/
package org.apache.camel.dsl.jbang.core.commands.tui;
+import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
+import java.util.zip.ZipOutputStream;
+import org.apache.camel.catalog.cve.OsvDatabase;
+import org.apache.camel.catalog.cve.VulnerabilitySource;
import org.apache.camel.dsl.jbang.core.common.CommandLineHelper;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
@@ -197,4 +201,25 @@ class TuiSettingsTest {
Files.deleteIfExists(localFile);
}
}
+
+ @Test
+ void theOsvDatabaseSettingIsTheSourceOfTheCveAudit(@TempDir Path tempDir)
throws Exception {
+ // CAMEL-27344: a ZIP on disk, as a mirror of the OSV export
+ useHome(tempDir);
+ Path zip = tempDir.resolve("all.zip");
+ try (OutputStream file = Files.newOutputStream(zip); ZipOutputStream
out = new ZipOutputStream(file)) {
+ out.finish();
+ }
+ TuiSettings settings = TuiSettings.load();
+ assertNull(settings.getOsvDatabase());
+ settings.setOsvDatabase(zip.toString());
+ settings.save();
+ assertEquals(zip.toString(), TuiSettings.load().getOsvDatabase());
+
+ VulnerabilitySource source = TuiSettings.vulnerabilitySource();
+
+ assertThat(source).isInstanceOf(OsvDatabase.class);
+ assertEquals(zip, ((OsvDatabase) source).file());
+ assertThat(CveAuditTab.databaseNote((OsvDatabase)
source)).startsWith("offline OSV database, updated ");
+ }
}