From 4e7aecbf4fa1b7c896d1efaeeee6016e5617a432 Mon Sep 17 00:00:00 2001 From: kkangmen Date: Sat, 14 Nov 2026 17:07:20 +0900 Subject: [PATCH 1/7] =?UTF-8?q?chore:=20Dockerfile=20=EC=B6=94=EA=B0=80=20?= =?UTF-8?q?=EB=B0=8F=20=EC=8B=A4=ED=96=89=20jar=EB=A7=8C=20=EB=B9=8C?= =?UTF-8?q?=EB=93=9C=ED=95=98=EB=8F=84=EB=A1=9D=20=EC=84=A4=EC=A0=95=20(#3?= =?UTF-8?q?2)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 --- .dockerignore | 3 +++ Dockerfile | 15 +++++++++++++++ build.gradle | 5 +++++ 3 files changed, 23 insertions(+) create mode 100644 .dockerignore create mode 100644 Dockerfile diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..0b353ea --- /dev/null +++ b/.dockerignore @@ -0,0 +1,3 @@ +# 이미지에는 실행 jar만 들어간다. .env 같은 비밀 값이 빌드 컨텍스트로 넘어가지 않게 나머지는 모두 제외한다. +* +!build/libs/*.jar diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..804d85d --- /dev/null +++ b/Dockerfile @@ -0,0 +1,15 @@ +FROM eclipse-temurin:21-jre-alpine + +# 컨테이너 시각을 한국 시간으로 맞춘다 (로그 · LocalDateTime.now) +ENV TZ=Asia/Seoul +RUN apk add --no-cache tzdata + +# root가 아닌 사용자로 실행한다 +RUN addgroup -S spring && adduser -S spring -G spring + +# CI에서 ./gradlew bootJar로 만든 실행 jar (plain jar는 build.gradle에서 만들지 않는다) +COPY build/libs/*.jar app.jar + +USER spring:spring + +ENTRYPOINT ["java", "-Duser.timezone=Asia/Seoul", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/app.jar"] diff --git a/build.gradle b/build.gradle index 72eea98..a999b0f 100644 --- a/build.gradle +++ b/build.gradle @@ -44,3 +44,8 @@ dependencies { tasks.named('test') { useJUnitPlatform() } + +// 실행 jar(bootJar)만 만든다. plain jar가 함께 생기면 Dockerfile의 COPY build/libs/*.jar가 파일 두 개와 매칭돼 실패한다. +tasks.named('jar') { + enabled = false +} From 861728c1b600067d356f5e95b5d64ed2fec219d5 Mon Sep 17 00:00:00 2001 From: kkangmen Date: Sat, 14 Nov 2026 17:07:21 +0900 Subject: [PATCH 2/7] =?UTF-8?q?feat:=20CORS=20=EC=84=A4=EC=A0=95=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80=20=EB=B0=8F=20RT=20=EC=BF=A0=ED=82=A4=20Secu?= =?UTF-8?q?re=20=ED=94=84=EB=A1=9C=ED=8C=8C=EC=9D=BC=EB=B3=84=20=EC=A0=81?= =?UTF-8?q?=EC=9A=A9=20(#32)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 --- .../sudam/global/config/SecurityConfig.java | 31 +++++++++++++++++++ .../global/security/util/CookieUtil.java | 11 +++++-- src/main/resources/application-local.yaml | 5 +++ 3 files changed, 44 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/sudam/global/config/SecurityConfig.java b/src/main/java/com/sudam/global/config/SecurityConfig.java index c3139fd..5eff272 100644 --- a/src/main/java/com/sudam/global/config/SecurityConfig.java +++ b/src/main/java/com/sudam/global/config/SecurityConfig.java @@ -9,14 +9,22 @@ import com.sudam.global.security.token.TokenStore; import com.sudam.global.security.util.JwtUtil; import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpHeaders; +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.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.CorsConfigurationSource; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; + +import java.util.List; @Configuration @EnableWebSecurity @@ -43,6 +51,9 @@ public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { return http + // 아래 corsConfigurationSource 빈을 쓴다. 프리플라이트(OPTIONS)는 인증 검사 전에 여기서 응답한다. + .cors(Customizer.withDefaults()) + .csrf(AbstractHttpConfigurer::disable) .httpBasic(AbstractHttpConfigurer::disable) @@ -68,4 +79,24 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .build(); } + + /*** + * 함수 기능: 프론트 출처에서 오는 요청을 허용하는 CORS 설정을 만든다. + * RT 쿠키(재발급 · 로그아웃)를 주고받아야 하므로 자격 증명을 허용하고, 그래서 출처는 "*"가 아니라 목록으로 지정한다. + * @param allowedOrigins 허용할 프론트 출처 (프로파일별 app.cors.allowed-origins) + * @return 모든 경로에 적용되는 CORS 설정 + */ + @Bean + public CorsConfigurationSource corsConfigurationSource( + @Value("${app.cors.allowed-origins}") List allowedOrigins) { + CorsConfiguration configuration = new CorsConfiguration(); + configuration.setAllowedOrigins(allowedOrigins); + configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")); + configuration.setAllowedHeaders(List.of(HttpHeaders.AUTHORIZATION, HttpHeaders.CONTENT_TYPE)); + configuration.setAllowCredentials(true); + + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/**", configuration); + return source; + } } diff --git a/src/main/java/com/sudam/global/security/util/CookieUtil.java b/src/main/java/com/sudam/global/security/util/CookieUtil.java index f1dc424..e587a3d 100644 --- a/src/main/java/com/sudam/global/security/util/CookieUtil.java +++ b/src/main/java/com/sudam/global/security/util/CookieUtil.java @@ -14,15 +14,19 @@ public class CookieUtil { public static final String REFRESH_TOKEN_COOKIE = "refreshToken"; private final long refreshTokenExpiration; + private final boolean secure; - public CookieUtil(@Value("${jwt.refresh-token-expiration}") long refreshTokenExpiration) { + public CookieUtil(@Value("${jwt.refresh-token-expiration}") long refreshTokenExpiration, + @Value("${app.cookie.secure}") boolean secure) { this.refreshTokenExpiration = refreshTokenExpiration; + this.secure = secure; } /*** * 함수 기능: 리프레시 토큰을 HttpOnly 쿠키로 응답에 싣는다. * JS에서 읽지 못하게 막고, 만료는 토큰 자체의 유효 기간과 맞춘다. - * 운영은 HTTPS + 다른 도메인이 되므로 secure(true) / sameSite("None")으로 바꿔야 한다. + * Secure 여부는 프로파일별 app.cookie.secure를 따른다 (HTTPS인 개발 서버는 true, HTTP인 로컬은 false). + * 프론트(sudam.app)와 API(api.sudam.app)는 같은 사이트라 SameSite=Lax로도 쿠키가 전달된다. * @param response 쿠키를 실을 응답 * @param refreshToken 발급된 리프레시 토큰 */ @@ -32,7 +36,7 @@ public void addRefreshTokenCookie(HttpServletResponse response, String refreshTo /*** * 함수 기능: 리프레시 토큰 쿠키를 즉시 만료시킨다. 로그아웃·탈퇴 후 브라우저에 쿠키가 남지 않게 한다. - * 속성(path·sameSite 등)이 발급 시점과 같아야 브라우저가 같은 쿠키로 인식해 덮어쓴다. + * 속성(path·secure·sameSite 등)이 발급 시점과 같아야 브라우저가 같은 쿠키로 인식해 덮어쓴다. * @param response 쿠키를 실을 응답 */ public void deleteRefreshTokenCookie(HttpServletResponse response) { @@ -43,6 +47,7 @@ private void addCookie(HttpServletResponse response, String value, Duration maxA ResponseCookie cookie = ResponseCookie.from(REFRESH_TOKEN_COOKIE, value) .httpOnly(true) + .secure(secure) .path("/") .maxAge(maxAge) .sameSite("Lax") diff --git a/src/main/resources/application-local.yaml b/src/main/resources/application-local.yaml index 690f109..976c751 100644 --- a/src/main/resources/application-local.yaml +++ b/src/main/resources/application-local.yaml @@ -15,3 +15,8 @@ app: oauth2: success-redirect-uri: http://localhost:8081/login/success failure-redirect-uri: http://localhost:8081/login/failure + cookie: + # 로컬은 HTTP라 Secure 쿠키를 쓰지 않는다 (Secure면 일부 브라우저가 HTTP에서 쿠키를 저장하지 않는다) + secure: false + cors: + allowed-origins: http://localhost:8081 From 15c6211954fee037a9f5540335e77c278f051c82 Mon Sep 17 00:00:00 2001 From: kkangmen Date: Sat, 14 Nov 2026 17:07:21 +0900 Subject: [PATCH 3/7] =?UTF-8?q?chore:=20=EA=B0=9C=EB=B0=9C=20=EC=84=9C?= =?UTF-8?q?=EB=B2=84=20=ED=94=84=EB=A1=9C=ED=8C=8C=EC=9D=BC=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80=20=EB=B0=8F=20=EC=95=BD=EA=B4=80=20=EC=8B=9C=EB=93=9C?= =?UTF-8?q?=20=EC=9E=AC=EC=8B=A4=ED=96=89=20=EB=8C=80=EC=9D=91=20(#32)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 --- .env.example | 5 ++++ src/main/resources/application-dev.yaml | 36 +++++++++++++++++++++++++ src/main/resources/data.sql | 5 ++-- 3 files changed, 44 insertions(+), 2 deletions(-) create mode 100644 src/main/resources/application-dev.yaml diff --git a/.env.example b/.env.example index 42791d5..8c4fbb7 100644 --- a/.env.example +++ b/.env.example @@ -6,3 +6,8 @@ KAKAO_CLIENT_SECRET= JWT_SECRET= # 계좌번호 암호화 키. Base64로 인코딩한 32바이트 (예: openssl rand -base64 32) ACCOUNT_ENCRYPTION_KEY= +# 아래 두 키는 개발 서버(dev 프로파일)에서만 쓴다. 로컬 실행에는 필요 없다. +# 백엔드 주소 (예: https://api.example.com). 카카오 redirect-uri에 쓴다 +APP_BASE_URL= +# 프론트 주소 (예: https://example.com). 로그인 성공 · 실패 리다이렉트에 쓴다 +FRONT_BASE_URL= diff --git a/src/main/resources/application-dev.yaml b/src/main/resources/application-dev.yaml new file mode 100644 index 0000000..7777614 --- /dev/null +++ b/src/main/resources/application-dev.yaml @@ -0,0 +1,36 @@ +# 개발 서버(EC2 + docker-compose) 프로파일. compose가 SPRING_PROFILES_ACTIVE=dev로 켠다. +server: + # Nginx가 HTTPS를 받아 HTTP로 넘기므로, Nginx가 보낸 X-Forwarded-Proto · Host로 원래 주소(https)를 복원한다. + # 없으면 Swagger가 서버 주소를 http로 만들어 HTTPS 페이지에서 호출이 차단된다. 앱은 루프백으로만 열려 있어 헤더를 신뢰해도 된다. + forward-headers-strategy: native + +spring: + jpa: + hibernate: + # 기본값 create는 부팅마다 스키마를 지우므로, RDS 데이터가 남도록 update를 쓴다. + ddl-auto: update + + data: + redis: + # 컨테이너 안의 localhost는 자기 자신이므로 compose 서비스명으로 연결한다. + host: redis + port: 6379 + + security: + oauth2: + client: + registration: + kakao: + # 카카오 개발자 콘솔에도 같은 URI를 등록해야 한다. + redirect-uri: ${APP_BASE_URL}/login/oauth2/code/kakao + +app: + oauth2: + success-redirect-uri: ${FRONT_BASE_URL}/login/success + failure-redirect-uri: ${FRONT_BASE_URL}/login/failure + cookie: + # 개발 서버는 HTTPS이므로 RT 쿠키를 HTTPS 요청에만 싣는다 + secure: true + cors: + # 배포된 프론트(FRONT_BASE_URL)와, 개발 서버 API를 쓰는 로컬 프론트 + allowed-origins: ${FRONT_BASE_URL}, http://localhost:8081 diff --git a/src/main/resources/data.sql b/src/main/resources/data.sql index 530b894..cc7d9f8 100644 --- a/src/main/resources/data.sql +++ b/src/main/resources/data.sql @@ -1,6 +1,7 @@ --- 약관 시드. ddl-auto: create라 부팅마다 스키마 생성 뒤 다시 들어간다. +-- 약관 시드. 부팅마다 실행된다. 로컬(ddl-auto: create)은 매번 새로 들어가고, +-- 개발 서버(update)는 이미 있는 행을 UNIQUE(code, version)로 건너뛴다 (INSERT IGNORE). -- 내용이 바뀌면 같은 code의 version을 올린 행을 추가한다 (기존 행은 그대로 둔다). -INSERT INTO terms (code, version, title, is_required, effective_at) VALUES +INSERT IGNORE INTO terms (code, version, title, is_required, effective_at) VALUES ('SERVICE', 1, '서비스 이용약관', true, '2026-01-01 00:00:00'), ('PRIVACY', 1, '개인정보 수집 · 이용', true, '2026-01-01 00:00:00'), ('CONTACT', 1, '학부모 · 학생 연락처 처리', true, '2026-01-01 00:00:00'); From 8864e833a83ae40009da2af48fd7fe270523b74c Mon Sep 17 00:00:00 2001 From: kkangmen Date: Sat, 14 Nov 2026 17:07:22 +0900 Subject: [PATCH 4/7] =?UTF-8?q?chore:=20=EA=B0=9C=EB=B0=9C=20=EC=84=9C?= =?UTF-8?q?=EB=B2=84=20docker-compose=20=EC=B6=94=EA=B0=80=20(#32)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 --- docker-compose.yaml | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 docker-compose.yaml diff --git a/docker-compose.yaml b/docker-compose.yaml new file mode 100644 index 0000000..fccf4ed --- /dev/null +++ b/docker-compose.yaml @@ -0,0 +1,45 @@ +name: sudam-app + +services: + # Spring Boot 애플리케이션 (DB는 외부 RDS를 사용하므로 컨테이너로 띄우지 않음) + spring-app: + # CD(dev-deploy.yaml)가 전달하는 IMAGE_NAME / IMAGE_TAG 로 교체됨 + image: ${IMAGE_NAME}:${IMAGE_TAG} + container_name: spring-app + # .env.example의 키(DB_*, KAKAO_*, JWT_SECRET, ACCOUNT_ENCRYPTION_KEY, APP_BASE_URL, FRONT_BASE_URL)를 주입 + env_file: + - .env + environment: + # application-dev.yaml 적용 (ddl-auto: update, Redis 호스트, 도메인 기준 리다이렉트 URI) + SPRING_PROFILES_ACTIVE: dev + TZ: Asia/Seoul + # Nginx만 접근하도록 호스트의 루프백에만 연다 (외부에서 8080 직접 접근 불가) + ports: + - "127.0.0.1:8080:8080" + depends_on: + redis: + condition: service_healthy + restart: unless-stopped + logging: + driver: json-file + options: + max-size: "10m" + max-file: "3" + + # 리프레시 토큰(rt:{userId}) · 액세스 토큰 차단 목록(bl:{jti}) 저장소. 외부 노출 없이 내부 네트워크로만 접근 + redis: + image: redis:7-alpine + container_name: redis + # 재시작해도 로그인 세션이 유지되도록 AOF로 디스크에 남긴다 + command: ["redis-server", "--appendonly", "yes"] + volumes: + - redis-data:/data + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 10s + timeout: 3s + retries: 5 + restart: unless-stopped + +volumes: + redis-data: From f00b2cfee28a433d57d369df0b29cbe33262ed6a Mon Sep 17 00:00:00 2001 From: kkangmen Date: Sat, 14 Nov 2026 17:07:22 +0900 Subject: [PATCH 5/7] =?UTF-8?q?chore:=20CI=20=C2=B7=20=EA=B0=9C=EB=B0=9C?= =?UTF-8?q?=20=EC=84=9C=EB=B2=84=20=EB=B0=B0=ED=8F=AC=20=EC=9B=8C=ED=81=AC?= =?UTF-8?q?=ED=94=8C=EB=A1=9C=20=EC=B6=94=EA=B0=80=20(#32)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 --- .github/workflows/ci.yaml | 80 +++++++++++++++++++++ .github/workflows/dev-deploy.yaml | 116 ++++++++++++++++++++++++++++++ 2 files changed, 196 insertions(+) create mode 100644 .github/workflows/ci.yaml create mode 100644 .github/workflows/dev-deploy.yaml diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml new file mode 100644 index 0000000..cff491a --- /dev/null +++ b/.github/workflows/ci.yaml @@ -0,0 +1,80 @@ +name: CI # dev로 머지되기 전에 테스트로 검증하는 워크플로 + +on: + pull_request: + branches: [ "dev" ] # dev를 대상으로 하는 PR에서 실행 + +permissions: + contents: read # 오직 읽기 권한만 부여 + +jobs: + test: + runs-on: ubuntu-latest + + # @SpringBootTest가 뜨려면 DB와 Redis가 떠 있어야 한다. + # runner의 localhost로 포트가 열려 application-local.yaml(Redis localhost:6379)과 아래 DB_URL에 그대로 맞는다. + services: + mysql: + image: mysql:8.0 # 잠금/격리 수준 동작이 버전에 따라 달라 로컬과 같은 버전으로 고정 + env: + MYSQL_ROOT_PASSWORD: root + MYSQL_DATABASE: sudam_test + ports: + - 3306:3306 + # 컨테이너가 떠도 MySQL이 접속을 받기까지는 시간이 걸리므로 준비될 때까지 기다린다 + options: >- + --health-cmd="mysqladmin ping -h 127.0.0.1 -uroot -proot" + --health-interval=10s + --health-timeout=5s + --health-retries=10 + + redis: + image: redis:7-alpine + ports: + - 6379:6379 + options: >- + --health-cmd="redis-cli ping" + --health-interval=10s + --health-timeout=5s + --health-retries=10 + + # .env는 저장소에 없으므로(gitignore) 플레이스홀더를 채울 값을 직접 넣는다. + # 전부 테스트 전용 더미이며 운영 값과 무관하다. + env: + DB_URL: jdbc:mysql://localhost:3306/sudam_test + DB_USERNAME: root + DB_PASSWORD: root + JWT_SECRET: ci-dummy-jwt-secret-key-not-for-production-use + KAKAO_CLIENT_ID: ci-dummy-kakao-client-id + KAKAO_CLIENT_SECRET: ci-dummy-kakao-client-secret + # Base64로 인코딩한 32바이트여야 기동된다 (AccountNumberConverter가 기동 시 길이를 검사) + ACCOUNT_ENCRYPTION_KEY: Y2ktZHVtbXktYWNjb3VudC1lbmNyeXB0aW9uLWtleSE= + + steps: + # PR의 소스 코드를 runner 머신 (여기서는 ubuntu-latest)으로 내려받는다. + - name: Checkout source code + uses: actions/checkout@v7 + + # 프로젝트를 빌드하고 테스트할 수 있도록 JDK 21을 설치한다. + - name: Set up JDK 21 + uses: actions/setup-java@v6 + with: + java-version: '21' + distribution: 'temurin' + + # 실행 환경을 준비하고 의존성 캐시를 설정해 다음 실행부터 빌드를 빠르게 한다. + - name: Set up Gradle + uses: gradle/actions/setup-gradle@v6 + + # 유닛 테스트와 통합 테스트를 포함한 전체 테스트를 실행해 PR 코드를 검증한다. + - name: Run tests + run: ./gradlew test + + # 테스트가 실패했을 경우 HTML 테스트 리포트를 아티팩트로 올려 7일간 내려받아 볼 수 있게 한다. + - name: Upload test report + if: failure() + uses: actions/upload-artifact@v4 + with: + name: test-report + path: build/reports/tests/test + retention-days: 7 \ No newline at end of file diff --git a/.github/workflows/dev-deploy.yaml b/.github/workflows/dev-deploy.yaml new file mode 100644 index 0000000..a3bb6c6 --- /dev/null +++ b/.github/workflows/dev-deploy.yaml @@ -0,0 +1,116 @@ +name: Deploy (dev) # dev 반영된 코드를 EC2에 배포하는 워크플로 + +# 테스트 검증은 PR 단계의 ci.yaml이 담당하므로 여기서는 빌드와 배포만 한다. +on: + push: + branches: [ "dev" ] # 직접 push와 PR 머지 모두 push 이벤트로 실행된다 + +# 워크 플로에 코드 읽기 권한만 부여 (최소 권한) +permissions: + contents: read + +# 배포를 한 번에 하나씩 순서대로 실행한다. 연달아 머지해도 이전 커밋이 나중에 올라가지 않는다. +concurrency: + group: dev-deploy + cancel-in-progress: false + +# 모든 job에서 공유하는 값 (태그에 커밋 SHA를 넣어 배포 버전 추적) +env: + IMAGE_NAME: ${{ vars.DOCKER_IMAGE_NAME }} + IMAGE_TAG: dev-${{ github.sha }} + +jobs: + # 1단계: 애플리케이션 빌드 후 Docker 이미지를 Docker Hub에 push + build-and-push: + runs-on: ubuntu-latest + steps: + # 저장소 코드를 runner로 가져옴 + - name: Checkout source code + uses: actions/checkout@v7 + + # JDK 21 설치 + - name: Set up JDK 21 + uses: actions/setup-java@v6 + with: + java-version: '21' + distribution: 'temurin' + + # Gradle 실행 환경 구성 + 의존성 캐싱 + - name: Set up Gradle + uses: gradle/actions/setup-gradle@v6 + + # 실행 가능한 Spring Boot jar 생성 + - name: Build with Gradle + run: ./gradlew bootJar + + # Secrets에 저장한 계정으로 Docker Hub 로그인 + - name: Login to Docker Hub + uses: docker/login-action@v4 + with: + username: ${{ secrets.DOCKER_USERNAME }} + password: ${{ secrets.DOCKER_PASSWORD }} + + # Dockerfile로 이미지를 만들고 Docker Hub에 업로드 + - name: Build and push image + run: | + docker build -t "$IMAGE_NAME:$IMAGE_TAG" . + docker push "$IMAGE_NAME:$IMAGE_TAG" + + # 2단계: EC2에 접속해 새 이미지로 컨테이너 교체 + deploy: + needs: build-and-push # build-and-push가 성공해야 실행 + runs-on: ubuntu-latest + steps: + + # 아래 scp 단계를 위해서 코드를 가져온다. + - name: Checkout source code + uses: actions/checkout@v7 + + # EC2에 compose 파일 복사 + - name: Copy compose files to EC2 + uses: appleboy/scp-action@v1 + with: + host: ${{ secrets.EC2_HOST }} + username: ubuntu + key: ${{ secrets.EC2_KEY }} + source: "docker-compose.yaml" + target: "/home/ubuntu/app" + + # EC2에서 애플리케이션 실행 + - name: Deploy to EC2 + uses: appleboy/ssh-action@v1 + env: + ENV_VARS: ${{ secrets.ENV_VARS }} + DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }} + DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }} + with: + host: ${{ secrets.EC2_HOST }} + username: ubuntu + key: ${{ secrets.EC2_KEY }} + # 지정한 환경변수를 EC2 쪽 스크립트로 전달 + envs: ENV_VARS,IMAGE_NAME,IMAGE_TAG,DOCKER_USERNAME,DOCKER_PASSWORD + script: | + + # 명령이 하나라도 실패하면 즉시 중단 + set -e + + # 애플리케이션 배포 디렉토리로 이동 + cd /home/ubuntu/app + + # 애플리케이션 실행에 필요한 환경변수 파일을 생성 (비밀 값이므로 소유자만 읽도록 600) + umask 077 + printf '%s\n' "$ENV_VARS" > .env + chmod 600 .env + + # Docker Hub 저장소가 private이어도 pull할 수 있도록 로그인 (DOCKER_PASSWORD는 읽기 전용 액세스 토큰 권장) + echo "$DOCKER_PASSWORD" | docker login -u "$DOCKER_USERNAME" --password-stdin + + # 새 이미지 pull. 실패해도 인증 정보가 EC2(~/.docker/config.json)에 남지 않게 로그아웃한다 + docker compose pull spring-app || { docker logout; exit 1; } + docker logout + + # 변경된 이미지로 컨테이너 교체 + docker compose up -d + + # 사용하지 않는 이전 이미지 정리 + docker image prune -af \ No newline at end of file From 719e00b64ad57713bf1caac78937b434d29a50c7 Mon Sep 17 00:00:00 2001 From: kkangmen Date: Sat, 14 Nov 2026 17:07:23 +0900 Subject: [PATCH 6/7] =?UTF-8?q?docs:=20CORS=20=C2=B7=20=EC=BF=A0=ED=82=A4?= =?UTF-8?q?=20Secure=20=EC=84=A4=EC=A0=95=EC=9D=84=20=EB=B3=B4=EC=95=88=20?= =?UTF-8?q?=EA=B7=9C=EC=B9=99=EA=B3=BC=20=EB=AC=B8=EC=84=9C=EC=97=90=20?= =?UTF-8?q?=EB=B0=98=EC=98=81=20(#32)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 --- .claude/rules/security-convention.md | 5 +++-- docs/api-spec.md | 2 +- docs/architecture.md | 3 +-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.claude/rules/security-convention.md b/.claude/rules/security-convention.md index 38e8918..e4581e9 100644 --- a/.claude/rules/security-convention.md +++ b/.claude/rules/security-convention.md @@ -13,6 +13,7 @@ paths: `SecurityConfig`의 단일 `SecurityFilterChain`: - `csrf`, `httpBasic`, `formLogin` 비활성화. 세션은 `SessionCreationPolicy.STATELESS`. +- CORS는 `corsConfigurationSource` 빈으로 켠다. 허용 출처는 프로파일별 `app.cors.allowed-origins`(개발 서버는 `FRONT_BASE_URL` + 로컬 프론트)에서 읽고, RT 쿠키를 주고받아야 해서 자격 증명을 허용한다(출처에 `*` 불가). 허용 헤더는 `Authorization` · `Content-Type`. - `allowUris`(`/oauth2/**`, `/login/**`, `/api/v1/auth/reissue`, Swagger 경로 `/swagger-ui/**`·`/swagger-ui.html`·`/v3/api-docs/**`)만 `permitAll`, 나머지는 `authenticated`. 재발급은 AT가 만료된 상태로 호출되므로 인증을 걸 수 없고, 인증 주체가 RT 쿠키다. - `oauth2Login`에 `CustomOAuth2UserService`(userInfo) + `OAuth2LoginSuccessHandler` + `OAuth2LoginFailureHandler`를 연결. - `JwtAuthenticationFilter`를 `UsernamePasswordAuthenticationFilter` 앞에 등록(빈이 아니라 `new`로 만들어 `JwtUtil`·`TokenStore`를 넘긴다). `exceptionHandling`에 `CustomAuthenticationEntryPoint`(401) + `CustomAccessDeniedHandler`(403) 연결. @@ -62,10 +63,10 @@ paths: ## 남아 있는 TODO (건드릴 때 함께 처리) -- RT 쿠키가 로컬 기준(`secure` 없음 / `SameSite=Lax`)이다. HTTPS·다른 도메인으로 배포하면 `CookieUtil`에서 `secure(true)` / `sameSite("None")`으로 바꿔야 한다. +- RT 쿠키는 `SameSite=Lax` 고정이고 `Secure`만 프로파일별 `app.cookie.secure`를 따른다(로컬 false, 개발 서버 true). 프론트(`sudam.app`)와 API(`api.sudam.app`)가 같은 사이트라 Lax로 충분하다. 프론트를 **다른 사이트**(다른 등록 도메인)로 옮기면 `sameSite("None")`으로 바꿔야 한다. - 다중 기기 로그인을 지원하지 않는다. `rt:{userId}`가 회원당 1개라 두 번째 로그인이 첫 번째 세션의 RT를 무효화한다. 기기별로 두려면 키를 `rt:{userId}:{deviceId}`로 바꿔야 한다. - 로그아웃·탈퇴는 **요청에 쓰인 AT 하나만** 차단한다. 다른 기기의 AT가 살아 있다면 만료(최대 30분)까지 유효하다. - AT 없이 RT 쿠키만으로 로그아웃하는 경로가 없다. AT가 만료됐으면 재발급 후 로그아웃해야 한다. - 탈퇴 시 카카오 연결 끊기(unlink)를 호출하지 않는다 (ERD 1.2.3). 넣을 때는 외부 API 호출이므로 트랜잭션 밖에서 처리한다. - 탈퇴가 `users` 행만 정리한다. 연락처가 담긴 다른 테이블(`tutoring_drafts` 등)은 해당 도메인이 생길 때 함께 처리한다. -- CORS 설정이 없다. 프론트를 다른 도메인에 배포하면 `SecurityConfig`에 추가해야 한다. +- 프론트 출처가 늘거나 바뀌면 `SecurityConfig`가 아니라 프로파일 yaml의 `app.cors.allowed-origins`를 고친다. 새 요청 헤더를 쓰게 되면 `corsConfigurationSource`의 허용 헤더에 추가한다. diff --git a/docs/api-spec.md b/docs/api-spec.md index 1a26fd3..c6e9a9a 100644 --- a/docs/api-spec.md +++ b/docs/api-spec.md @@ -99,7 +99,7 @@ | `POST` | `/api/v1/auth/logout` | 로그아웃 | **카카오 콜백** — 필수 동의: `profile_nickname`, `account_email` (누락 시 `AUTH401_1`). 리다이렉트 대상은 `app.oauth2.success-redirect-uri` / `failure-redirect-uri`. -- 성공: `302 {성공 URI}#accessToken={AT}` + `Set-Cookie: refreshToken={RT}; Path=/; Max-Age=1209600; HttpOnly; SameSite=Lax` +- 성공: `302 {성공 URI}#accessToken={AT}` + `Set-Cookie: refreshToken={RT}; Path=/; Max-Age=1209600; HttpOnly; SameSite=Lax` (개발 서버는 `Secure` 추가) - 실패: `302 {실패 URI}#code={에러 코드}` **인증 필터** — 서명 · 만료 · `typ=access` 확인 후 `jti`가 Redis 차단 목록(`bl:{jti}`)에 있는지 본다. AT 30분 / RT 14일. diff --git a/docs/architecture.md b/docs/architecture.md index 9de132d..94d136a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -161,7 +161,6 @@ GET /api/v1/users/me/settings profile · provider만 DB 값, 소개서 - 다중 기기 로그인 — `rt:{userId}`가 회원당 1개라 두 번째 로그인이 첫 세션을 끊는다. - 탈퇴 보강 — 카카오 unlink, 재가입 제한, 타 도메인 연락처 정리. -- 운영 프로파일 — `application-prod.yaml`, `ddl-auto` 전략, 마이그레이션 도구, 쿠키 `secure` / `SameSite=None` 전환. -- CORS — `SecurityConfig`에 설정 없음. +- 운영 프로파일 — `application-prod.yaml`, `ddl-auto` 전략, 마이그레이션 도구. 개발 서버는 `application-dev.yaml`(`ddl-auto: update`, 쿠키 `Secure`, 도메인 기준 리다이렉트 · CORS 출처)을 쓴다. - ERD의 생성 컬럼 + 유일 제약 — `ddl-auto`로 만들 수 없어 마이그레이션 도구 도입 전까지 서비스에서 보장한다. - 과외 · 참여자 · 교육비 API — 엔티티만 있고 컨트롤러 · 서비스는 아직 없다. 정산은 수업 기록 저장이 같은 트랜잭션에서 실행한다 (`RecordService` → `SettlementService.settleIfReached`). From cf6bfc5153666f8b4effc8b92563eea25bb5132d Mon Sep 17 00:00:00 2001 From: kkangmen Date: Sat, 14 Nov 2026 17:11:33 +0900 Subject: [PATCH 7/7] =?UTF-8?q?chore:=20gradlew=20=EC=8B=A4=ED=96=89=20?= =?UTF-8?q?=EA=B6=8C=ED=95=9C=20=EB=B6=80=EC=97=AC=20(#32)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 --- gradlew | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 gradlew diff --git a/gradlew b/gradlew old mode 100644 new mode 100755