This is an automated email from the ASF dual-hosted git repository.

Croway 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 591da6676dbd CAMEL-27118: camel-sftp - a refused request gives the 
SFTP status and the current directory, and preferredAuthentications is not 
case-sensitive
591da6676dbd is described below

commit 591da6676dbdbf92ac71e7145c4af56ae46afc51
Author: croway <[email protected]>
AuthorDate: Tue Nov 17 15:42:27 2026 +0100

    CAMEL-27118: camel-sftp - a refused request gives the SFTP status and the 
current directory, and preferredAuthentications is not case-sensitive
    
    - SftpOperations: the GenericFileOperationFailedException of a refused 
request ends its message with the SFTP status
      (such as SSH_FX_NO_SUCH_FILE: No such file), and getCode() / getReason() 
return the status code and its text, as
      FtpOperations does with the FTP reply. New 
GenericFileOperationFailedException(message, code, reason, cause).
    - A failed change to a relative directory gives the current directory, with 
sftp and ftp/ftps.
    - preferredAuthentications is trimmed and lower-cased before it is given to 
JSch, and SftpEndpoint logs a WARN for a
      method that JSch does not know.
---
 .../apache/camel/catalog/docs/ftp-component.adoc   |   5 +
 .../apache/camel/catalog/docs/sftp-component.adoc  |  17 +-
 .../file/GenericFileOperationFailedException.java  |  15 ++
 .../camel-ftp/src/main/docs/ftp-component.adoc     |   5 +
 .../camel-ftp/src/main/docs/sftp-component.adoc    |  17 +-
 .../camel/component/file/remote/FtpOperations.java |  19 +-
 .../camel/component/file/remote/SftpEndpoint.java  |  22 ++
 .../component/file/remote/SftpOperations.java      | 118 ++++++++--
 .../FtpChangeDirectoryFailureMessageIT.java        |  81 +++++++
 .../integration/SftpOperationFailureMessageIT.java | 240 +++++++++++++++++++++
 .../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc    |  15 ++
 11 files changed, 531 insertions(+), 23 deletions(-)

diff --git 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/ftp-component.adoc
 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/ftp-component.adoc
index 294010afe951..37eb067142e9 100644
--- 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/ftp-component.adoc
+++ 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/ftp-component.adoc
@@ -51,6 +51,11 @@ Camel translates the absolute path to relative by trimming 
all leading slashes f
 There'll be a warning (`WARN` level) message printed in the logs.
 =====
 
+When the server refuses the change to a directory, the 
`GenericFileOperationFailedException` holds the reply code
+(`getCode()`) and the reply of the server, and for a relative path its message 
gives the current directory, which the
+path starts from, such as `Cannot change directory to: inbox. The path is 
relative to the current directory:
+/home/admin`.
+
 The `autoCreate` option is supported. When consumer
 starts, before polling is scheduled, there's additional FTP operation
 performed to create the directory configured for endpoint. The default
diff --git 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/sftp-component.adoc
 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/sftp-component.adoc
index b6164adac772..0463c74fd36c 100644
--- 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/sftp-component.adoc
+++ 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/sftp-component.adoc
@@ -425,7 +425,9 @@ than 22, the entry starts with `[host]:port`.
 
 |`Auth fail for methods '...'`, `Auth fail for user '...': the server did not 
accept the password`
 |The server refused the credentials: check the username, password or key. With 
an RSA key and a server that only
-accepts `ssh-rsa` signatures, add `ssh-rsa` to `publicKeyAcceptedAlgorithms`.
+accepts `ssh-rsa` signatures, add `ssh-rsa` to `publicKeyAcceptedAlgorithms`. 
With `preferredAuthentications`, only
+the methods listed there are tried: the names are not case-sensitive, and a 
name that JSch does not know (it knows
+`password`, `keyboard-interactive`, `publickey` and `gssapi-with-mic`) is 
skipped, with a WARN when the endpoint starts.
 
 |`invalid privatekey`
 |JSch cannot read the key, for example because its line breaks were lost. See 
<<_providing_the_private_key,Providing the private key>>.
@@ -446,6 +448,19 @@ the password is right. A rejected login (`Auth fail ...` 
or `Auth cancel ...`) d
 poll, so a wrong password is sent once per poll (and once more when the 
consumer starts with `autoCreate=true`), and
 the producer tries again on its next message.
 
+=== Operation errors
+
+When the server refuses a request, such as a change of directory, a listing, 
an upload or a download, the exception is
+a `GenericFileOperationFailedException` whose message ends with the status of 
the server, for example
+`Cannot list directory: inbox: SSH_FX_NO_SUCH_FILE: No such file`. As with the 
reply of an FTP server, `getCode()`
+returns the SFTP status code, such as `2` for `SSH_FX_NO_SUCH_FILE` or `3` for 
`SSH_FX_PERMISSION_DENIED`, and
+`getReason()` its text. JSch reports an I/O failure as `SSH_FX_FAILURE` (`4`), 
with that failure as the cause.
+
+When the change to a relative directory fails, the message also gives the 
current directory, which the path starts
+from, such as `Cannot change directory to: inbox: SSH_FX_NO_SUCH_FILE: No such 
file. The path is relative to the
+current directory: /home/admin`. The directory of the endpoint starts from the 
login directory, see
+<<_uri_format_and_paths,URI format and paths>>.
+
 === Symbolic links and the starting directory
 
 With `jailStartingDirectory` enabled (the default), the consumer resolves a 
