commit 37b00599e99609901ae19c32a715634cc933fb0b Author: NYD Date: Fri Jan 30 11:28:18 2026 +0900 first commit diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..8af972c --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +/gradlew text eol=lf +*.bat text eol=crlf +*.jar binary diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c388efd --- /dev/null +++ b/.gitignore @@ -0,0 +1,69 @@ +# Gradle +.gradle/ +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +# IntelliJ IDEA +.idea/ +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +# Eclipse +.apt_generated +.classpath +.factorypath +.project +.settings/ +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +# NetBeans +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +# VS Code +.vscode/ + +# 환경 변수 파일 +.env +.env.local +.env.*.local +application-local.yml +application-local.yaml + +# 로그 파일 +*.log +logs/ + +# 운영체제 파일 +.DS_Store +.DS_Store? +._* +.Spotlight-V100 +.Trashes +ehthumbs.db +Thumbs.db +desktop.ini + +# 임시 파일 +*.tmp +*.temp +*.swp +*.swo +*~ + +# 아키텍처 문서 디렉터리 (참고용, 커밋 제외) +base_arcitectures_md/ + +# 기타 +HELP.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..dab095c --- /dev/null +++ b/README.md @@ -0,0 +1,982 @@ +# Backend 프로젝트 가이드 + +Spring Boot 3.x 기반 백엔드 프로젝트 개발 가이드입니다. + +--- + +## 목차 + +1. [개발 규칙](#1-개발-규칙) +2. [개발 환경 및 옵션 리스팅](#2-개발-환경-및-옵션-리스팅) +3. [설치 및 동작 방법](#3-설치-및-동작-방법) +4. [아키텍처 & 책임 분리 규칙](#4-아키텍처--책임-분리-규칙) +5. [네이밍 & 패키지 규칙](#5-네이밍--패키지-규칙) +6. [예외 처리 & 에러 응답 규칙](#6-예외-처리--에러-응답-규칙) +7. [로그 & 감사(Audit) 규칙](#7-로그--감사audit-규칙) +8. [설정 관리 규칙](#8-설정-관리-규칙) +9. [보안 관련 추가 규칙](#9-보안-관련-추가-규칙) +10. [테스트 & 검증 규칙](#10-테스트--검증-규칙) +11. [금지 패턴 / 안티 패턴 목록](#11-금지-패턴--안티-패턴-목록) +12. [성능 최적화 가이드](#12-성능-최적화-가이드) +13. [의존성 관리](#13-의존성-관리) +14. [트러블슈팅 가이드](#14-트러블슈팅-가이드) + +--- + +## 1. 개발 규칙 + +### 1.1 시큐어 코딩 규칙 준수 + +- **OWASP Top 10 기반 보안 규칙 준수 필수** +- 모든 입력값은 검증 후 사용 (DTO + `@Valid` 활용) +- SQL Injection 방지: MyBatis `#{}`만 사용, `${}` 절대 금지 +- Path Traversal 방지: `FileUtils.safeResolve()` 사용 필수 +- XSS 방지: 출력 시 HTML 이스케이프 처리 +- 세션 보안: HttpOnly, Secure, SameSite 설정 준수 +- 인가 검증: 모든 민감 기능에 소유권/권한 확인 필수 + +**상세 규칙은 `base_arcitectures_md/SECURE_RULE.md` 참조** + +### 1.2 공통 소스 기능 및 활용 방법 + +#### 공통 유틸리티 (`common/util/`) + +- **`Utils.java`**: Cookie, Crypto, DateTime, Json, Masking + - `Utils.Json.toJson()` / `fromJson()`: JSON 직렬화/역직렬화 + - `Utils.Crypto.sha256()`: SHA-256 해시 + - `Utils.Crypto.randomToken()`: 보안 토큰 생성 + - `Utils.DateTime.nowKst()`: KST 기준 현재 시간 + - `Utils.Masking.maskHeaders()`: 헤더 민감정보 마스킹 + - `Utils.Masking.sanitizeBodyForLog()`: 로그용 본문 마스킹 + +- **`FileUtils.java`**: 파일/경로 보안 처리 + - `FileUtils.safeResolve()`: Path Traversal 방지 경로 해석 + - `FileUtils.sanitizeFilename()`: 파일명 정제 + - `FileUtils.isAllowedExtension()`: 확장자 화이트리스트 검증 + +- **`ServletUtils.java`**: HttpServletRequest 보조 + - `ServletUtils.getClientIp()`: 클라이언트 IP 추출 + - `ServletUtils.getBearerToken()`: Bearer 토큰 추출 + - `ServletUtils.getCookieValue()`: 쿠키 값 추출 + - `ServletUtils.isAjax()` / `isJson()`: 요청 타입 판단 + +#### 공통 응답 (`common/response/`) + +- **`ApiResponse`**: 표준 API 응답 포맷 + ```java + ApiResponse.success(data); // 성공 응답 + ApiResponse.error(apiError); // 에러 응답 + ``` + +- **`PageQuery`**: 페이징 쿼리 파라미터 + - `pageIndex`, `pageSize`, `offset`, `limit` 자동 계산 + - `applyTotalCount()` 호출 후 `totalPages`, `hasNext`, `hasPrevious` 사용 + +- **`PageResult`**: 페이징 결과 래퍼 + - `items`: 실제 데이터 리스트 + - `page`: `PageQuery` 메타데이터 + +#### 공통 예외 (`common/exception/`) + +- **`ErrorCode`**: 표준 에러 코드 enum +- **`BizException`**: 비즈니스 예외 (ErrorCode 기반) +- **`GlobalExceptionHandler`**: 전역 예외 처리 (`@RestControllerAdvice`) + +### 1.3 공통소스 활용해서 서비스 구현하는 규칙 + +1. **Controller**: 요청/응답 변환만 담당 + - DTO 검증 (`@Valid`) + - Service 호출 + - `ApiResponse`로 래핑 + +2. **Service**: 비즈니스 로직 전담 + - 공통 유틸 활용 (`Utils.*`, `FileUtils.*`, `ServletUtils.*`) + - `BizException`으로 비즈니스 예외 처리 + - Mapper 호출 + +3. **Mapper**: 데이터 접근 전담 + - MyBatis XML 또는 `@Mapper` 인터페이스 + - `#{}`만 사용, `${}` 금지 + +4. **DTO**: 요청/응답 데이터 전달 객체 + - `@NotBlank`, `@NotNull`, `@Size` 등 검증 어노테이션 활용 + +### 1.4 공통 소스 수정 규칙 + +- **공통 소스는 불가피한 경우가 아니면 절대 수정 금지** +- **추가(Extension)는 허용**: 새로운 유틸 메서드 추가 가능 +- 수정이 필요한 경우 반드시 팀 리뷰 및 승인 필요 +- 공통 소스 수정 시 모든 도메인에 미치는 영향 검토 필수 + +--- + +## 2. 개발 환경 및 옵션 리스팅 + +### 2.1 필수 환경 + +- **Java**: 17 이상 +- **Gradle**: 8.x 이상 (Wrapper 포함) +- **Spring Boot**: 3.5.10 +- **Database**: MariaDB 10.x 이상 +- **IDE**: IntelliJ IDEA 권장 (또는 Eclipse, VS Code) + +### 2.2 주요 의존성 + +- `spring-boot-starter-web`: 웹 애플리케이션 +- `spring-boot-starter-security`: 인증/인가 +- `spring-boot-starter-validation`: 입력 검증 +- `mybatis-spring-boot-starter:3.0.4`: MyBatis 통합 +- `mariadb-java-client`: MariaDB 드라이버 +- `commons-lang3:3.20.0`: 공통 유틸리티 + +### 2.3 옵션 기능 + +현재 프로젝트는 기본 구조만 제공하며, 다음 기능들은 옵션으로 추가 가능: + +- **Redis**: 세션 저장소 (운영 환경 권장) +- **OAuth2**: 소셜 로그인 +- **스케줄러**: `@Scheduled` 기반 작업 +- **파일 업로드**: `FileUtils` 기반 보안 업로드 + +옵션 활성화는 `application.yml` 및 `build.gradle`에 의존성 추가 후 설정 파일에서 제어. + +--- + +## 3. 설치 및 동작 방법 + +### 3.1 사전 준비 + +1. **Java 17 설치 확인** + ```bash + java -version + ``` + +2. **MariaDB 설치 및 데이터베이스 생성** + ```sql + CREATE DATABASE tscc CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + CREATE USER 'tscc'@'localhost' IDENTIFIED BY 'tscc1234'; + GRANT ALL PRIVILEGES ON tscc.* TO 'tscc'@'localhost'; + FLUSH PRIVILEGES; + ``` + +### 3.2 프로젝트 설정 + +1. **의존성 설치** + ```bash + cd backend + ./gradlew build + ``` + 또는 IDE에서 Gradle Sync 실행 + +2. **환경별 설정 파일 확인** + - `src/main/resources/application.yaml`: 공통 설정 + - `src/main/resources/application-dev.yml`: 개발 환경 + - `src/main/resources/application-prod.yml`: 운영 환경 + +3. **데이터베이스 연결 정보 확인** + - `application-dev.yml`에서 `spring.datasource.*` 확인 + +### 3.3 실행 + +1. **IDE에서 실행** + - `BootstrapApplication.java`를 Run/Debug + +2. **Gradle로 실행** + ```bash + ./gradlew bootRun + ``` + +3. **빌드 후 JAR 실행** + ```bash + ./gradlew bootJar + java -jar build/libs/base-0.0.1-SNAPSHOT.jar + ``` + +### 3.4 확인 + +- 서버 시작 후 `http://localhost:8080/api/auth/csrf` 접속하여 CSRF 토큰 확인 +- 로그에서 "Started BootstrapApplication" 메시지 확인 + +--- + +## 4. 아키텍처 & 책임 분리 규칙 + +### 4.1 계층별 책임 명확화 + +#### Controller (`api//controller/`) +- **책임**: HTTP 요청/응답 처리 +- **역할**: + - 요청 파라미터 → DTO 변환 + - DTO 검증 (`@Valid`) + - Service 메서드 호출 + - `ApiResponse`로 응답 래핑 +- **금지**: + - 비즈니스 로직 포함 ❌ + - DB 직접 접근 ❌ + - Mapper 직접 호출 ❌ + +#### Service (`api//service/`) +- **책임**: 비즈니스 로직 처리 +- **역할**: + - 도메인 로직 구현 + - 트랜잭션 관리 (`@Transactional`) + - Mapper 호출 + - 공통 유틸 활용 + - `BizException` 발생 +- **필수**: 모든 비즈니스 로직은 Service에 위치 + +#### Mapper (`api//mapper/`) +- **책임**: 데이터 접근 +- **역할**: + - SQL 쿼리 실행 + - 결과 → 도메인 객체 변환 +- **금지**: + - 비즈니스 로직 포함 ❌ + - `${}` 사용 ❌ + +#### DTO (`api//dto/`) +- **책임**: 계층 간 데이터 전달 +- **구분**: + - Request DTO: Controller 입력 + - Response DTO: Controller 출력 +- **필수**: 검증 어노테이션 (`@NotBlank`, `@NotNull`, `@Size` 등) + +#### Common (`common/`) +- **책임**: 공통 기능 제공 +- **구성**: + - `util/`: 유틸리티 (Utils, FileUtils, ServletUtils) + - `response/`: 공통 응답 포맷 + - `exception/`: 공통 예외 처리 + - `config/`: 공통 설정 + - `validation/`: 공통 검증 로직 + +### 4.2 비즈니스 로직 위치 규칙 + +| 위치 | 비즈니스 로직 허용 여부 | +|------|----------------------| +| Controller | ❌ 금지 | +| Service | ⭕ 필수 | +| Mapper | ❌ 금지 | +| Util | ❌ 금지 | +| Common | ❌ 금지 (공통 기능만) | + +**예시**: +```java +// ❌ 잘못된 예: Controller에 비즈니스 로직 +@PostMapping("/users") +public ApiResponse createUser(@RequestBody UserRequest req) { + if (req.getEmail().contains("@admin.com")) { + throw new RuntimeException("Admin email not allowed"); + } + // ... +} + +// ⭕ 올바른 예: Service에 비즈니스 로직 +@Service +public class UserService { + public User createUser(UserRequest req) { + if (req.getEmail().contains("@admin.com")) { + throw new BizException(ErrorCode.INVALID_REQUEST, "Admin email not allowed"); + } + // ... + } +} +``` + +### 4.3 공통 모듈과 도메인 모듈의 경계 규칙 + +- **공통 모듈 (`common/`)**: 모든 도메인에서 공통으로 사용하는 기능 + - 도메인 특화 로직 포함 금지 + - 도메인별 분기 처리 최소화 + +- **도메인 모듈 (`api//`)**: 특정 도메인 전용 기능 + - 다른 도메인에서 직접 참조 금지 + - 도메인 간 통신은 Service → Service 호출 + +### 4.4 "이 로직은 어디에 두어야 하는가" 판단 기준 + +1. **입력 검증**: Controller (DTO + `@Valid`) +2. **비즈니스 규칙**: Service +3. **데이터 조회/저장**: Mapper +4. **공통 변환/포맷팅**: Common Util +5. **보안 처리**: Common Util (FileUtils, ServletUtils) +6. **예외 변환**: GlobalExceptionHandler + +--- + +## 5. 네이밍 & 패키지 규칙 + +### 5.1 패키지 네이밍 규칙 + +- **기본 패키지**: `kr.tscc.base` +- **도메인 패키지**: `kr.tscc.base.api.` + - 예: `kr.tscc.base.api.auth` + - 예: `kr.tscc.base.api.user` + - 예: `kr.tscc.base.api.document` + +- **계층별 서브패키지**: + - `controller/`: Controller 클래스 + - `service/`: Service 클래스 + - `dto/`: DTO 클래스 + - `mapper/`: Mapper 인터페이스 + +- **공통 패키지**: `kr.tscc.base.common` + - `config/`: 설정 클래스 + - `exception/`: 예외 클래스 + - `response/`: 응답 클래스 + - `util/`: 유틸리티 클래스 + - `validation/`: 검증 클래스 + +### 5.2 클래스 / 메소드 / 변수 네이밍 기준 + +#### 클래스 +- **Controller**: `{Domain}Controller` (예: `AuthController`) +- **Service**: `{Domain}Service` (예: `AuthService`) +- **DTO**: `{Purpose}{Domain}` (예: `LoginRequest`, `MeResponse`) +- **Mapper**: `{Domain}Mapper` (예: `UserMapper`) +- **Util**: `{Purpose}Utils` (예: `FileUtils`, `ServletUtils`) + +#### 메소드 +- **Controller**: HTTP 메서드 기반 (예: `login`, `logout`, `me`) +- **Service**: 비즈니스 동사 (예: `createUser`, `updateUser`, `deleteUser`) +- **Mapper**: CRUD 동사 (예: `findById`, `insert`, `update`, `delete`) + +#### 변수 +- **camelCase** 사용 +- **boolean**: `is`, `has`, `can` 접두사 (예: `isActive`, `hasPermission`) +- **Collection**: 복수형 (예: `users`, `items`) + +### 5.3 약어 사용 허용 / 금지 리스트 + +#### 허용 약어 +- `id`, `url`, `api`, `dto`, `vo`, `dao`, `util`, `config`, `auth`, `admin` + +#### 금지 약어 +- `usr` (→ `user`), `svc` (→ `service`), `ctrl` (→ `controller`) +- `mgr` (→ `manager`), `info` (→ `information`), `num` (→ `number`) + +### 5.4 DB 컬럼 ↔ DTO ↔ VO ↔ API 필드 매핑 규칙 + +#### DB 컬럼 → DTO/VO +- **스네이크 케이스 → 카멜 케이스** (MyBatis `map-underscore-to-camel-case: true` 활용) + - DB: `user_id`, `created_at` + - DTO: `userId`, `createdAt` + +#### DTO → API 응답 +- **카멜 케이스 유지** (JSON 기본) + - DTO: `userId`, `email` + - API: `{"userId": 1, "email": "user@example.com"}` + +#### 예외: API 명세서 요구사항 +- API 명세서에서 스네이크 케이스를 요구하는 경우, DTO에 `@JsonProperty` 사용 + ```java + @JsonProperty("user_id") + private Long userId; + ``` + +--- + +## 6. 예외 처리 & 에러 응답 규칙 + +### 6.1 공통 Exception 구조 + +#### ErrorCode (enum) +```java +public enum ErrorCode { + INVALID_REQUEST("C001", "Invalid request"), + UNAUTHORIZED("C002", "Unauthorized"), + FORBIDDEN("C003", "Forbidden"), + NOT_FOUND("C004", "Resource not found"), + INTERNAL_ERROR("C999", "Internal server error"); +} +``` + +#### BizException +```java +throw new BizException(ErrorCode.INVALID_REQUEST); +throw new BizException(ErrorCode.NOT_FOUND, "User not found: " + userId); +``` + +#### GlobalExceptionHandler +- `@RestControllerAdvice`로 전역 처리 +- `SecurityException` → 403 Forbidden +- `BizException` → 400 Bad Request (ErrorCode 기반) +- `Exception` → 500 Internal Server Error + +### 6.2 비즈니스 예외 vs 시스템 예외 구분 + +| 예외 타입 | 발생 위치 | 처리 방법 | 사용자 메시지 | +|----------|---------|----------|-------------| +| **비즈니스 예외** | Service | `BizException` | 구체적 메시지 | +| **시스템 예외** | 모든 계층 | `GlobalExceptionHandler` | 일반화된 메시지 | + +**예시**: +```java +// 비즈니스 예외: 사용자에게 구체적 메시지 +if (user == null) { + throw new BizException(ErrorCode.NOT_FOUND, "User not found: " + userId); +} + +// 시스템 예외: 일반화된 메시지 (상세는 로그에만) +catch (SQLException e) { + log.error("Database error", e); + throw new BizException(ErrorCode.INTERNAL_ERROR); +} +``` + +### 6.3 API 응답 포맷 통일 규칙 + +모든 API 응답은 `ApiResponse` 형식: + +```json +// 성공 응답 +{ + "success": true, + "data": { ... }, + "error": null +} + +// 에러 응답 +{ + "success": false, + "data": null, + "error": { + "code": "C001", + "message": "Invalid request" + } +} +``` + +**Controller 예시**: +```java +@PostMapping("/login") +public ApiResponse login(@Valid @RequestBody LoginRequest request) { + authService.login(request); + SessionUser user = (SessionUser) authService.me(); + return ApiResponse.success(new MeResponse(user.getUserId(), user.getEmail(), user.getDisplayName())); +} +``` + +### 6.4 로그 기록 기준과 사용자 노출 메시지 분리 규칙 + +- **로그**: 상세 정보 (스택 트레이스, 파라미터, 내부 상태) +- **사용자 메시지**: 일반화된 메시지 (민감 정보 제외) + +**예시**: +```java +// ❌ 잘못된 예: 사용자에게 상세 정보 노출 +catch (SQLException e) { + return ApiResponse.error(new ApiError("DB_ERROR", e.getMessage())); +} + +// ⭕ 올바른 예: 로그에는 상세, 사용자에게는 일반화 +catch (SQLException e) { + log.error("Database error: userId={}, operation={}", userId, operation, e); + return ApiResponse.error(new ApiError(ErrorCode.INTERNAL_ERROR.code(), ErrorCode.INTERNAL_ERROR.message())); +} +``` + +--- + +## 7. 로그 & 감사(Audit) 규칙 + +### 7.1 로그 레벨 사용 기준 + +| 레벨 | 사용 시기 | 예시 | +|------|---------|------| +| **DEBUG** | 개발 중 상세 디버깅 | 파라미터 값, 중간 상태 | +| **INFO** | 정상 흐름의 중요 이벤트 | 로그인 성공, 주요 비즈니스 작업 완료 | +| **WARN** | 예상 가능한 문제 | 잘못된 입력, 재시도 필요 | +| **ERROR** | 예상치 못한 오류 | 예외 발생, 시스템 오류 | + +**예시**: +```java +log.debug("Processing user request: userId={}, params={}", userId, params); +log.info("User logged in: userId={}", userId); +log.warn("Invalid input: field={}, value={}", field, value); +log.error("Failed to process request: userId={}", userId, exception); +``` + +### 7.2 개인정보 및 민감정보 마스킹 규칙 + +**마스킹 대상**: +- 비밀번호, 토큰, 세션 ID +- 주민번호, 카드번호, 계좌번호 +- 이메일 (일부 마스킹 가능) +- 전화번호 (일부 마스킹 가능) + +**마스킹 방법**: +- `Utils.Masking.maskHeaders()`: HTTP 헤더 마스킹 +- `Utils.Masking.sanitizeBodyForLog()`: 요청/응답 본문 마스킹 + +**예시**: +```java +// ❌ 잘못된 예: 민감정보 로그 출력 +log.info("User login: email={}, password={}", email, password); + +// ⭕ 올바른 예: 마스킹 후 로그 출력 +log.info("User login: email={}", Utils.Masking.maskEmail(email)); +``` + +### 7.3 공통 로깅 유틸 사용 규칙 + +- **RequestResponseLoggingFilter**: 모든 HTTP 요청/응답 자동 로깅 + - 민감 정보 자동 마스킹 + - `/health`, `/actuator` 제외 + +- **수동 로깅**: `logback-spring.xml` 설정 확인 + - 패키지별 로그 레벨 설정 + - 파일/콘솔 출력 설정 + +### 7.4 요청 추적용 식별자(Request ID 등) 사용 여부 + +현재는 기본 구조만 제공. 필요 시 다음 추가 가능: +- `MDC` (Mapped Diagnostic Context) 활용 +- `RequestResponseLoggingFilter`에서 Request ID 생성/추가 +- 로그에 Request ID 포함 + +--- + +## 8. 설정 관리 규칙 + +### 8.1 application.yml 분리 전략 + +- **`application.yaml`**: 공통 설정 (MyBatis, 로깅 등) +- **`application-dev.yml`**: 개발 환경 (데이터베이스, 로그 레벨 등) +- **`application-prod.yml`**: 운영 환경 (데이터베이스, 보안 설정 등) + +**활성 프로파일 설정**: +```yaml +# application.yaml +spring: + profiles: + active: dev # 또는 prod +``` + +### 8.2 환경별(dev / stage / prod) 설정 원칙 + +- **공통 설정**: `application.yaml` +- **환경별 설정**: `application-{profile}.yml` +- **민감 정보**: 환경 변수 또는 Secret Manager 사용 +- **데이터베이스**: 환경별 별도 인스턴스 + +### 8.3 옵션 처리 기준 (enable / disable 방식) + +옵션 기능은 다음 방식으로 제어: + +1. **의존성 추가/제거**: `build.gradle` +2. **설정 파일에서 활성화/비활성화**: `application-{profile}.yml` + ```yaml + feature: + redis: + enabled: true + oauth2: + enabled: false + ``` + +3. **조건부 Bean 생성**: `@ConditionalOnProperty` 활용 + ```java + @ConditionalOnProperty(name = "feature.redis.enabled", havingValue = "true") + @Bean + public RedisTemplate redisTemplate() { + // ... + } + ``` + +### 8.4 Redis, 외부 시스템 사용 여부를 옵션으로 제어하는 규칙 + +- **Redis**: 세션 저장소 옵션 + - 활성화: `spring.session.store-type=redis` + - 비활성화: 기본 인메모리 세션 + +- **외부 API**: 설정 파일에서 URL/키 관리 + - 개발: Mock 서버 또는 테스트 환경 + - 운영: 실제 외부 API + +--- + +## 9. 보안 관련 추가 규칙 (시큐어 코딩 보강) + +### 9.1 인증 / 인가 흐름 준수 규칙 + +#### 인증 (Authentication) +- **세션 기반 인증** 사용 +- 로그인 성공 시 `SessionUser` 세션 저장 +- `LoginUserPrincipal`로 Spring Security 통합 + +#### 인가 (Authorization) +- **Deny-by-default**: 명시적 허용만 접근 가능 +- **소유권 검증**: 리소스 접근 시 사용자 ID 확인 +- **RBAC**: 역할 기반 접근 제어 (`UserRoles` enum 활용) + +**예시**: +```java +// ❌ 잘못된 예: 소유권 검증 없음 +@GetMapping("/documents/{id}") +public ApiResponse getDocument(@PathVariable Long id) { + return ApiResponse.success(documentMapper.findById(id)); +} + +// ⭕ 올바른 예: 소유권 검증 포함 +@GetMapping("/documents/{id}") +public ApiResponse getDocument(@PathVariable Long id) { + Document doc = documentMapper.findById(id); + SessionUser user = getCurrentUser(); + if (!doc.getUserId().equals(user.getUserId())) { + throw new BizException(ErrorCode.FORBIDDEN); + } + return ApiResponse.success(doc); +} +``` + +### 9.2 세션 / 토큰 사용 시 주의 사항 + +- **세션 쿠키 보안 옵션**: + - `HttpOnly`: true (XSS 방지) + - `Secure`: true (HTTPS 전용, 운영 환경) + - `SameSite`: Strict 또는 Lax (CSRF 방지) + +- **세션 고정 공격 방지**: 로그인 시 세션 재발급 (`sessionFixation().migrateSession()`) + +- **세션 타임아웃**: 적절한 시간 설정 (기본 30분) + +### 9.3 파일 업로드 / 다운로드 처리 규칙 + +#### 업로드 +1. **확장자 화이트리스트**: `FileUtils.isAllowedExtension()` 사용 +2. **MIME 타입 검증**: Content-Type 확인 +3. **파일 크기 제한**: 설정 파일에서 제한 +4. **파일명 정제**: `FileUtils.sanitizeFilename()` 사용 +5. **저장 경로 검증**: `FileUtils.safeResolve()` 사용 +6. **웹루트 밖 저장**: 실행 파일 접근 방지 +7. **UUID 파일명**: 원본 파일명 노출 방지 + +#### 다운로드 +1. **Path Traversal 방지**: `FileUtils.safeResolve()` 사용 +2. **소유권 검증**: 파일 접근 권한 확인 +3. **Content-Disposition**: 안전한 파일명 설정 + +### 9.4 외부 API 연동 시 보안 체크리스트 + +- [ ] API 키/토큰 환경 변수 관리 (하드코딩 금지) +- [ ] HTTPS만 사용 (HTTP 금지) +- [ ] 타임아웃 설정 (무한 대기 방지) +- [ ] 입력값 검증 (외부 API로 전송 전) +- [ ] 응답 검증 (예상 형식 확인) +- [ ] 재시도 정책 (Rate Limiting 고려) +- [ ] 로깅 (민감 정보 제외) + +--- + +## 10. 테스트 & 검증 규칙 + +### 10.1 단위 테스트 작성 기준 (필수 / 선택 구분) + +#### 필수 테스트 +- **Service 비즈니스 로직**: 핵심 비즈니스 규칙 검증 +- **Util 보안 기능**: FileUtils, ServletUtils 등 + +#### 선택 테스트 +- **Controller**: 통합 테스트로 대체 가능 +- **Mapper**: 실제 DB 연동 테스트 (로컬 환경) + +**예시**: +```java +@SpringBootTest +class AuthServiceTest { + @Autowired + private AuthService authService; + + @Test + void testLoginSuccess() { + // Given + LoginRequest request = new LoginRequest(); + request.setEmail("user@example.com"); + request.setPassword("password123"); + + // When & Then + assertDoesNotThrow(() -> authService.login(request)); + } +} +``` + +### 10.2 테스트용 데이터 작성 규칙 + +- **테스트 전용 데이터**: `@Sql` 또는 `@TestPropertySource` 활용 +- **격리**: 각 테스트는 독립적으로 실행 가능해야 함 +- **정리**: `@AfterEach` 또는 `@Sql(scripts = "cleanup.sql", executionPhase = AFTER_TEST_METHOD)` + +### 10.3 로컬 테스트 → 통합 테스트 흐름 + +1. **로컬 단위 테스트**: Service, Util 등 +2. **로컬 통합 테스트**: Controller + Service + Mapper (로컬 DB) +3. **통합 테스트 환경**: 실제 테스트 서버 (선택) + +### 10.4 테스트 미수행 시 병합 제한 여부 + +- 현재는 권고 사항 (필수 아님) +- 향후 CI/CD 파이프라인에서 테스트 실패 시 병합 차단 가능 + +--- + +## 11. 금지 패턴 / 안티 패턴 목록 + +### 11.1 공통 Util에 비즈니스 로직 포함 ❌ + +```java +// ❌ 잘못된 예 +public class Utils { + public static boolean isAdminUser(String email) { + return email.contains("@admin.com"); + } +} + +// ⭕ 올바른 예: Service에 비즈니스 로직 +@Service +public class UserService { + public boolean isAdminUser(String email) { + return email.contains("@admin.com"); + } +} +``` + +### 11.2 Controller에서 DB 직접 접근 ❌ + +```java +// ❌ 잘못된 예 +@RestController +public class UserController { + @Autowired + private UserMapper userMapper; + + @GetMapping("/users/{id}") + public User getUser(@PathVariable Long id) { + return userMapper.findById(id); + } +} + +// ⭕ 올바른 예: Service를 통한 접근 +@RestController +public class UserController { + @Autowired + private UserService userService; + + @GetMapping("/users/{id}") + public ApiResponse getUser(@PathVariable Long id) { + return ApiResponse.success(userService.findById(id)); + } +} +``` + +### 11.3 옵션 무시 후 하드코딩 ❌ + +```java +// ❌ 잘못된 예 +@Value("${feature.redis.enabled:false}") +private boolean redisEnabled; + +public void someMethod() { + // 옵션 무시하고 하드코딩 + RedisTemplate redis = new RedisTemplate<>(); + // ... +} + +// ⭕ 올바른 예: 옵션 확인 +@ConditionalOnProperty(name = "feature.redis.enabled", havingValue = "true") +@Bean +public RedisTemplate redisTemplate() { + // ... +} +``` + +### 11.4 공통 코드 복사 후 개별 서비스에 포함 ❌ + +```java +// ❌ 잘못된 예: 공통 코드를 각 Service에 복사 +@Service +public class UserService { + private String maskEmail(String email) { + // 마스킹 로직 복사 + } +} + +@Service +public class DocumentService { + private String maskEmail(String email) { + // 동일한 마스킹 로직 복사 + } +} + +// ⭕ 올바른 예: 공통 Util 사용 +public class UserService { + public void someMethod() { + String masked = Utils.Masking.maskEmail(email); + } +} +``` + +### 11.5 MyBatis `${}` 사용 ❌ + +```xml + + + + + +``` + +### 11.6 민감 정보 로그 출력 ❌ + +```java +// ❌ 잘못된 예 +log.info("User login: email={}, password={}", email, password); + +// ⭕ 올바른 예: 마스킹 또는 제외 +log.info("User login: email={}", Utils.Masking.maskEmail(email)); +``` + +### 11.7 예외 삼키기 (Empty Catch) ❌ + +```java +// ❌ 잘못된 예 +try { + someMethod(); +} catch (Exception e) { + // 아무 처리 없음 +} + +// ⭕ 올바른 예: 로깅 또는 재throw +try { + someMethod(); +} catch (Exception e) { + log.error("Error occurred", e); + throw new BizException(ErrorCode.INTERNAL_ERROR); +} +``` + +--- + +## 12. 성능 최적화 가이드 + +### 12.1 데이터베이스 최적화 + +#### 쿼리 최적화 +- **인덱스 활용**: 자주 조회되는 컬럼에 인덱스 생성 +- **N+1 문제 방지**: JOIN 또는 `@BatchSize` 활용 +- **페이징 필수**: 대량 데이터 조회 시 `PageQuery` 사용 + +**예시**: +```java +// ❌ 잘못된 예: N+1 문제 +List users = userMapper.findAll(); +for (User user : users) { + List docs = documentMapper.findByUserId(user.getId()); // N번 쿼리 +} + +// ⭕ 올바른 예: JOIN 또는 배치 조회 +List users = userMapper.findAllWithDocuments(); // 1번 쿼리 +``` + +### 12.2 애플리케이션 최적화 + +#### 트랜잭션 최소화 +- **필요한 범위만 트랜잭션**: `@Transactional` 범위 최소화 +- **읽기 전용 트랜잭션**: 조회만 하는 경우 `readOnly = true` + +#### 로깅 최적화 +- **로그 레벨 조정**: 운영 환경에서는 INFO 이상만 +- **과도한 로깅 방지**: 반복적인 로그는 제한 + +--- + +## 13. 의존성 관리 + +### 13.1 버전 관리 원칙 + +- **명시적 버전 지정**: `build.gradle`에 버전 명시 +- **보안 패치 우선**: 취약점 발견 시 즉시 업데이트 +- **마이너 버전 업데이트**: 정기적으로 검토 및 업데이트 + +### 13.2 보안 취약점 점검 + +**정기 점검**: +```bash +./gradlew dependencyCheckAnalyze +``` + +**수동 점검**: +- [OWASP Dependency-Check](https://owasp.org/www-project-dependency-check/) 활용 +- GitHub Dependabot 설정 권장 + +### 13.3 업데이트 프로세스 + +1. **의존성 업데이트**: `build.gradle` 수정 +2. **로컬 테스트**: 업데이트 후 빌드 및 테스트 +3. **통합 테스트**: 개발 환경에서 검증 +4. **운영 배포**: 검증 완료 후 배포 + +--- + +## 14. 트러블슈팅 가이드 + +### 14.1 자주 발생하는 문제 + +#### 문제 1: MyBatis 매퍼 파일을 찾을 수 없음 +**증상**: `Could not find resource mapper/**/*.xml` + +**해결**: +1. `application.yaml`에서 `mybatis.mapper-locations` 확인 +2. `src/main/resources/mapper/` 디렉터리 구조 확인 +3. 빌드 후 `build/resources/main/mapper/`에 파일 존재 확인 + +#### 문제 2: 세션이 유지되지 않음 +**증상**: 로그인 후 요청 시 401 Unauthorized + +**해결**: +1. `withCredentials: true` 설정 확인 (프론트엔드) +2. CORS 설정에서 `allowCredentials: true` 확인 (백엔드) +3. 쿠키 도메인/경로 설정 확인 + +#### 문제 3: CSRF 토큰 오류 +**증상**: `403 Forbidden` (CSRF 토큰 불일치) + +**해결**: +1. `CookieCsrfTokenRepository.withHttpOnlyFalse()` 설정 확인 +2. 프론트엔드에서 `XSRF-TOKEN` 쿠키 읽기 확인 +3. 요청 헤더에 `X-XSRF-TOKEN` 포함 확인 + +### 14.2 디버깅 팁 + +#### 로그 레벨 조정 +```yaml +# application-dev.yml +logging: + level: + kr.tscc.base: DEBUG + org.springframework.web: DEBUG + org.mybatis: DEBUG +``` + +#### SQL 로깅 +```yaml +# application-dev.yml +mybatis: + configuration: + log-impl: org.apache.ibatis.logging.stdout.StdOutImpl +``` + +--- + +## 참고 문서 + +- **아키텍처 문서**: `base_arcitectures_md/BACK_ARCHITECTURE_V1.md` +- **보안 규칙**: `base_arcitectures_md/BACKEND_SECURE_RULE.md` +- **공통 보안 규칙**: `../SECURE_RULE.md` + +--- + +**마지막 업데이트**: 2024년 diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..a0ddc9c --- /dev/null +++ b/build.gradle @@ -0,0 +1,48 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.5.10' + id 'io.spring.dependency-management' version '1.1.7' +} + +group = 'kr.tscc' +version = '0.0.1-SNAPSHOT' +description = 'TSCC_BASE' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } +} + +repositories { + mavenCentral() +} + +dependencies { + // Spring Boot Web + implementation 'org.springframework.boot:spring-boot-starter-web' + + // Spring Security + implementation 'org.springframework.boot:spring-boot-starter-security' + + // Validation + implementation 'org.springframework.boot:spring-boot-starter-validation' + + // MyBatis + implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:3.0.4' + + // MariaDB Driver + runtimeOnly 'org.mariadb.jdbc:mariadb-java-client' + + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' + + // Commons Lang: 최신 라인(보안/취약점 표기 기준 최신 사용) + implementation 'org.apache.commons:commons-lang3:3.20.0' // :contentReference[oaicite:3]{index=3} +} + +// 의존성 설치: ./gradlew build (또는 IDE에서 Gradle Sync) + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..1b33c55 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..aaaabb3 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.4-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..23d15a9 --- /dev/null +++ b/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed 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 +# +# https://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. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..db3a6ac --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..01f3436 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'base' diff --git a/src/main/java/kr/tscc/base/BootstrapApplication.java b/src/main/java/kr/tscc/base/BootstrapApplication.java new file mode 100644 index 0000000..0c31f02 --- /dev/null +++ b/src/main/java/kr/tscc/base/BootstrapApplication.java @@ -0,0 +1,13 @@ +package kr.tscc.base; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class BootstrapApplication { + + public static void main(String[] args) { + SpringApplication.run(BootstrapApplication.class, args); + } + +} diff --git a/src/main/java/kr/tscc/base/api/auth/controller/AuthController.java b/src/main/java/kr/tscc/base/api/auth/controller/AuthController.java new file mode 100644 index 0000000..e6a88d5 --- /dev/null +++ b/src/main/java/kr/tscc/base/api/auth/controller/AuthController.java @@ -0,0 +1,87 @@ +package kr.tscc.base.api.auth.controller; + +import jakarta.validation.Valid; +import kr.tscc.base.api.auth.dto.LoginRequest; +import kr.tscc.base.api.auth.dto.MeResponse; +import kr.tscc.base.api.auth.service.AuthService; +import kr.tscc.base.common.exception.ErrorCode; +import kr.tscc.base.common.response.ApiError; +import kr.tscc.base.common.response.ApiResponse; +import org.springframework.web.bind.annotation.*; + +/** + * 인증 컨트롤러 + * + * 책임: + * - HTTP 요청/응답 처리 + * - 세션 직접 제어 금지 + * - 인증 처리 위임만 수행 + * + * 금지 사항: + * - 비즈니스 로직 포함 + * - Service 호출만 수행 + * - 인증/세션 직접 접근 금지 + */ +@RestController +@RequestMapping("/api/auth") +public class AuthController { + + private final AuthService authService; + + public AuthController(AuthService authService) { + this.authService = authService; + } + + /** + * CSRF 쿠키 발급 + * 목적: CSRF 쿠키 발급, 세션 초기화 트리거 + * 특징: 인증 불필요, 응답 body 없음, Cookie만 내려줌 + */ + @GetMapping("/csrf") + public ApiResponse csrf() { + return ApiResponse.success(); + } + + /** + * 로그인 + * 목적: 사용자 인증, 세션 생성 + * 동작: 인증 성공 시 HttpSession 생성, JSESSIONID 쿠키 발급, CSRF 토큰 재발급 + */ + @PostMapping("/login") + public ApiResponse login(@Valid @RequestBody LoginRequest request) { + authService.login(request); + return ApiResponse.success(); + } + + /** + * 로그아웃 + * 목적: 세션 종료 + * 동작: HttpSession invalidate, 쿠키 만료 + */ + @PostMapping("/logout") + public ApiResponse logout() { + authService.logout(); + return ApiResponse.success(); + } + + /** + * 내 인증 정보 조회 + * + * 보안 규칙: + * - 인증되지 않은 사용자는 401 응답 + * - null 체크 필수 (인증 실패 시 null 반환 가능) + */ + @GetMapping("/me") + public ApiResponse me() { + MeResponse me = authService.me(); + if (me == null) { + return ApiResponse.errorWithType( + new ApiError( + ErrorCode.UNAUTHORIZED.code(), + ErrorCode.UNAUTHORIZED.message() + ) + ); + } + return ApiResponse.success(me); + } +} diff --git a/src/main/java/kr/tscc/base/api/auth/dto/LoginRequest.java b/src/main/java/kr/tscc/base/api/auth/dto/LoginRequest.java new file mode 100644 index 0000000..15ef30a --- /dev/null +++ b/src/main/java/kr/tscc/base/api/auth/dto/LoginRequest.java @@ -0,0 +1,39 @@ +package kr.tscc.base.api.auth.dto; + +import jakarta.validation.constraints.NotBlank; + +/** + * 로그인 요청 DTO + * + * 역할: + * - 로그인 요청 입력 모델 + * - Validation은 DTO에서 수행 + * + * 보안 규칙: + * - @Valid 필수 + * - NotBlank 검증 + */ +public class LoginRequest { + + @NotBlank(message = "Username is required") + private String username; + + @NotBlank(message = "Password is required") + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } +} diff --git a/src/main/java/kr/tscc/base/api/auth/dto/MeResponse.java b/src/main/java/kr/tscc/base/api/auth/dto/MeResponse.java new file mode 100644 index 0000000..1ba0880 --- /dev/null +++ b/src/main/java/kr/tscc/base/api/auth/dto/MeResponse.java @@ -0,0 +1,39 @@ +package kr.tscc.base.api.auth.dto; + +/** + * 현재 사용자 정보 응답 DTO + * + * 보안 규칙: + * - password, token 등 민감정보 절대 포함 금지 + * - 최소 정보만 반환 + */ +public class MeResponse { + + private final Long userId; + private final String email; + private final String displayName; + private final String role; + + public MeResponse(Long userId, String email, String displayName, String role) { + this.userId = userId; + this.email = email; + this.displayName = displayName; + this.role = role; + } + + public Long getUserId() { + return userId; + } + + public String getEmail() { + return email; + } + + public String getDisplayName() { + return displayName; + } + + public String getRole() { + return role; + } +} diff --git a/src/main/java/kr/tscc/base/api/auth/service/AuthService.java b/src/main/java/kr/tscc/base/api/auth/service/AuthService.java new file mode 100644 index 0000000..389fafc --- /dev/null +++ b/src/main/java/kr/tscc/base/api/auth/service/AuthService.java @@ -0,0 +1,74 @@ +package kr.tscc.base.api.auth.service; + +import kr.tscc.base.api.auth.dto.LoginRequest; +import kr.tscc.base.api.auth.dto.MeResponse; +import kr.tscc.base.security.principal.LoginUserPrincipal; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Service; + +/** + * 인증 서비스 + * + * 책임: + * - Spring Security 인증 처리 위임 + * - 인증 성공 시 세션 생성 + * - 인증 실패 시 예외 처리 + * + * 금지 사항: + * - 사용자 상세 비즈니스 로직 처리 + * - 권한 판단 로직 포함 + * - 사용자 관리(User 도메인 영역 침범) + */ +@Service +public class AuthService { + + private final AuthenticationManager authenticationManager; + + public AuthService(AuthenticationManager authenticationManager) { + this.authenticationManager = authenticationManager; + } + + /** + * 로그인 처리 + */ + public void login(LoginRequest request) { + UsernamePasswordAuthenticationToken token = + new UsernamePasswordAuthenticationToken( + request.getUsername(), + request.getPassword() + ); + + Authentication auth = authenticationManager.authenticate(token); + SecurityContextHolder.getContext().setAuthentication(auth); + } + + /** + * 로그아웃 처리 + */ + public void logout() { + SecurityContextHolder.clearContext(); + } + + /** + * 현재 사용자 정보 조회 + */ + public MeResponse me() { + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + if (auth == null || !(auth.getPrincipal() instanceof LoginUserPrincipal)) { + return null; + } + + LoginUserPrincipal principal = (LoginUserPrincipal) auth.getPrincipal(); + var sessionUser = principal.getSessionUser(); + + return new MeResponse( + sessionUser.getUserId(), + sessionUser.getEmail(), + sessionUser.getDisplayName(), + sessionUser.getRole() + ); + } +} diff --git a/src/main/java/kr/tscc/base/common/config/RequestResponseLoggingFilter.java b/src/main/java/kr/tscc/base/common/config/RequestResponseLoggingFilter.java new file mode 100644 index 0000000..144a658 --- /dev/null +++ b/src/main/java/kr/tscc/base/common/config/RequestResponseLoggingFilter.java @@ -0,0 +1,155 @@ +package kr.tscc.base.common.config; + +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import kr.tscc.base.common.util.Utils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; +import org.springframework.web.util.ContentCachingRequestWrapper; +import org.springframework.web.util.ContentCachingResponseWrapper; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Enumeration; +import java.util.LinkedHashMap; +import java.util.Locale; +import java.util.Map; + +/** + * 요청/응답 로깅 필터 + * + * 설계 목적: + * - 요청/응답 로깅 중앙화 + * - 민감정보 마스킹 강제 (시큐어 코딩 규칙) + * - 로그 포맷 통일 + * + * 보안 규칙: + * - password/token/sessionId 로그 금지 + * - Authorization/Cookie 전체 로그 금지 + * - 요청/응답 raw dump 금지 + * - 민감정보는 Utils.Masking으로 마스킹 + */ +@Component +public class RequestResponseLoggingFilter extends OncePerRequestFilter { + + private static final Logger log = LoggerFactory.getLogger(RequestResponseLoggingFilter.class); + private final ObjectMapper objectMapper; + + public RequestResponseLoggingFilter(ObjectMapper objectMapper) { + this.objectMapper = objectMapper; + } + + @Override + protected boolean shouldNotFilter(HttpServletRequest request) { + String uri = request.getRequestURI(); + // health check, actuator는 로깅 제외 + return uri.startsWith("/health") || uri.startsWith("/actuator"); + } + + @Override + protected void doFilterInternal( + HttpServletRequest request, + HttpServletResponse response, + FilterChain filterChain + ) throws ServletException, IOException { + + ContentCachingRequestWrapper req = new ContentCachingRequestWrapper(request); + ContentCachingResponseWrapper res = new ContentCachingResponseWrapper(response); + + long start = System.currentTimeMillis(); + try { + filterChain.doFilter(req, res); + } finally { + long tookMs = System.currentTimeMillis() - start; + + // 헤더 수집 + Map headers = new LinkedHashMap<>(); + Enumeration names = req.getHeaderNames(); + while (names.hasMoreElements()) { + String n = names.nextElement(); + headers.put(n, req.getHeader(n)); + } + + // 헤더 마스킹 (민감정보 제거) + Map safeHeaders = Utils.Masking.maskHeaders(headers); + + // Body 읽기 + String reqBody = readBody(req.getContentAsByteArray(), req.getContentType()); + String resBody = readBody(res.getContentAsByteArray(), res.getContentType()); + + // 로깅 (민감정보 마스킹) + log.info("[HTTP] {} {} ({}ms) status={} headers={} reqBody={} resBody={}", + req.getMethod(), + req.getRequestURI(), + tookMs, + res.getStatus(), + safeHeaders, + sanitizeBodyForLog(reqBody), + sanitizeBodyForLog(resBody) + ); + + res.copyBodyToResponse(); + } + } + + /** + * Body 읽기 (JSON만 처리) + */ + private String readBody(byte[] bytes, String contentType) { + if (bytes == null || bytes.length == 0) return ""; + if (contentType == null) return "[non-json]"; + if (!contentType.contains(MediaType.APPLICATION_JSON_VALUE)) { + return "[non-json]"; + } + return new String(bytes, StandardCharsets.UTF_8); + } + + /** + * Body 마스킹 처리 + * - JSON 파싱 후 깊은 마스킹 + * - 파싱 실패 시 키워드 기반 마스킹 + */ + private String sanitizeBodyForLog(String json) { + if (json == null || json.isEmpty()) return json; + + try { + // JSON 파싱 후 깊은 마스킹 + Object parsed = objectMapper.readValue(json, Object.class); + Object masked = Utils.Masking.maskDeep(parsed); + String maskedJson = objectMapper.writeValueAsString(masked); + // 너무 긴 경우 truncate + return Utils.Masking.truncateForLog(maskedJson, 1000); + } catch (Exception e) { + // 파싱 실패 시 키워드 기반 마스킹 + String lower = json.toLowerCase(Locale.ROOT); + if (containsSensitiveKeyword(lower)) { + return "[masked]"; + } + // 길이 제한 + return Utils.Masking.truncateForLog(json, 500); + } + } + + /** + * 민감 키워드 포함 여부 확인 + */ + private boolean containsSensitiveKeyword(String text) { + String[] keywords = { + "password", "passwd", "pwd", + "token", "accesstoken", "refreshtoken", + "authorization", "cookie", "session", "sessionid" + }; + for (String keyword : keywords) { + if (text.contains(keyword)) { + return true; + } + } + return false; + } +} diff --git a/src/main/java/kr/tscc/base/common/config/WebMvcConfig.java b/src/main/java/kr/tscc/base/common/config/WebMvcConfig.java new file mode 100644 index 0000000..a34f4c9 --- /dev/null +++ b/src/main/java/kr/tscc/base/common/config/WebMvcConfig.java @@ -0,0 +1,36 @@ +package kr.tscc.base.common.config; + +import com.fasterxml.jackson.databind.ObjectMapper; +import kr.tscc.base.common.util.Utils; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +/** + * Web MVC 설정 + * + * - CORS 설정 + * - Jackson ObjectMapper 초기화 (Utils.Json 사용) + */ +@Configuration +public class WebMvcConfig implements WebMvcConfigurer { + + private final ObjectMapper objectMapper; + + public WebMvcConfig(Jackson2ObjectMapperBuilder builder) { + this.objectMapper = builder.build(); + // Utils.Json 초기화 + Utils.Json.init(objectMapper); + } + + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/api/**") + .allowedOrigins("http://localhost:5173", "http://localhost:3000") // 개발 환경 + .allowedMethods("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS") + .allowedHeaders("*") + .allowCredentials(true) + .maxAge(3600); + } +} diff --git a/src/main/java/kr/tscc/base/common/exception/BizException.java b/src/main/java/kr/tscc/base/common/exception/BizException.java new file mode 100644 index 0000000..df85737 --- /dev/null +++ b/src/main/java/kr/tscc/base/common/exception/BizException.java @@ -0,0 +1,25 @@ +package kr.tscc.base.common.exception; + +/** + * 비즈니스 예외 + * + * 비즈니스 로직에서 발생하는 예외를 명시적으로 처리하기 위한 예외 클래스 + */ +public class BizException extends RuntimeException { + + private final ErrorCode errorCode; + + public BizException(ErrorCode errorCode) { + super(errorCode.message()); + this.errorCode = errorCode; + } + + public BizException(ErrorCode errorCode, String message) { + super(message); + this.errorCode = errorCode; + } + + public ErrorCode getErrorCode() { + return errorCode; + } +} diff --git a/src/main/java/kr/tscc/base/common/exception/ErrorCode.java b/src/main/java/kr/tscc/base/common/exception/ErrorCode.java new file mode 100644 index 0000000..ca445b8 --- /dev/null +++ b/src/main/java/kr/tscc/base/common/exception/ErrorCode.java @@ -0,0 +1,34 @@ +package kr.tscc.base.common.exception; + +/** + * 에러 코드 정의 + * + * 설계 목적: + * - 예외를 외부로 그대로 노출하지 않음 + * - 예외 → ErrorCode → ApiError 변환 + * - 컨트롤러별 try/catch 제거 + */ +public enum ErrorCode { + + INVALID_REQUEST("C001", "Invalid request"), + UNAUTHORIZED("C002", "Unauthorized"), + FORBIDDEN("C003", "Forbidden"), + NOT_FOUND("C004", "Resource not found"), + INTERNAL_ERROR("C999", "Internal server error"); + + private final String code; + private final String message; + + ErrorCode(String code, String message) { + this.code = code; + this.message = message; + } + + public String code() { + return code; + } + + public String message() { + return message; + } +} diff --git a/src/main/java/kr/tscc/base/common/exception/GlobalExceptionHandler.java b/src/main/java/kr/tscc/base/common/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..62f3816 --- /dev/null +++ b/src/main/java/kr/tscc/base/common/exception/GlobalExceptionHandler.java @@ -0,0 +1,129 @@ +package kr.tscc.base.common.exception; + +import kr.tscc.base.common.response.ApiError; +import kr.tscc.base.common.response.ApiResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.core.AuthenticationException; +import org.springframework.validation.BindException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +/** + * 전역 예외 처리 핸들러 + * + * 설계 목적: + * - 예외를 외부로 그대로 노출하지 않음 + * - 예외 → ErrorCode → ApiError 변환 + * - 컨트롤러별 try/catch 제거 + * - 계단식 예외 처리 (구체 → 포괄) + * - StackTrace 응답 금지 (시큐어 코딩 규칙) + */ +@RestControllerAdvice +public class GlobalExceptionHandler { + + private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); + + /** + * 비즈니스 예외 처리 + */ + @ExceptionHandler(BizException.class) + public ResponseEntity> handleBizException(BizException e) { + ErrorCode errorCode = e.getErrorCode(); + log.warn("Business exception: {} - {}", errorCode.code(), e.getMessage()); + return ResponseEntity + .status(HttpStatus.BAD_REQUEST) + .body(ApiResponse.error(new ApiError(errorCode.code(), e.getMessage()))); + } + + /** + * 인증 예외 처리 + */ + @ExceptionHandler(AuthenticationException.class) + public ResponseEntity> handleAuthenticationException(AuthenticationException e) { + log.warn("Authentication exception: {}", e.getMessage()); + return ResponseEntity + .status(HttpStatus.UNAUTHORIZED) + .body(ApiResponse.error(new ApiError( + ErrorCode.UNAUTHORIZED.code(), + ErrorCode.UNAUTHORIZED.message() + ))); + } + + /** + * 인가 예외 처리 + */ + @ExceptionHandler({AccessDeniedException.class, SecurityException.class}) + public ResponseEntity> handleAccessDeniedException(Exception e) { + log.warn("Access denied exception: {}", e.getMessage()); + return ResponseEntity + .status(HttpStatus.FORBIDDEN) + .body(ApiResponse.error(new ApiError( + ErrorCode.FORBIDDEN.code(), + ErrorCode.FORBIDDEN.message() + ))); + } + + /** + * 입력 검증 예외 처리 (MethodArgumentNotValidException) + */ + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity> handleMethodArgumentNotValidException( + MethodArgumentNotValidException e + ) { + log.warn("Validation exception: {}", e.getMessage()); + return ResponseEntity + .status(HttpStatus.BAD_REQUEST) + .body(ApiResponse.error(new ApiError( + ErrorCode.INVALID_REQUEST.code(), + ErrorCode.INVALID_REQUEST.message() + ))); + } + + /** + * 입력 검증 예외 처리 (BindException) + */ + @ExceptionHandler(BindException.class) + public ResponseEntity> handleBindException(BindException e) { + log.warn("Bind exception: {}", e.getMessage()); + return ResponseEntity + .status(HttpStatus.BAD_REQUEST) + .body(ApiResponse.error(new ApiError( + ErrorCode.INVALID_REQUEST.code(), + ErrorCode.INVALID_REQUEST.message() + ))); + } + + /** + * IllegalArgumentException 처리 + */ + @ExceptionHandler(IllegalArgumentException.class) + public ResponseEntity> handleIllegalArgumentException(IllegalArgumentException e) { + log.warn("Illegal argument exception: {}", e.getMessage()); + return ResponseEntity + .status(HttpStatus.BAD_REQUEST) + .body(ApiResponse.error(new ApiError( + ErrorCode.INVALID_REQUEST.code(), + ErrorCode.INVALID_REQUEST.message() + ))); + } + + /** + * 일반 예외 처리 (최후의 수단) + * StackTrace는 로그에만 기록하고 응답에는 포함하지 않음 (시큐어 코딩 규칙) + */ + @ExceptionHandler(Exception.class) + public ResponseEntity> handleGeneralException(Exception e) { + log.error("Unexpected exception", e); + return ResponseEntity + .status(HttpStatus.INTERNAL_SERVER_ERROR) + .body(ApiResponse.error(new ApiError( + ErrorCode.INTERNAL_ERROR.code(), + ErrorCode.INTERNAL_ERROR.message() + ))); + } +} diff --git a/src/main/java/kr/tscc/base/common/response/ApiError.java b/src/main/java/kr/tscc/base/common/response/ApiError.java new file mode 100644 index 0000000..527c230 --- /dev/null +++ b/src/main/java/kr/tscc/base/common/response/ApiError.java @@ -0,0 +1,23 @@ +package kr.tscc.base.common.response; + +/** + * API 에러 응답 모델 + */ +public class ApiError { + + private final String code; + private final String message; + + public ApiError(String code, String message) { + this.code = code; + this.message = message; + } + + public String getCode() { + return code; + } + + public String getMessage() { + return message; + } +} diff --git a/src/main/java/kr/tscc/base/common/response/ApiResponse.java b/src/main/java/kr/tscc/base/common/response/ApiResponse.java new file mode 100644 index 0000000..ab90748 --- /dev/null +++ b/src/main/java/kr/tscc/base/common/response/ApiResponse.java @@ -0,0 +1,66 @@ +package kr.tscc.base.common.response; + +/** + * 공통 API 응답 구조 + * + * 설계 목적: + * - 모든 API 응답 포맷 통일 + * - 성공/실패 구분 명확화 + * - 프론트엔드 처리 단순화 + * + * @param 응답 데이터 타입 + */ +public class ApiResponse { + + private final boolean success; + private final T data; + private final ApiError error; + + private ApiResponse(boolean success, T data, ApiError error) { + this.success = success; + this.data = data; + this.error = error; + } + + /** + * 성공 응답 생성 (데이터 포함) + */ + public static ApiResponse success(T data) { + return new ApiResponse<>(true, data, null); + } + + /** + * 성공 응답 생성 (데이터 없음) + */ + public static ApiResponse success() { + return new ApiResponse<>(true, null, null); + } + + /** + * 에러 응답 생성 (Void 타입) + */ + public static ApiResponse error(ApiError error) { + return new ApiResponse<>(false, null, error); + } + + /** + * 에러 응답 생성 (제네릭 타입) + * + * @param 응답 데이터 타입 (에러 시 null) + */ + public static ApiResponse errorWithType(ApiError error) { + return new ApiResponse<>(false, null, error); + } + + public boolean isSuccess() { + return success; + } + + public T getData() { + return data; + } + + public ApiError getError() { + return error; + } +} diff --git a/src/main/java/kr/tscc/base/common/response/PageQuery.java b/src/main/java/kr/tscc/base/common/response/PageQuery.java new file mode 100644 index 0000000..ee07b70 --- /dev/null +++ b/src/main/java/kr/tscc/base/common/response/PageQuery.java @@ -0,0 +1,89 @@ +package kr.tscc.base.common.response; + +/** + * 페이징 조회 조건 베이스 객체 + * + * 역할: + * - 요청 파라미터 기반 페이징 조건 캡슐화 + * - offset/limit 계산 책임 + * - count 결과 주입 시 전체 페이지 계산 + * + * 설계 목적: + * - Controller/Service/Mapper 전반에서 일관된 페이징 처리 + * - page 계산 로직 중복 제거 + * - MyBatis limit/offset 계산의 중앙화 + * - total count 기반 페이지 메타 정보 제공 + */ +public class PageQuery { + + private final int pageIndex; + private final int pageSize; + + private int totalCount; + private int totalPages; + + /** + * 페이징 쿼리 생성 + * + * @param pageIndex 페이지 번호 (1-based, null이거나 1 미만이면 1로 설정) + * @param pageSize 페이지 크기 (null이거나 1 미만이면 20으로 설정) + */ + public PageQuery(Integer pageIndex, Integer pageSize) { + this.pageIndex = (pageIndex == null || pageIndex < 1) ? 1 : pageIndex; + this.pageSize = (pageSize == null || pageSize < 1) ? 20 : pageSize; + } + + public int getPageIndex() { + return pageIndex; + } + + public int getPageSize() { + return pageSize; + } + + /** + * MyBatis offset 계산 + */ + public int getOffset() { + return (pageIndex - 1) * pageSize; + } + + /** + * MyBatis limit 계산 + */ + public int getLimit() { + return pageSize; + } + + /** + * 전체 개수 적용 및 전체 페이지 수 계산 + * + * @param totalCount 전체 개수 + */ + public void applyTotalCount(int totalCount) { + this.totalCount = totalCount; + this.totalPages = (int) Math.ceil((double) totalCount / pageSize); + } + + public int getTotalCount() { + return totalCount; + } + + public int getTotalPages() { + return totalPages; + } + + /** + * 다음 페이지 존재 여부 + */ + public boolean hasNext() { + return pageIndex < totalPages; + } + + /** + * 이전 페이지 존재 여부 + */ + public boolean hasPrevious() { + return pageIndex > 1; + } +} diff --git a/src/main/java/kr/tscc/base/common/response/PageResult.java b/src/main/java/kr/tscc/base/common/response/PageResult.java new file mode 100644 index 0000000..c96fb5d --- /dev/null +++ b/src/main/java/kr/tscc/base/common/response/PageResult.java @@ -0,0 +1,31 @@ +package kr.tscc.base.common.response; + +import java.util.List; + +/** + * 페이징 응답 래퍼 + * + * 역할: + * - 실제 조회 결과와 페이징 메타 정보를 함께 반환 + * - API 응답 구조 표준화 + * + * @param 아이템 타입 + */ +public class PageResult { + + private final List items; + private final PageQuery page; + + public PageResult(List items, PageQuery page) { + this.items = items; + this.page = page; + } + + public List getItems() { + return items; + } + + public PageQuery getPage() { + return page; + } +} diff --git a/src/main/java/kr/tscc/base/common/util/FileUtils.java b/src/main/java/kr/tscc/base/common/util/FileUtils.java new file mode 100644 index 0000000..4f4255c --- /dev/null +++ b/src/main/java/kr/tscc/base/common/util/FileUtils.java @@ -0,0 +1,104 @@ +package kr.tscc.base.common.util; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.InvalidPathException; +import java.nio.file.Path; +import java.util.Set; + +/** + * 파일/경로 보안 전용 유틸리티 + * + * 설계 목적: + * - 파일/경로 관련 취약점(Path Traversal) 방지 + * - 보안 리뷰, 시큐어코딩 점검 시 독립적으로 확인 가능 + * - 문자열 유틸과 절대 섞지 않음 + * - 반드시 baseDir 하위 경로만 허용 + * + * 설계 원칙: + * - user input 경로는 절대 그대로 사용하지 않음 + * - Path.normalize() + startsWith(baseDir) 검증 필수 + * - 파일명은 별도로 sanitize 처리 + * - 확장자는 whitelist 방식으로만 허용 + */ +public final class FileUtils { + + private static final Set DEFAULT_ALLOWED_EXTENSIONS = + Set.of("txt", "pdf", "png", "jpg", "jpeg", "gif", "csv", "docx", "xlsx", "pptx"); + + private FileUtils() {} + + /** + * 안전한 경로 해석 (Path Traversal 방지) + * + * @param baseDir 기준 디렉터리 (절대 경로) + * @param userPath 사용자 입력 경로 + * @return baseDir 하위의 정규화된 경로 + * @throws SecurityException baseDir 밖으로 나가는 경우 + */ + public static Path safeResolve(Path baseDir, String userPath) { + try { + Path resolved = baseDir.resolve(userPath).normalize(); + if (!resolved.startsWith(baseDir)) { + throw new SecurityException("Path traversal attempt blocked"); + } + return resolved; + } catch (InvalidPathException e) { + throw new SecurityException("Invalid path", e); + } + } + + /** + * 파일명 sanitize (특수문자 제거) + * + * @param filename 원본 파일명 + * @return sanitize된 파일명 + */ + public static String sanitizeFilename(String filename) { + if (filename == null) { + return "unknown"; + } + return filename + .replaceAll("[\\\\/]", "") + .replaceAll("\\.\\.", "") + .replaceAll("[^a-zA-Z0-9._-]", "_"); + } + + /** + * 파일 확장자 추출 + * + * @param filename 파일명 + * @return 확장자 (소문자, 점 제외) + */ + public static String getExtension(String filename) { + if (filename == null) return ""; + int idx = filename.lastIndexOf('.'); + return (idx > -1) ? filename.substring(idx + 1).toLowerCase() : ""; + } + + /** + * 허용된 확장자인지 확인 (화이트리스트) + * + * @param filename 파일명 + * @return 허용 여부 + */ + public static boolean isAllowedExtension(String filename) { + return DEFAULT_ALLOWED_EXTENSIONS.contains(getExtension(filename)); + } + + /** + * 디렉터리 생성 (존재하지 않으면 생성) + * + * @param dir 디렉터리 경로 + * @throws IllegalStateException 생성 실패 시 + */ + public static void ensureDirectory(Path dir) { + try { + if (Files.notExists(dir)) { + Files.createDirectories(dir); + } + } catch (IOException e) { + throw new IllegalStateException("Failed to create directory", e); + } + } +} diff --git a/src/main/java/kr/tscc/base/common/util/ServletUtils.java b/src/main/java/kr/tscc/base/common/util/ServletUtils.java new file mode 100644 index 0000000..f163e12 --- /dev/null +++ b/src/main/java/kr/tscc/base/common/util/ServletUtils.java @@ -0,0 +1,101 @@ +package kr.tscc.base.common.util; + +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; + +/** + * HttpServletRequest 보조 유틸리티 + * + * 설계 목적: + * - HttpServletRequest 직접 접근 로직을 흩뿌리지 않음 + * - IP / Header / Token / Cookie 접근 로직을 중앙화 + * - Controller / Filter / Handler 어디서든 동일한 방식으로 사용 + * + * 설계 원칙: + * - X-Forwarded-For 우선 + * - Trust Chain 명확히 정의 + * - Authorization 파싱은 Bearer 한정 + * - null-safe 접근만 허용 + */ +public final class ServletUtils { + + private ServletUtils() {} + + /** + * 클라이언트 IP 주소 추출 + * 프록시 환경을 고려하여 X-Forwarded-For 헤더 우선 확인 + * + * @param request HttpServletRequest + * @return 클라이언트 IP 주소 + */ + public static String getClientIp(HttpServletRequest request) { + String[] headers = { + "X-Forwarded-For", + "X-Real-IP", + "Proxy-Client-IP", + "WL-Proxy-Client-IP" + }; + + for (String h : headers) { + String ip = request.getHeader(h); + if (ip != null && !ip.isBlank() && !"unknown".equalsIgnoreCase(ip)) { + // 여러 IP가 있을 경우 첫 번째 IP 반환 + return ip.split(",")[0].trim(); + } + } + return request.getRemoteAddr(); + } + + /** + * Bearer 토큰 추출 + * Authorization 헤더에서 Bearer 토큰만 추출 + * + * @param request HttpServletRequest + * @return Bearer 토큰 또는 null + */ + public static String getBearerToken(HttpServletRequest request) { + String auth = request.getHeader("Authorization"); + if (auth == null) return null; + if (!auth.startsWith("Bearer ")) return null; + return auth.substring(7); + } + + /** + * 쿠키 값 추출 + * + * @param request HttpServletRequest + * @param name 쿠키 이름 + * @return 쿠키 값 또는 null + */ + public static String getCookieValue(HttpServletRequest request, String name) { + if (request.getCookies() == null) return null; + for (Cookie c : request.getCookies()) { + if (name.equals(c.getName())) { + return c.getValue(); + } + } + return null; + } + + /** + * AJAX 요청 여부 확인 + * + * @param request HttpServletRequest + * @return AJAX 요청 여부 + */ + public static boolean isAjax(HttpServletRequest request) { + String header = request.getHeader("X-Requested-With"); + return "XMLHttpRequest".equalsIgnoreCase(header); + } + + /** + * JSON 요청 여부 확인 + * + * @param request HttpServletRequest + * @return JSON 요청 여부 + */ + public static boolean isJson(HttpServletRequest request) { + String ct = request.getContentType(); + return ct != null && ct.contains("application/json"); + } +} diff --git a/src/main/java/kr/tscc/base/common/util/Utils.java b/src/main/java/kr/tscc/base/common/util/Utils.java new file mode 100644 index 0000000..ce7089a --- /dev/null +++ b/src/main/java/kr/tscc/base/common/util/Utils.java @@ -0,0 +1,211 @@ +package kr.tscc.base.common.util; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.http.ResponseCookie; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.*; + +/** + * 공통 유틸리티 클래스 (CFGH: Cookie, Crypto, DateTime, Json, Masking) + * 프로젝트 전반 정책을 한 파일에서 통제 + */ +public final class Utils { + + private static final SecureRandom SECURE_RANDOM = new SecureRandom(); + private static volatile ObjectMapper OBJECT_MAPPER; + public static final ZoneId KST = ZoneId.of("Asia/Seoul"); + + private Utils() {} + + /** + * JSON 처리 유틸리티 + */ + public static final class Json { + public static void init(ObjectMapper mapper) { + OBJECT_MAPPER = mapper; + } + + private static ObjectMapper om() { + if (OBJECT_MAPPER == null) { + throw new IllegalStateException("ObjectMapper not initialized"); + } + return OBJECT_MAPPER; + } + + public static String toJson(Object value) { + try { + return om().writeValueAsString(value); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + public static T fromJson(String json, Class clazz) { + try { + return om().readValue(json, clazz); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + public static T fromJson(String json, TypeReference ref) { + try { + return om().readValue(json, ref); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + } + + /** + * 암호화/보안 관련 유틸리티 + */ + public static final class Crypto { + /** + * 상수 시간 비교 (타이밍 공격 방지) + */ + public static boolean constantTimeEquals(String a, String b) { + return MessageDigest.isEqual( + a.getBytes(StandardCharsets.UTF_8), + b.getBytes(StandardCharsets.UTF_8) + ); + } + + /** + * 보안 난수 토큰 생성 + */ + public static String randomToken(int bytes) { + byte[] buf = new byte[bytes]; + SECURE_RANDOM.nextBytes(buf); + return Base64.getUrlEncoder().withoutPadding().encodeToString(buf); + } + + /** + * SHA-256 해시 생성 + */ + public static String sha256(String input) { + try { + MessageDigest md = MessageDigest.getInstance("SHA-256"); + byte[] out = md.digest(input.getBytes(StandardCharsets.UTF_8)); + StringBuilder sb = new StringBuilder(); + for (byte b : out) sb.append(String.format("%02x", b)); + return sb.toString(); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + } + + /** + * 날짜/시간 처리 유틸리티 + */ + public static final class DateTime { + public static LocalDateTime nowKst() { + return LocalDateTime.now(KST); + } + + public static String format(LocalDateTime dt) { + return dt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + } + } + + /** + * 쿠키 생성 유틸리티 + */ + public static final class Cookie { + public static String build( + String name, + String value, + boolean httpOnly, + boolean secure, + String sameSite, + long maxAge + ) { + return ResponseCookie.from(name, value) + .httpOnly(httpOnly) + .secure(secure) + .sameSite(sameSite) + .maxAge(maxAge) + .path("/") + .build() + .toString(); + } + } + + /** + * 민감정보 마스킹 유틸리티 + */ + public static final class Masking { + private static final Set SENSITIVE_KEYS = Set.of( + "password", "passwd", "pwd", + "accesstoken", "refreshtoken", "token", + "authorization", "cookie", "set-cookie", + "session", "sessionid", "sid", "jsessionid", + "csrf", "xsrf", "xsrf-token" + ); + + /** + * Map/List 구조를 깊게 내려가며 민감키 값은 "***"로 치환 + */ + public static Object maskDeep(Object body) { + if (body == null) return null; + + if (body instanceof Map map) { + Map out = new LinkedHashMap<>(); + for (Map.Entry e : map.entrySet()) { + String k = String.valueOf(e.getKey()); + Object v = e.getValue(); + if (isSensitiveKey(k)) { + out.put(k, "***"); + } else { + out.put(k, maskDeep(v)); + } + } + return out; + } + + if (body instanceof List list) { + List out = new ArrayList<>(list.size()); + for (Object it : list) { + out.add(maskDeep(it)); + } + return out; + } + + return body; + } + + /** + * 헤더 맵 마스킹(Authorization/Cookie 등) + */ + public static Map maskHeaders(Map headers) { + if (headers == null) return new LinkedHashMap<>(); + Map out = new LinkedHashMap<>(); + headers.forEach((k, v) -> out.put(k, isSensitiveKey(k) ? "***" : v)); + return out; + } + + /** + * 로그용: 너무 긴 문자열은 잘라서 기록 + */ + public static String truncateForLog(String s, int maxLen) { + if (s == null) return null; + if (maxLen <= 0) return ""; + if (s.length() <= maxLen) return s; + return s.substring(0, maxLen) + "..."; + } + + private static boolean isSensitiveKey(String key) { + if (key == null) return false; + String k = key.toLowerCase(Locale.ROOT); + return SENSITIVE_KEYS.contains(k); + } + } +} diff --git a/src/main/java/kr/tscc/base/security/config/PasswordEncoderConfig.java b/src/main/java/kr/tscc/base/security/config/PasswordEncoderConfig.java new file mode 100644 index 0000000..db23a4a --- /dev/null +++ b/src/main/java/kr/tscc/base/security/config/PasswordEncoderConfig.java @@ -0,0 +1,22 @@ +package kr.tscc.base.security.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +/** + * 비밀번호 인코더 설정 + * + * 보안 규칙: + * - BCrypt 사용 (느린 해시 알고리즘) + * - DES/MD5/SHA-1 사용 금지 + */ +@Configuration +public class PasswordEncoderConfig { + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } +} diff --git a/src/main/java/kr/tscc/base/security/config/SecurityConfig.java b/src/main/java/kr/tscc/base/security/config/SecurityConfig.java new file mode 100644 index 0000000..9267b27 --- /dev/null +++ b/src/main/java/kr/tscc/base/security/config/SecurityConfig.java @@ -0,0 +1,104 @@ +package kr.tscc.base.security.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.ProviderManager; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +import org.springframework.security.config.Customizer; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.csrf.CookieCsrfTokenRepository; + +/** + * Spring Security 설정 + * + * 역할: + * - 인증/인가 정책 선언 + * - CSRF 설정 + * - 세션 정책 정의 + * - 필터 체인 구성 + * - AuthenticationManager Bean 명시적 정의 + * + * 보안 규칙: + * - SecurityConfig에 비즈니스 판단 로직 금지 + * - 세션 저장소 변경 로직 금지 + * - Redis 사용 여부는 코드에서 분기하지 않음 + * - CSRF는 CookieCsrfTokenRepository 사용 + */ +@Configuration +@EnableWebSecurity +public class SecurityConfig { + + /** + * AuthenticationManager Bean 명시적 정의 + * + * 역할: + * - UserDetailsService와 PasswordEncoder를 연결 + * - 인증 처리 로직 제공 + * + * 보안 규칙: + * - DaoAuthenticationProvider 사용 (DB 기반 인증) + * - PasswordEncoder는 BCrypt 사용 (PasswordEncoderConfig에서 정의) + * + * 참고: + * - Spring Security 6.x에서는 DaoAuthenticationProvider 생성자에 PasswordEncoder 전달 + * - setUserDetailsService는 여전히 사용 가능 (deprecated 경고 무시 가능) + */ + @Bean + @SuppressWarnings("deprecation") + public AuthenticationManager authenticationManager( + UserDetailsService userDetailsService, + PasswordEncoder passwordEncoder + ) { + DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); + authProvider.setUserDetailsService(userDetailsService); + authProvider.setPasswordEncoder(passwordEncoder); + return new ProviderManager(authProvider); + } + + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + + http + // CSRF 설정 (SPA 환경) + .csrf(csrf -> csrf + .csrfTokenRepository( + CookieCsrfTokenRepository.withHttpOnlyFalse() + ) + ) + + // 인가 설정 + .authorizeHttpRequests(auth -> auth + .requestMatchers( + "/api/auth/login", + "/api/auth/logout", + "/api/auth/csrf" + ).permitAll() + .anyRequest().authenticated() + ) + + // 세션 관리 + .sessionManagement(session -> session + .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) + .sessionFixation().migrateSession() + ) + + // 예외 처리 + .exceptionHandling(ex -> ex + .authenticationEntryPoint(new kr.tscc.base.security.handler.AuthenticationEntryPointImpl()) + .accessDeniedHandler(new kr.tscc.base.security.handler.AccessDeniedHandlerImpl()) + ) + + // 기본 인증 방식 비활성화 (REST API) + .formLogin(form -> form.disable()) + .httpBasic(basic -> basic.disable()) + .logout(Customizer.withDefaults()); + + return http.build(); + } +} diff --git a/src/main/java/kr/tscc/base/security/config/UserDetailsServiceImpl.java b/src/main/java/kr/tscc/base/security/config/UserDetailsServiceImpl.java new file mode 100644 index 0000000..705c936 --- /dev/null +++ b/src/main/java/kr/tscc/base/security/config/UserDetailsServiceImpl.java @@ -0,0 +1,66 @@ +package kr.tscc.base.security.config; + +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +/** + * UserDetailsService 구현 + * + * 역할: + * - Spring Security 인증 시 사용자 정보 조회 + * - username(실제로는 email)으로 사용자 조회 + * - LoginUserPrincipal 반환 + * + * 설계 원칙: + * - 실제 사용자 조회는 UserMapper를 통해 수행 (도메인 영역) + * - 이 클래스는 Spring Security와 도메인 영역을 연결하는 어댑터 역할 + * - 비밀번호 검증은 AuthenticationManager가 처리 + * + * 보안 규칙: + * - 사용자 조회 실패 시 UsernameNotFoundException 발생 + * - 비밀번호는 반환하지 않음 (LoginUserPrincipal에서 null 반환) + * - 민감 정보는 SessionUser에 포함하지 않음 + * + * 주의: + * - 실제 프로젝트에서는 UserMapper를 주입받아 사용자 조회 + * - 현재는 예제 구조만 제공 (실제 DB 조회 로직은 UserMapper에 구현) + */ +@Service +public class UserDetailsServiceImpl implements UserDetailsService { + + // TODO: 실제 프로젝트에서는 UserMapper 주입 + // private final UserMapper userMapper; + + /** + * 사용자 정보 조회 + * + * @param username 실제로는 email (LoginUserPrincipal.getUsername()이 email 반환) + * @return UserDetails (LoginUserPrincipal) + * @throws UsernameNotFoundException 사용자를 찾을 수 없을 때 + */ + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + // TODO: 실제 프로젝트에서는 UserMapper를 통해 사용자 조회 + // 예시: + // UserEntity user = userMapper.findByEmail(username) + // .orElseThrow(() -> new UsernameNotFoundException("User not found: " + username)); + // + // SessionUser sessionUser = new SessionUser( + // user.getId(), + // user.getEmail(), + // user.getDisplayName(), + // user.getRole() + // ); + // return new LoginUserPrincipal(sessionUser); + + // 현재는 예제 구조만 제공 + // 실제 프로젝트에서는 위의 주석 처리된 코드를 활성화하고 아래 코드를 제거 + throw new UsernameNotFoundException( + "UserDetailsService not implemented. " + + "Please implement user lookup logic using UserMapper. " + + "Username: " + username + ); + } +} diff --git a/src/main/java/kr/tscc/base/security/handler/AccessDeniedHandlerImpl.java b/src/main/java/kr/tscc/base/security/handler/AccessDeniedHandlerImpl.java new file mode 100644 index 0000000..75d2a5a --- /dev/null +++ b/src/main/java/kr/tscc/base/security/handler/AccessDeniedHandlerImpl.java @@ -0,0 +1,42 @@ +package kr.tscc.base.security.handler; + +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import kr.tscc.base.common.exception.ErrorCode; +import kr.tscc.base.common.response.ApiError; +import kr.tscc.base.common.response.ApiResponse; +import org.springframework.http.MediaType; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.web.access.AccessDeniedHandler; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; + +/** + * 접근 거부 핸들러 + * + * 403 Forbidden 응답 처리 + */ +public class AccessDeniedHandlerImpl implements AccessDeniedHandler { + + @Override + public void handle( + HttpServletRequest request, + HttpServletResponse response, + AccessDeniedException accessDeniedException + ) throws IOException, ServletException { + + response.setStatus(HttpServletResponse.SC_FORBIDDEN); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + response.setCharacterEncoding(StandardCharsets.UTF_8.name()); + + ApiResponse apiResponse = ApiResponse.error( + new ApiError(ErrorCode.FORBIDDEN.code(), ErrorCode.FORBIDDEN.message()) + ); + + response.getWriter().write( + new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(apiResponse) + ); + } +} diff --git a/src/main/java/kr/tscc/base/security/handler/AuthenticationEntryPointImpl.java b/src/main/java/kr/tscc/base/security/handler/AuthenticationEntryPointImpl.java new file mode 100644 index 0000000..2c0a2ac --- /dev/null +++ b/src/main/java/kr/tscc/base/security/handler/AuthenticationEntryPointImpl.java @@ -0,0 +1,42 @@ +package kr.tscc.base.security.handler; + +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import kr.tscc.base.common.exception.ErrorCode; +import kr.tscc.base.common.response.ApiError; +import kr.tscc.base.common.response.ApiResponse; +import org.springframework.http.MediaType; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.AuthenticationEntryPoint; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; + +/** + * 인증 진입점 핸들러 + * + * 401 Unauthorized 응답 처리 + */ +public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint { + + @Override + public void commence( + HttpServletRequest request, + HttpServletResponse response, + AuthenticationException authException + ) throws IOException, ServletException { + + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + response.setCharacterEncoding(StandardCharsets.UTF_8.name()); + + ApiResponse apiResponse = ApiResponse.error( + new ApiError(ErrorCode.UNAUTHORIZED.code(), ErrorCode.UNAUTHORIZED.message()) + ); + + response.getWriter().write( + new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(apiResponse) + ); + } +} diff --git a/src/main/java/kr/tscc/base/security/principal/LoginUserPrincipal.java b/src/main/java/kr/tscc/base/security/principal/LoginUserPrincipal.java new file mode 100644 index 0000000..7425ee3 --- /dev/null +++ b/src/main/java/kr/tscc/base/security/principal/LoginUserPrincipal.java @@ -0,0 +1,72 @@ +package kr.tscc.base.security.principal; + +import kr.tscc.base.security.session.SessionUser; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +import java.util.Collection; +import java.util.Collections; + +/** + * 인증 Principal + * + * Spring Security의 UserDetails를 구현하여 인증 정보를 담는 객체 + * + * 설계 원칙: + * - SessionUser를 기반으로 생성 + * - UserDetails 인터페이스 구현 + * - 권한 정보 포함 + */ +public class LoginUserPrincipal implements UserDetails { + + private final SessionUser sessionUser; + private final Collection authorities; + + public LoginUserPrincipal(SessionUser sessionUser) { + this.sessionUser = sessionUser; + this.authorities = Collections.singletonList( + new SimpleGrantedAuthority("ROLE_" + sessionUser.getRole()) + ); + } + + public SessionUser getSessionUser() { + return sessionUser; + } + + @Override + public Collection getAuthorities() { + return authorities; + } + + @Override + public String getPassword() { + // 세션 기반이므로 password 반환 불필요 + return null; + } + + @Override + public String getUsername() { + return sessionUser.getEmail(); + } + + @Override + public boolean isAccountNonExpired() { + return true; + } + + @Override + public boolean isAccountNonLocked() { + return true; + } + + @Override + public boolean isCredentialsNonExpired() { + return true; + } + + @Override + public boolean isEnabled() { + return true; + } +} diff --git a/src/main/java/kr/tscc/base/security/principal/UserRoles.java b/src/main/java/kr/tscc/base/security/principal/UserRoles.java new file mode 100644 index 0000000..aae85fb --- /dev/null +++ b/src/main/java/kr/tscc/base/security/principal/UserRoles.java @@ -0,0 +1,9 @@ +package kr.tscc.base.security.principal; + +/** + * 사용자 역할 정의 + */ +public enum UserRoles { + USER, + ADMIN +} diff --git a/src/main/java/kr/tscc/base/security/session/SessionConstants.java b/src/main/java/kr/tscc/base/security/session/SessionConstants.java new file mode 100644 index 0000000..9d4dd2e --- /dev/null +++ b/src/main/java/kr/tscc/base/security/session/SessionConstants.java @@ -0,0 +1,14 @@ +package kr.tscc.base.security.session; + +/** + * 세션 관련 상수 + */ +public final class SessionConstants { + + private SessionConstants() {} + + /** + * 세션에 저장되는 사용자 정보 키 + */ + public static final String SESSION_USER_KEY = "USER"; +} diff --git a/src/main/java/kr/tscc/base/security/session/SessionUser.java b/src/main/java/kr/tscc/base/security/session/SessionUser.java new file mode 100644 index 0000000..d96d667 --- /dev/null +++ b/src/main/java/kr/tscc/base/security/session/SessionUser.java @@ -0,0 +1,46 @@ +package kr.tscc.base.security.session; + +import java.io.Serializable; + +/** + * 세션 사용자 모델 + * + * 설계 원칙: + * - 세션에 저장되는 정보는 최소화 + * - UserEntity 전체 저장 금지 + * - Serializable 구현 (세션 직렬화 필요) + * + * 보안 규칙: + * - password, token 등 민감정보 절대 포함 금지 + * - 최소 정보만 저장 (userId, email, displayName 등) + */ +public class SessionUser implements Serializable { + + private final Long userId; + private final String email; + private final String displayName; + private final String role; + + public SessionUser(Long userId, String email, String displayName, String role) { + this.userId = userId; + this.email = email; + this.displayName = displayName; + this.role = role; + } + + public Long getUserId() { + return userId; + } + + public String getEmail() { + return email; + } + + public String getDisplayName() { + return displayName; + } + + public String getRole() { + return role; + } +} diff --git a/src/main/resources/application-dev.yml b/src/main/resources/application-dev.yml new file mode 100644 index 0000000..98dfef9 --- /dev/null +++ b/src/main/resources/application-dev.yml @@ -0,0 +1,10 @@ +spring: + datasource: + driver-class-name: org.mariadb.jdbc.Driver + url: jdbc:mariadb://localhost:3306/tscc + username: tscc + password: tscc1234 + + sql: + init: + mode: never diff --git a/src/main/resources/application-prod.yml b/src/main/resources/application-prod.yml new file mode 100644 index 0000000..697455d --- /dev/null +++ b/src/main/resources/application-prod.yml @@ -0,0 +1,10 @@ +spring: + datasource: + driver-class-name: org.mariadb.jdbc.Driver + url: jdbc:mariadb://localhost:3306/tscc + username: ${DB_USERNAME:tscc} + password: ${DB_PASSWORD:tscc1234} + + sql: + init: + mode: never diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml new file mode 100644 index 0000000..0beb3a3 --- /dev/null +++ b/src/main/resources/application.yaml @@ -0,0 +1,12 @@ +spring: + application: + name: base + profiles: + active: dev + +# MyBatis 설정 +mybatis: + mapper-locations: classpath:mapper/**/*.xml + type-aliases-package: kr.tscc.base.api + configuration: + map-underscore-to-camel-case: true \ No newline at end of file diff --git a/src/main/resources/logback-spring.xml b/src/main/resources/logback-spring.xml new file mode 100644 index 0000000..99020c7 --- /dev/null +++ b/src/main/resources/logback-spring.xml @@ -0,0 +1,31 @@ + + + + + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + logs/application.log + + logs/application-%d{yyyy-MM-dd}.log + 30 + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + diff --git a/src/test/java/kr/tscc/base/BootstrapApplicationTests.java b/src/test/java/kr/tscc/base/BootstrapApplicationTests.java new file mode 100644 index 0000000..ab00640 --- /dev/null +++ b/src/test/java/kr/tscc/base/BootstrapApplicationTests.java @@ -0,0 +1,13 @@ +package kr.tscc.base; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class BootstrapApplicationTests { + + @Test + void contextLoads() { + } + +}