Skip to content

Conversation

@lvalentine6
Copy link
Member

@lvalentine6 lvalentine6 commented Sep 21, 2025

✨ 개요

  • WAF를 prod 서버에 적용합니다.

🧾 관련 이슈

#199

🔍 참고 사항 (선택)

Summary by CodeRabbit

  • 신기능

    • 웹 애플리케이션 방화벽(WAF) 도입으로 공통/봇/SQLi/익명 IP 등 관리형 규칙과 IP 기반 요청 속도 제한 적용.
    • WAF 로그 수집 활성화로 보안 이벤트 가시성 향상.
  • 개선

    • 애플리케이션 로드 밸런서와 WAF 연동으로 외부 트래픽 보호 강화.
  • 유지보수

    • 모니터링 향상을 위해 Datadog ECS 서비스 스케줄링을 DAEMON으로 전환하고 EC2 메타데이터/태그 수집 옵션 활성화.
    • 운영 편의를 위한 관리 이메일 및 요청 임계값 로컬 설정 추가.

@coderabbitai
Copy link

coderabbitai bot commented Sep 21, 2025

Walkthrough

AWS WAF 통합이 추가되었고, ALB에 Web ACL이 연결되었습니다. WAF 로그용 CloudWatch Log Group과 로깅 설정이 생성되었습니다. 공통 locals에 admin_email과 request_threshold가 추가되었습니다. prod 환경 tfvars에서 Datadog 서비스 스케줄링이 DAEMON으로 변경되고 EC2 관련 환경 변수가 추가되었습니다.

Changes

Cohort / File(s) Change Summary
Common Locals
terraform/common/locals.tf
admin_email 로컬 추가, 별도 locals 블록에 request_threshold = 200 추가
Common Integration & Logging
terraform/common/main.tf
module "waf" 도입(프로젝트명/임계값/태그 전달), aws_wafv2_web_acl_association로 ALB에 WAF 연결, WAF 로그용 aws_cloudwatch_log_groupaws_wafv2_web_acl_logging_configuration 생성
WAF Module
terraform/common/waf/main.tf, terraform/common/waf/variables.tf, terraform/common/waf/outputs.tf
신규 WAFv2 Web ACL(Regional) 정의: Rate limit 규칙(var.request_threshold) 및 여러 AWS Managed Rule 추가, 변수(project_name, request_threshold, tags) 및 출력(web_acl_arn) 추가
Prod Env Vars & Scheduling
terraform/prod/terraform.tfvars
Datadog ECS 서비스 스케줄링 REPLICA → DAEMON 변경, Datadog 컨테이너에 EC2 IMDSv2/태그/메타데이터 수집용 환경 변수 3종 추가

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant U as Client
    participant A as ALB
    participant W as WAF Web ACL
    participant S as ECS Service/Targets
    participant L as CloudWatch Logs

    U->>A: HTTP(S) 요청
    rect rgba(200, 230, 255, 0.3)
    note over A,W: 신규 통합된 경로
    A->>W: 요청 평가 위임
    alt 규칙 매치/RateLimit 초과
        W-->>A: 차단(Block)
        A-->>U: 403 응답
    else 허용(Allow)
        W-->>A: 허용
        A->>S: 요청 전달
        S-->>A: 응답
        A-->>U: 200/응답
    end
    end
    rect rgba(220, 255, 220, 0.3)
    note over W,L: 로깅 활성화
    W-->>L: WAF 평가/샘플 로그 전송
    end
Loading

Estimated code review effort

🎯 3 (보통) | ⏱️ ~25 minutes

Poem

토끼는 귀를 쫑긋, 방패를 척 두었네 🛡️
웨브의 파도에선 속도 제한, 나쁜 봇은 못 지나네
로그는 구름에 사뿐히 쌓이고 ☁️
데몬처럼 걷는 개, 데이터독이 지키네 🐶
오늘의 인프라, 깡총깡총 더 단단해졌네 🐇

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed PR 제목은 "취약점 스캐닝, 크롤링 방지 장기 대응 작업 Prod 적용"으로 prod 환경에 WAF를 적용해 스캐닝·크롤링을 차단하려는 주요 목적을 명확히 요약하고 있으며, 새 WAF 모듈·웹 ACL·연동·로깅·rate-limit 설정 등 변경사항과 직접 연관되어 있어 핵심 의도를 빠르게 전달합니다.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch develop

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions
Copy link

📄 Terraform Plan Summary

🛡️ Common Infrastructure


No plan summary

Status: ✅ No Changes


🚀 Production Environment


No plan summary

Status: ✅ No Changes


📋 Full Results: View in Actions

@sonarqubecloud
Copy link

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (6)
terraform/common/locals.tf (2)

7-7: admin_email 로컬 값 사용처 확인 또는 공통 태그에 반영 권장

현재 파일 내외에서 참조되지 않으면 죽은 설정입니다. local.common_tagsOwner로 넣어 CMDB/청구 추적에 활용하거나 미사용이면 제거해 주세요.


253-255: WAF 임계값(200/5분·IP)은 과도할 수 있음 — 환경별 변수로 외부화 + 운영 모니터링 모드 권장

  • 0.67 rps 수준 차단으로 정상 트래픽 오탐 가능성이 큽니다. Prod/Dev 별로 다르게 튜닝할 수 있도록 local이 아닌 상위 변수(tfvars)로 노출하는 편이 좋습니다.
  • 최초 운영은 ‘차단’이 아닌 관찰(COUNT)로 시작하여 메트릭/샘플을 보고 상향 조정하세요.