listed file that the server reports as a
diff --git 
a/components/camel-file/src/main/java/org/apache/camel/component/file/GenericFileOperationFailedException.java
 
b/components/camel-file/src/main/java/org/apache/camel/component/file/GenericFileOperationFailedException.java
index 912e58ea2b99..bf3808b55408 100644
--- 
a/components/camel-file/src/main/java/org/apache/camel/component/file/GenericFileOperationFailedException.java
+++ 
b/components/camel-file/src/main/java/org/apache/camel/component/file/GenericFileOperationFailedException.java
@@ -59,6 +59,21 @@ public class GenericFileOperationFailedException extends 
RuntimeCamelException {
         this(code, reason + " " + message, cause);
     }
 
+    /**
+     * A failure with the status that the server answered, keeping the given 
message as it is.
+     *
+     * @param message the message
+     * @param code    the status code of the server
+     * @param reason  the status text of the server
+     * @param cause   the cause
+     * @since         4.24
+     */
+    public GenericFileOperationFailedException(String message, int code, 
String reason, Throwable cause) {
+        super(message, cause);
+        this.code = code;
+        this.reason = reason;
+    }
+
     /**
      * Return the file failure code (if any)
      */
diff --git a/components/camel-ftp/src/main/docs/ftp-component.adoc 
b/components/camel-ftp/src/main/docs/ftp-component.adoc
index 294010afe951..37eb067142e9 100644
--- a/components/camel-ftp/src/main/docs/ftp-component.adoc
+++ b/components/camel-ftp/src/main/docs/ftp-component.adoc
@@ -51,6 +51,11 @@ Camel translates the absolute path to relative by trimming 
all leading slashes f
 There'll be a warning (`WARN` level) message printed in the logs.
 =====
 
+When the server refuses the change to a directory, the 
`GenericFileOperationFailedException` holds the reply code
+(`getCode()`) and the reply of the server, and for a relative path its message 
gives the current directory, which the
+path starts from, such as `Cannot change directory to: inbox. The path is 
relative to the current directory:
+/home/admin`.
+
 The `autoCreate` option is supported. When consumer
 starts, before polling is scheduled, there's additional FTP operation
 performed to create the directory configured for endpoint. The default
diff --git a/components/camel-ftp/src/main/docs/sftp-component.adoc 
b/components/camel-ftp/src/main/docs/sftp-component.adoc
index b6164adac772..0463c74fd36c 100644
--- a/components/camel-ftp/src/main/docs/sftp-component.adoc
+++ b/components/camel-ftp/src/main/docs/sftp-component.adoc
@@ -425,7 +425,9 @@ than 22, the entry starts with `[host]:port`.
 
 |`Auth fail for methods '...'`, `Auth fail for user '...': the server did not 
accept the password`
 |The server refused the credentials: check the username, password or key. With 
an RSA key and a server that only
-accepts `ssh-rsa` signatures, add `ssh-rsa` to `publicKeyAcceptedAlgorithms`.
+accepts `ssh-rsa` signatures, add `ssh-rsa` to `publicKeyAcceptedAlgorithms`. 
With `preferredAuthentications`, only
+the methods listed there are tried: the names are not case-sensitive, and a 
name that JSch does not know (it knows
+`password`, `keyboard-interactive`, `publickey` and `gssapi-with-mic`) is 
skipped, with a WARN when the endpoint starts.
 
 |`invalid privatekey`
 |JSch cannot read the key, for example because its line breaks were lost. See 
<<_providing_the_private_key,Providing the private key>>.
@@ -446,6 +448,19 @@ the password is right. A rejected login (`Auth fail ...` 
or `Auth cancel ...`) d
 poll, so a wrong password is sent once per poll (and once more when the 
consumer starts with `autoCreate=true`), and
 the producer tries again on its next message.
 
+=== Operation errors
+
+When the server refuses a request, such as a change of directory, a listing, 
an upload or a download, the exception is
+a `GenericFileOperationFailedException` whose message ends with the status of 
the server, for example
+`Cannot list directory: inbox: SSH_FX_NO_SUCH_FILE: No such file`. As with the 
reply of an FTP server, `getCode()`
+returns the SFTP status code, such as `2` for `SSH_FX_NO_SUCH_FILE` or `3` for 
`SSH_FX_PERMISSION_DENIED`, and
+`getReason()` its text. JSch reports an I/O failure as `SSH_FX_FAILURE` (`4`), 
with that failure as the cause.
+
+When the change to a relative directory fails, the message also gives the 
current directory, which the path starts
+from, such as `Cannot change directory to: inbox: SSH_FX_NO_SUCH_FILE: No such 
file. The path is relative to the
+current directory: /home/admin`. The directory of the endpoint starts from the 
login directory, see
+<<_uri_format_and_paths,URI format and paths>>.
+
 === Symbolic links and the starting directory
 
 With `jailStartingDirectory` enabled (the default), the consumer resolves a 
listed file that the server reports as a
diff --git 
a/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/FtpOperations.java
 
