파일 업로드 SFTP 추가 ::VM옵션 추가(README 참조), maven install 실행해주세요

This commit is contained in:
주수현
2025-06-23 20:14:41 +09:00
parent 2a9fe5e3d9
commit 72faf02cf9
11 changed files with 444 additions and 5 deletions

View File

@@ -112,6 +112,14 @@ recycle 의 demo 가 궁금하다면 아래 URL 에서 확인 해주세요.
-Dspring.datasource.url=jdbc:postgresql://15.165.180.203:5432/korea_research
-Dspring.datasource.username=ko_research
-Dspring.datasource.password=koresearch1@#4
-Daes.secret-key=092HW829O0A0AVR0
-Dpath.upload.storage=SFTP
-Dpath.upload.sftp.public=/home/etribe/data/upload
-Dpath.upload.sftp.tmpdir=${user.home}/upload/tmpdir
-Dfile.upload.sftp.ip=115.68.193.117
-Dfile.upload.sftp.id=etribe
-Dfile.upload.sftp.password=Etribe@3415
-Dfile.upload.sftp.port=22
```
## JDBC 및 데이터 핸들링 구성 옵션

View File

@@ -7,6 +7,7 @@ import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
public enum FileStorageType {
LOCAL("로컬 스토리지"),
S3("AWS S3 스토리지");
S3("AWS S3 스토리지"),
SFTP("SFTP");
private final String desc;
}

View File

@@ -41,7 +41,7 @@ public enum FileUploadType {
AcceptableFileType.PDF,
AcceptableFileType.ZIP)),
NOTICE(
FileStorageType.LOCAL,
FileStorageType.SFTP,
"/notice",
Set.of(
AcceptableFileType.IMAGE,
@@ -55,7 +55,7 @@ public enum FileUploadType {
AcceptableFileType.ZIP)),
RECEIPT(
FileStorageType.LOCAL,
FileStorageType.SFTP,
"/receipt",
Set.of(
AcceptableFileType.IMAGE

View File

@@ -11,18 +11,24 @@ import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class AESEncryptUtil {
@Value("${encrypt.aes.key}")
@Value("${aes.secret-key}")
private String key;
@Value("${encrypt.aes.iv}")
private String iv;
private static final String AES_ALGORITHM = "AES/CBC/PKCS5PADDING";
public static final String ENCRYPT_IV = "0123456789ABCDEF";
public String encrypt(String text)
throws NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException,
IllegalBlockSizeException, InvalidAlgorithmParameterException, InvalidKeyException {
@@ -48,6 +54,42 @@ public class AESEncryptUtil {
return new String(decrypted, StandardCharsets.UTF_8);
}
public byte[] encryptAesCbc(byte[] plainData) {
if (plainData == null || plainData.length == 0) {
throw new IllegalArgumentException("데이터는 null이거나 비어 있을 수 없습니다.");
}
try {
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
IvParameterSpec ivSpec = new IvParameterSpec(ENCRYPT_IV.getBytes(StandardCharsets.UTF_8));
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
return org.apache.commons.codec.binary.Base64.encodeBase64(cipher.doFinal(plainData));
} catch (Exception e) {
log.error("바이너리 데이터 암호화 실패", e);
throw new RuntimeException("바이너리 데이터 암호화 실패", e);
}
}
public byte[] decryptAesCbc(byte[] cipherData) {
if (cipherData == null || cipherData.length == 0) {
throw new IllegalArgumentException("암호문은 null이거나 비어 있을 수 없습니다.");
}
try {
byte[] encrypted = org.apache.commons.codec.binary.Base64.decodeBase64(cipherData);
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
IvParameterSpec ivSpec = new IvParameterSpec(ENCRYPT_IV.getBytes(StandardCharsets.UTF_8));
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
return cipher.doFinal(encrypted);
} catch (Exception e) {
log.error("바이너리 데이터 복호화 실패", e);
throw new RuntimeException("바이너리 데이터 복호화 실패", e);
}
}
private String getTransformation() {
return "AES/CBC/PKCS5Padding";
}

View File

@@ -3,9 +3,16 @@ package app.module.core.config.application.util;
import app.module.core.config.adapters.web.security.domain.SocialUser;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
@@ -14,6 +21,7 @@ import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
@Slf4j
public class CommonUtil {
/**
@@ -106,4 +114,41 @@ public class CommonUtil {
flashMessages.add(msg);
session.setAttribute("flashAlertMessages", flashMessages);
}
public static String normalizePath(String path) {
if (path == null || path.trim().isEmpty()) {
log.warn("normalizePath: Input path is null or empty, returning default path");
String defaultPath = System.getProperty("user.home") + File.separator + "Downloads";
return Paths.get(defaultPath).toAbsolutePath().normalize().toString();
}
try {
// Paths.get을 사용하여 경로 정규화
Path normalizedPath = Paths.get(path).toAbsolutePath().normalize();
String result = normalizedPath.toString();
log.debug("Normalized path: {}", result);
return result;
} catch (Exception e) {
log.error("Error normalizing path: {}", path, e);
throw new IllegalArgumentException("Failed to normalize path: " + path, e);
}
}
public static void createDirectories(File directory) {
if (directory == null) {
throw new IllegalArgumentException("Directory cannot be null");
}
try {
if (!directory.exists()) {
boolean created = directory.mkdirs();
log.info("Directory created: {} (Success: {})", directory.getAbsolutePath(), created);
}
if (!directory.canWrite()) {
throw new IOException("No write permission for directory: " + directory.getAbsolutePath());
}
} catch (Exception e) {
log.error("Failed to create directory: {}", directory.getAbsolutePath(), e);
throw new RuntimeException("Failed to create directory", e);
}
}
}

View File

@@ -0,0 +1,102 @@
package app.module.core.config.application.util;
import app.module.core.usecase.file.getFile.ports.application.domain.GetFile;
import app.module.core.usecase.file.saveToStorage.ports.application.strategy.SftpConnector;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
@Slf4j
@Component
@RequiredArgsConstructor
public class SftpFileDownloader {
private final SftpConnector sftpConnector;
private final AESEncryptUtil encryptUtil;
@Value("${path.upload.sftp.public}")
private String publicPath;
@Value("${file.download.base-path:/tmp/downloads}")
private String defaultDownloadBasePath;
public void downloadFile(GetFile file) throws JSchException, SftpException, IOException {
// SFTP 연결 확인 및 재연결
if (!sftpConnector.isConnected()) {
log.info("SFTP connection lost, attempting to reconnect");
sftpConnector.connect();
}
ChannelSftp channelSftp = sftpConnector.getChannelSftp();
if (channelSftp == null) {
throw new SftpException(ChannelSftp.SSH_FX_NO_CONNECTION, "SFTP channel is not initialized");
}
try {
// 원격 파일 경로 (암호화된 파일명 사용)
String remoteFilePath = CommonUtil.removeLastChar(publicPath, "/") + file.getPath() + "/" +"encrypted_"+ file.getName();
log.info("Remote file path: {}", remoteFilePath);
// 다운로드 경로 정규화
String basePath = CommonUtil.normalizePath(defaultDownloadBasePath);
log.info("Base path: {}", basePath);
String localEncryptedFilePath = basePath + File.separator + "encrypted_" + file.getOriginName();
String localDecryptedFilePath = basePath + File.separator + file.getOriginName();
log.info("Local encrypted file path: {}", localEncryptedFilePath);
log.info("Local decrypted file path: {}", localDecryptedFilePath);
// 로컬 디렉토리 생성
File localDir = new File(localEncryptedFilePath).getParentFile();
CommonUtil.createDirectories(localDir);
// 원격 파일 존재 여부 확인 (디버깅 용)
try {
channelSftp.lstat(remoteFilePath);
log.info("Remote file exists: {}", remoteFilePath);
} catch (SftpException e) {
log.error("Remote file does not exist: {}", remoteFilePath, e);
throw new SftpException(ChannelSftp.SSH_FX_NO_SUCH_FILE, "Remote file does not exist: " + remoteFilePath);
}
// 암호화된 파일 다운로드
try (FileOutputStream fos = new FileOutputStream(localEncryptedFilePath)) {
channelSftp.get(remoteFilePath, fos);
log.info("File downloaded to: {}", localEncryptedFilePath);
}
// 파일 복호화
try {
byte[] encryptedContent = Files.readAllBytes(Paths.get(localEncryptedFilePath));
byte[] decryptedContent = encryptUtil.decryptAesCbc(encryptedContent);
Files.write(Paths.get(localDecryptedFilePath), decryptedContent);
log.info("File decrypted and saved to: {}", localDecryptedFilePath);
file.setLocalPath(localDecryptedFilePath);
} catch (Exception e) {
log.error("Failed to decrypt file: {}", file.getOriginName(), e);
throw new IOException("Failed to decrypt file", e);
} finally {
// 암호화된 임시 파일 삭제
Files.deleteIfExists(Paths.get(localEncryptedFilePath));
log.info("Temporary encrypted file deleted: {}", localEncryptedFilePath);
}
} catch (SftpException e) {
log.error("Failed to download file: {} (Error: {})", file.getOriginName(), e.getMessage());
throw e;
} catch (IOException e) {
log.error("IO error during file download or decryption: {}", file.getOriginName(), e);
throw e;
} catch (Exception e) {
log.error("Unexpected error during file download: {}", file.getOriginName(), e);
throw new RuntimeException("Unexpected error during file download", e);
}
}
}

View File

@@ -18,8 +18,10 @@ public class GetFile {
private String name;
private String originName;
private Long fileLength;
private String localPath;
private LocalDateTime createdAt;
private String createdBy;
private LocalDateTime updatedAt;
private String updatedBy;
}

View File

@@ -0,0 +1,71 @@
package app.module.core.usecase.file.saveToStorage.ports.application.strategy;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class SftpConnector {
@Value("${file.upload.sftp.ip}")
private String host;
@Value("${file.upload.sftp.id}")
private String id;
@Value("${file.upload.sftp.password}")
private String password;
@Value("${file.upload.sftp.port}")
private int port;
private Session session;
private ChannelSftp channelSftp;
public void connect() throws JSchException {
if (host == null || id == null || password == null) {
throw new IllegalStateException("SFTP configuration is incomplete: host=" + host + ", id=" + id + ", password=" + (password != null ? "****" : null));
}
try {
JSch jsch = new JSch();
// 세션 설정
session = jsch.getSession(id, host, port);
session.setPassword(password);
// 호스트 키 검증 비활성화 (개발 환경에서만 사용, 프로덕션에서는 적절히 설정)
session.setConfig("StrictHostKeyChecking", "no");
// 연결
session.connect();
// SFTP 채널 열기
channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
log.info("SFTP connection established successfully");
}catch (JSchException e){
log.error("Failed to connect to SFTP server", e);
}
}
public void disconnect() {
if (channelSftp != null && channelSftp.isConnected()) {
channelSftp.disconnect();
log.info("SFTP channel disconnected");
}
if (session != null && session.isConnected()) {
session.disconnect();
log.info("SFTP channel disconnected");
}
}
public boolean isConnected() {
return channelSftp != null && channelSftp.isConnected() && session != null && session.isConnected();
}
// ChannelSftp 객체 반환
public ChannelSftp getChannelSftp() {
return channelSftp;
}
}

View File

@@ -0,0 +1,140 @@
package app.module.core.usecase.file.saveToStorage.ports.application.strategy;
import app.module.core.config.application.enums.FileStorageType;
import app.module.core.config.application.util.AESEncryptUtil;
import app.module.core.config.application.util.CommonUtil;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
@Service
@RequiredArgsConstructor
@Slf4j
public class SftpStorageFileUploadStrategy implements FileUploadStrategy {
@Value("${path.upload.sftp.public}")
private String publicPath;
@Value("${path.upload.sftp.tmpdir}")
private String tmpPath;
private final SftpConnector sftpConnector;
private final AESEncryptUtil encryptUtil; // EncryptUtil 주입
@PostConstruct
public void initialize() throws Exception {
log.info("FileIoService - initialize : path.upload.public is {}", publicPath);
log.info("FileIoService - initialize : path.upload.tmpdir is {}", tmpPath);
try {
Files.createDirectories(Paths.get(tmpPath));
// SFTP 연결 초기화
sftpConnector.connect();
// 원격 디렉토리 생성
createRemoteDirectories(publicPath);
} catch (JSchException | SftpException e) {
throw new IOException("Could not initialize SFTP connection or directories", e);
}
}
private void createRemoteDirectories(String path) throws SftpException {
ChannelSftp channelSftp = sftpConnector.getChannelSftp();
if (channelSftp != null) {
String[] folders = path.split("/");
String currentPath = "";
for (String folder : folders) {
if (!folder.isEmpty()) {
currentPath += "/" + folder;
try {
channelSftp.cd(currentPath);
} catch (SftpException e) {
channelSftp.mkdir(currentPath);
channelSftp.cd(currentPath);
}
}
}
}
}
@Override
public FileStorageType getStorageType() {
return FileStorageType.SFTP;
}
@Override
public void operate(MultipartFile multipartFile, String createSubPath, String createFilename) throws IOException {
if (multipartFile == null || multipartFile.isEmpty()) {
throw new RuntimeException("Failed to store empty file.");
}
// 로컬 임시 파일 저장
Path tmpFile = Paths.get(tmpPath, createFilename);
Files.createDirectories(tmpFile.getParent());
try (InputStream inputStream = multipartFile.getInputStream()) {
Files.copy(inputStream, tmpFile, StandardCopyOption.REPLACE_EXISTING);
}
// 파일 내용 암호화
Path encryptedFile = Paths.get(tmpPath, "encrypted_" + createFilename);
try {
// 파일 읽기
byte[] fileContent = Files.readAllBytes(tmpFile);
// 암호화
byte[] encryptedContent = encryptUtil.encryptAesCbc(fileContent);
// 암호화된 내용을 임시 파일로 저장
Files.write(encryptedFile, encryptedContent);
} catch (Exception e) {
log.error("Failed to encrypt file: {}", createFilename, e);
throw new IOException("Failed to encrypt file", e);
}
String remotePath = CommonUtil.removeLastChar(publicPath, "/") + createSubPath;
String remoteFilePath = remotePath + "/" + "encrypted_" + createFilename;
try {
// 연결 상태 확인 및 재연결
if (!sftpConnector.isConnected()) {
log.warn("SFTP connection lost, attempting to reconnect");
sftpConnector.connect();
}
createRemoteDirectories(remotePath);
ChannelSftp channelSftp = sftpConnector.getChannelSftp();
if (channelSftp == null) {
throw new SftpException(ChannelSftp.SSH_FX_NO_CONNECTION, "SFTP channel is not initialized");
}
// 암호화된 파일 업로드
try (InputStream encryptedInputStream = Files.newInputStream(encryptedFile)) {
channelSftp.put(encryptedInputStream, remoteFilePath);
channelSftp.chmod(0644, remoteFilePath); // 권한 변경 (0777 -> 0644로 보안 강화)
log.info("Encrypted file uploaded to SFTP: {}", remoteFilePath);
}
} catch (SftpException | JSchException e) {
throw new RuntimeException("Failed to upload encrypted file to SFTP", e);
} finally {
// 임시 파일 삭제
Files.deleteIfExists(tmpFile);
Files.deleteIfExists(encryptedFile);
}
}
@PreDestroy
public void cleanup() {
sftpConnector.disconnect();
}
}

View File

@@ -0,0 +1,24 @@
package app.module.core.usecase.file.url.strategy;
import app.module.core.config.application.enums.FileStorageType;
import org.springframework.stereotype.Service;
@Service
public class SftpFileUrlStrategy implements FileUrlStrategy {
@Override
public FileStorageType getStorageType() {
return FileStorageType.SFTP;
}
@Override
public String getInlineURL(String subPath, String filename) {
return String.format("/content-disposition/inline%s/%s", subPath, filename);
}
@Override
public String getAttachmentURL(Long fileId) {
return String.format("/api/file/download/%s", fileId);
}
}

View File

@@ -88,7 +88,11 @@
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>