terraform/common/waf/variables.tf (1)

5-8: request_threshold에 입력값 검증 추가 권장

최소/최대 한계를 명시해 오입력으로 인한 대규모 차단을 예방하세요.

 variable "request_threshold" {
   type        = number
   description = "Rate-Limit 규칙에 적용할 5분당 IP별 최대 요청 수"
+  validation {
+    condition     = var.request_threshold >= 100 && var.request_threshold <= 2000000
+    error_message = "request_threshold는 100 이상 2,000,000 이하(5분당 요청 수)여야 합니다."
+  }
 }
terraform/common/main.tf (1)

55-60: 임계값을 local이 아닌 상위 변수로 전달하는 구조 권장

환경별로 다른 값을 tfvars에서 주입할 수 있게 request_threshold = var.request_threshold 형태가 더 운영 친화적입니다. 현재처럼 local 고정은 환경별 튜닝이 어렵습니다.

terraform/common/waf/main.tf (2)

10-27: Rate limit을 즉시 차단(block)보다는 초기에 관찰(count) 모드로 권장

새 규칙 도입 시 오탐 리스크가 큽니다. 1~2일 관찰 후 기준 상향/예외 경로(/health 등) scope-down 적용을 권장합니다.

예시:

-    action {
-      block {}
-    }
+    action { count {} }
+    # 필요 시 scope_down_statement로 특정 경로/메서드만 제한

91-101: Bot Control는 별도 과금 — 비용/효과 검토 필요

AWSManagedRulesBotControlRuleSet 활성화 시 추가 비용이 발생합니다. 실제 트래픽 특성 대비 차단 효과/비용을 확인해 주세요. 필요 시 우선 제외 또는 COUNT 모드로 시작을 고려하세요.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 739f230 and 813a4be.

📒 Files selected for processing (6)
  • terraform/common/locals.tf (2 hunks)
  • terraform/common/main.tf (1 hunks)
  • terraform/common/waf/main.tf (1 hunks)
  • terraform/common/waf/outputs.tf (1 hunks)
  • terraform/common/waf/variables.tf (1 hunks)
  • terraform/prod/terraform.tfvars (2 hunks)
🧰 Additional context used
🪛 GitHub Actions: Notify Discord on `/noti` Comment
terraform/common/waf/outputs.tf

[error] 86-86: No such file or directory

terraform/common/locals.tf

[error] 86-86: No such file or directory

terraform/common/waf/main.tf

[error] 86-86: No such file or directory

terraform/prod/terraform.tfvars

[error] 86: No such file or directory

terraform/common/waf/variables.tf

[error] 86-86: No such file or directory

terraform/common/main.tf

[error] 86-86: No such file or directory

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: test
🔇 Additional comments (4)
terraform/prod/terraform.tfvars (2)

14-14: Datadog 서비스를 DAEMON으로 전환 — 모듈 호환성/desired_count 미설정 확인 필요

ECS Service가 DAEMON일 때는 desired_count를 설정하면 오류가 납니다. 사용 중인 서비스 모듈이 스케줄링 전략에 따라 desired_count를 생략하도록 처리되어 있는지 확인해 주세요.


52-54: EC2 태그/메타데이터 수집용 IAM 권한 확인 — Datadog TaskRole 검색 실패

rg 검사 결과 레포에서 Datadog TaskRole 참조를 찾지 못했습니다. terraform/prod/terraform.tfvars(줄 52–54)의 DD_COLLECT_EC2_TAGS=true는 에이전트가 ec2:DescribeInstances 및 ec2:DescribeTags 권한을 필요로 합니다. Datadog 에이전트에 할당된 IAM role과 해당 정책 존재 여부를 확인하십시오.

예시 정책(JSON):

{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": ["ec2:DescribeInstances", "ec2:DescribeTags"],
    "Resource": "*"
  }]
}

검증 명령(레포 루트에서 실행):

rg -n --hidden -S 'datadog' || echo "datadog 참조 없음"
rg -n --hidden -S -e 'task_role_arn' -e 'task_role' -e 'role_arn' || echo "role 참조 없음"
rg -n --hidden -S -e 'ec2:DescribeInstances' -e 'ec2:DescribeTags' || echo "ec2 권한 참조 없음"
terraform/common/waf/outputs.tf (1)

1-3: LGTM — WAF ARN 출력 적절

모듈 간 연결(Association/로깅)에 필요한 최소 출력이 잘 노출되었습니다.

terraform/common/main.tf (1)

62-65: ALB ↔ WAF 연결 구성 적절

의존성도 출력값 참조로 자연스럽게 해소됩니다.

Copy link
Member

@leegwichan leegwichan left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CodeRabbit이 말하는 것 중에 추가할 만한 것들 확인해주세요!
고생하셨습니다 승로님!

@lvalentine6 lvalentine6 merged commit f241c9e into main Sep 22, 2025
19 of 20 checks passed
@github-actions
Copy link

🎉 This PR is included in version 1.9.0 🎉

The release is available on GitHub release

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants