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 33c50ff9d80b CAMEL-27031: mina-sftp: do not retry on login rejection 
(#30709)
33c50ff9d80b is described below

commit 33c50ff9d80b52d93261216b4787aff17a30c7bb
Author: Guillaume Nodet <[email protected]>
AuthorDate: Tue Nov 24 21:15:43 2026 +0100

    CAMEL-27031: mina-sftp: do not retry on login rejection (#30709)
    
    When the server rejects the credentials, the login fails with an 
SshException.
    It was caught as a plain IOException, so the reconnect loop opened a new
    session and sent the same rejected credentials again on each of the
    maximumReconnectAttempts iterations (default 3), which can lock the account.
    
    The connect now catches SshException before the generic IOException handler.
    When it carries the disconnect code 
SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
    or its message contains "Authentication failed", it is rethrown at once as
    GenericFileOperationFailedException and the reconnect loop stops. Other
    SshExceptions, such as a refused connection, are still retried.
    
    MinaSftpAuthRetryIT checks that a rejected login is not retried and that a
    transient connection failure still goes through the retry loop. The upgrade
    guide and the component docs describe the change.
    
    AI-assisted: Hermès on behalf of gnodet.
---
 .../camel/catalog/docs/mina-sftp-component.adoc    |   6 +-
 .../src/main/docs/mina-sftp-component.adoc         |   6 +-
 .../file/remote/mina/MinaSftpOperations.java       |  24 +++
 .../mina/integration/MinaSftpAuthRetryIT.java      | 204 +++++++++++++++++++++
 .../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc    |   9 +
 5 files changed, 247 insertions(+), 2 deletions(-)

diff --git 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/mina-sftp-component.adoc
 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/mina-sftp-component.adoc
index 220a59954d30..eb32b73399e5 100644
--- 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/mina-sftp-component.adoc
+++ 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/mina-sftp-component.adoc
@@ -466,7 +466,11 @@ The component provides clear error messages for common 
failure scenarios:
 * **Connection timeout**: `Connection timed out after \{timeout\}ms`
 
 ==== Authentication Errors
-* **Authentication failure**: `Authentication failed: \{reason\}`
+* **Login rejected** (wrong credentials): `Login rejected by 
\{host\}:\{port\}: No more authentication methods available`
++
+When the server definitively rejects the credentials, `mina-sftp` throws 
`GenericFileOperationFailedException`
+immediately, without retrying. Transient connection failures (server 
unreachable, network error) are still retried up
+to `maximumReconnectAttempts` times.
 * **Authentication timeout**: `Authentication timed out after \{timeout\}ms`
 
 ==== Configuration Errors
diff --git a/components/camel-mina-sftp/src/main/docs/mina-sftp-component.adoc 
b/components/camel-mina-sftp/src/main/docs/mina-sftp-component.adoc
index 220a59954d30..eb32b73399e5 100644
--- a/components/camel-mina-sftp/src/main/docs/mina-sftp-component.adoc
+++ b/components/camel-mina-sftp/src/main/docs/mina-sftp-component.adoc
@@ -466,7 +466,11 @@ The component provides clear error messages for common 
failure scenarios:
 * **Connection timeout**: `Connection timed out after \{timeout\}ms`
 
 ==== Authentication Errors
-* **Authentication failure**: `Authentication failed: \{reason\}`
+* **Login rejected** (wrong credentials): `Login rejected by 
\{host\}:\{port\}: No more authentication methods available`
++
+When the server definitively rejects the credentials, `mina-sftp` throws 
`GenericFileOperationFailedException`
+immediately, without retrying. Transient connection failures (server 
unreachable, network error) are still retried up
+to `maximumReconnectAttempts` times.
 * **Authentication timeout**: `Authentication timed out after \{timeout\}ms`
 
 ==== Configuration Errors
diff --git 
a/components/camel-mina-sftp/src/main/java/org/apache/camel/component/file/remote/mina/MinaSftpOperations.java
 
b/components/camel-mina-sftp/src/main/java/org/apache/camel/component/file/remote/mina/MinaSftpOperations.java
index fa07b6237475..03973a80491b 100644
--- 
a/components/camel-mina-sftp/src/main/java/org/apache/camel/component/file/remote/mina/MinaSftpOperations.java
+++ 
b/components/camel-mina-sftp/src/main/java/org/apache/camel/component/file/remote/mina/MinaSftpOperations.java
@@ -67,6 +67,8 @@ import 
org.apache.sshd.client.keyverifier.AcceptAllServerKeyVerifier;
 import org.apache.sshd.client.keyverifier.ServerKeyVerifier;
 import org.apache.sshd.client.session.ClientSession;
 import org.apache.sshd.common.NamedFactory;
+import org.apache.sshd.common.SshConstants;
+import org.apache.sshd.common.SshException;
 import org.apache.sshd.common.cipher.BuiltinCiphers;
 import org.apache.sshd.common.cipher.Cipher;
 import org.apache.sshd.common.compression.BuiltinCompressions;
@@ -217,6 +219,28 @@ public class MinaSftpOperations
                     LOG.debug("Connected to {}", 
payload.configuration.remoteServerInformation());
                 }
             }