b/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/FtpOperations.java
index 19a07b2f5bbf..be176170ce81 100644
--- 
a/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/FtpOperations.java
+++ 
b/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/FtpOperations.java
@@ -1021,8 +1021,23 @@ public class FtpOperations implements 
RemoteFileOperations<FTPFile> {
             throw new 
GenericFileOperationFailedException(client.getReplyCode(), 
client.getReplyString(), e.getMessage(), e);
         }
         if (!success) {
-            throw new GenericFileOperationFailedException(
-                    client.getReplyCode(), client.getReplyString(), "Cannot 
change directory to: " + path);
+            // the reply to the change of directory, before the command that 
reads the current directory replaces it
+            int replyCode = client.getReplyCode();
+            String replyString = client.getReplyString();
+            String message = "Cannot change directory to: " + path;
+            if (!FileUtil.hasLeadingSeparator(path)) {
+                // give the directory that a relative path starts from (the 
login directory, for the directory of the
+                // endpoint)
+                try {
+                    String current = client.printWorkingDirectory();
+                    if (current != null) {
+                        message += ". The path is relative to the current 
directory: " + current;
+                    }
+                } catch (IOException e) {
+                    log.trace("Cannot get the current directory: {}", 
e.getMessage(), e);
+                }
+            }
+            throw new GenericFileOperationFailedException(replyCode, 
replyString, message);
         }
     }
 
diff --git 
a/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/SftpEndpoint.java
 
b/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/SftpEndpoint.java
index 38d33901ea14..4751f3b1ba5e 100644
--- 
a/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/SftpEndpoint.java
+++ 
b/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/SftpEndpoint.java
@@ -16,6 +16,8 @@
  */
 package org.apache.camel.component.file.remote;
 
+import java.util.List;
+
 import com.jcraft.jsch.Proxy;
 import org.apache.camel.Category;
 import org.apache.camel.Processor;
@@ -30,6 +32,8 @@ import org.apache.camel.spi.BodyTypes;
 import org.apache.camel.spi.Metadata;
 import org.apache.camel.spi.UriEndpoint;
 import org.apache.camel.spi.UriParam;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  * Upload and download files to/from SFTP servers.
