diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 00000000..b2d92d30 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,20 @@ +# 팀원 이름 +# 박시윤 @siiiirru +# 한동연 @1dyn +# 양정모 @kaiju782 +# 서예은 @michelle259 +# 조성민 @csm123455 +# 조성욱 @KingZuto + +# 특정 디렉토리 오너 +/backend/auth/ @1dyn +/backend/config/ @KingZuto +/backend/gateway/ @siiiirru +/backend/recommend/ @michelle259 +/backend/review/ @csm123455 +/backend/schedule/ @kaiju782 + + + +# 특정 파일 오너 +# /.github/workflows/deploy.yml @devops-lead diff --git a/.github/workflows/backend-ci-cd.yaml b/.github/workflows/backend-ci-cd.yaml new file mode 100644 index 00000000..1fda21b7 --- /dev/null +++ b/.github/workflows/backend-ci-cd.yaml @@ -0,0 +1,167 @@ +name: Backend CI/CD + +on: + push: + branches: + - dev + paths: + - 'backend/**' + +permissions: + contents: write + id-token: write + +jobs: + detect-changes: + runs-on: ubuntu-latest + outputs: + services: ${{ steps.detect.outputs.services }} + commit_hash: ${{ steps.hash.outputs.commit_hash }} + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Detect changed services + id: detect + run: | + git fetch origin dev + CHANGED=$(git diff --name-only ${{ github.event.before }} ${{ github.sha }} | grep '^backend/' | cut -d '/' -f2 | sort | uniq | jq -R -s -c 'split("\n") | map(select(. != ""))') + echo "services=$CHANGED" >> $GITHUB_OUTPUT + + - name: Get short git commit hash + id: hash + run: echo "commit_hash=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT + + build-and-push: + needs: detect-changes + runs-on: ubuntu-latest + if: ${{ fromJson(needs.detect-changes.outputs.services) != '[]' }} + strategy: + matrix: + service: ${{ fromJson(needs.detect-changes.outputs.services) }} + fail-fast: false + env: + IMAGE_TAG: ${{ needs.detect-changes.outputs.commit_hash }} + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up JDK 17 + uses: actions/setup-java@v4 + with: + java-version: '17' + distribution: 'temurin' + cache: maven + + - name: Configure AWS credentials + uses: aws-actions/configure-aws-credentials@v4 + with: + role-to-assume: arn:aws:iam::${{ secrets.AWS_ACCOUNT_ID }}:role/mapzip-dev-GitHubActionsOIDCRole + role-session-name: GitHub_to_AWS_via_FederatedOIDC + aws-region: ap-northeast-2 + + - name: Login to Amazon ECR Private + id: login-ecr-private + uses: aws-actions/amazon-ecr-login@v2 + + - name: Build and push Docker image + id: build + env: + REGISTRY: ${{ steps.login-ecr-private.outputs.registry }} + run: | + SERVICE="${{ matrix.service }}" + echo "Building and pushing $SERVICE" + + cd "./backend/$SERVICE" || exit 1 + mvn -B package -DskipTests --file pom.xml + mv ./target/*.jar ./target/app.jar + cd - || exit 1 + + docker build -t "$REGISTRY/mapzip-dev-ecr-$SERVICE:$IMAGE_TAG" "./backend/$SERVICE" + docker push "$REGISTRY/mapzip-dev-ecr-$SERVICE:$IMAGE_TAG" + + - name: Save successful service name + if: success() + run: | + mkdir -p success + echo "${{ matrix.service }}" > "success/${{ matrix.service }}.txt" + + - name: Upload success list + if: success() + uses: actions/upload-artifact@v4 + with: + name: successful-service-${{ matrix.service }} + path: success/${{ matrix.service }}.txt + + update-argocd-yaml: + needs: + - detect-changes + - build-and-push + runs-on: ubuntu-latest + if: ${{ fromJson(needs.detect-changes.outputs.services) != '[]' }} + steps: + - name: Download all success artifacts + uses: actions/download-artifact@v4 + with: + pattern: successful-service-* + path: ./services + merge-multiple: true + + - name: Read success list + id: get-success + run: | + SUCCESS_SERVICES="" + if [ -d "./services" ]; then + for file in ./services/*.txt; do + if [ -f "$file" ]; then + SERVICE=$(basename "$file" .txt) + SUCCESS_SERVICES="$SUCCESS_SERVICES $SERVICE" + fi + done + fi + echo "success_services=$(echo $SUCCESS_SERVICES | xargs)" >> $GITHUB_OUTPUT + + - name: Checkout Infra repo + uses: actions/checkout@v4 + with: + repository: CLD3rd-Team4/Infra + ref: dev + token: ${{ secrets.INFRA_PAT }} + path: infra + + - name: Update YAMLs with new image tags + env: + IMAGE_TAG: ${{ needs.detect-changes.outputs.commit_hash }} + run: | + INFRA_PATH="argocd" + git config --global user.name "github-actions" + git config --global user.email "github-actions@github.com" + cd infra + + for SERVICE_NAME in ${{ steps.get-success.outputs.success_services }}; do + echo "Updating image tag for service: $SERVICE_NAME" + + if [[ "$SERVICE_NAME" == "auth" || "$SERVICE_NAME" == "gateway" || "$SERVICE_NAME" == "config" ]]; then + SERVICE_DIR="$INFRA_PATH/platform" + else + SERVICE_DIR="$INFRA_PATH/service-$SERVICE_NAME" + fi + + FILE_NAME="${SERVICE_NAME#service-}.yaml" + YAML_FILE="$SERVICE_DIR/$FILE_NAME" + + if [ ! -f "$YAML_FILE" ]; then + echo "Warning: YAML file not found: $YAML_FILE" + continue + fi + + sed -i -E "/containers:/,/(^[[:space:]]*[^-[:space:]]|^$)/ s|(image:[[:space:]]*[^[:space:]]+:)[^[:space:]]+|\1$IMAGE_TAG|" "$YAML_FILE" + + git add "$YAML_FILE" + git commit -m "Update $SERVICE_NAME image tag to $IMAGE_TAG [ci skip]" || echo "No changes to commit for $SERVICE_NAME" + done + + git push origin dev + \ No newline at end of file diff --git a/.github/workflows/config-ci-cd.yaml b/.github/workflows/config-ci-cd.yaml new file mode 100644 index 00000000..59687886 --- /dev/null +++ b/.github/workflows/config-ci-cd.yaml @@ -0,0 +1,124 @@ +name: Config CI/CD + +on: + push: + branches: + - dev + paths: + - 'config-repo/**' + +permissions: + id-token: write + contents: read + +jobs: + detect-config-changes: + runs-on: ubuntu-latest + outputs: + services: ${{ steps.detect.outputs.services }} + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Detect changed config services + id: detect + run: | + git fetch origin dev + + # Backend 변경사항도 확인 (중복 재시작 방지) + BACKEND_CHANGED=$(git diff --name-only ${{ github.event.before }} ${{ github.sha }} | grep '^backend/' | cut -d '/' -f2 | sort | uniq) + + # config-repo/application.yml 변경 확인 + APPLICATION_CHANGED=$(git diff --name-only ${{ github.event.before }} ${{ github.sha }} | grep '^config-repo/application\.yml$' | wc -l) + + # config-repo/ 폴더에서 변경된 개별 설정 파일들 찾기 + CONFIG_SERVICES=$(git diff --name-only ${{ github.event.before }} ${{ github.sha }} | grep '^config-repo/.*\.yml$' | grep -v '^config-repo/application\.yml$' | sed 's|config-repo/||g' | sed 's|\.yml||g' | sort | uniq) + + # application.yml이 바뀌면 모든 서비스 재시작 + if [ "$APPLICATION_CHANGED" -gt 0 ]; then + ALL_SERVICES="auth gateway schedule recommend review" + else + # 그렇지 않으면 변경된 서비스들만 + ALL_SERVICES="$CONFIG_SERVICES" + fi + + # Backend에서 변경된 서비스는 제외 (ArgoCD가 자동 재배포하므로) + FILTERED_SERVICES="" + for service in $ALL_SERVICES; do + if ! echo "$BACKEND_CHANGED" | grep -q "^$service$"; then + FILTERED_SERVICES="$FILTERED_SERVICES $service" + else + echo "⏭️ Skipping $service restart (backend changed - ArgoCD will handle deployment)" + fi + done + + # JSON 배열로 변환 + CHANGED=$(echo "$FILTERED_SERVICES" | tr ' ' '\n' | sort | uniq | jq -R -s -c 'split("\n") | map(select(. != ""))') + echo "services=$CHANGED" >> $GITHUB_OUTPUT + echo "🔄 Services to restart: $FILTERED_SERVICES" + + restart-services: + needs: detect-config-changes + runs-on: ubuntu-latest + if: ${{ fromJson(needs.detect-config-changes.outputs.services) != '[]' }} + strategy: + matrix: + service: ${{ fromJson(needs.detect-config-changes.outputs.services) }} + fail-fast: false + steps: + - name: Configure AWS credentials + uses: aws-actions/configure-aws-credentials@v4 + with: + role-to-assume: arn:aws:iam::${{ secrets.AWS_ACCOUNT_ID }}:role/mapzip-dev-GitHubActionsOIDCRole + role-session-name: GitHub_to_AWS_via_FederatedOIDC + aws-region: ap-northeast-2 + + - name: Install kubectl + run: | + curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl" + chmod +x kubectl + sudo mv kubectl /usr/local/bin/ + + - name: Configure kubectl + run: | + aws eks update-kubeconfig --region ap-northeast-2 --name mapzip-dev-eks + + - name: Restart ${{ matrix.service }} service + run: | + SERVICE="${{ matrix.service }}" + echo "🔄 Restarting $SERVICE service (config-only change)..." + + # 서비스별 deployment 이름과 네임스페이스 매핑 + case $SERVICE in + "auth") + DEPLOYMENT="auth-deployment" + NAMESPACE="service-platform" + ;; + "gateway") + DEPLOYMENT="spring-gateway-deployment" + NAMESPACE="service-platform" + ;; + "schedule") + DEPLOYMENT="schedule-deployment" + NAMESPACE="service-schedule" + ;; + "recommend") + DEPLOYMENT="recommend-deployment" + NAMESPACE="service-recommend" + ;; + "review") + DEPLOYMENT="review-deployment" + NAMESPACE="service-review" + ;; + *) + echo "❌ Unknown service: $SERVICE" + exit 1 + ;; + esac + + kubectl rollout restart deployment/$DEPLOYMENT -n $NAMESPACE + kubectl rollout status deployment/$DEPLOYMENT -n $NAMESPACE --timeout=300s + + echo "✅ $SERVICE service restarted successfully in $NAMESPACE namespace" diff --git a/.github/workflows/frontend-ci-cd.yaml b/.github/workflows/frontend-ci-cd.yaml new file mode 100644 index 00000000..ae84f171 --- /dev/null +++ b/.github/workflows/frontend-ci-cd.yaml @@ -0,0 +1,77 @@ +name: frontend CI/CD + +on: + push: + branches: + - dev + paths: + - 'frontend/**' + + + +permissions: + id-token: write + contents: read + +jobs: + ci: + runs-on: ubuntu-latest + + steps: + - name: Checkout source code + uses: actions/checkout@v3 + + - name: Setup Node + uses: actions/setup-node@v3 + with: + node-version: '18' + cache: 'npm' + cache-dependency-path: 'frontend/package-lock.json' + + - name: Install dependencies + run: | + cd frontend + npm ci + + - name: Build Next.js app + run: | + cd frontend + npm run build + env: + NEXT_PUBLIC_API_BASE_URL: ${{ secrets.NEXT_PUBLIC_API_BASE_URL }} + NEXT_PUBLIC_KAKAO_MAP_KEY: ${{ secrets.KAKAO_MAP_KEY }} + + + - name: Upload build artifact + uses: actions/upload-artifact@v4 + with: + name: build-files + path: frontend/out/ + include-hidden-files: true + + cd: + needs: ci + runs-on: ubuntu-latest + steps: + - name: Download build artifact + uses: actions/download-artifact@v4 + with: + name: build-files + path: out/ + + - name: Configure AWS credentials + uses: aws-actions/configure-aws-credentials@v4 + with: + role-to-assume: arn:aws:iam::${{ secrets.AWS_ACCOUNT_ID }}:role/mapzip-dev-GitHubActionsOIDCRole + role-session-name: GitHub_to_AWS_via_FederatedOIDC + aws-region: ap-northeast-2 + + - name: Upload to S3 using AWS CLI + run: | + aws s3 sync ./out s3://${{ secrets.S3_BUCKET_NAME }} --delete + + - name: Invalidate CloudFront cache + run: | + aws cloudfront create-invalidation \ + --distribution-id ${{ secrets.AWS_CLOUDFRONT_DISTRIBUTION_ID }} \ + --paths "/*" diff --git a/.github/workflows/pb-filter-ci-cd.yaml b/.github/workflows/pb-filter-ci-cd.yaml new file mode 100644 index 00000000..921ed404 --- /dev/null +++ b/.github/workflows/pb-filter-ci-cd.yaml @@ -0,0 +1,121 @@ +name: pb filter CI/CD + +on: + push: + branches: + - dev + paths: + - 'backend/**/**_proto.pb' + +permissions: + contents: write + id-token: write + +jobs: + build-pb-image: + runs-on: ubuntu-latest + outputs: + short_sha: ${{ steps.vars.outputs.short_sha }} + changed_services: ${{ steps.servers.outputs.changed_services }} + + steps: + - name: Checkout code + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Configure AWS credentials + uses: aws-actions/configure-aws-credentials@v4 + with: + role-to-assume: arn:aws:iam::${{ secrets.AWS_ACCOUNT_ID }}:role/mapzip-dev-GitHubActionsOIDCRole + role-session-name: GitHub_to_AWS_via_FederatedOIDC + aws-region: ap-northeast-2 + + - name: Login to Amazon ECR Private + id: login-ecr-private + uses: aws-actions/amazon-ecr-login@v2 + + - name: Get short SHA + id: vars + run: echo "short_sha=${GITHUB_SHA::7}" >> $GITHUB_OUTPUT + + - name: Extract changed server names + id: servers + run: | + BASE_SHA="${{ github.event.before }}" + if [ -z "$BASE_SHA" ]; then + BASE_SHA="HEAD~1" + fi + + echo "🔍 BASE_SHA: $BASE_SHA" + echo "🔍 CURRENT_SHA: ${{ github.sha }}" + + SERVER_NAMES=$(git diff --name-only $BASE_SHA ${{ github.sha }} | grep '_proto.pb' | awk -F '/' '{print $2}' | sort -u | xargs) + echo "changed_services=$SERVER_NAMES" >> $GITHUB_OUTPUT + echo "🔧 Changed services: $SERVER_NAMES" + + - name: Copy all .pb files + run: | + mkdir -p pb-files + find backend -name "*_proto.pb" -exec cp {} pb-files/ \; + + - name: Create Dockerfile + run: | + echo 'FROM busybox:1.36' > pb-files/Dockerfile + for f in pb-files/*_proto.pb; do + echo "COPY $(basename "$f") /data/" >> pb-files/Dockerfile + done + echo 'CMD ["sleep", "3600"]' >> pb-files/Dockerfile + + - name: Build Docker image + env: + REGISTRY: ${{ steps.login-ecr-private.outputs.registry }} + IMAGE_TAG: ${{ steps.vars.outputs.short_sha }} + run: | + docker build -t "$REGISTRY/mapzip-dev-ecr-pb:$IMAGE_TAG" "pb-files" + docker push "$REGISTRY/mapzip-dev-ecr-pb:$IMAGE_TAG" + + + change-infra-yaml: + needs: build-pb-image + runs-on: ubuntu-latest + + steps: + - name: Checkout infra repository + uses: actions/checkout@v3 + with: + repository: CLD3rd-Team4/Infra + ref: dev + token: ${{ secrets.INFRA_PAT }} + + - name: Install yq + run: | + sudo wget https://github.com/mikefarah/yq/releases/download/v4.43.1/yq_linux_amd64 -O /usr/local/bin/yq + sudo chmod +x /usr/local/bin/yq + + - name: Patch ArgoCD YAML files + env: + SHORT_SHA: ${{ needs.build-pb-image.outputs.short_sha }} + SERVICES: ${{ needs.build-pb-image.outputs.changed_services }} + run: | + for srv in $SERVICES; do + YAML_FILE="argocd/service-$srv/$srv.yaml" + if [ -f "$YAML_FILE" ]; then + echo "🔧 패치 중: $YAML_FILE" + + export IMAGE="061039804626.dkr.ecr.ap-northeast-2.amazonaws.com/mapzip-dev-ecr-pb:$SHORT_SHA" + + yq eval ' + (select(.kind == "Deployment").spec.template.spec.initContainers[] | select(.name == "copy-pb")).image = strenv(IMAGE) + ' -i "$YAML_FILE" + else + echo "⚠️ 파일 없음: $YAML_FILE" + fi + done + + - name: Commit and push changes + run: | + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + git add argocd/ + git commit -m "ci: update initContainer image" && git push || echo "No changes to commit" diff --git a/.gitignore b/.gitignore index 9d40b281..9bbf2287 100644 --- a/.gitignore +++ b/.gitignore @@ -72,6 +72,8 @@ local.properties # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 # User-specific stuff +**/.idea/ + .idea/**/workspace.xml .idea/**/tasks.xml .idea/**/usage.statistics.xml @@ -281,6 +283,15 @@ sketch !.vscode/extensions.json !.vscode/*.code-snippets +### Build output ### +.next/ +dist/ +out/ + +### Env files ### +.env +.env.* + # Local History for Visual Studio Code .history/ @@ -318,4 +329,11 @@ $RECYCLE.BIN/ # Windows shortcuts *.lnk +**/application.properties # End of https://www.toptal.com/developers/gitignore/api/java,macos,windows,intellij,react,maven,eclipse,visualstudiocode + +**/googleapis/ +target/ +build/ +.gradle/ + diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..f582a1f6 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "java.configuration.updateBuildConfiguration": "disabled" +} \ No newline at end of file diff --git a/backend/auth/.gitattributes b/backend/auth/.gitattributes new file mode 100644 index 00000000..3b41682a --- /dev/null +++ b/backend/auth/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/backend/auth/.mvn/wrapper/maven-wrapper.properties b/backend/auth/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..12fbe1e9 --- /dev/null +++ b/backend/auth/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.11/apache-maven-3.9.11-bin.zip diff --git a/backend/auth/Dockerfile b/backend/auth/Dockerfile new file mode 100644 index 00000000..b51c7cf4 --- /dev/null +++ b/backend/auth/Dockerfile @@ -0,0 +1,4 @@ +FROM openjdk:17-jdk-slim +ARG JAR_FILE=target/*.jar +COPY ${JAR_FILE} app.jar +ENTRYPOINT ["java", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/app.jar"] diff --git a/backend/auth/mvnw b/backend/auth/mvnw new file mode 100644 index 00000000..19529ddf --- /dev/null +++ b/backend/auth/mvnw @@ -0,0 +1,259 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.2 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + 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" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/backend/auth/mvnw.cmd b/backend/auth/mvnw.cmd new file mode 100644 index 00000000..249bdf38 --- /dev/null +++ b/backend/auth/mvnw.cmd @@ -0,0 +1,149 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.2 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' +$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/backend/auth/pom.xml b/backend/auth/pom.xml new file mode 100644 index 00000000..78768e8c --- /dev/null +++ b/backend/auth/pom.xml @@ -0,0 +1,162 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 3.5.3 + + + + com.mapzip.auth + auth-service + 0.0.1-SNAPSHOT + jar + auth-service + Spring Cloud 기반 인증 서버 + + + 17 + 2025.0.0 + + + + + + org.springframework.boot + spring-boot-starter-web + + + + + org.springframework.boot + spring-boot-starter-security + + + + + org.springframework.security + spring-security-oauth2-authorization-server + 1.4.1 + + + + org.springframework.cloud + spring-cloud-starter-config + + + + + org.springframework.boot + spring-boot-starter-actuator + + + + + io.micrometer + micrometer-registry-prometheus + + + + + org.springframework.cloud + spring-cloud-starter-bootstrap + + + + + org.projectlombok + lombok + 1.18.36 + provided + + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + + com.h2database + h2 + runtime + + + + + org.postgresql + postgresql + runtime + + + + org.springframework.boot + spring-boot-starter-webflux + + + + org.springframework.boot + spring-boot-starter-data-redis + + + + + org.springframework.security + spring-security-oauth2-core + + + + io.jsonwebtoken + jjwt-api + 0.11.5 + + + io.jsonwebtoken + jjwt-impl + 0.11.5 + runtime + + + io.jsonwebtoken + jjwt-jackson + 0.11.5 + runtime + + + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/backend/auth/src/main/java/com/mapzip/auth/auth_service/AuthServiceApplication.java b/backend/auth/src/main/java/com/mapzip/auth/auth_service/AuthServiceApplication.java new file mode 100644 index 00000000..eb6b14b3 --- /dev/null +++ b/backend/auth/src/main/java/com/mapzip/auth/auth_service/AuthServiceApplication.java @@ -0,0 +1,11 @@ +package com.mapzip.auth.auth_service; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class AuthServiceApplication { + public static void main(String[] args) { + SpringApplication.run(AuthServiceApplication.class, args); + } +} \ No newline at end of file diff --git a/backend/auth/src/main/java/com/mapzip/auth/auth_service/config/CorsConfig.java b/backend/auth/src/main/java/com/mapzip/auth/auth_service/config/CorsConfig.java new file mode 100644 index 00000000..56f998c5 --- /dev/null +++ b/backend/auth/src/main/java/com/mapzip/auth/auth_service/config/CorsConfig.java @@ -0,0 +1,23 @@ +//package com.mapzip.auth.auth_service.config; +// +//import org.springframework.context.annotation.Bean; +//import org.springframework.context.annotation.Configuration; +//import org.springframework.web.servlet.config.annotation.CorsRegistry; +//import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +// +//@Configuration +//public class CorsConfig { +// @Bean +// public WebMvcConfigurer corsConfigurer() { +// return new WebMvcConfigurer() { +// @Override +// public void addCorsMappings(CorsRegistry registry) { +// registry.addMapping("/**") +// .allowedOrigins("http://localhost:3000") +// .allowedMethods("*") +// .allowCredentials(true) +// .allowedHeaders("*"); +// } +// }; +// } +//} \ No newline at end of file diff --git a/backend/auth/src/main/java/com/mapzip/auth/auth_service/config/RedisConfig.java b/backend/auth/src/main/java/com/mapzip/auth/auth_service/config/RedisConfig.java new file mode 100644 index 00000000..1826b80c --- /dev/null +++ b/backend/auth/src/main/java/com/mapzip/auth/auth_service/config/RedisConfig.java @@ -0,0 +1,42 @@ +package com.mapzip.auth.auth_service.config; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.*; +import org.springframework.data.redis.connection.*; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.data.redis.core.*; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +@Configuration +public class RedisConfig { + + @Value("${spring.data.valkey.host}") + private String host; + + @Value("${spring.data.valkey.port}") + private int port; + + @Bean + public RedisConnectionFactory redisConnectionFactory() { + return new LettuceConnectionFactory(host, port); + } + + @Bean + public StringRedisTemplate stringRedisTemplate() { + StringRedisTemplate template = new StringRedisTemplate(); + template.setConnectionFactory(redisConnectionFactory()); + return template; + } + + @Bean + public RedisTemplate redisTemplate() { + RedisTemplate template = new RedisTemplate<>(); + template.setConnectionFactory(redisConnectionFactory()); + + // 직렬화 설정 + template.setKeySerializer(new StringRedisSerializer()); + template.setValueSerializer(new StringRedisSerializer()); + + return template; + } +} diff --git a/backend/auth/src/main/java/com/mapzip/auth/auth_service/config/SecurityConfig.java b/backend/auth/src/main/java/com/mapzip/auth/auth_service/config/SecurityConfig.java new file mode 100644 index 00000000..ffcc65e4 --- /dev/null +++ b/backend/auth/src/main/java/com/mapzip/auth/auth_service/config/SecurityConfig.java @@ -0,0 +1,83 @@ +package com.mapzip.auth.auth_service.config; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.config.Customizer; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.CorsConfigurationSource; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; +import org.springframework.web.reactive.function.client.WebClient; +import org.springframework.boot.actuate.web.exchanges.InMemoryHttpExchangeRepository; +import org.springframework.boot.actuate.web.exchanges.HttpExchangeRepository; + +import java.util.List; + +@Configuration +@RequiredArgsConstructor +@Slf4j +public class SecurityConfig { + + @Bean + public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { + return http + .csrf(csrf -> csrf.disable()) + .sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .cors(Customizer.withDefaults()) // CORS 활성화 + .authorizeHttpRequests(auth -> auth + // 프리플라이트는 전역 허용 + .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll() + // 카카오 콜백은 비인증 허용 + .requestMatchers(HttpMethod.POST, "/auth/kakao/callback").permitAll() + // 토큰 관련 엔드포인트(리프레시/로그아웃 등) + .requestMatchers("/auth/token/**").permitAll() + // 헬스체크 + .requestMatchers("/actuator/health/**", "/actuator/info").permitAll() + .anyRequest().authenticated() + ) + .build(); + } + + @Bean + public CorsConfigurationSource corsConfigurationSource() { + CorsConfiguration c = new CorsConfiguration(); + c.setAllowedOrigins(List.of( + "https://www.mapzip.shop", // dev + "http://localhost:3000" // 로컬 + )); + c.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS")); + c.setAllowedHeaders(List.of("*")); + c.setAllowCredentials(true); // 쿠키 전송 허용 + c.setMaxAge(3600L); + + UrlBasedCorsConfigurationSource s = new UrlBasedCorsConfigurationSource(); + s.registerCorsConfiguration("/**", c); + return s; + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + @Bean + public WebClient webClient(WebClient.Builder builder) { + return builder.build(); + } + + + + @Bean + public HttpExchangeRepository httpExchangeRepository() { + InMemoryHttpExchangeRepository repo = new InMemoryHttpExchangeRepository(); + repo.setCapacity(1000); // 보관 개수 + return repo; + } +} \ No newline at end of file diff --git a/backend/auth/src/main/java/com/mapzip/auth/auth_service/controller/UserController.java b/backend/auth/src/main/java/com/mapzip/auth/auth_service/controller/UserController.java new file mode 100644 index 00000000..61d833ea --- /dev/null +++ b/backend/auth/src/main/java/com/mapzip/auth/auth_service/controller/UserController.java @@ -0,0 +1,122 @@ +package com.mapzip.auth.auth_service.controller; + +import com.mapzip.auth.auth_service.dto.KakaoLoginRequestDto; +import com.mapzip.auth.auth_service.dto.RefreshTokenRequestDto; +import com.mapzip.auth.auth_service.dto.TokenResponseDto; +import com.mapzip.auth.auth_service.service.KakaoOAuthService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpHeaders; +import org.springframework.http.ResponseCookie; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.*; + +import java.time.Duration; +import java.util.HashMap; +import java.util.Map; + +@RestController +@RequestMapping("/auth") +@RequiredArgsConstructor +@Slf4j +public class UserController { + + private final KakaoOAuthService kakaoOAuthService; + + @PostMapping("/kakao/callback") + public ResponseEntity> handleKakaoCallback(@RequestParam String code) { + log.info("callback 요청 수신"); + TokenResponseDto token = kakaoOAuthService.loginWithKakao(code); + + // 쿠키 설정 + ResponseCookie accessTokenCookie = ResponseCookie.from("accessToken", token.getAccessToken()) + .httpOnly(true) + .secure(true) + .domain(".mapzip.shop") + .path("/") + .maxAge(Duration.ofDays(1)) + .sameSite("None") + .build(); + + // refreshToken 쿠키 설정 + ResponseCookie refreshTokenCookie = ResponseCookie.from("refreshToken", token.getRefreshToken()) + .httpOnly(true) + .secure(true) + .domain(".mapzip.shop") + .path("/auth/token") + .maxAge(Duration.ofDays(1)) + .sameSite("None") + .build(); + + Map response = new HashMap<>(); + response.put("message", "로그인 성공"); + + return ResponseEntity.ok() + .headers(headers -> { + headers.add(HttpHeaders.SET_COOKIE, accessTokenCookie.toString()); + headers.add(HttpHeaders.SET_COOKIE, refreshTokenCookie.toString()); + }) + .body(response); + } + + @GetMapping("/me/kakaoid") + public ResponseEntity getKakaoId( + @AuthenticationPrincipal(expression = "principal") String kakaoId + ) { + log.info("kakaoid 요청 수신"); + return ResponseEntity.ok("내 카카오 ID: " + kakaoId); + } + + // Refresh Token을 통한 Access Token 재발급 + @PostMapping("/token/refresh") + public ResponseEntity> refresh(@CookieValue("refreshToken") String refreshToken) { + log.info("refresh 요청 수신"); + TokenResponseDto token = kakaoOAuthService.reissueAccessToken(refreshToken); + + ResponseCookie access = ResponseCookie.from("accessToken", token.getAccessToken()) + .httpOnly(true) + .secure(true) + .domain(".mapzip.shop") + .path("/") + .maxAge(Duration.ofHours(1)) + .sameSite("None") + .build(); + + return ResponseEntity.ok() + .header(HttpHeaders.SET_COOKIE, access.toString()) + .body(Map.of("message", "토큰 재발급 완료")); + } + + @PostMapping("/token/logout") + public ResponseEntity logout(@CookieValue("refreshToken") String refreshToken) { + log.info("logout 요청 수신"); + + kakaoOAuthService.logout(refreshToken); // Redis에서 삭제 + + // access 쿠키 만료 + ResponseCookie expiredAccessToken = ResponseCookie.from("accessToken", "") + .httpOnly(true) + .secure(true) + .domain(".mapzip.shop") + .path("/") + .sameSite("None") + .maxAge(0) + .build(); + + // refresh 쿠키 만료 + ResponseCookie expiredRefreshToken = ResponseCookie.from("refreshToken", "") + .httpOnly(true) + .secure(true) + .domain(".mapzip.shop") + .path("/auth/token") + .sameSite("None") + .maxAge(0) + .build(); + + return ResponseEntity.noContent() + .header(HttpHeaders.SET_COOKIE, expiredAccessToken.toString()) + .header(HttpHeaders.SET_COOKIE, expiredRefreshToken.toString()) + .build(); + } +} diff --git a/backend/auth/src/main/java/com/mapzip/auth/auth_service/dto/ErrorResponse.java b/backend/auth/src/main/java/com/mapzip/auth/auth_service/dto/ErrorResponse.java new file mode 100644 index 00000000..560f873e --- /dev/null +++ b/backend/auth/src/main/java/com/mapzip/auth/auth_service/dto/ErrorResponse.java @@ -0,0 +1,9 @@ +package com.mapzip.auth.auth_service.dto; + +import lombok.*; + +@Getter +@AllArgsConstructor +public class ErrorResponse { + private String message; +} diff --git a/backend/auth/src/main/java/com/mapzip/auth/auth_service/dto/KakaoLoginRequestDto.java b/backend/auth/src/main/java/com/mapzip/auth/auth_service/dto/KakaoLoginRequestDto.java new file mode 100644 index 00000000..021e6568 --- /dev/null +++ b/backend/auth/src/main/java/com/mapzip/auth/auth_service/dto/KakaoLoginRequestDto.java @@ -0,0 +1,10 @@ +package com.mapzip.auth.auth_service.dto; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class KakaoLoginRequestDto { + private String code; // 프론트에서 받은 인가코드 +} diff --git a/backend/auth/src/main/java/com/mapzip/auth/auth_service/dto/KakaoUserInfo.java b/backend/auth/src/main/java/com/mapzip/auth/auth_service/dto/KakaoUserInfo.java new file mode 100644 index 00000000..ce34200c --- /dev/null +++ b/backend/auth/src/main/java/com/mapzip/auth/auth_service/dto/KakaoUserInfo.java @@ -0,0 +1,3 @@ +package com.mapzip.auth.auth_service.dto; + +public record KakaoUserInfo (Long kakaoId, String nickname) {} diff --git a/backend/auth/src/main/java/com/mapzip/auth/auth_service/dto/RefreshTokenRequestDto.java b/backend/auth/src/main/java/com/mapzip/auth/auth_service/dto/RefreshTokenRequestDto.java new file mode 100644 index 00000000..0a173f2d --- /dev/null +++ b/backend/auth/src/main/java/com/mapzip/auth/auth_service/dto/RefreshTokenRequestDto.java @@ -0,0 +1,8 @@ +package com.mapzip.auth.auth_service.dto; + +import lombok.Getter; + +@Getter +public class RefreshTokenRequestDto { + private String refreshToken; +} \ No newline at end of file diff --git a/backend/auth/src/main/java/com/mapzip/auth/auth_service/dto/TokenResponseDto.java b/backend/auth/src/main/java/com/mapzip/auth/auth_service/dto/TokenResponseDto.java new file mode 100644 index 00000000..507c3bff --- /dev/null +++ b/backend/auth/src/main/java/com/mapzip/auth/auth_service/dto/TokenResponseDto.java @@ -0,0 +1,11 @@ +package com.mapzip.auth.auth_service.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class TokenResponseDto { + private String accessToken; + private String refreshToken; +} diff --git a/backend/auth/src/main/java/com/mapzip/auth/auth_service/entity/AppUser.java b/backend/auth/src/main/java/com/mapzip/auth/auth_service/entity/AppUser.java new file mode 100644 index 00000000..e57190a5 --- /dev/null +++ b/backend/auth/src/main/java/com/mapzip/auth/auth_service/entity/AppUser.java @@ -0,0 +1,24 @@ +package com.mapzip.auth.auth_service.entity; + +import jakarta.persistence.*; +import lombok.*; + +@Entity +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class AppUser { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(unique = true, nullable = false) + private Long kakaoId; + + @Column(unique = true) + private String nickname; + +} diff --git a/backend/auth/src/main/java/com/mapzip/auth/auth_service/filter/JwtAuthenticationFilter.java b/backend/auth/src/main/java/com/mapzip/auth/auth_service/filter/JwtAuthenticationFilter.java new file mode 100644 index 00000000..45c91e7c --- /dev/null +++ b/backend/auth/src/main/java/com/mapzip/auth/auth_service/filter/JwtAuthenticationFilter.java @@ -0,0 +1,71 @@ +package com.mapzip.auth.auth_service.filter; + +import io.jsonwebtoken.*; +import jakarta.servlet.*; +import jakarta.servlet.http.*; +import lombok.RequiredArgsConstructor; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.jwt.JwtException; +import org.springframework.util.StringUtils; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; +import java.util.List; + +@RequiredArgsConstructor +public class JwtAuthenticationFilter extends OncePerRequestFilter { + + private final String jwtSecret; + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) + throws ServletException, IOException { + + String token = resolveToken(request); + + if (token != null && validateToken(token)) { + String kakaoId = getSubject(token); + + // SecurityContext에 인증 객체 주입 (필요 최소한만) + UsernamePasswordAuthenticationToken authentication = + new UsernamePasswordAuthenticationToken(kakaoId, null, List.of()); + SecurityContextHolder.getContext().setAuthentication(authentication); + } + + filterChain.doFilter(request, response); + } + + @Override + protected boolean shouldNotFilter(HttpServletRequest request) { + String path = request.getRequestURI(); + return path.startsWith("/auth/"); + } + + private String resolveToken(HttpServletRequest request) { + String bearer = request.getHeader("Authorization"); + if (StringUtils.hasText(bearer) && bearer.startsWith("Bearer ")) { + return bearer.substring(7); + } + return null; + } + + private boolean validateToken(String token) { + try { + Jwts.parser() + .setSigningKey(jwtSecret.getBytes()) + .parseClaimsJws(token); + return true; + } catch (JwtException | IllegalArgumentException e) { + return false; + } + } + + private String getSubject(String token) { + return Jwts.parser() + .setSigningKey(jwtSecret.getBytes()) + .parseClaimsJws(token) + .getBody() + .getSubject(); + } +} diff --git a/backend/auth/src/main/java/com/mapzip/auth/auth_service/handler/GlobalExceptionHandler.java b/backend/auth/src/main/java/com/mapzip/auth/auth_service/handler/GlobalExceptionHandler.java new file mode 100644 index 00000000..247e9545 --- /dev/null +++ b/backend/auth/src/main/java/com/mapzip/auth/auth_service/handler/GlobalExceptionHandler.java @@ -0,0 +1,25 @@ +package com.mapzip.auth.auth_service.handler; + +import com.mapzip.auth.auth_service.dto.ErrorResponse; +import org.springframework.http.*; +import org.springframework.web.bind.annotation.*; + +@RestControllerAdvice +public class GlobalExceptionHandler { + + @ExceptionHandler(IllegalArgumentException.class) + public ResponseEntity handleIllegalArgument(IllegalArgumentException ex) { + return ResponseEntity.badRequest().body(new ErrorResponse(ex.getMessage())); + } + + @ExceptionHandler(IllegalStateException.class) + public ResponseEntity handleIllegalState(IllegalStateException ex) { + return ResponseEntity.badRequest().body(new ErrorResponse(ex.getMessage())); + } + + @ExceptionHandler(RuntimeException.class) + public ResponseEntity handleRuntime(RuntimeException ex) { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body(new ErrorResponse("서버 내부 오류: " + ex.getMessage())); + } +} diff --git a/backend/auth/src/main/java/com/mapzip/auth/auth_service/repository/UserRepository.java b/backend/auth/src/main/java/com/mapzip/auth/auth_service/repository/UserRepository.java new file mode 100644 index 00000000..3ab0409d --- /dev/null +++ b/backend/auth/src/main/java/com/mapzip/auth/auth_service/repository/UserRepository.java @@ -0,0 +1,13 @@ +package com.mapzip.auth.auth_service.repository; + +import com.mapzip.auth.auth_service.entity.AppUser; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; + +public interface UserRepository extends JpaRepository { + Optional findByKakaoId(Long kakaoId); + + boolean existsByNickname(String nickname); + +} \ No newline at end of file diff --git a/backend/auth/src/main/java/com/mapzip/auth/auth_service/service/KakaoOAuthService.java b/backend/auth/src/main/java/com/mapzip/auth/auth_service/service/KakaoOAuthService.java new file mode 100644 index 00000000..0f56f1f4 --- /dev/null +++ b/backend/auth/src/main/java/com/mapzip/auth/auth_service/service/KakaoOAuthService.java @@ -0,0 +1,145 @@ +package com.mapzip.auth.auth_service.service; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.mapzip.auth.auth_service.dto.KakaoUserInfo; +import com.mapzip.auth.auth_service.dto.TokenResponseDto; +import com.mapzip.auth.auth_service.entity.AppUser; +import com.mapzip.auth.auth_service.repository.UserRepository; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.web.reactive.function.client.WebClient; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import io.jsonwebtoken.security.Keys; + +import java.util.Date; +import java.util.UUID; + +@Service +@RequiredArgsConstructor +@Slf4j +public class KakaoOAuthService { + + private final UserRepository userRepository; + private final RefreshTokenService refreshTokenService; + private final WebClient webClient; + + private final ObjectMapper objectMapper = new ObjectMapper(); + + @Value("${kakao.client-id}") + private String clientId; + + @Value("${kakao.redirect-uri}") + private String redirectUri; + + @Value("${kakao.client-secret:}") + private String clientSecret; + + @Value("${jwt.secret}") + private String jwtSecret; + + public TokenResponseDto loginWithKakao(String code) { + String kakaoAccessToken = getKakaoAccessToken(code); + KakaoUserInfo kakaoUserInfo = getKakaoUserInfo(kakaoAccessToken); + + AppUser user = userRepository.findByKakaoId(kakaoUserInfo.kakaoId()) + .orElseGet(() -> userRepository.save(AppUser.builder() + .kakaoId(kakaoUserInfo.kakaoId()) + .nickname(kakaoUserInfo.nickname()) + .build())); + + String accessToken = Jwts.builder() + .setSubject(kakaoUserInfo.kakaoId().toString()) + .setIssuedAt(new Date()) + .setExpiration(new Date(System.currentTimeMillis() + 3600000)) // 1시간 + .claim("kakaoId", kakaoUserInfo.kakaoId().toString()) + .claim("nickname", kakaoUserInfo.nickname()) + .signWith(Keys.hmacShaKeyFor(jwtSecret.getBytes()), SignatureAlgorithm.HS256) + .compact(); + + String refreshToken = UUID.randomUUID().toString(); + + refreshTokenService.save(refreshToken, kakaoUserInfo.kakaoId().toString()); + + return new TokenResponseDto(accessToken, refreshToken); + } + + private String getKakaoAccessToken(String code) { + + String requestBody = "grant_type=authorization_code" + + "&client_id=" + clientId + + "&redirect_uri=" + redirectUri + + "&code=" + code + + "&client_secret=" + clientSecret; + + String response = webClient.post() + .uri("https://kauth.kakao.com/oauth/token") + .header("Content-Type", "application/x-www-form-urlencoded") + .bodyValue(requestBody) + .retrieve() + .onStatus( + status -> status.isError(), + clientResponse -> clientResponse.bodyToMono(String.class).map(body -> { + log.info("kakao 응답 오류"); + return new RuntimeException("카카오 응답 오류: " + body); + }) + ) + .bodyToMono(String.class) + .block(); + + try { + JsonNode jsonNode = objectMapper.readTree(response); + return jsonNode.get("access_token").asText(); + } catch (Exception e) { + throw new IllegalArgumentException("카카오 access token 파싱 실패", e); + } + } + + + private KakaoUserInfo getKakaoUserInfo(String accessToken) { + String response = webClient.get() + .uri("https://kapi.kakao.com/v2/user/me") + .header("Authorization", "Bearer " + accessToken) + .retrieve() + .bodyToMono(String.class) + .block(); + + try { + JsonNode jsonNode = objectMapper.readTree(response); + Long kakaoId = jsonNode.get("id").asLong(); + String nickname = jsonNode.path("properties").path("nickname").asText(null); + + return new KakaoUserInfo(kakaoId, nickname); + } catch (Exception e) { + throw new IllegalArgumentException("카카오 사용자 정보 파싱 실패", e); + } + } + + public TokenResponseDto reissueAccessToken(String refreshToken) { + String kakaoId = refreshTokenService.getUserIdFromRefreshToken(refreshToken) + .orElseThrow(() -> new IllegalArgumentException("유효하지 않은 refresh token")); + + // JWT 재발급 시 nickname 포함 + AppUser user = userRepository.findByKakaoId(Long.valueOf(kakaoId)) + .orElseThrow(() -> new IllegalArgumentException("사용자 정보 없음")); + + String newAccessToken = Jwts.builder() + .setSubject(kakaoId) + .setIssuedAt(new Date()) + .setExpiration(new Date(System.currentTimeMillis() + 3600000)) + .claim("kakaoId", kakaoId) + .claim("nickname", user.getNickname()) + .signWith(Keys.hmacShaKeyFor(jwtSecret.getBytes()), SignatureAlgorithm.HS256) + .compact(); + + return new TokenResponseDto(newAccessToken, refreshToken); + } + + public void logout(String refreshToken) { + refreshTokenService.delete(refreshToken); + } +} diff --git a/backend/auth/src/main/java/com/mapzip/auth/auth_service/service/RefreshTokenService.java b/backend/auth/src/main/java/com/mapzip/auth/auth_service/service/RefreshTokenService.java new file mode 100644 index 00000000..1a7f0bfc --- /dev/null +++ b/backend/auth/src/main/java/com/mapzip/auth/auth_service/service/RefreshTokenService.java @@ -0,0 +1,36 @@ +package com.mapzip.auth.auth_service.service; + +import lombok.RequiredArgsConstructor; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Service; + +import java.time.Duration; +import java.util.Optional; + +@Service +@RequiredArgsConstructor +public class RefreshTokenService { + + private final StringRedisTemplate redis; + private static final Duration TTL = Duration.ofDays(1); + + private String key(String refreshToken) { + return "rt:token:" + refreshToken; + } + + // 발급/로그인 시 저장 (멀티 세션 허용) + public void save(String refreshToken, String kakaoId) { + redis.opsForValue().set(key(refreshToken), kakaoId, TTL); + } + + // 리프레시 요청에서 토큰으로 사용자(kakaoId) + public Optional getUserIdFromRefreshToken(String refreshToken) { + return Optional.ofNullable(redis.opsForValue().get(key(refreshToken))); + } + + //단일 세션로그아웃: 그 토큰만 무효화 + public void delete(String refreshToken) { + redis.delete(key(refreshToken)); + } +} + diff --git a/backend/auth/src/main/main.iml b/backend/auth/src/main/main.iml new file mode 100644 index 00000000..fd348ac4 --- /dev/null +++ b/backend/auth/src/main/main.iml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/backend/auth/src/main/resources/application.yml b/backend/auth/src/main/resources/application.yml new file mode 100644 index 00000000..efa363d4 --- /dev/null +++ b/backend/auth/src/main/resources/application.yml @@ -0,0 +1,6 @@ +spring: + application: + name: auth + + config: + import: optional:configserver:http://config.service-platform.svc.cluster.local:8888 \ No newline at end of file diff --git a/backend/auth/src/test/java/com/mapzip/auth/auth_service/AuthServiceApplicationTests.java b/backend/auth/src/test/java/com/mapzip/auth/auth_service/AuthServiceApplicationTests.java new file mode 100644 index 00000000..0d1b7c74 --- /dev/null +++ b/backend/auth/src/test/java/com/mapzip/auth/auth_service/AuthServiceApplicationTests.java @@ -0,0 +1,13 @@ +package com.mapzip.auth.auth_service; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class AuthServiceApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/backend/auth/src/test/test.iml b/backend/auth/src/test/test.iml new file mode 100644 index 00000000..a0e49a3b --- /dev/null +++ b/backend/auth/src/test/test.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/backend/config/.dockerignore b/backend/config/.dockerignore new file mode 100644 index 00000000..62e793a4 --- /dev/null +++ b/backend/config/.dockerignore @@ -0,0 +1,58 @@ +# Maven +target/ +!target/app.jar +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties +dependency-reduced-pom.xml +buildNumber.properties +.mvn/timing.properties +.mvn/wrapper/maven-wrapper.jar + +# IDE +.idea/ +.vscode/ +*.swp +*.swo +*~ +.project +.classpath +.settings/ +.metadata/ +bin/ + +# OS +.DS_Store +.DS_Store? +._* +.Spotlight-V100 +.Trashes +ehthumbs.db +Thumbs.db + +# Git +.git/ +.gitignore +.gitattributes + +# Documentation +README.md +HELP.md +*.md + +# Scripts and configs (not needed in container) +scripts/ +k8s/ +.github/ + +# Logs +*.log +logs/ + +# Temporary files +*.tmp +*.temp +.tmp/ +.temp/ diff --git a/backend/config/.gitattributes b/backend/config/.gitattributes new file mode 100644 index 00000000..b0cd697f --- /dev/null +++ b/backend/config/.gitattributes @@ -0,0 +1,20 @@ +# Maven wrapper scripts should have LF line endings on all platforms +/mvnw text eol=lf +*.bat text eol=crlf + +# Binary files +*.jar binary +*.war binary +*.ear binary + +# Text files should be normalized (Convert crlf => lf) +*.java text +*.xml text +*.properties text +*.yml text +*.yaml text +*.md text +*.txt text + +# Dockerfile +Dockerfile text diff --git a/backend/config/.gitignore b/backend/config/.gitignore new file mode 100644 index 00000000..35b18290 --- /dev/null +++ b/backend/config/.gitignore @@ -0,0 +1,64 @@ +HELP.md + +# Maven +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties +dependency-reduced-pom.xml +buildNumber.properties +.mvn/timing.properties +.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### macOS ### +.DS_Store +.DS_Store? +._* +.Spotlight-V100 +.Trashes +ehthumbs.db +Thumbs.db + +### Logs ### +*.log +logs/ + +### Temporary files ### +*.tmp +*.temp +.tmp/ +.temp/ + diff --git a/backend/config/.mvn/wrapper/maven-wrapper.properties b/backend/config/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..d58dfb70 --- /dev/null +++ b/backend/config/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/backend/config/Dockerfile b/backend/config/Dockerfile new file mode 100644 index 00000000..c2c1038a --- /dev/null +++ b/backend/config/Dockerfile @@ -0,0 +1,51 @@ +# 멀티 스테이지 빌드를 사용하여 이미지 크기 최적화 +FROM maven:3.9.6-eclipse-temurin-17 AS build + +# 작업 디렉토리 설정 +WORKDIR /app + +# Maven 파일들을 먼저 복사 (캐시 최적화) +COPY pom.xml ./ +COPY .mvn/ .mvn/ +COPY mvnw ./ + +# 의존성 다운로드 (캐시 레이어) +RUN ./mvnw dependency:go-offline -B + +# 소스 코드 복사 +COPY src/ src/ + +# 애플리케이션 빌드 +RUN ./mvnw clean package -DskipTests -B + + +FROM eclipse-temurin:17-jre + +# curl 설치 (헬스체크용) +RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/* + + +# 애플리케이션 실행을 위한 사용자 생성 (보안) +RUN addgroup --system spring && adduser --system spring --ingroup spring + +# 작업 디렉토리 설정 +WORKDIR /app + +# 빌드된 JAR 파일 복사 +COPY --from=build /app/target/config-0.0.1-SNAPSHOT.jar app.jar + +# 소유권 변경 +RUN chown spring:spring app.jar + +# 사용자 변경 +USER spring:spring + +# 포트 노출 +EXPOSE 8888 + +# 헬스체크 추가 +HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ + CMD curl -f http://localhost:8888/actuator/health || exit 1 + +# 애플리케이션 실행 +ENTRYPOINT ["java", "-jar", "/app/app.jar"] diff --git a/backend/config/README.md b/backend/config/README.md new file mode 100644 index 00000000..5983ee48 --- /dev/null +++ b/backend/config/README.md @@ -0,0 +1,207 @@ +# MapZip Config Server + +MapZip 마이크로서비스 아키텍처의 중앙 설정 서버입니다. + +## 🏗️ 아키텍처 + +``` +┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ +│ Gateway │ │ Auth Service │ │ Review Service │ +│ (Port: 8080) │ │ (Port: 8081) │ │ (Port: 8083) │ +└─────────┬───────┘ └─────────┬───────┘ └─────────┬───────┘ + │ │ │ + └──────────────────────┼──────────────────────┘ + │ + ┌─────────────▼───────────┐ + │ Config Server │ + │ (Port: 8888) │ + └─────────────────────────┘ +``` + +## 🚀 빠른 시작 + +### 로컬 개발 환경 + +1. **Maven으로 빌드 및 실행** + ```bash + cd ~/mapzip/app/backend/config + ./mvnw clean package + java -jar target/app.jar + ``` + +2. **Docker로 실행** + ```bash + docker build -t mapzip/config:latest . + docker run -p 8888:8888 mapzip/config:latest + ``` + +### 설정 확인 + +Config Server가 실행되면 다음 URL에서 설정을 확인할 수 있습니다: + +- 헬스체크: http://localhost:8888/actuator/health +- Gateway 설정: http://localhost:8888/gateway/default +- Auth 설정: http://localhost:8888/auth/default + +## 🐳 Docker 배포 + +### 1. 로컬 빌드 +```bash +./scripts/build.sh +``` + +### 2. ECR에 푸시 +```bash +./scripts/push-to-ecr.sh [태그명] +``` + +## ☸️ Kubernetes 배포 + +### 전제조건 +- AWS CLI 설치 및 설정 +- kubectl 설치 +- EKS 클러스터 접근 권한 + +### 배포 명령어 +```bash +# kubeconfig 업데이트 +aws eks update-kubeconfig --region ap-northeast-2 --name mapzip-dev-eks + +# 네임스페이스 생성 +kubectl create namespace platform + +# 배포 +cd k8s +kubectl apply -f configmap.yaml +kubectl apply -f deployment.yaml +kubectl apply -f service.yaml + +# 배포 상태 확인 +kubectl get pods -n platform -l app=config +``` + +### Kubernetes 서비스 접근 +- 클러스터 내부: `config.platform.svc.cluster.local:8888` +- 외부 접근: LoadBalancer를 통한 접근 가능 + +## 🔧 CI/CD + +통합 CI/CD 파이프라인(`backend-ci-cd.yaml`)을 통한 자동 배포가 설정되어 있습니다. + +### 트리거 조건 +- `dev` 브랜치에 푸시 +- `backend/config/**` 경로의 파일 변경 + +### 배포 과정 +1. 변경사항 감지 +2. Maven 빌드 (`mvn -B package -DskipTests`) +3. Docker 이미지 빌드 및 ECR 푸시 (`mapzip-dev-ecr-config:커밋해시`) +4. ArgoCD YAML 업데이트 (`argocd/platform/config.yaml`) +5. ArgoCD를 통한 자동 배포 + +## 📁 프로젝트 구조 + +``` +config/ +├── src/ +│ └── main/ +│ ├── java/ +│ │ └── com/mapzip/config/ +│ │ └── ConfigServerApplication.java +│ └── resources/ +│ └── application.yml +├── k8s/ +│ ├── deployment.yaml +│ ├── service.yaml +│ └── configmap.yaml +├── scripts/ +│ ├── build.sh +│ └── push-to-ecr.sh +├── .mvn/ +│ └── wrapper/ +├── Dockerfile +├── pom.xml +├── mvnw +├── mvnw.cmd +└── README.md +``` + +## ⚙️ 설정 관리 + +### Config Repository 구조 +``` +config-repo/ +├── application.yml # 공통 설정 +├── auth/ +│ └── auth.yml # Auth 서비스 설정 +├── gateway/ +│ └── gateway.yml # Gateway 서비스 설정 +├── review/ +│ └── review.yml # Review 서비스 설정 +├── recommend/ +│ └── recommend.yml # Recommend 서비스 설정 +└── schedule/ + └── schedule.yml # Schedule 서비스 설정 +``` + +### 설정 접근 방법 +- URL 패턴: `http://config.platform.svc.cluster.local:8888/{application}/{profile}` +- 예시: `http://config.platform.svc.cluster.local:8888/auth/dev` + +## 🔍 트러블슈팅 + +### 일반적인 문제들 + +1. **Config Server가 시작되지 않는 경우** + ```bash + # 로그 확인 + kubectl logs -n platform deployment/config + + # 포트 확인 + netstat -tulpn | grep 8888 + ``` + +2. **설정 파일을 찾을 수 없는 경우** + - config-repo 디렉토리 경로 확인 + - Git 저장소 URL 및 인증 정보 확인 + +3. **Maven 빌드 실패** + ```bash + # Maven 캐시 정리 + ./mvnw clean + + # Docker 캐시 정리 + docker system prune -f + ``` + +## 🔐 보안 설정 + +### 암호화 키 설정 +```yaml +encrypt: + key: ${ENCRYPT_KEY} # Kubernetes Secret으로 관리 +``` + +### 민감한 정보 암호화 +```bash +# 설정값 암호화 +curl -X POST http://localhost:8888/encrypt -d "민감한정보" + +# 설정값 복호화 +curl -X POST http://localhost:8888/decrypt -d "암호화된값" +``` + +## 📚 참고 자료 + +- [Spring Cloud Config 공식 문서](https://spring.io/projects/spring-cloud-config) +- [AWS EKS 사용자 가이드](https://docs.aws.amazon.com/eks/) +- [Docker 공식 문서](https://docs.docker.com/) +- [ArgoCD 공식 문서](https://argo-cd.readthedocs.io/) + +## 🤝 기여하기 + +1. 이슈 생성 +2. 기능 브랜치 생성 (`git checkout -b feature/amazing-feature`) +3. 변경사항 커밋 (`git commit -m 'Add amazing feature'`) +4. 브랜치에 푸시 (`git push origin feature/amazing-feature`) +5. Pull Request 생성 diff --git a/backend/config/config-server/.gradle/8.14.3/checksums/checksums.lock b/backend/config/config-server/.gradle/8.14.3/checksums/checksums.lock new file mode 100644 index 00000000..2e770788 Binary files /dev/null and b/backend/config/config-server/.gradle/8.14.3/checksums/checksums.lock differ diff --git a/backend/config/config-server/.gradle/8.14.3/checksums/md5-checksums.bin b/backend/config/config-server/.gradle/8.14.3/checksums/md5-checksums.bin new file mode 100644 index 00000000..c216627a Binary files /dev/null and b/backend/config/config-server/.gradle/8.14.3/checksums/md5-checksums.bin differ diff --git a/backend/config/config-server/.gradle/8.14.3/checksums/sha1-checksums.bin b/backend/config/config-server/.gradle/8.14.3/checksums/sha1-checksums.bin new file mode 100644 index 00000000..ff32ccbb Binary files /dev/null and b/backend/config/config-server/.gradle/8.14.3/checksums/sha1-checksums.bin differ diff --git a/backend/config/config-server/.gradle/8.14.3/executionHistory/executionHistory.bin b/backend/config/config-server/.gradle/8.14.3/executionHistory/executionHistory.bin new file mode 100644 index 00000000..88751685 Binary files /dev/null and b/backend/config/config-server/.gradle/8.14.3/executionHistory/executionHistory.bin differ diff --git a/backend/config/config-server/.gradle/8.14.3/executionHistory/executionHistory.lock b/backend/config/config-server/.gradle/8.14.3/executionHistory/executionHistory.lock new file mode 100644 index 00000000..e227f9d0 Binary files /dev/null and b/backend/config/config-server/.gradle/8.14.3/executionHistory/executionHistory.lock differ diff --git a/backend/config/config-server/.gradle/8.14.3/fileChanges/last-build.bin b/backend/config/config-server/.gradle/8.14.3/fileChanges/last-build.bin new file mode 100644 index 00000000..f76dd238 Binary files /dev/null and b/backend/config/config-server/.gradle/8.14.3/fileChanges/last-build.bin differ diff --git a/backend/config/config-server/.gradle/8.14.3/fileHashes/fileHashes.bin b/backend/config/config-server/.gradle/8.14.3/fileHashes/fileHashes.bin new file mode 100644 index 00000000..6b113676 Binary files /dev/null and b/backend/config/config-server/.gradle/8.14.3/fileHashes/fileHashes.bin differ diff --git a/backend/config/config-server/.gradle/8.14.3/fileHashes/fileHashes.lock b/backend/config/config-server/.gradle/8.14.3/fileHashes/fileHashes.lock new file mode 100644 index 00000000..9752f7e4 Binary files /dev/null and b/backend/config/config-server/.gradle/8.14.3/fileHashes/fileHashes.lock differ diff --git a/backend/config/config-server/.gradle/8.14.3/fileHashes/resourceHashesCache.bin b/backend/config/config-server/.gradle/8.14.3/fileHashes/resourceHashesCache.bin new file mode 100644 index 00000000..ed341736 Binary files /dev/null and b/backend/config/config-server/.gradle/8.14.3/fileHashes/resourceHashesCache.bin differ diff --git a/backend/auth/.gitkeep b/backend/config/config-server/.gradle/8.14.3/gc.properties similarity index 100% rename from backend/auth/.gitkeep rename to backend/config/config-server/.gradle/8.14.3/gc.properties diff --git a/backend/config/config-server/.gradle/buildOutputCleanup/buildOutputCleanup.lock b/backend/config/config-server/.gradle/buildOutputCleanup/buildOutputCleanup.lock new file mode 100644 index 00000000..3fb50106 Binary files /dev/null and b/backend/config/config-server/.gradle/buildOutputCleanup/buildOutputCleanup.lock differ diff --git a/backend/config/config-server/.gradle/buildOutputCleanup/cache.properties b/backend/config/config-server/.gradle/buildOutputCleanup/cache.properties new file mode 100644 index 00000000..ebbc0e24 --- /dev/null +++ b/backend/config/config-server/.gradle/buildOutputCleanup/cache.properties @@ -0,0 +1,2 @@ +#Mon Jul 28 14:33:55 KST 2025 +gradle.version=8.14.3 diff --git a/backend/config/config-server/.gradle/buildOutputCleanup/outputFiles.bin b/backend/config/config-server/.gradle/buildOutputCleanup/outputFiles.bin new file mode 100644 index 00000000..8360eb66 Binary files /dev/null and b/backend/config/config-server/.gradle/buildOutputCleanup/outputFiles.bin differ diff --git a/backend/config/config-server/.gradle/file-system.probe b/backend/config/config-server/.gradle/file-system.probe new file mode 100644 index 00000000..5644d8ca Binary files /dev/null and b/backend/config/config-server/.gradle/file-system.probe differ diff --git a/backend/config/.gitkeep b/backend/config/config-server/.gradle/vcs-1/gc.properties similarity index 100% rename from backend/config/.gitkeep rename to backend/config/config-server/.gradle/vcs-1/gc.properties diff --git a/backend/config/mvnw b/backend/config/mvnw new file mode 100755 index 00000000..19529ddf --- /dev/null +++ b/backend/config/mvnw @@ -0,0 +1,259 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.2 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + 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" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/backend/config/mvnw.cmd b/backend/config/mvnw.cmd new file mode 100644 index 00000000..b150b91e --- /dev/null +++ b/backend/config/mvnw.cmd @@ -0,0 +1,149 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.2 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' +$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/backend/config/pom.xml b/backend/config/pom.xml new file mode 100644 index 00000000..f8a4ebb0 --- /dev/null +++ b/backend/config/pom.xml @@ -0,0 +1,74 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.5.3 + + + com.mapzip + config + 0.0.1-SNAPSHOT + config + Config Server for MapZip MSA + + + + + + + + + + + + + + + 17 + 2025.0.0 + + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.cloud + spring-cloud-config-server + + + io.micrometer + micrometer-registry-prometheus + runtime + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/backend/config/src/main/java/com/mapzip/config/ConfigServerApplication.java b/backend/config/src/main/java/com/mapzip/config/ConfigServerApplication.java new file mode 100644 index 00000000..ba4285a9 --- /dev/null +++ b/backend/config/src/main/java/com/mapzip/config/ConfigServerApplication.java @@ -0,0 +1,15 @@ +package com.mapzip.config; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.config.server.EnableConfigServer; + +@SpringBootApplication +@EnableConfigServer +public class ConfigServerApplication { + + public static void main(String[] args) { + SpringApplication.run(ConfigServerApplication.class, args); + } + +} diff --git a/backend/config/src/main/resources/application.yml b/backend/config/src/main/resources/application.yml new file mode 100644 index 00000000..1057efa3 --- /dev/null +++ b/backend/config/src/main/resources/application.yml @@ -0,0 +1,69 @@ +server: + port: 8888 + +# 암호화 설정 (민감한 정보 보호용) +encrypt: + key: ${ENCRYPT_KEY} # Kubernetes Secret으로 관리 필요 + +spring: + application: + name: config + cloud: + config: + server: + git: + uri: ${CONFIG_REPO_URI:https://github.com/CLD3rd-Team4/App} + search-paths: config-repo + default-label: dev + clone-on-start: true + timeout: 10 + # Git 인증 (필요시) + username: ${GIT_USERNAME:} + password: ${GIT_TOKEN:} + +# Actuator 설정 (헬스체크 + 모니터링) +management: + endpoints: + web: + exposure: + include: health,info,env,configprops,refresh,encrypt,decrypt,prometheus,metrics + endpoint: + health: + show-details: always + probes: + enabled: true + refresh: + enabled: true + encrypt: + enabled: true + decrypt: + enabled: true + prometheus: + enabled: true + metrics: + enabled: true + metrics: + export: + prometheus: + enabled: true + tags: + service: config + environment: ${spring.profiles.active:dev} + health: + livenessstate: + enabled: true + readinessstate: + enabled: true + config: + enabled: true + diskspace: + enabled: true + git: + enabled: true + +# 로깅 설정 +logging: + level: + org.springframework.cloud.config: ${LOG_LEVEL:INFO} + org.springframework.web: ${LOG_LEVEL:INFO} + root: INFO diff --git a/backend/config/src/test/java/com/mapzip/config/ConfigServerApplicationTests.java b/backend/config/src/test/java/com/mapzip/config/ConfigServerApplicationTests.java new file mode 100644 index 00000000..af9af06d --- /dev/null +++ b/backend/config/src/test/java/com/mapzip/config/ConfigServerApplicationTests.java @@ -0,0 +1,13 @@ +package com.mapzip.config; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class ConfigServerApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/backend/gateway/.dockerignore b/backend/gateway/.dockerignore new file mode 100644 index 00000000..8ded8f97 --- /dev/null +++ b/backend/gateway/.dockerignore @@ -0,0 +1,9 @@ +target/ +!target/*.jar +.git +.gitignore +.idea +*.iml +*.log +*.env +node_modules/ diff --git a/backend/gateway/.gitattributes b/backend/gateway/.gitattributes new file mode 100644 index 00000000..3b41682a --- /dev/null +++ b/backend/gateway/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/backend/gateway/.gitignore b/backend/gateway/.gitignore new file mode 100644 index 00000000..667aaef0 --- /dev/null +++ b/backend/gateway/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/backend/gateway/.mvn/wrapper/maven-wrapper.properties b/backend/gateway/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..12fbe1e9 --- /dev/null +++ b/backend/gateway/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.11/apache-maven-3.9.11-bin.zip diff --git a/backend/gateway/Dockerfile b/backend/gateway/Dockerfile new file mode 100644 index 00000000..b51c7cf4 --- /dev/null +++ b/backend/gateway/Dockerfile @@ -0,0 +1,4 @@ +FROM openjdk:17-jdk-slim +ARG JAR_FILE=target/*.jar +COPY ${JAR_FILE} app.jar +ENTRYPOINT ["java", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/app.jar"] diff --git a/backend/gateway/mvnw b/backend/gateway/mvnw new file mode 100644 index 00000000..19529ddf --- /dev/null +++ b/backend/gateway/mvnw @@ -0,0 +1,259 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.2 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + 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" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/backend/gateway/mvnw.cmd b/backend/gateway/mvnw.cmd new file mode 100644 index 00000000..249bdf38 --- /dev/null +++ b/backend/gateway/mvnw.cmd @@ -0,0 +1,149 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.2 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' +$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/backend/gateway/pom.xml b/backend/gateway/pom.xml new file mode 100644 index 00000000..21c1a794 --- /dev/null +++ b/backend/gateway/pom.xml @@ -0,0 +1,157 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.5.4 + + + io.test + gateway + 0.0.1-SNAPSHOT + gateway + gateway + + + + + + + + + + + + + + + 17 + + 2025.0.0 + + + + + + org.springframework.cloud + spring-cloud-starter + + + org.springframework.cloud + spring-cloud-starter-config + + + org.springframework.cloud + spring-cloud-starter-circuitbreaker-resilience4j + + + org.springframework.cloud + spring-cloud-starter-gateway-server-webflux + + + + io.jsonwebtoken + jjwt-api + 0.12.6 + + + io.jsonwebtoken + jjwt-impl + 0.12.6 + + + io.jsonwebtoken + jjwt-jackson + 0.12.6 + + + com.fasterxml.jackson.core + jackson-databind + + + com.googlecode.owasp-java-html-sanitizer + owasp-java-html-sanitizer + 20240325.1 + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + io.projectreactor + reactor-test + test + + + org.mockito + mockito-core + test + + + org.springframework.boot + spring-boot-starter-webflux + + + org.springframework.boot + spring-boot-starter-actuator + + + + io.micrometer + micrometer-registry-prometheus + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + org.projectlombok + lombok + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/backend/gateway/src/main/java/mapzip/gateway/GatewayApplication.java b/backend/gateway/src/main/java/mapzip/gateway/GatewayApplication.java new file mode 100644 index 00000000..ab49f3ab --- /dev/null +++ b/backend/gateway/src/main/java/mapzip/gateway/GatewayApplication.java @@ -0,0 +1,13 @@ +package mapzip.gateway; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class GatewayApplication { + + public static void main(String[] args) { + SpringApplication.run(GatewayApplication.class, args); + } + +} diff --git a/backend/gateway/src/main/java/mapzip/gateway/config/CustomRouteLocator.java b/backend/gateway/src/main/java/mapzip/gateway/config/CustomRouteLocator.java new file mode 100644 index 00000000..892d00f9 --- /dev/null +++ b/backend/gateway/src/main/java/mapzip/gateway/config/CustomRouteLocator.java @@ -0,0 +1,108 @@ +package mapzip.gateway.config; + +import mapzip.gateway.filter.JwtAuthenticationFilter; +import mapzip.gateway.filter.XssProtectionFilter; +import org.springframework.cloud.gateway.route.RouteLocator; +import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class CustomRouteLocator { + + private final JwtAuthenticationFilter jwtAuthenticationFilter; + private final XssProtectionFilter xssProtectionFilter; + + public CustomRouteLocator(JwtAuthenticationFilter jwtAuthenticationFilter, + XssProtectionFilter xssProtectionFilter) { + this.jwtAuthenticationFilter = jwtAuthenticationFilter; + this.xssProtectionFilter = xssProtectionFilter; + } + + @Bean + public RouteLocator gatewayRoutes(RouteLocatorBuilder builder) { + return builder.routes() + // 인증 서비스 라우팅 + .route("auth-service", r -> r.path("/auth/**") + .filters(f -> f + .filter(xssProtectionFilter.apply(new XssProtectionFilter.Config())) + .filter(jwtAuthenticationFilter.apply(new JwtAuthenticationFilter.Config()))) + .uri("http://auth.service-platform:8080")) + + // 추천 서비스 라우팅 + .route("recommend-service", r -> r.path("/recommend/**") + .and().method("GET", "POST") // 추천 조회 및 생성 + .filters(f -> f + .filter(xssProtectionFilter.apply(new XssProtectionFilter.Config())) + .filter(jwtAuthenticationFilter.apply(new JwtAuthenticationFilter.Config()))) + .uri("http://recommend.service-recommend:9092")) + + // HTTP (port 8080): 이미지 처리 + HTTP 전용 API + .route("review-http-post", r -> r.path("/review") + .and().method("POST") // 이미지 업로드 전용 + .filters(f -> f + .filter(xssProtectionFilter.apply(new XssProtectionFilter.Config())) + .filter(jwtAuthenticationFilter.apply(new JwtAuthenticationFilter.Config()))) + .uri("http://review.service-review:8080")) + + .route("review-http-verify", r -> r.path("/review/verify-receipt") + .and().method("POST") // OCR 검증 전용 + .filters(f -> f + .filter(xssProtectionFilter.apply(new XssProtectionFilter.Config())) + .filter(jwtAuthenticationFilter.apply(new JwtAuthenticationFilter.Config()))) + .uri("http://review.service-review:8080")) + + .route("review-http-user", r -> r.path("/review/user") + .and().method("GET") // 사용자 리뷰 목록 조회 + .filters(f -> f + .filter(xssProtectionFilter.apply(new XssProtectionFilter.Config())) + .filter(jwtAuthenticationFilter.apply(new JwtAuthenticationFilter.Config()))) + .uri("http://review.service-review:8080")) + + .route("review-http-pending", r -> r.path("/review/pending", "/review/pending/**") + .and().method("GET", "DELETE") // 미작성 리뷰 관리 + .filters(f -> f + .filter(xssProtectionFilter.apply(new XssProtectionFilter.Config())) + .filter(jwtAuthenticationFilter.apply(new JwtAuthenticationFilter.Config()))) + .uri("http://review.service-review:8080")) + + .route("review-http-health", r -> r.path("/review/health") + .and().method("GET") // 헬스체크 + .filters(f -> f + .filter(xssProtectionFilter.apply(new XssProtectionFilter.Config())) + .filter(jwtAuthenticationFilter.apply(new JwtAuthenticationFilter.Config()))) + .uri("http://review.service-review:8080")) + + .route("review-http-detail", r -> r.path("/review/http/**") // 상세조회 수정 삭제 + .and().method("GET", "PUT", "DELETE") + .filters(f -> f + .filter(xssProtectionFilter.apply(new XssProtectionFilter.Config())) + .filter(jwtAuthenticationFilter.apply(new JwtAuthenticationFilter.Config()))) + .uri("http://review.service-review:8080")) + + // gRPC (port 50051): 일반 조회 API + .route("review-grpc", r -> r.path("/review/**") + .and().method("GET", "PUT", "DELETE") // 나머지 API들 + .filters(f -> f + .filter(xssProtectionFilter.apply(new XssProtectionFilter.Config())) + .filter(jwtAuthenticationFilter.apply(new JwtAuthenticationFilter.Config()))) + .uri("http://review.service-review:50051")) + + // 스케줄 서비스 라우팅 + .route("schedule-service", r -> r.path("/schedule/**") + .and().method("GET", "POST", "PUT", "DELETE") // 스케줄 CRUD + .filters(f -> f + .filter(xssProtectionFilter.apply(new XssProtectionFilter.Config())) + .filter(jwtAuthenticationFilter.apply(new JwtAuthenticationFilter.Config()))) + .uri("http://schedule.service-schedule:9090")) + + // 데모 서비스 라우팅 + .route("demo-service", r -> r.path("/demo/**") + .filters(f -> f + .stripPrefix(1) + .filter(xssProtectionFilter.apply(new XssProtectionFilter.Config())) + .filter(jwtAuthenticationFilter.apply(new JwtAuthenticationFilter.Config()))) + .uri("http://demo.demo:9090")) + .build(); + } +} diff --git a/backend/gateway/src/main/java/mapzip/gateway/filter/JwtAuthenticationFilter.java b/backend/gateway/src/main/java/mapzip/gateway/filter/JwtAuthenticationFilter.java new file mode 100644 index 00000000..3901a712 --- /dev/null +++ b/backend/gateway/src/main/java/mapzip/gateway/filter/JwtAuthenticationFilter.java @@ -0,0 +1,101 @@ +package mapzip.gateway.filter; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import mapzip.gateway.util.JwtUtil; +import mapzip.gateway.util.TokenValidationResult; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.cloud.gateway.filter.GatewayFilter; +import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.server.reactive.ServerHttpRequest; +import org.springframework.http.server.reactive.ServerHttpResponse; +import org.springframework.stereotype.Component; +import reactor.core.publisher.Mono; + +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +@Component +public class JwtAuthenticationFilter extends AbstractGatewayFilterFactory { + + private static final Logger log = LoggerFactory.getLogger(JwtAuthenticationFilter.class); + + private final JwtUtil jwtUtil; + private final ObjectMapper objectMapper; + + public JwtAuthenticationFilter(JwtUtil jwtUtil, ObjectMapper objectMapper) { + super(Config.class); + this.jwtUtil = jwtUtil; + this.objectMapper = objectMapper; + } + + @Override + public GatewayFilter apply(Config config) { + return (exchange, chain) -> { + ServerHttpRequest request = exchange.getRequest(); + String path = request.getPath().value(); + + log.info("JWT Filter - Request: {} {}", request.getMethod(), path); + + // 로그인 요청, 액세스 토큰 쿠키 재발급, 로그아웃 요청은 JWT 검증 제외 + if (path.startsWith("/auth/kakao/callback")|| path.startsWith("/auth/token/")) { + log.info("JWT Filter - Skipping auth for login path: {}", path); + return chain.filter(exchange); + } + + String token = extractTokenFromCookie(request); + log.debug("JWT Filter - Token extracted: {}", token != null ? "present" : "null"); + + if (token == null) { + log.warn("JWT Filter - No token found in cookies"); + return createErrorResponse(exchange.getResponse(), "TOKEN_INVALID"); + } + + TokenValidationResult validationResult = jwtUtil.validateTokenWithResult(token); + if (validationResult != TokenValidationResult.VALID) { + String errorMessage = validationResult == TokenValidationResult.EXPIRED ? "TOKEN_EXPIRED" : "TOKEN_INVALID"; + log.warn("JWT Filter - Token validation failed: {}", errorMessage); + return createErrorResponse(exchange.getResponse(), errorMessage); + } + + // JWT에서 사용자 ID 추출하여 http 헤더에 추가 + String userId = jwtUtil.extractUserId(token); + log.info("JWT Filter - User authenticated: {}", userId); + + ServerHttpRequest modifiedRequest = request.mutate() + .header("x-user-id", userId) //gRPC 메타데이터 헤더는 모두 소문자 + .build(); + + return chain.filter(exchange.mutate().request(modifiedRequest).build()); + }; + } + + private String extractTokenFromCookie(ServerHttpRequest request) { + return request.getCookies().getFirst("accessToken") != null ? + Objects.requireNonNull(request.getCookies().getFirst("accessToken")).getValue() : null; + } + + private Mono createErrorResponse(ServerHttpResponse response, String errorMessage) { + response.setStatusCode(HttpStatus.UNAUTHORIZED); + response.getHeaders().add("Content-Type", "application/json"); + + try { + Map errorBody = new HashMap<>(); + errorBody.put("error", errorMessage); + String jsonResponse = objectMapper.writeValueAsString(errorBody); + + org.springframework.core.io.buffer.DataBuffer buffer = response.bufferFactory().wrap(jsonResponse.getBytes()); + return response.writeWith(Mono.just(buffer)); + } catch (JsonProcessingException e) { + log.error("Error creating JSON response", e); + return response.setComplete(); + } + } + + public static class Config { + // 설정이 필요한 경우 여기에 추가 + } +} diff --git a/backend/gateway/src/main/java/mapzip/gateway/filter/XssProtectionFilter.java b/backend/gateway/src/main/java/mapzip/gateway/filter/XssProtectionFilter.java new file mode 100644 index 00000000..c43a71e8 --- /dev/null +++ b/backend/gateway/src/main/java/mapzip/gateway/filter/XssProtectionFilter.java @@ -0,0 +1,208 @@ +package mapzip.gateway.filter; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.owasp.html.PolicyFactory; +import org.owasp.html.Sanitizers; +import org.springframework.cloud.gateway.filter.GatewayFilter; +import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory; +import org.springframework.core.io.buffer.DataBuffer; +import org.springframework.core.io.buffer.DataBufferUtils; +import org.springframework.http.MediaType; +import org.springframework.http.server.reactive.ServerHttpRequest; +import org.springframework.http.server.reactive.ServerHttpRequestDecorator; +import org.springframework.stereotype.Component; +import org.springframework.web.util.UriComponentsBuilder; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.net.URI; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.stream.Collectors; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Component +public class XssProtectionFilter extends AbstractGatewayFilterFactory { + + private final PolicyFactory policy; + private final ObjectMapper objectMapper; + private static final Logger log = LoggerFactory.getLogger(XssProtectionFilter.class); + + public XssProtectionFilter() { + super(Config.class); + this.policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS).and(Sanitizers.BLOCKS); + this.objectMapper = new ObjectMapper(); + } + + @Override + public GatewayFilter apply(Config config) { + return (exchange, chain) -> { + ServerHttpRequest request = exchange.getRequest(); + + // GET 요청은 쿼리 파라미터만 필터링 + if ("GET".equals(request.getMethod().name())) { + URI originalUri = request.getURI(); + String query = originalUri.getQuery(); + + if (query != null) { + log.info("[XSS Filter] GET Query - Original: {}", query); + + // 안전하게 각 파라미터별로 sanitize + String sanitizedQuery = Arrays.stream(query.split("&")) + .map(param -> { + String[] kv = param.split("=", 2); + if (kv.length == 2) { + String key = kv[0]; + String value = URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + String sanitizedValue = sanitizeXss(value); + return URLEncoder.encode(key, StandardCharsets.UTF_8) + "=" + + URLEncoder.encode(sanitizedValue, StandardCharsets.UTF_8); + } + return param; + }) + .collect(Collectors.joining("&")); + + log.info("[XSS Filter] GET Query - Sanitized: {}", sanitizedQuery); + + URI newUri = UriComponentsBuilder.fromUri(originalUri) + .replaceQuery(sanitizedQuery) + .build() + .toUri(); + + ServerHttpRequest filteredRequest = request.mutate() + .uri(newUri) + .build(); + + return chain.filter(exchange.mutate().request(filteredRequest).build()); + } + + return chain.filter(exchange); + } + + + // multipart/form-data 요청은 XSS 필터링 완전히 건너뛰기 + MediaType contentType = request.getHeaders().getContentType(); + if (MediaType.MULTIPART_FORM_DATA.isCompatibleWith(contentType)) { + log.debug("[XSS Filter] Bypassing multipart/form-data request completely"); + return chain.filter(exchange); + } + + // POST/PUT 요청은 body 필터링 + ServerHttpRequestDecorator decorator = new ServerHttpRequestDecorator(request) { + @Override + public Flux getBody() { + return super.getBody() + .collectList() + .flatMapMany(dataBuffers -> { + // 1) 모든 DataBuffer 바이트를 합침 + byte[] bytes = dataBuffers.stream() + .map(DataBuffer::asByteBuffer) + .collect(() -> ByteBuffer.allocate(dataBuffers.stream().mapToInt(DataBuffer::readableByteCount).sum()), + ByteBuffer::put, + ByteBuffer::put) + .array(); + + dataBuffers.forEach(DataBufferUtils::release); // 안전하게 해제 + + String body = new String(bytes, StandardCharsets.UTF_8); + String sanitizedBody = sanitizeBody(body, request); + byte[] sanitizedBytes = sanitizedBody.getBytes(StandardCharsets.UTF_8); + + DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(sanitizedBytes); + return Flux.just(buffer); + }); + } + }; + + ServerHttpRequest filteredRequest = decorator.mutate() + .headers(httpHeaders -> httpHeaders.remove("Content-Length")) + .build(); + + return chain.filter(exchange.mutate().request(filteredRequest).build()); + }; + } + + String sanitizeXss(String input) { + if (input == null) return null; + return policy.sanitize(input); + } + + String sanitizeBody(String body, ServerHttpRequest request) { + if (body == null || body.isEmpty()) return body; + + MediaType contentType = request.getHeaders().getContentType(); + if (MediaType.APPLICATION_JSON.isCompatibleWith(contentType)) { + return sanitizeJsonBody(body); + } else if (MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(contentType)) { + return sanitizeFormBody(body); + } else if (MediaType.MULTIPART_FORM_DATA.isCompatibleWith(contentType)) { + log.debug("[XSS Filter] Skipping multipart/form-data content type"); + return body; + } + + return sanitizeXss(body); + } + + String sanitizeJsonBody(String jsonBody) { + try { + log.debug("[XSS Filter] Parsing JSON body"); + JsonNode rootNode = objectMapper.readTree(jsonBody); + JsonNode sanitizedNode = sanitizeJsonNode(rootNode); + return objectMapper.writeValueAsString(sanitizedNode); + } catch (Exception e) { + log.warn("[XSS Filter] JSON parsing failed, fallback to text sanitize: {}", e.getMessage()); + return sanitizeXss(jsonBody); + } + } + + String sanitizeFormBody(String formBody) { + try { + log.debug("[XSS Filter] Parsing form-urlencoded body"); + return Arrays.stream(formBody.split("&")) + .map(pair -> { + String[] keyValue = pair.split("=", 2); + if (keyValue.length == 2) { + String key = URLDecoder.decode(keyValue[0], StandardCharsets.UTF_8); + String value = URLDecoder.decode(keyValue[1], StandardCharsets.UTF_8); + String sanitizedValue = sanitizeXss(value); + log.debug("[XSS Filter] Form field '{}': '{}' -> '{}'", key, value, sanitizedValue); + return URLEncoder.encode(key, StandardCharsets.UTF_8) + "=" + + URLEncoder.encode(sanitizedValue, StandardCharsets.UTF_8); + } + return pair; + }) + .collect(Collectors.joining("&")); + } catch (Exception e) { + log.warn("[XSS Filter] Form parsing failed, fallback to text sanitize: {}", e.getMessage()); + return sanitizeXss(formBody); + } + } + + + private JsonNode sanitizeJsonNode(JsonNode node) { + if (node.isTextual()) { + return objectMapper.getNodeFactory().textNode(sanitizeXss(node.asText())); + } else if (node.isObject()) { + ObjectNode objectNode = objectMapper.createObjectNode(); + node.fields().forEachRemaining(entry -> + objectNode.set(entry.getKey(), sanitizeJsonNode(entry.getValue())) + ); + return objectNode; + } else if (node.isArray()) { + var arrayNode = objectMapper.createArrayNode(); + node.forEach(item -> arrayNode.add(sanitizeJsonNode(item))); + return arrayNode; + } + return node; + } + + public static class Config { + // 설정이 필요한 경우 여기에 추가 + } +} \ No newline at end of file diff --git a/backend/gateway/src/main/java/mapzip/gateway/util/JwtUtil.java b/backend/gateway/src/main/java/mapzip/gateway/util/JwtUtil.java new file mode 100644 index 00000000..12250d2d --- /dev/null +++ b/backend/gateway/src/main/java/mapzip/gateway/util/JwtUtil.java @@ -0,0 +1,46 @@ +package mapzip.gateway.util; + +import io.jsonwebtoken.*; +import io.jsonwebtoken.security.Keys; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import javax.crypto.SecretKey; +import java.util.Date; + +@Component +public class JwtUtil { + + private final String secret; + + public JwtUtil(@Value("${jwt.secret}") String secret) { + this.secret = secret; + } + + private SecretKey getSigningKey() { + return Keys.hmacShaKeyFor(secret.getBytes()); + } + + public Claims extractAllClaims(String token) { + return Jwts.parser() + .verifyWith(getSigningKey()) + .build() + .parseSignedClaims(token) + .getPayload(); + } + + public String extractUserId(String token) { + return extractAllClaims(token).getSubject(); + } + + public TokenValidationResult validateTokenWithResult(String token) { + try { + extractAllClaims(token); + return TokenValidationResult.VALID; + } catch (ExpiredJwtException e) { + return TokenValidationResult.EXPIRED; // 만료된 토큰 + } catch (JwtException | IllegalArgumentException e) { + return TokenValidationResult.INVALID; // 서명 오류 등 + } + } +} \ No newline at end of file diff --git a/backend/gateway/src/main/java/mapzip/gateway/util/TokenValidationResult.java b/backend/gateway/src/main/java/mapzip/gateway/util/TokenValidationResult.java new file mode 100644 index 00000000..71cc195f --- /dev/null +++ b/backend/gateway/src/main/java/mapzip/gateway/util/TokenValidationResult.java @@ -0,0 +1,7 @@ +package mapzip.gateway.util; + +public enum TokenValidationResult { + VALID, + INVALID, + EXPIRED +} \ No newline at end of file diff --git a/backend/gateway/src/main/resources/application.yaml b/backend/gateway/src/main/resources/application.yaml new file mode 100644 index 00000000..d00fef9c --- /dev/null +++ b/backend/gateway/src/main/resources/application.yaml @@ -0,0 +1,8 @@ +#from config server +spring: + application: + name: gateway + config: + import: "configserver:http://config.service-platform.svc.cluster.local:8888" + profiles: + active: dev diff --git a/backend/gateway/src/test/java/mapzip/gateway/GatewayApplicationTests.java b/backend/gateway/src/test/java/mapzip/gateway/GatewayApplicationTests.java new file mode 100644 index 00000000..16ef993b --- /dev/null +++ b/backend/gateway/src/test/java/mapzip/gateway/GatewayApplicationTests.java @@ -0,0 +1,13 @@ +package mapzip.gateway; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class GatewayApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/backend/gateway/src/test/java/mapzip/gateway/config/GatewayMockTest.java b/backend/gateway/src/test/java/mapzip/gateway/config/GatewayMockTest.java new file mode 100644 index 00000000..aafb8d1e --- /dev/null +++ b/backend/gateway/src/test/java/mapzip/gateway/config/GatewayMockTest.java @@ -0,0 +1,130 @@ +package mapzip.gateway.config; + +import mapzip.gateway.filter.JwtAuthenticationFilter; +import mapzip.gateway.filter.XssProtectionFilter; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.cloud.gateway.filter.GatewayFilter; +import org.springframework.cloud.gateway.route.Route; +import org.springframework.cloud.gateway.route.RouteLocator; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Primary; +import org.springframework.test.context.TestPropertySource; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; + +@SpringBootTest +@TestPropertySource(properties = { + "jwt.secret=test-secret-key-for-testing-purposes-only", + "spring.cloud.config.enabled=false" +}) +class GatewayMockTest { + + @Autowired + private RouteLocator routeLocator; + + @Autowired + private JwtAuthenticationFilter jwtAuthenticationFilter; + + @Autowired + private XssProtectionFilter xssProtectionFilter; + + @TestConfiguration + static class TestConfig { + + @Bean + @Primary + public JwtAuthenticationFilter jwtAuthenticationFilter() { + return mock(JwtAuthenticationFilter.class); + } + + @Bean + @Primary + public XssProtectionFilter xssProtectionFilter() { + return mock(XssProtectionFilter.class); + } + } + + + @Test + void shouldConfigureAuthServiceRoute() { + // Mock 필터 설정 - 실제 필터 로직 없이 통과만 하도록 설정 + doReturn(mockGatewayFilter()).when(jwtAuthenticationFilter).apply(any(JwtAuthenticationFilter.Config.class)); + doReturn(mockGatewayFilter()).when(xssProtectionFilter).apply(any(XssProtectionFilter.Config.class)); + + // 설정된 모든 라우트 조회 + List routes = routeLocator.getRoutes().collectList().block(); + + // auth-service 라우트 찾기 + Route authRoute = routes.stream() + .filter(route -> "auth-service".equals(route.getId())) + .findFirst() + .orElseThrow(() -> new AssertionError("auth-service route not found")); + + // URI 검증: 인증 서비스의 올바른 주소로 라우팅되는지 확인 + assertThat(authRoute.getUri().toString()) + .isEqualTo("http://auth.service-platform:50051"); + // 경로 패턴 검증: /auth/** 패턴이 설정되어 있는지 확인 + assertThat(authRoute.getPredicate().toString()) + .contains("/auth/**"); + } + + + @Test + void shouldConfigureRecommendServiceRoute() { + doReturn(mockGatewayFilter()).when(jwtAuthenticationFilter).apply(any(JwtAuthenticationFilter.Config.class)); + doReturn(mockGatewayFilter()).when(xssProtectionFilter).apply(any(XssProtectionFilter.Config.class)); + + List routes = routeLocator.getRoutes().collectList().block(); + + + Route recommendRoute = routes.stream() + .filter(route -> "recommend-service".equals(route.getId())) + .findFirst() + .orElseThrow(() -> new AssertionError("recommend-service route not found")); + + + assertThat(recommendRoute.getUri().toString()) + .isEqualTo("http://recommend.service-recommend:50051"); + + assertThat(recommendRoute.getPredicate().toString()) + .contains("/recommend/**"); + } + + + @Test + void shouldConfigureAllRoutes() { + doReturn(mockGatewayFilter()).when(jwtAuthenticationFilter).apply(any(JwtAuthenticationFilter.Config.class)); + doReturn(mockGatewayFilter()).when(xssProtectionFilter).apply(any(XssProtectionFilter.Config.class)); + + List routes = routeLocator.getRoutes().collectList().block(); + + // 라우트 개수 검증: 정확히 4개의 서비스 라우트가 설정되어야 함 + assertThat(routes).hasSize(4); + + // 모든 라우트 ID 추출 + List routeIds = routes.stream() + .map(Route::getId) + .toList(); + + // 라우트 ID 검증: 4개 마이크로서비스 라우트가 모두 존재하는지 확인 + assertThat(routeIds).containsExactlyInAnyOrder( + "auth-service", // 인증 서비스 + "recommend-service", // 추천 서비스 + "review-service", // 리뷰 서비스 + "schedule-service" // 스케줄 서비스 + ); + } + + // 테스트용 더미 필터 생성 + private GatewayFilter mockGatewayFilter() { + return (exchange, chain) -> chain.filter(exchange); + } +} \ No newline at end of file diff --git a/backend/gateway/src/test/java/mapzip/gateway/filter/JwtAuthenticationFilterTest.java b/backend/gateway/src/test/java/mapzip/gateway/filter/JwtAuthenticationFilterTest.java new file mode 100644 index 00000000..ed877712 --- /dev/null +++ b/backend/gateway/src/test/java/mapzip/gateway/filter/JwtAuthenticationFilterTest.java @@ -0,0 +1,186 @@ +package mapzip.gateway.filter; + +import com.fasterxml.jackson.databind.ObjectMapper; +import mapzip.gateway.util.JwtUtil; +import mapzip.gateway.util.TokenValidationResult; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.cloud.gateway.filter.GatewayFilter; +import org.springframework.cloud.gateway.filter.GatewayFilterChain; +import org.springframework.http.HttpCookie; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseCookie; +import org.springframework.mock.http.server.reactive.MockServerHttpRequest; +import org.springframework.mock.web.server.MockServerWebExchange; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +import java.nio.charset.StandardCharsets; + +class JwtAuthenticationFilterTest { + + @Mock + private JwtUtil jwtUtil; + + @Mock + private GatewayFilterChain filterChain; + + private JwtAuthenticationFilter jwtAuthenticationFilter; + private ObjectMapper objectMapper; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + objectMapper = new ObjectMapper(); + jwtAuthenticationFilter = new JwtAuthenticationFilter(jwtUtil, objectMapper); + } + + @Test + void shouldAllowLoginRequest() { + // Given + MockServerHttpRequest request = MockServerHttpRequest + .get("/auth/kakao/login") + .build(); + MockServerWebExchange exchange = MockServerWebExchange.from(request); + + when(filterChain.filter(any())).thenReturn(Mono.empty()); + + // When + GatewayFilter filter = jwtAuthenticationFilter.apply(new JwtAuthenticationFilter.Config()); + Mono result = filter.filter(exchange, filterChain); + + // Then + StepVerifier.create(result) + .verifyComplete(); + + verify(filterChain).filter(exchange); + verifyNoInteractions(jwtUtil); + } + + @Test + void shouldReturn401WithTokenInvalidWhenNoJwtCookie() { + // Given + MockServerHttpRequest request = MockServerHttpRequest + .get("/auth/profile") + .build(); + MockServerWebExchange exchange = MockServerWebExchange.from(request); + + // When + GatewayFilter filter = jwtAuthenticationFilter.apply(new JwtAuthenticationFilter.Config()); + Mono result = filter.filter(exchange, filterChain); + + // Then + StepVerifier.create(result) + .verifyComplete(); + + assertEquals(HttpStatus.UNAUTHORIZED, exchange.getResponse().getStatusCode()); + assertTrue(exchange.getResponse().getHeaders().getFirst("Content-Type").contains("application/json")); + + // 응답 바디에 TOKEN_INVALID가 포함되어 있는지 확인 + String responseBody = exchange.getResponse().getBodyAsString().block(); + assertTrue(responseBody.contains("TOKEN_INVALID")); + + verifyNoInteractions(filterChain); + } + + @Test + void shouldReturn401WithTokenInvalidWhenInvalidToken() { + // Given + String tokenValue = "invalid-token"; + HttpCookie cookie = new HttpCookie("accessToken", tokenValue); + + MockServerHttpRequest request = MockServerHttpRequest + .get("/auth/profile") + .cookie(cookie) + .build(); + MockServerWebExchange exchange = MockServerWebExchange.from(request); + + when(jwtUtil.validateTokenWithResult("invalid-token")).thenReturn(TokenValidationResult.INVALID); + + // When + GatewayFilter filter = jwtAuthenticationFilter.apply(new JwtAuthenticationFilter.Config()); + Mono result = filter.filter(exchange, filterChain); + + // Then + StepVerifier.create(result) + .verifyComplete(); + + assertEquals(HttpStatus.UNAUTHORIZED, exchange.getResponse().getStatusCode()); + + // 응답 바디에 TOKEN_INVALID가 포함되어 있는지 확인 + String responseBody = exchange.getResponse().getBodyAsString().block(); + assertTrue(responseBody.contains("TOKEN_INVALID")); + + verify(jwtUtil).validateTokenWithResult("invalid-token"); + verifyNoInteractions(filterChain); + } + + @Test + void shouldReturn401WithTokenExpiredWhenExpiredToken() { + // Given + String tokenValue = "expired-token"; + HttpCookie cookie = new HttpCookie("accessToken", tokenValue); + + MockServerHttpRequest request = MockServerHttpRequest + .get("/auth/profile") + .cookie(cookie) + .build(); + MockServerWebExchange exchange = MockServerWebExchange.from(request); + + when(jwtUtil.validateTokenWithResult("expired-token")).thenReturn(TokenValidationResult.EXPIRED); + + // When + GatewayFilter filter = jwtAuthenticationFilter.apply(new JwtAuthenticationFilter.Config()); + Mono result = filter.filter(exchange, filterChain); + + // Then + StepVerifier.create(result) + .verifyComplete(); + + assertEquals(HttpStatus.UNAUTHORIZED, exchange.getResponse().getStatusCode()); + + // 응답 바디에 TOKEN_EXPIRED가 포함되어 있는지 확인 + String responseBody = exchange.getResponse().getBodyAsString().block(); + assertTrue(responseBody.contains("TOKEN_EXPIRED")); + + verify(jwtUtil).validateTokenWithResult("expired-token"); + verifyNoInteractions(filterChain); + } + + @Test + void shouldPassThroughWhenValidToken() { + // Given + String userId = "testuser"; + String validToken = "valid-token"; + HttpCookie cookie = new HttpCookie("accessToken", validToken); + + MockServerHttpRequest request = MockServerHttpRequest + .get("/auth/profile") + .cookie(cookie) + .build(); + MockServerWebExchange exchange = MockServerWebExchange.from(request); + + when(jwtUtil.validateTokenWithResult(validToken)).thenReturn(TokenValidationResult.VALID); + when(jwtUtil.extractUserId(validToken)).thenReturn(userId); + when(filterChain.filter(any())).thenReturn(Mono.empty()); + + // When + GatewayFilter filter = jwtAuthenticationFilter.apply(new JwtAuthenticationFilter.Config()); + Mono result = filter.filter(exchange, filterChain); + + // Then + StepVerifier.create(result) + .verifyComplete(); + + verify(jwtUtil).validateTokenWithResult(validToken); + verify(jwtUtil).extractUserId(validToken); + verify(filterChain).filter(any()); + } +} \ No newline at end of file diff --git a/backend/gateway/src/test/java/mapzip/gateway/filter/XssProtectionFilterTest.java b/backend/gateway/src/test/java/mapzip/gateway/filter/XssProtectionFilterTest.java new file mode 100644 index 00000000..08ff0e36 --- /dev/null +++ b/backend/gateway/src/test/java/mapzip/gateway/filter/XssProtectionFilterTest.java @@ -0,0 +1,89 @@ +package mapzip.gateway.filter; + +import org.junit.jupiter.api.Test; +import org.springframework.http.MediaType; +import org.springframework.mock.http.server.reactive.MockServerHttpRequest; +import org.springframework.mock.web.server.MockServerWebExchange; +import org.springframework.web.server.ServerWebExchange; +import java.lang.reflect.Method; + +import static org.junit.jupiter.api.Assertions.*; + +class XssProtectionFilterTest { + + private final XssProtectionFilter filter = new XssProtectionFilter(); + + @Test + void testJsonBodySanitization() { + String maliciousJson = "{\"name\":\"John\",\"message\":\"Hello world\"}"; + + MockServerHttpRequest request = MockServerHttpRequest.post("/test") + .contentType(MediaType.APPLICATION_JSON) + .body(maliciousJson); + + ServerWebExchange exchange = MockServerWebExchange.from(request); + + // JSON 파싱 테스트를 위한 직접 호출 + String result = filter.sanitizeJsonBody(maliciousJson); + + assertFalse(result.contains("Hello"; + + String result = filter.sanitizeXss(maliciousText); + + assertFalse(result.contains("Test\",\"tags\":[\"\",\"safe\"]}}"; + + String result = filter.sanitizeJsonBody(nestedJson); + + assertFalse(result.contains("John\r\n" + + "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\n" + + "Content-Disposition: form-data; name=\"file\"; filename=\"test.txt\"\r\n" + + "Content-Type: application/octet-stream\r\n\r\n" + + "binary data here\r\n" + + "------WebKitFormBoundary7MA4YWxkTrZu0gW--"; + + MediaType contentType = MediaType.parseMediaType("multipart/form-data; boundary=" + boundary); + + Method method = XssProtectionFilter.class.getDeclaredMethod("sanitizeMultipartBody", String.class, MediaType.class); + method.setAccessible(true); + String result = (String) method.invoke(filter, multipartBody, contentType); + + assertFalse(result.contains("