+        } catch (SshException e) {
+            // SshException is thrown for two kinds of authentication failures:
+            //   * ClientUserAuthService.tryNext() — exhausted all auth 
methods; carries
+            //     disconnect code 
SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE (14).
+            //   * DefaultAuthFuture.verify() — saw false instead of true; 
carries no
+            //     disconnect code but the message contains "Authentication 
failed".
+            // In both cases the credentials are definitively rejected and 
retrying will not
+            // help; the server may lock the account after repeated failures. 
Rethrow
+            // immediately so the reconnect loop does not keep sending the bad 
credentials.
+            //
+            // SshException is also thrown for transient failures (e.g. 
connection refused via
+            // ConnectFuture) that should be retried; check the disconnect 
code / message.
+            String msg = e.getMessage();
+            if (e.getDisconnectCode() == 
SshConstants.SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE
+                    || (msg != null && msg.contains("Authentication failed"))) 
{
+                throw new GenericFileOperationFailedException(
+                        "Login rejected by " + 
payload.configuration.remoteServerInformation()
+                                                              + ": " + msg,
+                        e);
+            }
+            payload.exception = e;
+            return false;
         } catch (IOException e) {
             payload.exception = e;
             return false;
diff --git 
a/components/camel-mina-sftp/src/test/java/org/apache/camel/component/file/remote/mina/integration/MinaSftpAuthRetryIT.java
 
b/components/camel-mina-sftp/src/test/java/org/apache/camel/component/file/remote/mina/integration/MinaSftpAuthRetryIT.java
new file mode 100644
index 000000000000..c0705c449f43
--- /dev/null
+++ 
b/components/camel-mina-sftp/src/test/java/org/apache/camel/component/file/remote/mina/integration/MinaSftpAuthRetryIT.java
@@ -0,0 +1,204 @@
+/*
+ * 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.component.file.remote.mina.integration;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.camel.component.file.GenericFileOperationFailedException;
+import org.apache.camel.component.file.remote.mina.MinaSftpConfiguration;
+import org.apache.camel.component.file.remote.mina.MinaSftpEndpoint;
+import org.apache.camel.component.file.remote.mina.MinaSftpOperations;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.sshd.common.SshException;
+import org.apache.sshd.server.SshServer;
+import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider;
+import org.apache.sshd.sftp.server.SftpSubsystemFactory;
+import org.junit.jupiter.api.AfterEach;
+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.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Regression test for CAMEL-27031: a rejected login must not be retried 
maximumReconnectAttempts times.
+ * <p/>
+ * Before the fix, MinaSftpOperations.tryConnect() caught any IOException from 
createSession(), including the
+ * SshException that AuthFuture.verify() throws when the server rejects the 
credentials. The reconnect loop then sent
+ * the wrong password again on each of its maximumReconnectAttempts (default 
3) iterations.
+ * <p/>
+ * After the fix, SshException is caught before the generic IOException 
handler. Auth-rejection SshExceptions (detected
+ * via disconnect code {@code SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE} 
or the \"Authentication failed\" message)
+ * are rethrown immediately as GenericFileOperationFailedException, stopping 
the reconnect loop. Non-auth SshExceptions
+ * (e.g. connection refused) are still retried.
+ */
+class MinaSftpAuthRetryIT {
+
+    private SshServer sshd;
+    private int port;
+    /** Counts how many times the server's password authenticator is called 
per connect(). */
+    private final AtomicInteger passwordAttempts = new AtomicInteger();
+    private Path tempDir;
+    private DefaultCamelContext camelContext;
+
+    @BeforeEach
+    void setUp() throws Exception {
+        passwordAttempts.set(0);
+        tempDir = Files.createTempDirectory("camel-mina-sftp-auth-retry-it");
+
+        sshd = SshServer.setUpDefaultServer();
+        sshd.setPort(0); // OS-assigned port
+        sshd.setKeyPairProvider(new 
SimpleGeneratorHostKeyProvider(tempDir.resolve("host.ser")));
+        sshd.setSubsystemFactories(Collections.singletonList(new 
SftpSubsystemFactory()));
+
+        // Always reject: count attempts and return false
+        sshd.setPasswordAuthenticator((username, password, session) -> {
+            passwordAttempts.incrementAndGet();
+            return false;
+        });
+
+        sshd.start();
+        port = ((InetSocketAddress) 
sshd.getBoundAddresses().iterator().next()).getPort();
+
+        camelContext = new DefaultCamelContext();
+        camelContext.start();
+    }
+
+    @AfterEach
+    void tearDown() throws Exception {
+        if (camelContext != null) {
+            camelContext.stop();
+        }
+        if (sshd != null) {
+            sshd.stop(true);
+        }
+        deleteDir(tempDir);
+    }
+
+    /**
+     * A rejected login must throw GenericFileOperationFailedException 
immediately, not loop over
+     * maximumReconnectAttempts.
+     * <p/>
+     * With the default maximumReconnectAttempts=3 and a server offering only 
password auth, the unfixed code sends the
+     * wrong password 3 times. With the fix it is sent at most twice (once per 
auth method offered by the server:
+     * password and keyboard-interactive), not once per reconnect attempt.
+     */
+    @Test
+    void testRejectedLoginIsNotRetried() {
+        MinaSftpConfiguration config = buildConfiguration();
+        MinaSftpEndpoint endpoint = buildEndpoint(config, 3, 0);
+        MinaSftpOperations operations = new MinaSftpOperations();
+        operations.setEndpoint(endpoint);
+
+        GenericFileOperationFailedException ex = assertThrows(
+                GenericFileOperationFailedException.class,
+                () -> operations.connect(config, null),
+                "connect() must throw when login is rejected");
+
+        // The error must mention the rejection, not just "Cannot connect"
+        String msg = ex.getMessage();
+        assertTrue(msg != null && msg.contains("Login rejected"),
+                "Exception message should say 'Login rejected' but was: " + 
msg);
+
+        // The underlying cause must be the SshException from 
AuthFuture.verify()
+        assertInstanceOf(SshException.class, ex.getCause(),
+                "Cause must be SshException");
+
+        // The server must have checked the password at most twice (once for 
each auth method the
+        // MINA SSHD client tries: password and keyboard-interactive). Without 
the fix the client
+        // would open a new session for each of the maximumReconnectAttempts 
(3), tripling the count.
+        int attempts = passwordAttempts.get();
+        assertTrue(attempts <= 2,
+                "Password must be checked at most twice (once per auth method 
per session); got " + attempts);
+    }
+
+    /**
+     * A transient connection failure (server stopped) must still be retried 
up to maximumReconnectAttempts.
+     * <p/>
+     * The connection failure surfaces as an {@link 
org.apache.sshd.common.SshException} wrapping the underlying
+     * {@link java.net.ConnectException}, which exercises the non-auth {@code 
SshException} branch in
+     * {@code MinaSftpOperations.tryConnect()}. This verifies that the fix 
does not break the existing retry behaviour
+     * for failures that are not authentication rejections.
+     */
+    @Test
+    void testTransientFailureIsStillRetried() throws Exception {
+        // Stop the server so the client gets a connection failure 
(SshException wrapping ConnectException)
+        sshd.stop(true);
+
+        // maximumReconnectAttempts=2, reconnectDelay=0 → task runs 
atLeastOnce(2) = max 2 iterations
+        MinaSftpConfiguration config = buildConfiguration();
+        MinaSftpEndpoint endpoint = buildEndpoint(config, 2, 0);
+        MinaSftpOperations operations = new MinaSftpOperations();
+        operations.setEndpoint(endpoint);
+
+        GenericFileOperationFailedException ex = assertThrows(
+                GenericFileOperationFailedException.class,
+                () -> operations.connect(config, null),
+                "connect() must throw when server is unreachable");
+
+        // "Cannot connect" message means the budget was exhausted (not an 
immediate rethrow)
+        assertTrue(ex.getMessage().contains("Cannot connect"),
+                "Exception message should say 'Cannot connect' but was: " + 
ex.getMessage());
+
+        // No password check at all — the connection failed before auth
+        assertEquals(0, passwordAttempts.get(), "No password check expected 
for connection failure");
+    }
+
+    // ---- helpers ----
+
+    private MinaSftpEndpoint buildEndpoint(
+            MinaSftpConfiguration config, int maximumReconnectAttempts,
+            long reconnectDelay) {
+        MinaSftpEndpoint endpoint = new MinaSftpEndpoint(
+                "mina-sftp://localhost:"; + port + "/tmp", null, config);
+        endpoint.setMaximumReconnectAttempts(maximumReconnectAttempts);
+        endpoint.setReconnectDelay(reconnectDelay);
+        endpoint.setCamelContext(camelContext);
+        return endpoint;
+    }
+
+    private MinaSftpConfiguration buildConfiguration() {
+        MinaSftpConfiguration config = new MinaSftpConfiguration();
+        config.setHost("localhost");
+        config.setPort(port);
+        config.setUsername("admin");
+        config.setPassword("wrong-password");
+        config.setStrictHostKeyChecking("no");
+        config.setUseUserKnownHostsFile(false);
+        return config;
+    }
+
+    private static void deleteDir(Path dir) throws IOException {
+        if (dir == null || !Files.exists(dir)) {
+            return;
+        }
+        try (var walk = Files.walk(dir)) {
+            walk.sorted(Comparator.reverseOrder())
+                    .map(Path::toFile)
+                    .forEach(File::delete);
+        }
+    }
+}
diff --git 
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc 
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
index 5b052598c91d..dfc8906148fc 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
@@ -937,6 +937,15 @@ Apache MINA SSHD leaves it off by default, so a small 
request, such as one that
 listing, could wait for the server to acknowledge the previous reply. The 
`org.apache.sshd.config.tcp-nodelay` system
 property no longer applies to the connections of `mina-sftp`.
 
+=== camel-mina-sftp - a rejected login is not retried
+
+When the SFTP server rejects the credentials, `mina-sftp` now throws 
`GenericFileOperationFailedException` immediately
+instead of retrying the connection `maximumReconnectAttempts` times (default 
3). Retrying a rejected login sends the
+wrong password to the server repeatedly, which may trigger an account lockout. 
This change aligns `mina-sftp` with the
+`sftp` component (see CAMEL-27019).
+
+Transient connection failures (server unreachable, network error) are still 
retried as before.
+
 === camel-mllp - maxConcurrentConsumers limits the connections again
 
 The MLLP consumer resets a new connection when `maxConcurrentConsumers` 
connections are already being served, as the

Reply via email to