@@ -59,6 +63,8 @@ import org.apache.camel.spi.UriParam;
            producerOut = @BodyType(Carrier.UNCHANGED))
 public class SftpEndpoint extends RemoteFileEndpoint<SftpRemoteFile> {
 
+    private static final Logger LOG = 
LoggerFactory.getLogger(SftpEndpoint.class);
+
     @UriParam
     protected SftpConfiguration configuration;
     @UriParam(label = "advanced")
@@ -87,6 +93,22 @@ public class SftpEndpoint extends 
RemoteFileEndpoint<SftpRemoteFile> {
         super.setConfiguration(configuration);
     }
 
+    @Override
+    protected void doInit() throws Exception {
+        super.doInit();
+
+        String preferredAuthentications = 
configuration.getPreferredAuthentications();
+        if (preferredAuthentications != null) {
+            List<String> unknown = 
SftpOperations.unknownAuthenticationMethods(preferredAuthentications);
+            if (!unknown.isEmpty()) {
+                LOG.warn("The preferredAuthentications option of {} has 
authentication methods that JSch does not know,"
+                         + " which it skips: {}. The methods are password, 
keyboard-interactive, publickey and"
+                         + " gssapi-with-mic.",
+                        configuration.remoteServerInformation(), 
String.join(", ", unknown));
+            }
+        }
+    }
+
     @Override
     protected RemoteFileConsumer<SftpRemoteFile> buildConsumer(Processor 
processor) {
         return new SftpConsumer(
diff --git 
a/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/SftpOperations.java
 
b/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/SftpOperations.java
index e3ef97455f1e..1250230e5cd8 100644
--- 
a/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/SftpOperations.java
+++ 
b/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/SftpOperations.java
@@ -31,8 +31,10 @@ import java.nio.file.Files;
 import java.nio.file.Paths;
 import java.security.KeyPair;
 import java.time.Duration;
+import java.util.Arrays;
 import java.util.Base64;
 import java.util.List;
+import java.util.Locale;
 import java.util.Vector;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.TimeUnit;
@@ -40,6 +42,7 @@ import java.util.concurrent.locks.Lock;
 import java.util.concurrent.locks.ReentrantLock;
 import java.util.function.Predicate;
 import java.util.regex.Pattern;
+import java.util.stream.Collectors;
 
 import com.jcraft.jsch.ChannelSftp;
 import com.jcraft.jsch.JSch;
@@ -193,6 +196,28 @@ public class SftpOperations
         }
     }
 
+    /**
+     * The authentication methods of the preferredAuthentications option as 
JSch compares them with the methods that the
+     * server offers, which JSch turns to lower case: in lower case, without 
the spaces around them. JSch skips a method
+     * written in another case, such as {@code Password}, as one that the 
server does not offer.
+     */
+    static String normalizePreferredAuthentications(String methods) {
+        return Arrays.stream(methods.split(","))
+                .map(String::trim)
+                .filter(method -> !method.isEmpty())
+                .map(method -> method.toLowerCase(Locale.ROOT))
+                .collect(Collectors.joining(","));
+    }
+
+    /**
+     * The methods of the preferredAuthentications option that JSch has no 
implementation for, which it skips.
+     */
+    static List<String> unknownAuthenticationMethods(String methods) {
+        return 
Arrays.stream(normalizePreferredAuthentications(methods).split(","))
+                .filter(method -> !method.isEmpty() && 
JSch.getConfig("userauth." + method) == null)
+                .toList();
+    }
+
     /**
      * One attempt of the reconnect task.
      *
@@ -412,8 +437,9 @@ public class SftpOperations
 
         // set the PreferredAuthentications
         if (sftpConfig.getPreferredAuthentications() != null) {
-            LOG.debug("Using PreferredAuthentications: {}", 
sftpConfig.getPreferredAuthentications());
-            session.setConfig("PreferredAuthentications", 
sftpConfig.getPreferredAuthentications());
+            String preferredAuthentications = 
normalizePreferredAuthentications(sftpConfig.getPreferredAuthentications());
+            LOG.debug("Using PreferredAuthentications: {}", 
preferredAuthentications);
+            session.setConfig("PreferredAuthentications", 
preferredAuthentications);
         }
 
         // set the ServerHostKeys
@@ -806,7 +832,7 @@ public class SftpOperations
             return true;
         } catch (SftpException e) {
             LOG.debug("Cannot delete file {}: {}", name, e.getMessage(), e);
-            throw new GenericFileOperationFailedException("Cannot delete file: 
" + name, e);
+            throw operationFailed("Cannot delete file: " + name, e);
         } finally {
             lock.unlock();
         }
@@ -825,7 +851,7 @@ public class SftpOperations
             return true;
         } catch (SftpException e) {
             LOG.debug("Cannot rename file from: {} to: {}", from, to, e);
-            throw new GenericFileOperationFailedException("Cannot rename file 
from: " + from + " to: " + to, e);
+            throw operationFailed("Cannot rename file from: " + from + " to: " 
+ to, e);
         } finally {
             lock.unlock();
         }
@@ -884,7 +910,7 @@ public class SftpOperations
                     changeCurrentDirectory(originalDirectory);
                 }
             } catch (SftpException e) {
-                throw new GenericFileOperationFailedException("Cannot build 
directory: " + directory, e);
+                throw operationFailed("Cannot build directory: " + directory, 
e);
             }
 
             return success;
@@ -940,7 +966,7 @@ public class SftpOperations
             LOG.trace("Current dir: {}", answer);
             return answer;
         } catch (SftpException e) {
-            throw new GenericFileOperationFailedException("Cannot get current 
directory", e);
+            throw operationFailed("Cannot get current directory", e);
         } finally {
             lock.unlock();
         }
@@ -1026,7 +1052,18 @@ public class SftpOperations
         try {
             channel.cd(quotePathForJsch(path));
         } catch (SftpException e) {
-            throw new GenericFileOperationFailedException("Cannot change 
directory to: " + path, e);
+            String status = sftpStatus(e);
+            String message = "Cannot change directory to: " + path + ": " + 
status;
+            if (e.getCause() == null && !FileUtil.hasLeadingSeparator(path)) {
+                // the server answered: give the directory that a relative 
path starts from (the login directory, for
+                // the directory of the endpoint)
+                try {
+                    message += ". The path is relative to the current 
directory: " + channel.pwd();
+                } catch (SftpException pwdFailure) {
+                    LOG.trace("Cannot get the current directory: {}", 
pwdFailure.getMessage(), pwdFailure);
+                }
+            }
+            throw new GenericFileOperationFailedException(message, e.id, 
status, e);
         }
     }
 
@@ -1075,7 +1112,7 @@ public class SftpOperations
                     .map(f -> new SftpRemoteFileJCraft((ChannelSftp.LsEntry) 
f))
                     .toArray(SftpRemoteFileJCraft[]::new);
         } catch (SftpException e) {
-            throw new GenericFileOperationFailedException("Cannot list 
directory: " + path, e);
+            throw operationFailed("Cannot list directory: " + path, e);
         } finally {
             lock.unlock();
         }
@@ -1102,7 +1139,7 @@ public class SftpOperations
                 throw failure[0];
             }
         } catch (SftpException e) {
-            throw new GenericFileOperationFailedException("Cannot list 
directory: " + dir, e);
+            throw operationFailed("Cannot list directory: " + dir, e);
         } finally {
             lock.unlock();
         }
@@ -1123,7 +1160,7 @@ public class SftpOperations
         try {
             return channel.getHome();
         } catch (SftpException e) {
-            throw new GenericFileOperationFailedException("Cannot get the home 
directory", e);
+            throw operationFailed("Cannot get the home directory", e);
         } finally {
             lock.unlock();
         }
@@ -1135,7 +1172,7 @@ public class SftpOperations
         try {
             return channel.lstat(quotePathForJsch(path)).isLink();
         } catch (SftpException e) {
-            throw new GenericFileOperationFailedException("Cannot get the 
attributes of: " + path, e);
+            throw operationFailed("Cannot get the attributes of: " + path, e);
         } finally {
             lock.unlock();
         }
@@ -1147,7 +1184,7 @@ public class SftpOperations
         try {
             return channel.readlink(quotePathForJsch(path));
         } catch (SftpException e) {
-            throw new GenericFileOperationFailedException("Cannot read the 
symbolic link: " + path, e);
+            throw operationFailed("Cannot read the symbolic link: " + path, e);
         } finally {
             lock.unlock();
         }
@@ -1284,7 +1321,7 @@ public class SftpOperations
             return true;
         } catch (SftpException e) {
             createResultHeadersFromExchange(e, exchange);
-            throw new GenericFileOperationFailedException("Cannot retrieve 
file: " + name, e);
+            throw operationFailed("Cannot retrieve file: " + name, e);
         } catch (IOException e) {
             throw new GenericFileOperationFailedException("Cannot retrieve 
file: " + name, e);
         } finally {
@@ -1382,7 +1419,7 @@ public class SftpOperations
                 LOG.warn("Error occurred during retrieving file: {} to local 
directory. Cannot delete local work file: {}",
                         name, temp);
             }
-            throw new GenericFileOperationFailedException("Cannot retrieve 
file: " + name, e);
+            throw operationFailed("Cannot retrieve file: " + name, e);
         } finally {
             IOHelper.close(os, "retrieve: " + name, LOG);
             // change back to current directory if we changed directory
@@ -1547,7 +1584,7 @@ public class SftpOperations
 
         } catch (SftpException e) {
             createResultHeadersFromExchange(e, exchange);
-            throw new GenericFileOperationFailedException("Cannot store file: 
" + name, e);
+            throw operationFailed("Cannot store file: " + name, e);
         } catch (IOException | InvalidPayloadException e) {
             throw new GenericFileOperationFailedException("Cannot store file: 
" + name, e);
         } finally {
@@ -1563,7 +1600,7 @@ public class SftpOperations
             channel.put(bis, quotePathForJsch(name));
             return true;
         } catch (SftpException e) {
-            throw new GenericFileOperationFailedException("Cannot store file: 
" + name, e);
+            throw operationFailed("Cannot store file: " + name, e);
         } finally {
             IOHelper.close(bis);
             lock.unlock();
@@ -1606,7 +1643,7 @@ public class SftpOperations
                 attrs = lstat(name);
             } catch (SftpException e) {
                 if (!isLstatUnanswered(e)) {
-                    throw new 
GenericFileOperationFailedException(e.getMessage(), e);
+                    throw operationFailed("Cannot get the attributes of: " + 
name, e);
                 }
                 LOG.debug("Cannot get the attributes of: {} due to: {}. 
Listing its directory instead.", name,
                         e.getMessage());
@@ -1704,7 +1741,7 @@ public class SftpOperations
                 return null;
             }
             // otherwise its a more serious error so rethrow
-            throw new GenericFileOperationFailedException(e.getMessage(), e);
+            throw operationFailed("Cannot list directory: " + directory, e);
         }
     }
 
@@ -1793,6 +1830,49 @@ public class SftpOperations
         return socket;
     }
 
+    /**
+     * The failure of an SFTP request, with the status of the server after the 
given message, and as the code and reason
+     * of the exception, as {@link FtpOperations} does with the reply code and 
reply text of an FTP server.
+     */
+    private static GenericFileOperationFailedException operationFailed(String 
message, SftpException e) {
+        String status = sftpStatus(e);
+        return new GenericFileOperationFailedException(message + ": " + 
status, e.id, status, e);
+    }
+
+    /**
+     * The status of a failed SFTP request, such as {@code 
SSH_FX_NO_SUCH_FILE: No such file}.
+     */
+    static String sftpStatus(SftpException e) {
+        String text = e.getMessage();
+        if (ObjectHelper.isEmpty(text) && e.getCause() != null) {
+            // JSch reports an I/O or session failure as SSH_FX_FAILURE, with 
that failure as its cause
+            text = e.getCause().toString();
+        }
+        String name = sftpStatusName(e.id);
+        if (ObjectHelper.isEmpty(text)) {
+            return name;
+        }
+        // JSch starts the text of a status sent by the server with the name 
of the status, but not the text of a
+        // failure it detects itself, such as "Can't change directory: <path>" 
for a path that is not a directory
+        return text.startsWith(name) ? text : name + ": " + text;
+    }
+
+    private static String sftpStatusName(int id) {
+        return switch (id) {
+            case ChannelSftp.SSH_FX_OK -> "SSH_FX_OK";
+            case ChannelSftp.SSH_FX_EOF -> "SSH_FX_EOF";
+            case ChannelSftp.SSH_FX_NO_SUCH_FILE -> "SSH_FX_NO_SUCH_FILE";
+            case ChannelSftp.SSH_FX_PERMISSION_DENIED -> 
"SSH_FX_PERMISSION_DENIED";
+            case ChannelSftp.SSH_FX_FAILURE -> "SSH_FX_FAILURE";
+            case ChannelSftp.SSH_FX_BAD_MESSAGE -> "SSH_FX_BAD_MESSAGE";
+            case ChannelSftp.SSH_FX_NO_CONNECTION -> "SSH_FX_NO_CONNECTION";
+            case ChannelSftp.SSH_FX_CONNECTION_LOST -> 
"SSH_FX_CONNECTION_LOST";
+            case ChannelSftp.SSH_FX_OP_UNSUPPORTED -> "SSH_FX_OP_UNSUPPORTED";
+            // as JSch names a status of a later version of the protocol
+            default -> "Unknown code: (" + id + ")";
+        };
+    }
+
     /**
      * Helper method which gets result code and message from sftpException and 
puts it into header. In case that
      * exception is null, it sets successfully response.
@@ -1821,7 +1901,7 @@ public class SftpOperations
             try {
                 channel.chmod(permissions, quotePathForJsch(directory));
             } catch (SftpException e) {
-                throw new GenericFileOperationFailedException("Cannot set 
permission on directory: " + directory, e);
+                throw operationFailed("Cannot set permission on directory: " + 
directory, e);
             }
         }
     }
diff --git 
a/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FtpChangeDirectoryFailureMessageIT.java
 
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FtpChangeDirectoryFailureMessageIT.java
new file mode 100644
index 000000000000..a37637ed234c
--- /dev/null
+++ 
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FtpChangeDirectoryFailureMessageIT.java
@@ -0,0 +1,81 @@
+/*
+ * 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.integration;
+
+import java.nio.file.Files;
+
+import org.apache.camel.Exchange;
+import org.apache.camel.component.file.GenericFileOperationFailedException;
+import org.junit.jupiter.api.Test;
+
+import static org.apache.camel.test.junit6.TestSupport.assertIsInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * A failed change of directory gives the reply of the server and the current 
directory, that a relative path starts
+ * from. The home directory of the user is the root of the server.
+ */
+class FtpChangeDirectoryFailureMessageIT extends FtpServerTestSupport {
+
+    private Exchange send(String directory) {
+        return template.send("ftp://admin@localhost:{{ftp.server.port}}/"; + 
directory + "?password=admin&autoCreate=false",
+                e -> {
+                    e.getIn().setBody("Hello World");
+                    e.getIn().setHeader(Exchange.FILE_NAME, "hello.txt");
+                });
+    }
+
+    @Test
+    void changeDirectoryFailureGivesTheReplyAndTheCurrentDirectory() {
+        Exchange out = send("missing");
+
+        GenericFileOperationFailedException e
+                = 
assertIsInstanceOf(GenericFileOperationFailedException.class, 
out.getException());
+        // the reply to the change of directory, not to the command that reads 
the current directory
+        assertEquals(550, e.getCode());
+        assertTrue(e.getReason().startsWith("550 "), e.getReason());
+        assertTrue(e.getMessage().endsWith(
+                " Cannot change directory to: missing. The path is relative to 
the current directory: /. Code: 550"),
+                e.getMessage());
+    }
+
+    @Test
+    void changeDirectoryFailureGivesTheDirectoryOfThePreviousSegment() throws 
Exception {
+        Files.createDirectories(service.getFtpRootDir().resolve("existing"));
+
+        Exchange out = send("existing/missing");
+
+        GenericFileOperationFailedException e
+                = 
assertIsInstanceOf(GenericFileOperationFailedException.class, 
out.getException());
+        assertEquals(550, e.getCode());
+        assertTrue(e.getMessage().endsWith(
+                " Cannot change directory to: missing. The path is relative to 
the current directory: /existing. Code: 550"),
+                e.getMessage());
+    }
+
+    @Test
+    void existingDirectoryUploads() throws Exception {
+        Files.createDirectories(service.getFtpRootDir().resolve("existing"));
+
+        Exchange out = send("existing");
+
+        assertNull(out.getException());
+        
assertTrue(Files.exists(service.getFtpRootDir().resolve("existing/hello.txt")));
+    }
+}
diff --git 
a/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/sftp/integration/SftpOperationFailureMessageIT.java
 
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/sftp/integration/SftpOperationFailureMessageIT.java
new file mode 100644
index 000000000000..b9a1cef56f96
--- /dev/null
+++ 
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/sftp/integration/SftpOperationFailureMessageIT.java
@@ -0,0 +1,240 @@
+/*
+ * 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.sftp.integration;
+
+import java.nio.file.Files;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+import com.jcraft.jsch.ChannelSftp;
+import com.jcraft.jsch.SftpException;
+import org.apache.camel.Exchange;
+import org.apache.camel.component.file.GenericFileOperationFailedException;
+import org.apache.camel.component.file.remote.BaseServerTestSupport;
+import org.apache.camel.component.file.remote.FtpConstants;
+import org.apache.camel.component.file.remote.RemoteFileOperations;
+import org.apache.camel.component.file.remote.SftpEndpoint;
+import org.apache.camel.component.file.remote.SftpRemoteFile;
+import org.apache.camel.test.infra.ftp.services.embedded.SftpEmbeddedService;
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.core.LogEvent;
+import org.apache.logging.log4j.core.LoggerContext;
+import org.apache.logging.log4j.core.appender.AbstractAppender;
+import org.apache.logging.log4j.core.config.Property;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.condition.EnabledIf;
+import org.junit.jupiter.api.extension.RegisterExtension;
+
+import static org.apache.camel.test.junit6.TestSupport.assertIsInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * A failed SFTP request gives the status of the server in the message, the 
code and the reason of the exception, and a
+ * failed change of directory gives the current directory, that a relative 
path starts from. The methods of the
+ * preferredAuthentications option are compared with the methods of the server 
in lower case, and a method that JSch
+ * does not know is logged.
+ */
+@EnabledIf(value = 
"org.apache.camel.test.infra.ftp.services.embedded.SftpUtil#hasRequiredAlgorithms('src/test/resources/hostkey.pem')")
+class SftpOperationFailureMessageIT extends BaseServerTestSupport {
+
+    // the root of the server, "/", is the login directory of the user, and 
the ftp root directory is a directory in it
+    @RegisterExtension
+    SftpEmbeddedService service = new SftpEmbeddedService(true);
+
+    private final WarnCapture warnings = new WarnCapture();
+
+    @BeforeEach
+    void captureWarnings() {
+        warnings.attach();
+    }
+
+    @AfterEach
+    void releaseWarnings() {
+        warnings.detach();
+    }
+
+    /**
+     * The path of a directory of the ftp root directory, as the server names 
it from the login directory.
+     */
+    private String dir(String name) {
+        return service.getFtpRootDir().getFileName() + "/" + name;
+    }
+
+    private String uri(String directory, String options) {
+        return "sftp://admin@localhost:"; + service.getPort() + "/" + directory 
+ "?password=admin&knownHostsFile="
+               + service.getKnownHostsFile() + options;
+    }
+
+    private Exchange send(String uri) {
+        return template.send(uri, e -> {
+            e.getIn().setBody("Hello World");
+            e.getIn().setHeader(Exchange.FILE_NAME, "hello.txt");
+        });
+    }
+
+    @Test
+    void changeDirectoryFailureGivesTheStatusAndTheCurrentDirectory() {
+        Exchange out = send(uri("missing", "&autoCreate=false"));
+
+        GenericFileOperationFailedException e
+                = 
assertIsInstanceOf(GenericFileOperationFailedException.class, 
out.getException());
+        SftpException cause = assertIsInstanceOf(SftpException.class, 
e.getCause());
+        assertEquals(ChannelSftp.SSH_FX_NO_SUCH_FILE, cause.id);
+        assertEquals(ChannelSftp.SSH_FX_NO_SUCH_FILE, e.getCode());
+        assertTrue(e.getReason().startsWith("SSH_FX_NO_SUCH_FILE: "), 
e.getReason());
+        assertEquals("Cannot change directory to: missing: " + e.getReason()
+                     + ". The path is relative to the current directory: /",
+                e.getMessage());
+    }
+
+    @Test
+    void changeDirectoryFailureGivesTheDirectoryOfThePreviousSegment() {
+        Exchange out = send(uri(dir("missing"), "&autoCreate=false"));
+
+        GenericFileOperationFailedException e
+                = 
assertIsInstanceOf(GenericFileOperationFailedException.class, 
out.getException());
+        assertEquals(ChannelSftp.SSH_FX_NO_SUCH_FILE, e.getCode());
+        assertEquals("Cannot change directory to: missing: " + e.getReason()
+                     + ". The path is relative to the current directory: /" + 
service.getFtpRootDir().getFileName(),
+                e.getMessage());
+    }
+
+    @Test
+    void changeDirectoryToAFileGivesTheFailureThatJSchDetects() throws 
Exception {
+        Files.createDirectories(service.getFtpRootDir());
+        Files.writeString(service.getFtpRootDir().resolve("afile"), "x");
+
+        Exchange out = send(uri(dir("afile"), "&autoCreate=false"));
+
+        GenericFileOperationFailedException e
+                = 
assertIsInstanceOf(GenericFileOperationFailedException.class, 
out.getException());
+        String current = "/" + service.getFtpRootDir().getFileName();
+        assertEquals(ChannelSftp.SSH_FX_FAILURE, e.getCode());
+        assertEquals("SSH_FX_FAILURE: Can't change directory: " + current + 
"/afile", e.getReason());
+        assertEquals("Cannot change directory to: afile: SSH_FX_FAILURE: Can't 
change directory: " + current + "/afile"
+                     + ". The path is relative to the current directory: " + 
current,
+                e.getMessage());
+    }
+
+    @Test
+    void storeFailureGivesTheStatus() {
+        // not stepwise, the file is written with its path, in a directory 
that does not exist
+        Exchange out = send(uri(dir("missing"), 
"&autoCreate=false&stepwise=false"));
+
+        GenericFileOperationFailedException e
+                = 
assertIsInstanceOf(GenericFileOperationFailedException.class, 
out.getException());
+        assertEquals(ChannelSftp.SSH_FX_NO_SUCH_FILE, e.getCode());
+        assertTrue(e.getReason().startsWith("SSH_FX_NO_SUCH_FILE: "), 
e.getReason());
+        assertEquals("Cannot store file: " + dir("missing/hello.txt") + ": " + 
e.getReason(), e.getMessage());
+        // the reply headers are set as before
+        assertEquals(ChannelSftp.SSH_FX_NO_SUCH_FILE, 
out.getIn().getHeader(FtpConstants.FTP_REPLY_CODE));
+    }
+
+    @Test
+    void deleteAndListFailuresGiveTheStatus() {
+        SftpEndpoint endpoint = context.getEndpoint(uri("", ""), 
SftpEndpoint.class);
+        RemoteFileOperations<SftpRemoteFile> operations = 
endpoint.createRemoteFileOperations();
+        operations.connect(endpoint.getConfiguration(), null);
+        try {
+            GenericFileOperationFailedException e = 
assertThrows(GenericFileOperationFailedException.class,
+                    () -> operations.deleteFile("missing.txt"));
+            assertEquals(ChannelSftp.SSH_FX_NO_SUCH_FILE, e.getCode());
+            assertEquals("Cannot delete file: missing.txt: " + e.getReason(), 
e.getMessage());
+
+            e = assertThrows(GenericFileOperationFailedException.class, () -> 
operations.listFiles("missing"));
+            assertEquals(ChannelSftp.SSH_FX_NO_SUCH_FILE, e.getCode());
+            assertEquals("Cannot list directory: missing: " + e.getReason(), 
e.getMessage());
+        } finally {
+            operations.disconnect();
+        }
+    }
+
+    @Test
+    void existingDirectoryUploads() throws Exception {
+        Files.createDirectories(service.getFtpRootDir().resolve("existing"));
+
+        Exchange out = send(uri(dir("existing"), "&autoCreate=false"));
+
+        assertNull(out.getException());
+        
assertTrue(Files.exists(service.getFtpRootDir().resolve("existing/hello.txt")));
+    }
+
+    @Test
+    void preferredAuthenticationsInAnotherCaseLogsIn() {
+        Exchange out = send(uri(dir("auth"), 
"&preferredAuthentications=publickey, Password"));
+
+        assertNull(out.getException());
+        
assertTrue(Files.exists(service.getFtpRootDir().resolve("auth/hello.txt")));
+        assertEquals(List.of(), warnings.messages());
+    }
+
+    @Test
+    void unknownPreferredAuthenticationIsLoggedOncePerEndpoint() {
+        String uri = uri(dir("auth"), 
"&preferredAuthentications=pasword,password");
+
+        assertNull(send(uri).getException());
+        assertNull(send(uri).getException());
+
+        assertEquals(List.of("The preferredAuthentications option of 
sftp://admin@localhost:"; + service.getPort()
+                             + " has authentication methods that JSch does not 
know, which it skips: pasword."
+                             + " The methods are password, 
keyboard-interactive, publickey and gssapi-with-mic."),
+                warnings.messages());
+    }
+
+    /**
+     * Captures the WARN messages of the sftp endpoint.
+     */
+    private static final class WarnCapture extends AbstractAppender {
+
+        private final List<String> messages = new CopyOnWriteArrayList<>();
+
+        WarnCapture() {
+            super("SftpEndpointWarnCapture", null, null, true, 
Property.EMPTY_ARRAY);
+        }
+
+        void attach() {
+            start();
+            LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
+            ctx.getConfiguration().getRootLogger().addAppender(this, 
Level.WARN, null);
+            ctx.updateLoggers();
+        }
+
+        void detach() {
+            LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
+            ctx.getConfiguration().getRootLogger().removeAppender(getName());
+            ctx.updateLoggers();
+            stop();
+        }
+
+        List<String> messages() {
+            return messages;
+        }
+
+        @Override
+        public void append(LogEvent event) {
+            if (SftpEndpoint.class.getName().equals(event.getLoggerName())) {
+                messages.add(event.getMessage().getFormattedMessage());
+            }
+        }
+    }
+}
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 d02df3eeba0e..8cab29e3f158 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
@@ -558,6 +558,21 @@ starting directory (`autoCreate=true`), it now logs
 `Cannot auto-create starting directory <directory> at: ... due to: ... Will 
skip this poll.` instead.
 See the xref:components::sftp-component.adoc[SFTP component].
 
+=== camel-ftp - sftp failures give the status of the server, and 
preferredAuthentications is not case-sensitive
+
+When the server refuses a request, the `GenericFileOperationFailedException` 
of the `sftp` component now gives the
+status of the server after its message, such as `Cannot list directory: inbox: 
SSH_FX_NO_SUCH_FILE: No such file`, and
+`getCode()` and `getReason()` return the SFTP status code and its text, as for 
`ftp`. Before, the status was only in the
+cause, and `getCode()` was `0`. The messages start as before, except when the 
attributes of a file cannot be read: the
+message starts with `Cannot get the attributes of: <name>` (or `Cannot list 
directory: <directory>`) instead of the
+status. A failed change to a relative directory, with `sftp`, `ftp` and 
`ftps`, also gives the current directory, such
+as `. The path is relative to the current directory: /home/admin`. Update code 
that compares the whole message.
+
+The `preferredAuthentications` option of `sftp` now takes the method names in 
any case, and with spaces around them.
+Before, JSch skipped a name such as `Password`, as it compares the names with 
the lower-case names of the server, and the
+login failed with `Auth fail for methods '...'`. A name that JSch does not 
know is logged at WARN when the endpoint
+starts. See the xref:components::sftp-component.adoc[SFTP component].
+
 === camel-smb - a starting directory that cannot be created
 
 When the server refuses to create the starting directory of the `smb` consumer 
as the route starts (`autoCreate=true`),

Reply via email to