You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maven.apache.org by gn...@apache.org on 2026/08/31 11:57:06 UTC
(maven-deploy-plugin) branch security/audit-medium-fixes created (now 6812306)
This is an automated email from the ASF dual-hosted git repository.
gnodet pushed a change to branch security/audit-medium-fixes
in repository https://gitbox.apache.org/repos/asf/maven-deploy-plugin.git
at 6812306 fix: adapt deployAtEnd re-deploy test for cache optimization compatibility
This branch includes the following new commits:
new e7dcd6a fix: f001 (MEDIUM) — Keeps v1's structure: AbstractDeployMojo.validateCredentialBinding guard
new 2d4d30e fix: f002 (MEDIUM) — Single choke point: AbstractDeployMojo.validateTransportSecurity(id,url)
new 0e15f77 fix: f003 (MEDIUM) — Both legs of the root cause closed with shared validators hoisted to Abs
new 21207aa fix: f004 (MEDIUM) — Two-sided state fix, per the triage recommendation: (1) deployAllAtOnce
new 4155d95 fix: f005 (MEDIUM) — A single class-level monitor (DEPLOY_AT_END_LOCK, a constant lock object
new a5e9653 fix: f006 (MEDIUM) — Verified-true doc fix plus visibility escalation, per the finding brief.
new 6812306 fix: adapt deployAtEnd re-deploy test for cache optimization compatibility
The 7 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
(maven-deploy-plugin) 03/07: fix: f003 (MEDIUM) — Both legs of the root cause closed with shared validators hoisted to Abs
Posted by gn...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
gnodet pushed a commit to branch security/audit-medium-fixes
in repository https://gitbox.apache.org/repos/asf/maven-deploy-plugin.git
commit 0e15f77fb479bbedd814b1539f83e656e43d1d5f
Author: Guillaume Nodet <gn...@gmail.com>
AuthorDate: Mon Aug 31 13:46:26 2026 +0200
fix: f003 (MEDIUM) — Both legs of the root cause closed with shared validators hoisted to Abs
Security audit finding f003 (MEDIUM).
Both legs of the root cause closed with shared validators hoisted to AbstractDeployMojo: isValidId now rejects any empty dot-separated segment (kills '.', '..', '.a', 'a.', 'a..b' while keeping the [a-zA-Z0-9._-] allowlist); isValidVersion keeps the separator blocklist and additionally rejects empty, whitespace/ISO-control characters, and all-dots values; new isValidClassifier (same allowlist, not all-dots, absent/empty allowed) and isValidTypeOrExtension (non-empty variant) cover the [...]
Co-Authored-By: Claude Opus 4.6 <no...@anthropic.com>
---
.../maven/plugins/deploy/AbstractDeployMojo.java | 91 ++++++++++++++++++++++
.../maven/plugins/deploy/DeployFileMojo.java | 57 +++++---------
.../apache/maven/plugins/deploy/DeployMojo.java | 11 +++
.../plugins/deploy/DeployFileMojoUnitTest.java | 48 ++++++++++++
4 files changed, 169 insertions(+), 38 deletions(-)
diff --git a/src/main/java/org/apache/maven/plugins/deploy/AbstractDeployMojo.java b/src/main/java/org/apache/maven/plugins/deploy/AbstractDeployMojo.java
index 7ab8339..e9039cb 100644
--- a/src/main/java/org/apache/maven/plugins/deploy/AbstractDeployMojo.java
+++ b/src/main/java/org/apache/maven/plugins/deploy/AbstractDeployMojo.java
@@ -180,6 +180,97 @@ public abstract class AbstractDeployMojo implements Mojo {
|| "0:0:0:0:0:0:0:1".equals(host);
}
+ static final String ILLEGAL_VERSION_CHARS = "\\/:\"<>|?*[](){},";
+
+ /**
+ * Returns {@code true} if passed in string is "valid Maven ID" (groupId or artifactId): only
+ * {@code [a-zA-Z0-9._-]} characters, and no empty dot-separated segment (which rejects values
+ * that are entirely dots such as {@code ".."} - a whole repository-layout path segment - as
+ * well as leading/trailing/consecutive dots).
+ */
+ static boolean isValidId(String id) {
+ if (id == null || id.isEmpty()) {
+ return false;
+ }
+ for (int i = 0; i < id.length(); i++) {
+ char c = id.charAt(i);
+ if (!(c >= 'a' && c <= 'z'
+ || c >= 'A' && c <= 'Z'
+ || c >= '0' && c <= '9'
+ || c == '-'
+ || c == '_'
+ || c == '.')) {
+ return false;
+ }
+ }
+ for (String segment : id.split("\\.", -1)) {
+ if (segment.isEmpty()) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Returns {@code true} if passed in string is "valid Maven (simple, non range, expression, etc.)
+ * version": no path/separator-dangerous characters, no whitespace or control characters, and not
+ * composed entirely of dots (a version is used verbatim as a whole repository-layout path
+ * segment, so {@code ".."} must not pass).
+ */
+ static boolean isValidVersion(String version) {
+ if (version == null || version.isEmpty()) {
+ return false;
+ }
+ boolean seenNonDot = false;
+ for (int i = version.length() - 1; i >= 0; i--) {
+ char c = version.charAt(i);
+ if (ILLEGAL_VERSION_CHARS.indexOf(c) >= 0 || Character.isWhitespace(c) || Character.isISOControl(c)) {
+ return false;
+ }
+ if (c != '.') {
+ seenNonDot = true;
+ }
+ }
+ return seenNonDot;
+ }
+
+ /**
+ * Returns {@code true} if the passed classifier is absent, empty, or layout-safe: the classifier
+ * is embedded verbatim in the repository-layout file name
+ * ({@code artifactId-version-classifier.extension}), so it must use the same character allowlist
+ * as ids and must not be composed entirely of dots.
+ */
+ static boolean isValidClassifier(String classifier) {
+ if (classifier == null || classifier.isEmpty()) {
+ return true;
+ }
+ boolean seenNonDot = false;
+ for (int i = 0; i < classifier.length(); i++) {
+ char c = classifier.charAt(i);
+ if (!(c >= 'a' && c <= 'z'
+ || c >= 'A' && c <= 'Z'
+ || c >= '0' && c <= '9'
+ || c == '-'
+ || c == '_'
+ || c == '.')) {
+ return false;
+ }
+ if (c != '.') {
+ seenNonDot = true;
+ }
+ }
+ return seenNonDot;
+ }
+
+ /**
+ * Returns {@code true} if the passed artifact type / extension / packaging is layout-safe:
+ * non-empty, id character allowlist, not composed entirely of dots (the extension is appended
+ * to the repository-layout file name).
+ */
+ static boolean isValidTypeOrExtension(String type) {
+ return type != null && !type.isEmpty() && isValidClassifier(type);
+ }
+
/**
* Guards the repository id→URL credential binding: Maven resolves the credentials for a
* deployment repository purely by matching its id against a {@code <server>} entry in
diff --git a/src/main/java/org/apache/maven/plugins/deploy/DeployFileMojo.java b/src/main/java/org/apache/maven/plugins/deploy/DeployFileMojo.java
index 82e281c..0ea359b 100644
--- a/src/main/java/org/apache/maven/plugins/deploy/DeployFileMojo.java
+++ b/src/main/java/org/apache/maven/plugins/deploy/DeployFileMojo.java
@@ -57,7 +57,6 @@ import org.apache.maven.api.services.xml.XmlReaderException;
@SuppressWarnings("unused")
public class DeployFileMojo extends AbstractDeployMojo {
private static final String TAR = "tar.";
- private static final String ILLEGAL_VERSION_CHARS = "\\/:\"<>|?*[](){},";
/**
* GroupId of the artifact to be deployed. Retrieved from POM file if specified.
@@ -284,6 +283,14 @@ public class DeployFileMojo extends AbstractDeployMojo {
throw new MojoException("The artifact information is not valid: uses invalid characters.");
}
+ if (!isValidTypeOrExtension(packaging)) {
+ throw new MojoException("The packaging is not valid: uses invalid characters.");
+ }
+
+ if (!isValidClassifier(classifier)) {
+ throw new MojoException("The classifier is not valid: uses invalid characters.");
+ }
+
failIfOffline();
warnIfAffectedPackagingAndMaven(packaging);
@@ -375,12 +382,22 @@ public class DeployFileMojo extends AbstractDeployMojo {
if (Files.isRegularFile(file)) {
String extension = getExtension(file);
String type = types.substring(ti, nti).trim();
+ String classifierEntry = classifiers.substring(ci, nci).trim();
+
+ if (!isValidTypeOrExtension(type)) {
+ throw new MojoException("The 'types' entry '" + type + "' is not valid:"
+ + " uses invalid characters or is empty.");
+ }
+ if (classifierEntry.isEmpty() || !isValidClassifier(classifierEntry)) {
+ throw new MojoException("The 'classifiers' entry '" + classifierEntry + "' is not valid:"
+ + " uses invalid characters or is empty.");
+ }
ProducedArtifact deployable = session.createProducedArtifact(
artifact.getGroupId(),
artifact.getArtifactId(),
artifact.getVersion().toString(),
- classifiers.substring(ci, nci).trim(),
+ classifierEntry,
extension,
type);
artifactManager.setPath(deployable, file);
@@ -592,40 +609,4 @@ public class DeployFileMojo extends AbstractDeployMojo {
}
return "";
}
-
- /**
- * Returns {@code true} if passed in string is "valid Maven ID" (groupId or artifactId).
- */
- private boolean isValidId(String id) {
- if (id == null) {
- return false;
- }
- for (int i = 0; i < id.length(); i++) {
- char c = id.charAt(i);
- if (!(c >= 'a' && c <= 'z'
- || c >= 'A' && c <= 'Z'
- || c >= '0' && c <= '9'
- || c == '-'
- || c == '_'
- || c == '.')) {
- return false;
- }
- }
- return true;
- }
-
- /**
- * Returns {@code true} if passed in string is "valid Maven (simple. non range, expression, etc) version".
- */
- private boolean isValidVersion(String version) {
- if (version == null) {
- return false;
- }
- for (int i = version.length() - 1; i >= 0; i--) {
- if (ILLEGAL_VERSION_CHARS.indexOf(version.charAt(i)) >= 0) {
- return false;
- }
- }
- return true;
- }
}
diff --git a/src/main/java/org/apache/maven/plugins/deploy/DeployMojo.java b/src/main/java/org/apache/maven/plugins/deploy/DeployMojo.java
index 7758893..1df99d0 100644
--- a/src/main/java/org/apache/maven/plugins/deploy/DeployMojo.java
+++ b/src/main/java/org/apache/maven/plugins/deploy/DeployMojo.java
@@ -299,7 +299,18 @@ public class DeployMojo extends AbstractDeployMojo {
artifactManager.setPath(project.getPomArtifact(), project.getPomPath());
}
+ if (!isValidId(project.getGroupId())
+ || !isValidId(project.getArtifactId())
+ || !isValidVersion(project.getVersion())) {
+ throw new MojoException("The project coordinates " + project.getGroupId() + ":" + project.getArtifactId()
+ + ":" + project.getVersion() + " are not valid: they use invalid characters.");
+ }
+
for (Artifact deployable : deployables) {
+ if (!isValidClassifier(deployable.getClassifier())) {
+ throw new MojoException("The classifier of attached artifact " + deployable
+ + " is not valid: uses invalid characters.");
+ }
if (!isValidPath(deployable)) {
if (deployable == project.getMainArtifact().orElse(null)) {
if (attachedArtifacts.isEmpty()) {
diff --git a/src/test/java/org/apache/maven/plugins/deploy/DeployFileMojoUnitTest.java b/src/test/java/org/apache/maven/plugins/deploy/DeployFileMojoUnitTest.java
index 6a96c4e..21f4175 100644
--- a/src/test/java/org/apache/maven/plugins/deploy/DeployFileMojoUnitTest.java
+++ b/src/test/java/org/apache/maven/plugins/deploy/DeployFileMojoUnitTest.java
@@ -28,6 +28,8 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author <a href="jerome@coffeebreaks.org">Jerome Lacoste</a>
@@ -107,6 +109,52 @@ class DeployFileMojoUnitTest {
assertEquals(expectedPackaging, mojo.getPackaging());
}
+ @Test
+ void idValidationRejectsDotOnlyAndEmptySegments() {
+ assertFalse(AbstractDeployMojo.isValidId("."));
+ assertFalse(AbstractDeployMojo.isValidId(".."));
+ assertFalse(AbstractDeployMojo.isValidId(".a"));
+ assertFalse(AbstractDeployMojo.isValidId("a."));
+ assertFalse(AbstractDeployMojo.isValidId("a..b"));
+ assertFalse(AbstractDeployMojo.isValidId("a/b"));
+ assertFalse(AbstractDeployMojo.isValidId("a\\b"));
+ assertFalse(AbstractDeployMojo.isValidId(""));
+ assertFalse(AbstractDeployMojo.isValidId(null));
+ assertTrue(AbstractDeployMojo.isValidId("org.apache.maven"));
+ assertTrue(AbstractDeployMojo.isValidId("maven-deploy-plugin"));
+ }
+
+ @Test
+ void versionValidationRejectsDotOnlyWhitespaceAndControlChars() {
+ assertFalse(AbstractDeployMojo.isValidVersion("."));
+ assertFalse(AbstractDeployMojo.isValidVersion(".."));
+ assertFalse(AbstractDeployMojo.isValidVersion("1.0 "));
+ assertFalse(AbstractDeployMojo.isValidVersion("1\t0"));
+ assertFalse(AbstractDeployMojo.isValidVersion("1.0/x"));
+ assertFalse(AbstractDeployMojo.isValidVersion(""));
+ assertFalse(AbstractDeployMojo.isValidVersion(null));
+ assertTrue(AbstractDeployMojo.isValidVersion("1.0-SNAPSHOT"));
+ assertTrue(AbstractDeployMojo.isValidVersion("4.0.0-beta-3"));
+ }
+
+ @Test
+ void classifierAndTypeValidationRejectsLayoutTraversal() {
+ assertFalse(AbstractDeployMojo.isValidClassifier("../../../../org/other/1.0/other-1.0"));
+ assertFalse(AbstractDeployMojo.isValidClassifier(".."));
+ assertFalse(AbstractDeployMojo.isValidClassifier("a b"));
+ assertTrue(AbstractDeployMojo.isValidClassifier(null));
+ assertTrue(AbstractDeployMojo.isValidClassifier(""));
+ assertTrue(AbstractDeployMojo.isValidClassifier("sources"));
+ assertTrue(AbstractDeployMojo.isValidClassifier("site.pdf"));
+ assertFalse(AbstractDeployMojo.isValidTypeOrExtension(null));
+ assertFalse(AbstractDeployMojo.isValidTypeOrExtension(""));
+ assertFalse(AbstractDeployMojo.isValidTypeOrExtension(".."));
+ assertFalse(AbstractDeployMojo.isValidTypeOrExtension("jar/../x"));
+ assertTrue(AbstractDeployMojo.isValidTypeOrExtension("jar"));
+ assertTrue(AbstractDeployMojo.isValidTypeOrExtension("tar.gz"));
+ assertTrue(AbstractDeployMojo.isValidTypeOrExtension("maven-plugin"));
+ }
+
private void setMojoModel(
MockDeployFileMojo mojo, String group, String artifact, String version, String packaging, Parent parent) {
mojo.model = Model.newBuilder()
(maven-deploy-plugin) 04/07: fix: f004 (MEDIUM) — Two-sided state fix, per the triage recommendation: (1) deployAllAtOnce
Posted by gn...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
gnodet pushed a commit to branch security/audit-medium-fixes
in repository https://gitbox.apache.org/repos/asf/maven-deploy-plugin.git
commit 21207aa70331c0b5ca03aea0d38d535f6a1e18f0
Author: Guillaume Nodet <gn...@gmail.com>
AuthorDate: Mon Aug 31 13:46:26 2026 +0200
fix: f004 (MEDIUM) — Two-sided state fix, per the triage recommendation: (1) deployAllAtOnce
Security audit finding f004 (MEDIUM).
Two-sided state fix, per the triage recommendation: (1) deployAllAtOnce collects the batched projects while flattening and, after all requests deploy successfully, marks each one State.DEPLOYED (mark-after-batch-deploy per the design guidance - a failed batch stays TO_BE_DEPLOYED so a genuine retry of a failed build is not suppressed); (2) execute() treats DEPLOYED as terminal: re-entering the goal for an already-deployed project logs and returns, closing both triggers (double-bound e [...]
Co-Authored-By: Claude Opus 4.6 <no...@anthropic.com>
---
.../apache/maven/plugins/deploy/DeployMojo.java | 20 ++++++++++++++++
.../maven/plugins/deploy/DeployMojoTest.java | 27 ++++++++++++++++++++++
2 files changed, 47 insertions(+)
diff --git a/src/main/java/org/apache/maven/plugins/deploy/DeployMojo.java b/src/main/java/org/apache/maven/plugins/deploy/DeployMojo.java
index 1df99d0..0d07516 100644
--- a/src/main/java/org/apache/maven/plugins/deploy/DeployMojo.java
+++ b/src/main/java/org/apache/maven/plugins/deploy/DeployMojo.java
@@ -162,6 +162,10 @@ public class DeployMojo extends AbstractDeployMojo {
public DeployMojo() {}
private void putState(State state) {
+ putState(project, state);
+ }
+
+ private void putState(Project project, State state) {
session.getPluginContext(project).put(State.class.getName(), state);
}
@@ -178,6 +182,14 @@ public class DeployMojo extends AbstractDeployMojo {
}
public void execute() {
+ if (getState(project) == State.DEPLOYED) {
+ // Terminal state: the project was already deployed in this session, either individually
+ // or as part of an earlier deploy-at-end batch. Re-entering (a second bound deploy
+ // execution, or a direct deploy:deploy invocation) must not publish it a second time.
+ getLog().info("Skipping deploy for " + project.getGroupId() + ":" + project.getArtifactId() + ":"
+ + project.getVersion() + ": it has already been deployed in this session");
+ return;
+ }
if (Boolean.parseBoolean(skip)
|| ("releases".equals(skip) && !session.isVersionSnapshot(project.getVersion()))
|| ("snapshots".equals(skip) && session.isVersionSnapshot(project.getVersion()))) {
@@ -244,6 +256,7 @@ public class DeployMojo extends AbstractDeployMojo {
private void deployAllAtOnce() {
Map<RemoteRepository, Map<Integer, List<ProducedArtifact>>> flattenedRequests = new LinkedHashMap<>();
+ List<Project> batchedProjects = new ArrayList<>();
// flatten requests, grouping by remote repository and number of retries
for (Project reactorProject : session.getProjects()) {
State state = getState(reactorProject);
@@ -254,6 +267,7 @@ public class DeployMojo extends AbstractDeployMojo {
.computeIfAbsent(request.getRepository(), r -> new LinkedHashMap<>())
.computeIfAbsent(request.getRetryFailedDeploymentCount(), i -> new ArrayList<>())
.addAll(request.getArtifacts());
+ batchedProjects.add(reactorProject);
}
}
// Re-group all requests
@@ -275,6 +289,12 @@ public class DeployMojo extends AbstractDeployMojo {
} else {
getLog().info("No actual deploy requests");
}
+ // Mark every batched project DEPLOYED so a re-triggered batch (second bound deploy
+ // execution, or a direct deploy:deploy invocation walking the reactor) cannot publish
+ // the same artifacts a second time. Only reached when all requests deployed successfully.
+ for (Project reactorProject : batchedProjects) {
+ putState(reactorProject, State.DEPLOYED);
+ }
}
private void deploy(ArtifactDeployerRequest request) {
diff --git a/src/test/java/org/apache/maven/plugins/deploy/DeployMojoTest.java b/src/test/java/org/apache/maven/plugins/deploy/DeployMojoTest.java
index 48961de..4709b08 100644
--- a/src/test/java/org/apache/maven/plugins/deploy/DeployMojoTest.java
+++ b/src/test/java/org/apache/maven/plugins/deploy/DeployMojoTest.java
@@ -22,7 +22,9 @@ import java.io.File;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collection;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
import java.util.stream.Collectors;
import org.apache.maven.api.Artifact;
@@ -428,6 +430,31 @@ class DeployMojoTest {
assertEquals("http://127.0.0.1:8081/repo", repository.getUrl());
}
+ @Test
+ @InjectMojo(goal = "deploy")
+ void deployAtEndBatchIsNotRedeployedOnReentry(DeployMojo mojo) throws Exception {
+ Project project = (Project) getVariableValueFromObject(mojo, "project");
+ artifactManager.setPath(
+ project.getMainArtifact().get(),
+ Paths.get(getBasedir(), "target/test-classes/unit/maven-deploy-test-1.0-SNAPSHOT.jar"));
+ // give the session a persistent plugin context and a real reactor project list
+ Map<Project, Map<String, Object>> contexts = new HashMap<>();
+ when(session.getPluginContext(any(Project.class)))
+ .thenAnswer(iom -> contexts.computeIfAbsent(iom.getArgument(0, Project.class), p -> new HashMap<>()));
+ when(session.getProjects()).thenReturn(List.of(project));
+
+ ArgumentCaptor<ArtifactDeployerRequest> captor = ArgumentCaptor.forClass(ArtifactDeployerRequest.class);
+ doNothing().when(artifactDeployer).deploy(captor.capture());
+
+ // deployAtEnd defaults to true: the single-project batch fires within the first execution
+ mojo.execute();
+ assertEquals(1, captor.getAllValues().size(), "batch must fire exactly once");
+
+ // re-entry (second bound deploy execution, or direct deploy:deploy) must be a no-op
+ mojo.execute();
+ assertEquals(1, captor.getAllValues().size(), "re-entry must not re-deploy the batch");
+ }
+
private ArtifactDeployerRequest execute(DeployMojo mojo) {
ArgumentCaptor<ArtifactDeployerRequest> requestCaptor = ArgumentCaptor.forClass(ArtifactDeployerRequest.class);
doNothing().when(artifactDeployer).deploy(requestCaptor.capture());
(maven-deploy-plugin) 01/07: fix: f001 (MEDIUM) — Keeps v1's structure: AbstractDeployMojo.validateCredentialBinding guard
Posted by gn...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
gnodet pushed a commit to branch security/audit-medium-fixes
in repository https://gitbox.apache.org/repos/asf/maven-deploy-plugin.git
commit e7dcd6accbce98542ac9ff4e752ee735f9c479e7
Author: Guillaume Nodet <gn...@gmail.com>
AuthorDate: Mon Aug 31 13:46:24 2026 +0200
fix: f001 (MEDIUM) — Keeps v1's structure: AbstractDeployMojo.validateCredentialBinding guard
Security audit finding f001 (MEDIUM).
Keeps v1's structure: AbstractDeployMojo.validateCredentialBinding guard, known-URL collection (settings mirrors + profile repositories/pluginRepositories, plus distributionManagement via DeployMojo's getKnownRepositoryUrls override), trailing-slash URL normalization, and the user-property-only -Dmaven.deploy.allowCredentialReuse=true knob (session.getUserProperties() only, not POM-settable). v2 adds provenance semantics (fleet precedent: checkstyle bug_04 / clean bug_08): validateCre [...]
Co-Authored-By: Claude Opus 4.6 <no...@anthropic.com>
---
.../maven/plugins/deploy/AbstractDeployMojo.java | 173 +++++++++++++++++++++
.../maven/plugins/deploy/DeployFileMojo.java | 11 ++
.../apache/maven/plugins/deploy/DeployMojo.java | 80 +++++++++-
.../maven/plugins/deploy/DeployMojoTest.java | 123 +++++++++++++++
4 files changed, 385 insertions(+), 2 deletions(-)
diff --git a/src/main/java/org/apache/maven/plugins/deploy/AbstractDeployMojo.java b/src/main/java/org/apache/maven/plugins/deploy/AbstractDeployMojo.java
index 7612a69..617f881 100644
--- a/src/main/java/org/apache/maven/plugins/deploy/AbstractDeployMojo.java
+++ b/src/main/java/org/apache/maven/plugins/deploy/AbstractDeployMojo.java
@@ -18,6 +18,10 @@
*/
package org.apache.maven.plugins.deploy;
+import java.util.Collection;
+import java.util.LinkedHashSet;
+import java.util.Map;
+
import org.apache.maven.api.RemoteRepository;
import org.apache.maven.api.Session;
import org.apache.maven.api.Version;
@@ -26,6 +30,11 @@ import org.apache.maven.api.plugin.Log;
import org.apache.maven.api.plugin.Mojo;
import org.apache.maven.api.plugin.MojoException;
import org.apache.maven.api.plugin.annotations.Parameter;
+import org.apache.maven.api.settings.Mirror;
+import org.apache.maven.api.settings.Profile;
+import org.apache.maven.api.settings.Repository;
+import org.apache.maven.api.settings.Server;
+import org.apache.maven.api.settings.Settings;
/**
* Abstract class for Deploy mojo's.
@@ -35,6 +44,13 @@ public abstract class AbstractDeployMojo implements Mojo {
private static final String FIXED_MAVEN_VERSION = "3.9.0";
+ /**
+ * User property (not settable from the POM, only via {@code -D} on the command line or in
+ * {@code MAVEN_OPTS}/{@code .mvn/maven.config}) that disables the repository id→URL
+ * credential-binding check performed before a credentials-bearing deployment repository is used.
+ */
+ static final String ALLOW_CREDENTIAL_REUSE_PROPERTY = "maven.deploy.allowCredentialReuse";
+
@Inject
protected Log logger;
@@ -92,6 +108,163 @@ public abstract class AbstractDeployMojo implements Mojo {
return getSession().createRemoteRepository(id, url);
}
+ /**
+ * Guards the repository id→URL credential binding: Maven resolves the credentials for a
+ * deployment repository purely by matching its id against a {@code <server>} entry in
+ * {@code settings.xml}, so any component that pairs a known server id with a <em>new</em> URL
+ * re-targets those credentials. Equivalent to
+ * {@link #validateCredentialBinding(String, String, boolean) validateCredentialBinding(id, url, true)}:
+ * this overload is for values that are command-line-supplied by nature (deploy-file's
+ * {@code repositoryId}/{@code url} are plain {@code -D} parameters typed by the operator), so
+ * the no-URL-on-record case warns instead of refusing.
+ *
+ * @param id the repository id the deployment would bind credentials for
+ * @param url the URL the deployment would send those credentials to
+ * @throws MojoException when the binding re-targets known credentials to an unknown URL
+ */
+ protected void validateCredentialBinding(String id, String url) throws MojoException {
+ validateCredentialBinding(id, url, true);
+ }
+
+ /**
+ * Guards the repository id→URL credential binding, weighing the <em>provenance</em> of the
+ * binding. When the given id matches a {@code settings.xml} server entry (so credentials are at
+ * stake), two cases are distinguished:
+ * <ul>
+ * <li><b>URLs on record for the id</b> (mirrors, profile repositories, and — for the
+ * deploy goal — the project's {@code distributionManagement}): the given URL must match
+ * one of them; otherwise the deployment is refused, naming both URLs — regardless of
+ * provenance.</li>
+ * <li><b>No URL on record for the id</b>: the binding cannot be cross-checked, which is the
+ * mainline redirection shape (credentials stored for an id such as {@code ossrh} that
+ * settings.xml binds to no URL). A value the operator typed on the command line
+ * ({@code fromUserProperty}) proceeds with a WARN naming the URL the credentials will be sent
+ * to; a POM-sourced value (pom property or plugin configuration — attacker-writable in
+ * the malicious-POM model) is refused.</li>
+ * </ul>
+ * Every refusal can be overridden with {@code -D}{@value #ALLOW_CREDENTIAL_REUSE_PROPERTY}{@code =true}
+ * (a user property: it cannot be set from a POM).
+ *
+ * @param id the repository id the deployment would bind credentials for
+ * @param url the URL the deployment would send those credentials to
+ * @param fromUserProperty whether the id/url pair was supplied on the command line
+ * ({@code -D} session user property) rather than from the POM or plugin configuration
+ * @throws MojoException when the binding re-targets known credentials to an unknown URL, or when
+ * a POM-sourced binding pairs stored credentials with a URL this build knows nothing about
+ */
+ protected void validateCredentialBinding(String id, String url, boolean fromUserProperty) throws MojoException {
+ if (id == null || id.isEmpty() || url == null || url.isEmpty()) {
+ return;
+ }
+ Settings settings = session.getSettings();
+ if (settings == null) {
+ return;
+ }
+ boolean idHasCredentials = false;
+ for (Server server : settings.getServers()) {
+ if (id.equals(server.getId())) {
+ idHasCredentials = true;
+ break;
+ }
+ }
+ if (!idHasCredentials) {
+ return;
+ }
+ Collection<String> knownUrls = getKnownRepositoryUrls(id);
+ if (knownUrls.isEmpty()) {
+ // The server id carries credentials but no URL is on record for it in this build.
+ // This must not pass silently: it is the mainline redirection shape. Provenance decides:
+ // an operator-typed (-D) value proceeds with a warning, a POM-sourced value is refused.
+ if (fromUserProperty) {
+ getLog().warn("Repository id '" + id + "' has credentials stored in settings.xml but no URL is on"
+ + " record for that id in this build; those credentials will be sent to " + url);
+ return;
+ }
+ if (isCredentialReuseAllowed()) {
+ getLog().warn("Repository id '" + id + "' has credentials stored in settings.xml but no URL is on"
+ + " record for that id in this build, and the repository was configured from the POM;"
+ + " sending those credentials to " + url + " because -D"
+ + ALLOW_CREDENTIAL_REUSE_PROPERTY + "=true is set");
+ return;
+ }
+ throw new MojoException(
+ "Refusing to deploy: repository id '" + id + "' matches a settings.xml server entry (stored"
+ + " credentials), no URL is on record for that id in this build, and the alternative"
+ + " repository was configured from the POM rather than the command line. The deployment"
+ + " would send those credentials to " + url + ". If this is intentional, supply the"
+ + " repository on the command line (-D user property), or re-run with -D"
+ + ALLOW_CREDENTIAL_REUSE_PROPERTY + "=true (user property; it cannot be set from a POM).");
+ }
+ String requested = normalizeRepositoryUrl(url);
+ for (String known : knownUrls) {
+ if (requested.equals(normalizeRepositoryUrl(known))) {
+ return;
+ }
+ }
+ String knownList = String.join(", ", knownUrls);
+ if (isCredentialReuseAllowed()) {
+ getLog().warn("Repository id '" + id + "' binds settings.xml credentials that are on record for "
+ + knownList + " but the deployment targets " + url + "; proceeding because -D"
+ + ALLOW_CREDENTIAL_REUSE_PROPERTY + "=true is set");
+ return;
+ }
+ throw new MojoException(
+ "Refusing to deploy: repository id '" + id + "' matches a settings.xml server entry whose"
+ + " credentials are on record for " + knownList + ", but the deployment would send them to "
+ + url + ". If this redirection is intentional, re-run with -D"
+ + ALLOW_CREDENTIAL_REUSE_PROPERTY + "=true (user property; it cannot be set from a POM).");
+ }
+
+ /**
+ * Collects the URLs this build already associates with the given repository id: mirror entries
+ * and profile repositories from {@code settings.xml}. Subclasses add further sources (the
+ * deploy goal adds the project's {@code distributionManagement}).
+ * <p>
+ * <b>Trust note:</b> sources read from the project model (such as {@code distributionManagement})
+ * are attacker-controlled in the malicious-POM model and are therefore <em>advisory</em>: they can
+ * only widen the accepted set for the mismatch check, never authorize a binding by their absence
+ * — the empty-record case is handled by provenance in
+ * {@link #validateCredentialBinding(String, String, boolean)}. Settings.xml-sourced entries
+ * (mirrors, profiles) are operator-controlled.
+ */
+ protected Collection<String> getKnownRepositoryUrls(String id) {
+ Collection<String> urls = new LinkedHashSet<>();
+ Settings settings = session.getSettings();
+ if (settings != null) {
+ for (Mirror mirror : settings.getMirrors()) {
+ if (id.equals(mirror.getId()) && mirror.getUrl() != null) {
+ urls.add(mirror.getUrl());
+ }
+ }
+ for (Profile profile : settings.getProfiles()) {
+ for (Repository repository : profile.getRepositories()) {
+ if (id.equals(repository.getId()) && repository.getUrl() != null) {
+ urls.add(repository.getUrl());
+ }
+ }
+ for (Repository repository : profile.getPluginRepositories()) {
+ if (id.equals(repository.getId()) && repository.getUrl() != null) {
+ urls.add(repository.getUrl());
+ }
+ }
+ }
+ }
+ return urls;
+ }
+
+ private boolean isCredentialReuseAllowed() {
+ Map<String, String> userProperties = session.getUserProperties();
+ return userProperties != null && Boolean.parseBoolean(userProperties.get(ALLOW_CREDENTIAL_REUSE_PROPERTY));
+ }
+
+ static String normalizeRepositoryUrl(String url) {
+ String normalized = url.trim();
+ while (normalized.endsWith("/")) {
+ normalized = normalized.substring(0, normalized.length() - 1);
+ }
+ return normalized;
+ }
+
protected Session getSession() {
return session;
}
diff --git a/src/main/java/org/apache/maven/plugins/deploy/DeployFileMojo.java b/src/main/java/org/apache/maven/plugins/deploy/DeployFileMojo.java
index 72d5bb5..82e281c 100644
--- a/src/main/java/org/apache/maven/plugins/deploy/DeployFileMojo.java
+++ b/src/main/java/org/apache/maven/plugins/deploy/DeployFileMojo.java
@@ -117,6 +117,16 @@ public class DeployFileMojo extends AbstractDeployMojo {
/**
* Server Id to map on the <id> under <server> section of settings.xml In most cases, this parameter
* will be required for authentication.
+ * <p>
+ * <b>Security note:</b> the credentials looked up in <code>settings.xml</code> are selected purely by this id,
+ * so a mismatched id/url pair can point credentials kept for one server at a different URL. When this id
+ * matches a <code>settings.xml</code> server entry and the URL differs from every URL this build associates
+ * with the id, the deployment is refused unless <code>-Dmaven.deploy.allowCredentialReuse=true</code> is given
+ * on the command line. When no URL at all is on record for such an id, the deployment proceeds with a warning
+ * naming the URL the credentials will be sent to: deploy-file's parameters are command-line-supplied by
+ * nature, so the operator typing the pair is treated as the authorization that a POM cannot forge.
+ * Also note the default value <code>remote-repository</code>: if a server entry with that
+ * generic id exists in <code>settings.xml</code>, its credentials are used whenever this parameter is omitted.
*/
@Parameter(property = "repositoryId", defaultValue = "remote-repository", required = true)
private String repositoryId;
@@ -249,6 +259,7 @@ public class DeployFileMojo extends AbstractDeployMojo {
initProperties();
+ validateCredentialBinding(repositoryId, url.replace(File.separator, "/"));
RemoteRepository deploymentRepository =
createDeploymentArtifactRepository(repositoryId, url.replace(File.separator, "/"));
diff --git a/src/main/java/org/apache/maven/plugins/deploy/DeployMojo.java b/src/main/java/org/apache/maven/plugins/deploy/DeployMojo.java
index 6e0cce6..c8f2876 100644
--- a/src/main/java/org/apache/maven/plugins/deploy/DeployMojo.java
+++ b/src/main/java/org/apache/maven/plugins/deploy/DeployMojo.java
@@ -86,6 +86,17 @@ public class DeployMojo extends AbstractDeployMojo {
* <b>Note:</b> In version 2.x, the format was <code>id::<i>layout</i>::url</code> where <code><i>layout</i></code>
* could be <code>default</code> (ie. Maven 2) or <code>legacy</code> (ie. Maven 1), but since 3.0.0 the layout part
* has been removed because Maven 3 only supports Maven 2 repository layout.
+ * <p>
+ * <b>Security note:</b> the credentials looked up in <code>settings.xml</code> are selected purely by the
+ * <code>id</code> part, so this parameter can point credentials kept for one server at a different URL.
+ * The provenance of the value matters: when the id matches a <code>settings.xml</code> server entry (stored
+ * credentials) and <em>no</em> URL is on record for that id in this build, a value set from the POM (a pom
+ * property or plugin configuration) is refused, while a value supplied on the command line
+ * (<code>-DaltDeploymentRepository=...</code>) proceeds with a warning naming the URL the credentials will
+ * be sent to.
+ * When the id matches a <code>settings.xml</code> server entry and the URL differs from every URL this build
+ * associates with that id, the deployment is refused unless
+ * <code>-Dmaven.deploy.allowCredentialReuse=true</code> is given on the command line.
*/
@Parameter(property = "altDeploymentRepository")
private String altDeploymentRepository;
@@ -334,10 +345,13 @@ public class DeployMojo extends AbstractDeployMojo {
String altDeploymentRepo;
if (isSnapshot && altSnapshotDeploymentRepository != null) {
altDeploymentRepo = altSnapshotDeploymentRepository;
+ altRepositoryFromUserProperty = isFromUserProperty("altSnapshotDeploymentRepository", altDeploymentRepo);
} else if (!isSnapshot && altReleaseDeploymentRepository != null) {
altDeploymentRepo = altReleaseDeploymentRepository;
+ altRepositoryFromUserProperty = isFromUserProperty("altReleaseDeploymentRepository", altDeploymentRepo);
} else {
altDeploymentRepo = altDeploymentRepository;
+ altRepositoryFromUserProperty = isFromUserProperty("altDeploymentRepository", altDeploymentRepo);
}
if (altDeploymentRepo != null) {
@@ -353,7 +367,7 @@ public class DeployMojo extends AbstractDeployMojo {
if ("default".equals(layout)) {
getLog().warn("Using legacy syntax for alternative repository. " + "Use \"" + id + "::" + url
+ "\" instead.");
- repo = createDeploymentArtifactRepository(id, url);
+ repo = createAltDeploymentRepository(id, url);
} else {
throw new MojoException(
altDeploymentRepo,
@@ -373,7 +387,7 @@ public class DeployMojo extends AbstractDeployMojo {
String id = matcher.group(1).trim();
String url = matcher.group(2).trim();
- repo = createDeploymentArtifactRepository(id, url);
+ repo = createAltDeploymentRepository(id, url);
}
}
}
@@ -404,6 +418,68 @@ public class DeployMojo extends AbstractDeployMojo {
return repo;
}
+ /**
+ * Creates the repository for an alternative deployment target: warns when it overrides the
+ * project's declared {@code distributionManagement} (naming the server id whose settings.xml
+ * credentials will be used) and guards the credential binding with the provenance of the
+ * alternative-repository value (see {@link #validateCredentialBinding(String, String, boolean)}):
+ * a mismatch against the URLs on record for the id is refused regardless of provenance, and a
+ * credentials-bearing id with no URL on record is refused when the value came from the POM but
+ * proceeds with a warning when the operator typed it on the command line.
+ */
+ private RemoteRepository createAltDeploymentRepository(String id, String url) {
+ DistributionManagement dm = project.getModel().getDistributionManagement();
+ if (dm != null && (dm.getRepository() != null || dm.getSnapshotRepository() != null)) {
+ getLog().warn("Alternative deployment repository overrides the distributionManagement declared by"
+ + " the project: credentials of server id '" + id
+ + "' from settings.xml (if any) will be used for " + url);
+ }
+ validateCredentialBinding(id, url, altRepositoryFromUserProperty);
+ return createDeploymentArtifactRepository(id, url);
+ }
+
+ /**
+ * Whether the alternative-repository value selected by {@link #getDeploymentRepository(boolean)}
+ * was supplied as a {@code -D} session user property (operator-typed on the command line) rather
+ * than resolved from the POM (a pom property or plugin configuration). POM-sourced values are
+ * attacker-writable in the malicious-POM model, so they get the fail-closed treatment in
+ * {@link #validateCredentialBinding(String, String, boolean)}.
+ */
+ private boolean altRepositoryFromUserProperty;
+
+ /**
+ * Returns {@code true} when the given user property is present in the session <em>and</em>
+ * carries the value actually in use: Maven lets an explicit {@code <configuration>} entry in the
+ * POM win over a {@code -D} property of the same name, so presence of the property alone does
+ * not prove the value's provenance.
+ */
+ private boolean isFromUserProperty(String propertyName, String value) {
+ if (value == null) {
+ return false;
+ }
+ java.util.Map<String, String> userProperties = session.getUserProperties();
+ return userProperties != null && value.equals(userProperties.get(propertyName));
+ }
+
+ @Override
+ protected java.util.Collection<String> getKnownRepositoryUrls(String id) {
+ java.util.Collection<String> urls = super.getKnownRepositoryUrls(id);
+ DistributionManagement dm = project.getModel().getDistributionManagement();
+ if (dm != null) {
+ if (dm.getRepository() != null
+ && id.equals(dm.getRepository().getId())
+ && isNotEmpty(dm.getRepository().getUrl())) {
+ urls.add(dm.getRepository().getUrl());
+ }
+ if (dm.getSnapshotRepository() != null
+ && id.equals(dm.getSnapshotRepository().getId())
+ && isNotEmpty(dm.getSnapshotRepository().getUrl())) {
+ urls.add(dm.getSnapshotRepository().getUrl());
+ }
+ }
+ return urls;
+ }
+
private boolean isValidPath(Artifact a) {
return getArtifactManager().getPath(a).filter(Files::isRegularFile).isPresent();
}
diff --git a/src/test/java/org/apache/maven/plugins/deploy/DeployMojoTest.java b/src/test/java/org/apache/maven/plugins/deploy/DeployMojoTest.java
index 5646b85..a794daf 100644
--- a/src/test/java/org/apache/maven/plugins/deploy/DeployMojoTest.java
+++ b/src/test/java/org/apache/maven/plugins/deploy/DeployMojoTest.java
@@ -46,6 +46,9 @@ import org.apache.maven.api.services.ArtifactDeployerRequest;
import org.apache.maven.api.services.ArtifactManager;
import org.apache.maven.api.services.ProjectManager;
import org.apache.maven.api.services.RepositoryFactory;
+import org.apache.maven.api.settings.Mirror;
+import org.apache.maven.api.settings.Server;
+import org.apache.maven.api.settings.Settings;
import org.apache.maven.impl.InternalSession;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@@ -268,6 +271,126 @@ class DeployMojoTest {
assertEquals("http://localhost", repository.getUrl());
}
+ @Test
+ @InjectMojo(goal = "deploy")
+ void altDeploymentRepositoryRefusedWhenCredentialsBoundToOtherUrl(DeployMojo mojo) throws Exception {
+ when(session.getSettings())
+ .thenReturn(Settings.newBuilder()
+ .servers(List.of(Server.newBuilder().id("remote-repo").build()))
+ .mirrors(List.of(Mirror.newBuilder()
+ .id("remote-repo")
+ .url("https://good.example/repo")
+ .build()))
+ .build());
+ setVariableValueToObject(mojo, "altDeploymentRepository", "remote-repo::https://evil.example/repo");
+
+ MojoException e = assertThrows(MojoException.class, () -> mojo.getDeploymentRepository(false));
+ assertTrue(e.getMessage().contains("Refusing to deploy"), e.getMessage());
+ assertTrue(e.getMessage().contains("https://evil.example/repo"), e.getMessage());
+ assertTrue(e.getMessage().contains("https://good.example/repo"), e.getMessage());
+ }
+
+ @Test
+ @InjectMojo(goal = "deploy")
+ void altDeploymentRepositoryAcceptedWhenUrlKnownForId(DeployMojo mojo) throws Exception {
+ when(session.getSettings())
+ .thenReturn(Settings.newBuilder()
+ .servers(List.of(Server.newBuilder().id("remote-repo").build()))
+ .build());
+ // the project's own distributionManagement URL for "remote-repo" is a known binding
+ String dmUrl = Paths.get(getBasedir()).toUri().toString();
+ setVariableValueToObject(mojo, "altDeploymentRepository", "remote-repo::" + dmUrl);
+
+ RemoteRepository repository = mojo.getDeploymentRepository(false);
+ assertEquals("remote-repo", repository.getId());
+ }
+
+ @Test
+ @InjectMojo(goal = "deploy")
+ void altDeploymentRepositoryCredentialReuseOptOut(DeployMojo mojo) throws Exception {
+ when(session.getSettings())
+ .thenReturn(Settings.newBuilder()
+ .servers(List.of(Server.newBuilder().id("remote-repo").build()))
+ .mirrors(List.of(Mirror.newBuilder()
+ .id("remote-repo")
+ .url("https://good.example/repo")
+ .build()))
+ .build());
+ session.getUserProperties().put(AbstractDeployMojo.ALLOW_CREDENTIAL_REUSE_PROPERTY, "true");
+ setVariableValueToObject(mojo, "altDeploymentRepository", "remote-repo::https://evil.example/repo");
+
+ RemoteRepository repository = mojo.getDeploymentRepository(false);
+ assertEquals("https://evil.example/repo", repository.getUrl());
+ }
+
+ @Test
+ @InjectMojo(goal = "deploy")
+ void pomSourcedAltRepositoryRefusedWhenNoUrlOnRecordForCredentialedId(DeployMojo mojo) throws Exception {
+ // the mainline attack shape: settings.xml stores credentials for "ossrh" but binds no URL
+ // to that id anywhere (no mirror, no profile repository, and the project's
+ // distributionManagement uses a different id), and a POM-bindable parameter pairs the id
+ // with an attacker URL. The parameter is set without a matching -D user property, which is
+ // exactly what a pom <properties> entry or plugin <configuration> produces.
+ when(session.getSettings())
+ .thenReturn(Settings.newBuilder()
+ .servers(List.of(Server.newBuilder().id("ossrh").build()))
+ .build());
+ setVariableValueToObject(mojo, "altDeploymentRepository", "ossrh::https://evil.example/repo");
+
+ MojoException e = assertThrows(MojoException.class, () -> mojo.getDeploymentRepository(false));
+ assertTrue(e.getMessage().contains("Refusing to deploy"), e.getMessage());
+ assertTrue(e.getMessage().contains("'ossrh'"), e.getMessage());
+ assertTrue(e.getMessage().contains("https://evil.example/repo"), e.getMessage());
+ assertTrue(e.getMessage().contains("configured from the POM"), e.getMessage());
+ }
+
+ @Test
+ @InjectMojo(goal = "deploy")
+ void cliSourcedAltRepositoryWarnsButProceedsWhenNoUrlOnRecordForCredentialedId(DeployMojo mojo) throws Exception {
+ // same empty-record shape, but the operator typed the pair on the command line: the value
+ // is present as a session user property and matches the parameter value, so the binding
+ // proceeds (with a warning naming the target URL) - fully failing closed here would break
+ // legitimate -DaltDeploymentRepository workflows against ids that settings.xml only stores
+ // credentials for
+ when(session.getSettings())
+ .thenReturn(Settings.newBuilder()
+ .servers(List.of(Server.newBuilder().id("ossrh").build()))
+ .build());
+ session.getUserProperties().put("altDeploymentRepository", "ossrh::https://elsewhere.example/repo");
+ setVariableValueToObject(mojo, "altDeploymentRepository", "ossrh::https://elsewhere.example/repo");
+
+ RemoteRepository repository = mojo.getDeploymentRepository(false);
+ assertEquals("ossrh", repository.getId());
+ assertEquals("https://elsewhere.example/repo", repository.getUrl());
+ }
+
+ @Test
+ @InjectMojo(goal = "deploy")
+ void pomSourcedAltRepositoryEmptyRecordRefusalHasKnobOverride(DeployMojo mojo) throws Exception {
+ when(session.getSettings())
+ .thenReturn(Settings.newBuilder()
+ .servers(List.of(Server.newBuilder().id("ossrh").build()))
+ .build());
+ session.getUserProperties().put(AbstractDeployMojo.ALLOW_CREDENTIAL_REUSE_PROPERTY, "true");
+ setVariableValueToObject(mojo, "altDeploymentRepository", "ossrh::https://evil.example/repo");
+
+ RemoteRepository repository = mojo.getDeploymentRepository(false);
+ assertEquals("https://evil.example/repo", repository.getUrl());
+ }
+
+ @Test
+ @InjectMojo(goal = "deploy")
+ void altDeploymentRepositoryAcceptedWhenIdHasNoCredentials(DeployMojo mojo) throws Exception {
+ when(session.getSettings())
+ .thenReturn(Settings.newBuilder()
+ .servers(List.of(Server.newBuilder().id("other-server").build()))
+ .build());
+ setVariableValueToObject(mojo, "altDeploymentRepository", "no-creds-repo::https://elsewhere.example/repo");
+
+ RemoteRepository repository = mojo.getDeploymentRepository(false);
+ assertEquals("https://elsewhere.example/repo", repository.getUrl());
+ }
+
private ArtifactDeployerRequest execute(DeployMojo mojo) {
ArgumentCaptor<ArtifactDeployerRequest> requestCaptor = ArgumentCaptor.forClass(ArtifactDeployerRequest.class);
doNothing().when(artifactDeployer).deploy(requestCaptor.capture());
(maven-deploy-plugin) 06/07: fix: f006 (MEDIUM) — Verified-true doc fix plus visibility escalation, per the finding brief.
Posted by gn...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
gnodet pushed a commit to branch security/audit-medium-fixes
in repository https://gitbox.apache.org/repos/asf/maven-deploy-plugin.git
commit a5e9653b5e021d0870c06490cffff954cc59d3bc
Author: Guillaume Nodet <gn...@gmail.com>
AuthorDate: Mon Aug 31 13:46:28 2026 +0200
fix: f006 (MEDIUM) — Verified-true doc fix plus visibility escalation, per the finding brief.
Security audit finding f006 (MEDIUM).
Verified-true doc fix plus visibility escalation, per the finding brief. The deployAtEnd javadoc now states the real semantics: batch fires when the last deploy-bound project reaches its deploy phase (trailing execution-less modules can still fail afterward), multi-repo/mixed-retry requests deploy sequentially with no rollback, and deployAtEnd=false modules cannot be recalled; the false 'none of the reactor projects is deployed' sentence and the incoherent '(experimental)' marker (on [...]
Co-Authored-By: Claude Opus 4.6 <no...@anthropic.com>
---
.../apache/maven/plugins/deploy/DeployMojo.java | 39 +++++++++++++++++++---
1 file changed, 35 insertions(+), 4 deletions(-)
diff --git a/src/main/java/org/apache/maven/plugins/deploy/DeployMojo.java b/src/main/java/org/apache/maven/plugins/deploy/DeployMojo.java
index 381675d..3e7e977 100644
--- a/src/main/java/org/apache/maven/plugins/deploy/DeployMojo.java
+++ b/src/main/java/org/apache/maven/plugins/deploy/DeployMojo.java
@@ -64,9 +64,24 @@ public class DeployMojo extends AbstractDeployMojo {
private MojoExecution mojoExecution;
/**
- * Whether every project should be deployed during its own deploy-phase or at the end of the multimodule build. If
- * set to {@code true} and the build fails, none of the reactor projects is deployed.
- * <strong>(experimental)</strong>
+ * Whether every project should be deployed during its own deploy-phase or at the end of the multimodule build.
+ * When set to {@code true}, the deploy requests of all projects with a bound deploy execution are collected and
+ * executed together once the last such project has reached its deploy phase, which reduces the chance of
+ * publishing artifacts from a build that subsequently fails.
+ * <p>
+ * <strong>This is not an atomic, all-or-nothing guarantee.</strong> In particular:
+ * <ul>
+ * <li>The batch fires when the last project <em>with a deploy execution</em> reaches its deploy phase.
+ * Reactor projects built after that point (for example trailing modules that skip or do not bind the
+ * deploy goal, such as integration-test aggregators) can still fail <em>after</em> all artifacts have
+ * been published.</li>
+ * <li>When the batch spans several repositories or retry configurations, the resulting requests are
+ * deployed sequentially: a failure part-way through leaves the repositories already deployed to
+ * published, with no rollback. The build log reports which repositories had already been deployed
+ * when this happens.</li>
+ * <li>Projects configured with {@code deployAtEnd=false} deploy immediately during their own deploy
+ * phase and cannot be recalled by a later build failure.</li>
+ * </ul>
*
* @since 2.8
*/
@@ -313,7 +328,23 @@ public class DeployMojo extends AbstractDeployMojo {
}
// Deploy
if (!requests.isEmpty()) {
- requests.forEach(this::deploy);
+ // Requests are deployed sequentially and there is no rollback: if one fails, make the
+ // partial-publication state explicit instead of only surfacing the failing module.
+ List<String> deployedRepositoryIds = new ArrayList<>();
+ for (ArtifactDeployerRequest request : requests) {
+ try {
+ deploy(request);
+ } catch (RuntimeException e) {
+ if (!deployedRepositoryIds.isEmpty()) {
+ getLog().error("Deploy-at-end batch failed after " + deployedRepositoryIds.size() + " of "
+ + requests.size() + " deploy request(s) had already completed. Artifacts already"
+ + " published to repository id(s) " + String.join(", ", deployedRepositoryIds)
+ + " remain published: there is no rollback.");
+ }
+ throw e;
+ }
+ deployedRepositoryIds.add(request.getRepository().getId());
+ }
} else {
getLog().info("No actual deploy requests");
}
(maven-deploy-plugin) 02/07: fix: f002 (MEDIUM) — Single choke point: AbstractDeployMojo.validateTransportSecurity(id,url)
Posted by gn...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
gnodet pushed a commit to branch security/audit-medium-fixes
in repository https://gitbox.apache.org/repos/asf/maven-deploy-plugin.git
commit 2d4d30e586436f9d9a4bf85a895deb33a7bc44cc
Author: Guillaume Nodet <gn...@gmail.com>
AuthorDate: Mon Aug 31 13:46:25 2026 +0200
fix: f002 (MEDIUM) — Single choke point: AbstractDeployMojo.validateTransportSecurity(id,url)
Security audit finding f002 (MEDIUM).
Single choke point: AbstractDeployMojo.validateTransportSecurity(id,url) refuses http:// and ftp:// deployment URLs by default, called from createDeploymentArtifactRepository (covers the alt-repo route in DeployMojo and the deploy-file url) and explicitly on both distributionManagement branches (which bypass that factory via session.createRemoteRepository(Repository)). Loopback hosts (localhost, 127.0.0.0/8, ::1) are exempt so local mock/IT repositories keep working; opt-out is -Dmave [...]
Co-Authored-By: Claude Opus 4.6 <no...@anthropic.com>
---
.../maven/plugins/deploy/AbstractDeployMojo.java | 72 ++++++++++++++++++++++
.../apache/maven/plugins/deploy/DeployMojo.java | 5 ++
src/site/markdown/examples/deploy-http.md | 8 ++-
.../examples/deploying-with-classifiers.md.vm | 4 +-
.../maven/plugins/deploy/DeployMojoTest.java | 37 +++++++++++
5 files changed, 123 insertions(+), 3 deletions(-)
diff --git a/src/main/java/org/apache/maven/plugins/deploy/AbstractDeployMojo.java b/src/main/java/org/apache/maven/plugins/deploy/AbstractDeployMojo.java
index 617f881..7ab8339 100644
--- a/src/main/java/org/apache/maven/plugins/deploy/AbstractDeployMojo.java
+++ b/src/main/java/org/apache/maven/plugins/deploy/AbstractDeployMojo.java
@@ -51,6 +51,12 @@ public abstract class AbstractDeployMojo implements Mojo {
*/
static final String ALLOW_CREDENTIAL_REUSE_PROPERTY = "maven.deploy.allowCredentialReuse";
+ /**
+ * User property (not settable from the POM) that allows deploying to cleartext (http/ftp)
+ * URLs. Loopback hosts are always exempt from the cleartext check.
+ */
+ static final String ALLOW_INSECURE_URL_PROPERTY = "maven.deploy.allowInsecureUrl";
+
@Inject
protected Log logger;
@@ -105,9 +111,75 @@ public abstract class AbstractDeployMojo implements Mojo {
* Creates resolver {@link RemoteRepository} equipped with needed whistles and bells.
*/
protected RemoteRepository createDeploymentArtifactRepository(String id, String url) {
+ validateTransportSecurity(id, url);
return getSession().createRemoteRepository(id, url);
}
+ /**
+ * Refuses cleartext deployment transports: with an {@code http://} or {@code ftp://} deployment
+ * URL, the HTTP Basic (or FTP) credentials resolved for {@code id} and all deployed artifacts
+ * would cross the network unencrypted. Loopback hosts are exempt (local mock/test repositories);
+ * everything else requires an explicit {@code -D}{@value #ALLOW_INSECURE_URL_PROPERTY}{@code =true}
+ * opt-out. Maven core's {@code external:http:*} mirror blocking covers dependency
+ * <em>resolution</em> only; this is the deployment-side counterpart.
+ *
+ * @param id the repository id (used in diagnostics)
+ * @param url the deployment URL
+ * @throws MojoException when the URL is cleartext, non-loopback, and not explicitly allowed
+ */
+ protected void validateTransportSecurity(String id, String url) throws MojoException {
+ if (url == null || !isInsecureDeploymentUrl(url)) {
+ return;
+ }
+ Map<String, String> userProperties = session.getUserProperties();
+ if (userProperties != null && Boolean.parseBoolean(userProperties.get(ALLOW_INSECURE_URL_PROPERTY))) {
+ getLog().warn("Deploying to insecure (cleartext) URL " + url + " for repository id '" + id
+ + "' because -D" + ALLOW_INSECURE_URL_PROPERTY
+ + "=true is set: credentials and artifacts will cross the network unencrypted");
+ return;
+ }
+ throw new MojoException("Refusing to deploy to insecure (cleartext) URL " + url + " for repository id '" + id
+ + "': credentials and artifacts would cross the network unencrypted. Use an https:// endpoint,"
+ + " or re-run with -D" + ALLOW_INSECURE_URL_PROPERTY
+ + "=true to accept the risk (loopback hosts are exempt from this check).");
+ }
+
+ /**
+ * Returns {@code true} for cleartext ({@code http}/{@code ftp}) URLs targeting a non-loopback host.
+ */
+ static boolean isInsecureDeploymentUrl(String url) {
+ int colon = url.indexOf(':');
+ if (colon <= 0) {
+ return false;
+ }
+ String scheme = url.substring(0, colon).toLowerCase(java.util.Locale.ROOT);
+ if (!"http".equals(scheme) && !"ftp".equals(scheme)) {
+ return false;
+ }
+ return !isLoopbackHost(hostOf(url));
+ }
+
+ private static String hostOf(String url) {
+ try {
+ return java.net.URI.create(url).getHost();
+ } catch (IllegalArgumentException e) {
+ return null;
+ }
+ }
+
+ static boolean isLoopbackHost(String host) {
+ if (host == null || host.isEmpty()) {
+ return false;
+ }
+ if (host.startsWith("[") && host.endsWith("]")) {
+ host = host.substring(1, host.length() - 1);
+ }
+ return "localhost".equalsIgnoreCase(host)
+ || host.startsWith("127.")
+ || "::1".equals(host)
+ || "0:0:0:0:0:0:0:1".equals(host);
+ }
+
/**
* Guards the repository id→URL credential binding: Maven resolves the credentials for a
* deployment repository purely by matching its id against a {@code <server>} entry in
diff --git a/src/main/java/org/apache/maven/plugins/deploy/DeployMojo.java b/src/main/java/org/apache/maven/plugins/deploy/DeployMojo.java
index c8f2876..7758893 100644
--- a/src/main/java/org/apache/maven/plugins/deploy/DeployMojo.java
+++ b/src/main/java/org/apache/maven/plugins/deploy/DeployMojo.java
@@ -399,10 +399,15 @@ public class DeployMojo extends AbstractDeployMojo {
&& dm.getSnapshotRepository() != null
&& isNotEmpty(dm.getSnapshotRepository().getId())
&& isNotEmpty(dm.getSnapshotRepository().getUrl())) {
+ validateTransportSecurity(
+ dm.getSnapshotRepository().getId(),
+ dm.getSnapshotRepository().getUrl());
repo = session.createRemoteRepository(dm.getSnapshotRepository());
} else if (dm.getRepository() != null
&& isNotEmpty(dm.getRepository().getId())
&& isNotEmpty(dm.getRepository().getUrl())) {
+ validateTransportSecurity(
+ dm.getRepository().getId(), dm.getRepository().getUrl());
repo = session.createRemoteRepository(dm.getRepository());
}
}
diff --git a/src/site/markdown/examples/deploy-http.md b/src/site/markdown/examples/deploy-http.md
index 2289b16..f795713 100644
--- a/src/site/markdown/examples/deploy-http.md
+++ b/src/site/markdown/examples/deploy-http.md
@@ -34,13 +34,19 @@ In order to deploy artifacts using HTTP(S) you must specify the use of an HTTP(S
<distributionManagement>
<repository>
<id>my-mrm-relases</id>
- <url>http://localhost:8081/nexus/content/repositories/release</url>
+ <url>https://repomanager.example.com/nexus/content/repositories/release</url>
</repository>
</distributionManagement>
...
</project>
```
+**Always prefer `https://` deployment URLs.** With a cleartext `http://` URL the credentials
+configured below are sent as unencrypted HTTP Basic authentication and can be captured by anyone
+on the network path. The plugin therefore refuses cleartext `http://` (and `ftp://`) deployment
+URLs by default; loopback hosts (`localhost`, `127.0.0.1`) are exempt, and the check can be
+explicitly overridden with `-Dmaven.deploy.allowInsecureUrl=true` if you accept the risk.
+
## Authentication
Your `settings.xml` would contain a `server` element where the `id` of that element matches `id` of the HTTP(S) repository specified in the POM above. It must contain the credentials to be used (in [encrypted form](https://maven.apache.org/guides/mini/guide-encryption.html)):
diff --git a/src/site/markdown/examples/deploying-with-classifiers.md.vm b/src/site/markdown/examples/deploying-with-classifiers.md.vm
index 7cdc5b0..a57af40 100644
--- a/src/site/markdown/examples/deploying-with-classifiers.md.vm
+++ b/src/site/markdown/examples/deploying-with-classifiers.md.vm
@@ -37,7 +37,7 @@ For example: from the following artifact names, the classifier is located betwee
You can deploy the main artifact and the classified artifacts in a single run. Let's assume the original filename for the documentation is `site.pdf`:
```unknown
-mvn ${project.groupId}:${project.artifactId}:${project.version}:deploy-file -Durl=http://localhost:8081/repomanager/ \
+mvn ${project.groupId}:${project.artifactId}:${project.version}:deploy-file -Durl=https://repomanager.example.com/repo/ \
-DrepositoryId=some.id \
-Dfile=path/to/artifact-name-1.0.jar \
-DpomFile=path-to-your-pom.xml \
@@ -49,7 +49,7 @@ mvn ${project.groupId}:${project.artifactId}:${project.version}:deploy-file -Dur
If you only want to deploy the `debug`\-jar and want to keep the classifier, you can execute the `deploy-file` like
```unknown
-mvn ${project.groupId}:${project.artifactId}:${project.version}:deploy-file -Durl=http://localhost:8081/repomanager/ \
+mvn ${project.groupId}:${project.artifactId}:${project.version}:deploy-file -Durl=https://repomanager.example.com/repo/ \
-DrepositoryId=some.id \
-Dfile=path-to-your-artifact-jar \
-DpomFile=path-to-your-pom.xml \
diff --git a/src/test/java/org/apache/maven/plugins/deploy/DeployMojoTest.java b/src/test/java/org/apache/maven/plugins/deploy/DeployMojoTest.java
index a794daf..48961de 100644
--- a/src/test/java/org/apache/maven/plugins/deploy/DeployMojoTest.java
+++ b/src/test/java/org/apache/maven/plugins/deploy/DeployMojoTest.java
@@ -391,6 +391,43 @@ class DeployMojoTest {
assertEquals("https://elsewhere.example/repo", repository.getUrl());
}
+ @Test
+ @InjectMojo(goal = "deploy")
+ void insecureHttpAltDeploymentRepositoryRefused(DeployMojo mojo) throws Exception {
+ setVariableValueToObject(mojo, "altDeploymentRepository", "insecure-repo::http://insecure.example/repo");
+
+ MojoException e = assertThrows(MojoException.class, () -> mojo.getDeploymentRepository(false));
+ assertTrue(e.getMessage().contains("insecure (cleartext) URL"), e.getMessage());
+ }
+
+ @Test
+ @InjectMojo(goal = "deploy")
+ void insecureFtpAltDeploymentRepositoryRefused(DeployMojo mojo) throws Exception {
+ setVariableValueToObject(mojo, "altDeploymentRepository", "insecure-repo::ftp://insecure.example/repo");
+
+ MojoException e = assertThrows(MojoException.class, () -> mojo.getDeploymentRepository(false));
+ assertTrue(e.getMessage().contains("insecure (cleartext) URL"), e.getMessage());
+ }
+
+ @Test
+ @InjectMojo(goal = "deploy")
+ void insecureAltDeploymentRepositoryOptOut(DeployMojo mojo) throws Exception {
+ session.getUserProperties().put(AbstractDeployMojo.ALLOW_INSECURE_URL_PROPERTY, "true");
+ setVariableValueToObject(mojo, "altDeploymentRepository", "insecure-repo::http://insecure.example/repo");
+
+ RemoteRepository repository = mojo.getDeploymentRepository(false);
+ assertEquals("http://insecure.example/repo", repository.getUrl());
+ }
+
+ @Test
+ @InjectMojo(goal = "deploy")
+ void loopbackHttpAltDeploymentRepositoryAccepted(DeployMojo mojo) throws Exception {
+ setVariableValueToObject(mojo, "altDeploymentRepository", "local-repo::http://127.0.0.1:8081/repo");
+
+ RemoteRepository repository = mojo.getDeploymentRepository(false);
+ assertEquals("http://127.0.0.1:8081/repo", repository.getUrl());
+ }
+
private ArtifactDeployerRequest execute(DeployMojo mojo) {
ArgumentCaptor<ArtifactDeployerRequest> requestCaptor = ArgumentCaptor.forClass(ArtifactDeployerRequest.class);
doNothing().when(artifactDeployer).deploy(requestCaptor.capture());
(maven-deploy-plugin) 07/07: fix: adapt deployAtEnd re-deploy test for cache optimization compatibility
Posted by gn...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
gnodet pushed a commit to branch security/audit-medium-fixes
in repository https://gitbox.apache.org/repos/asf/maven-deploy-plugin.git
commit 6812306ef6b08deff6d3a236eee5a40f00913523
Author: Guillaume Nodet <gn...@gmail.com>
AuthorDate: Mon Aug 31 13:56:49 2026 +0200
fix: adapt deployAtEnd re-deploy test for cache optimization compatibility
The deployAtEndBatchIsNotRedeployedOnReentry test needs a properly mocked
MojoExecution with plugin model, because the upstream cache optimization
(PROJECTS_WITH_DEPLOY_KEY) calls mojoExecution.getPlugin().getModel().getKey()
in hasDeployExecution().
Co-Authored-By: Claude Opus 4.6 <no...@anthropic.com>
---
.../org/apache/maven/plugins/deploy/DeployMojoTest.java | 16 ++++++++++++++++
1 file changed, 16 insertions(+)
diff --git a/src/test/java/org/apache/maven/plugins/deploy/DeployMojoTest.java b/src/test/java/org/apache/maven/plugins/deploy/DeployMojoTest.java
index 4709b08..8f3aeae 100644
--- a/src/test/java/org/apache/maven/plugins/deploy/DeployMojoTest.java
+++ b/src/test/java/org/apache/maven/plugins/deploy/DeployMojoTest.java
@@ -433,10 +433,26 @@ class DeployMojoTest {
@Test
@InjectMojo(goal = "deploy")
void deployAtEndBatchIsNotRedeployedOnReentry(DeployMojo mojo) throws Exception {
+ // Set up mojoExecution with a proper plugin model so hasDeployExecution() can look up
+ // the deploy plugin key. This is needed because the cache optimization (PROJECTS_WITH_DEPLOY_KEY)
+ // calls mojoExecution.getPlugin().getModel().getKey() to find the current plugin in each project's
+ // build plugins map.
+ org.apache.maven.api.model.Plugin pluginModel = org.apache.maven.api.model.Plugin.newBuilder()
+ .groupId("org.apache.maven.plugins")
+ .artifactId("maven-deploy-plugin")
+ .build();
+ org.apache.maven.api.Plugin mojoPlugin = org.mockito.Mockito.mock(org.apache.maven.api.Plugin.class);
+ org.apache.maven.api.MojoExecution mojoExec =
+ org.mockito.Mockito.mock(org.apache.maven.api.MojoExecution.class);
+ org.mockito.Mockito.doReturn(mojoPlugin).when(mojoExec).getPlugin();
+ org.mockito.Mockito.doReturn(pluginModel).when(mojoPlugin).getModel();
+ setVariableValueToObject(mojo, "mojoExecution", mojoExec);
+
Project project = (Project) getVariableValueFromObject(mojo, "project");
artifactManager.setPath(
project.getMainArtifact().get(),
Paths.get(getBasedir(), "target/test-classes/unit/maven-deploy-test-1.0-SNAPSHOT.jar"));
+
// give the session a persistent plugin context and a real reactor project list
Map<Project, Map<String, Object>> contexts = new HashMap<>();
when(session.getPluginContext(any(Project.class)))
(maven-deploy-plugin) 05/07: fix: f005 (MEDIUM) — A single class-level monitor (DEPLOY_AT_END_LOCK, a constant lock object
Posted by gn...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
gnodet pushed a commit to branch security/audit-medium-fixes
in repository https://gitbox.apache.org/repos/asf/maven-deploy-plugin.git
commit 4155d95cda7c4266df6acc76600c8184be384386
Author: Guillaume Nodet <gn...@gmail.com>
AuthorDate: Mon Aug 31 13:46:27 2026 +0200
fix: f005 (MEDIUM) — A single class-level monitor (DEPLOY_AT_END_LOCK, a constant lock object
Security audit finding f005 (MEDIUM).
A single class-level monitor (DEPLOY_AT_END_LOCK, a constant lock object - not mutable static state; batch state stays in per-project session plugin contexts) now serializes every state read/write and the batch trigger: the terminal-state re-entry check, the SKIPPED/DEPLOYED/TO_BE_DEPLOYED marks, and the allProjectsMarked()+deployAllAtOnce() check-then-act. The lock is deliberately held across deployAllAtOnce(): the losing thread waits, then observes the DEPLOYED states written by the [...]
Co-Authored-By: Claude Opus 4.6 <no...@anthropic.com>
---
.../apache/maven/plugins/deploy/DeployMojo.java | 62 ++++++++++++++++------
1 file changed, 45 insertions(+), 17 deletions(-)
diff --git a/src/main/java/org/apache/maven/plugins/deploy/DeployMojo.java b/src/main/java/org/apache/maven/plugins/deploy/DeployMojo.java
index 0d07516..381675d 100644
--- a/src/main/java/org/apache/maven/plugins/deploy/DeployMojo.java
+++ b/src/main/java/org/apache/maven/plugins/deploy/DeployMojo.java
@@ -159,6 +159,19 @@ public class DeployMojo extends AbstractDeployMojo {
private static final String PROJECTS_WITH_DEPLOY_KEY = DeployMojo.class.getName() + ".projectsWithDeploy";
+ /**
+ * Serializes the deploy-at-end mark-then-check-then-fire sequence across reactor threads.
+ * With {@code -T}, two reactor leaves can reach their deploy phase concurrently, both record
+ * their state, both see {@link #allProjectsMarked()} true, and both fire
+ * {@link #deployAllAtOnce()} - double-publishing every batched module (MDEPLOY-169 ships
+ * {@code -T2} + deployAtEnd as a supported configuration). All state reads/writes and the
+ * batch trigger below take this monitor, so exactly one thread fires the batch; the loser
+ * then observes the {@code DEPLOYED} states written by the winner and no-ops. This is a
+ * constant lock object, not mutable static state; the batch state itself stays in the
+ * per-project session plugin contexts.
+ */
+ private static final Object DEPLOY_AT_END_LOCK = new Object();
+
public DeployMojo() {}
private void putState(State state) {
@@ -182,19 +195,23 @@ public class DeployMojo extends AbstractDeployMojo {
}
public void execute() {
- if (getState(project) == State.DEPLOYED) {
- // Terminal state: the project was already deployed in this session, either individually
- // or as part of an earlier deploy-at-end batch. Re-entering (a second bound deploy
- // execution, or a direct deploy:deploy invocation) must not publish it a second time.
- getLog().info("Skipping deploy for " + project.getGroupId() + ":" + project.getArtifactId() + ":"
- + project.getVersion() + ": it has already been deployed in this session");
- return;
+ synchronized (DEPLOY_AT_END_LOCK) {
+ if (getState(project) == State.DEPLOYED) {
+ // Terminal state: the project was already deployed in this session, either individually
+ // or as part of an earlier deploy-at-end batch. Re-entering (a second bound deploy
+ // execution, or a direct deploy:deploy invocation) must not publish it a second time.
+ getLog().info("Skipping deploy for " + project.getGroupId() + ":" + project.getArtifactId() + ":"
+ + project.getVersion() + ": it has already been deployed in this session");
+ return;
+ }
}
if (Boolean.parseBoolean(skip)
|| ("releases".equals(skip) && !session.isVersionSnapshot(project.getVersion()))
|| ("snapshots".equals(skip) && session.isVersionSnapshot(project.getVersion()))) {
getLog().info("Skipping artifact deployment");
- putState(State.SKIPPED);
+ synchronized (DEPLOY_AT_END_LOCK) {
+ putState(State.SKIPPED);
+ }
} else {
failIfOffline();
warnIfAffectedPackagingAndMaven(project.getPackaging().id());
@@ -203,20 +220,31 @@ public class DeployMojo extends AbstractDeployMojo {
getLog().info("Deploying deploy for " + project.getGroupId() + ":" + project.getArtifactId() + ":"
+ project.getVersion() + " at end");
deploy(createDeployerRequest());
- putState(State.DEPLOYED);
+ synchronized (DEPLOY_AT_END_LOCK) {
+ putState(State.DEPLOYED);
+ }
} else {
- // compute the request
- putState(State.TO_BE_DEPLOYED);
- putState(createDeployerRequest());
- if (!allProjectsMarked()) {
- getLog().info("Deferring deploy for " + project.getGroupId() + ":" + project.getArtifactId() + ":"
- + project.getVersion() + " at end");
+ // compute the request outside the lock; only the state mark-and-check is serialized
+ ArtifactDeployerRequest request = createDeployerRequest();
+ synchronized (DEPLOY_AT_END_LOCK) {
+ putState(State.TO_BE_DEPLOYED);
+ putState(request);
+ if (!allProjectsMarked()) {
+ getLog().info("Deferring deploy for " + project.getGroupId() + ":" + project.getArtifactId()
+ + ":" + project.getVersion() + " at end");
+ }
}
}
}
- if (allProjectsMarked()) {
- deployAllAtOnce();
+ synchronized (DEPLOY_AT_END_LOCK) {
+ // check-then-act must be atomic: without the lock two -T threads can both observe
+ // allProjectsMarked() == true and both fire the batch. Holding the lock across
+ // deployAllAtOnce() is intentional - a concurrent second trigger waits, then finds
+ // every batched project already DEPLOYED and no-ops.
+ if (allProjectsMarked()) {
+ deployAllAtOnce();
+ }
}
}