Okay after more investigation i found this issue SSHD-731 which depicts a very similar situation.
Looking at the changes made in the commit to patch it it's possible to see how to detect the "open for write" action. It must be done in the opening
method of the SftpEventListener
and it's like this:
@Override
public void opening(ServerSession serverSession, String remoteHandle, Handle localHandle) throws IOException {
if (localHandle instanceof FileHandle fileHandle) {
if (GenericUtils.containsAny(fileHandle.getOpenOptions(), IoUtils.WRITEABLE_OPEN_OPTIONS)
&& localHandle.toString().startsWith(this.storageReportsDirectoryPathString)
&& /* Custom condition like "file is inside a given read-only directory" */) {
throw new AccessDeniedException("Operation not permitted for the authenticated user");
}
}
}
Hope it helps anyone facing the same issue.