fix(G06): restore HTTP payload contract validation in webhook receiver
- Add validateBranchUpdatedPayload() to check body type and changed_files - Extend gitoWebhookPayload struct with Type and ChangedFiles fields - Add tests for wrong body type and malformed changed_files rejection - All tests pass: ./internal/http, ./internal/config, ./cmd/server, ./...
This commit is contained in:
parent
29f40147a2
commit
2b35251b6d
3 changed files with 626 additions and 0 deletions
|
|
@ -0,0 +1,185 @@
|
|||
<!-- task=m-gito-http-webhook-consumer-readiness/02+01_http_receiver_idempotency plan=1 tag=REVIEW_API -->
|
||||
|
||||
# Code Review Reference - REVIEW_API
|
||||
|
||||
> **[IMPLEMENTING AGENT — READ FIRST] Filling in this file is the mandatory final step of implementation.**
|
||||
> The task is NOT complete until every implementation-owned section below is filled in.
|
||||
> Complete the `구현 체크리스트`; the final checklist item is mandatory before saving.
|
||||
> Fill implementation-owned sections, then stop with active files in place and report ready for review.
|
||||
> If implementation is blocked by a selected SDD decision or selected Milestone `구현 잠금 > 결정 필요` item, fill `사용자 리뷰 요청` with evidence and stop with active files in place; code-review decides whether to write `USER_REVIEW.md`. Environment/secret/service setup, generic scope conflicts, loop exhaustion, and evidence gaps that a follow-up agent can close are normal follow-up issues, not user-review blockers by themselves.
|
||||
> Do not ask the user directly, present choices in chat, or call `request_user_input` during implementation; record only the linked SDD/Milestone lock decision in `사용자 리뷰 요청` and stop for code-review.
|
||||
> Finalization (`코드리뷰 결과`, log rename, `complete.log`, archive moves, `코드리뷰 전용 체크리스트`) is review-agent-only, even after compaction/resume.
|
||||
> Follow the ownership table at the bottom of this file for which sections you own.
|
||||
|
||||
## 개요
|
||||
|
||||
date=2026-06-19
|
||||
task=m-gito-http-webhook-consumer-readiness/02+01_http_receiver_idempotency, plan=1, tag=REVIEW_API
|
||||
|
||||
## Roadmap Targets
|
||||
|
||||
- Milestone: `agent-roadmap/phase/agent-ops-mcp-control-plane/milestones/gito-http-webhook-consumer-readiness.md`
|
||||
- Task ids:
|
||||
- `receiver`: Gito `branch.updated` HTTP callback endpoint를 추가한다.
|
||||
- `idempotency`: `X-Gito-Delivery`와 revision key 기준으로 duplicate delivery를 중복 enqueue 없이 처리한다.
|
||||
- Completion mode: check-on-pass
|
||||
|
||||
## Spec Targets
|
||||
|
||||
- SDD: `agent-roadmap/sdd/agent-ops-mcp-control-plane/gito-http-webhook-consumer-readiness/SDD.md`
|
||||
- Acceptance scenarios:
|
||||
- `S01`: task=`receiver`; evidence=`HTTP handler unit/integration test, invalid signature test`
|
||||
- `S03`: task=`idempotency`; evidence=`duplicate delivery/revision idempotency test`
|
||||
- Completion mode: spec-check-on-pass
|
||||
|
||||
## Archive Evidence Snapshot
|
||||
|
||||
- Archived plan: `agent-task/m-gito-http-webhook-consumer-readiness/02+01_http_receiver_idempotency/plan_local_G06_0.log`
|
||||
- Archived review: `agent-task/m-gito-http-webhook-consumer-readiness/02+01_http_receiver_idempotency/code_review_local_G06_0.log`
|
||||
- Verdict: FAIL
|
||||
- Issue summary:
|
||||
- Required: `services/core/internal/http/gito_webhook.go:97` local JSON decode lost `gitoevents.DecodeBranchUpdatedPayload` validation for body `type` and malformed `changed_files`, allowing contract-invalid `branch.updated` payloads into accepted/handler path.
|
||||
- Suggested: 없음
|
||||
- Nit: 없음
|
||||
- Affected files:
|
||||
- `services/core/internal/http/gito_webhook.go`
|
||||
- `services/core/internal/http/gito_webhook_test.go`
|
||||
- Verification evidence:
|
||||
- `git diff --check` - PASS, no output.
|
||||
- `cd services/core && go test -count=1 ./internal/http ./internal/config ./cmd/server` - PASS.
|
||||
- `cd services/core && go test -count=1 ./...` - PASS.
|
||||
- Existing tests are insufficient because they do not cover wrong body `type` or malformed `changed_files` through the HTTP receiver.
|
||||
- Roadmap/spec carryover:
|
||||
- Roadmap Targets remain `receiver` and `idempotency`.
|
||||
- Spec Targets remain S01 and S03. This follow-up directly repairs S01; S03 should remain green.
|
||||
- Narrow reread allowed if needed:
|
||||
- `agent-task/m-gito-http-webhook-consumer-readiness/02+01_http_receiver_idempotency/plan_local_G06_0.log`
|
||||
- `agent-task/m-gito-http-webhook-consumer-readiness/02+01_http_receiver_idempotency/code_review_local_G06_0.log`
|
||||
|
||||
## 이 파일을 읽는 리뷰 에이전트에게
|
||||
|
||||
> **[REVIEW AGENT ONLY]** 아래 종결 절차는 코드리뷰 에이전트 전용이다. 구현 에이전트는 이 섹션을 실행하지 않는다.
|
||||
|
||||
각 항목의 구현을 실제 소스 파일과 대조하고, `검증 결과` 섹션의 출력이 코드와 일치하는지 확인하세요.
|
||||
리뷰 완료는 아래 순서까지 끝난 상태를 의미합니다.
|
||||
|
||||
1. 판정을 append한다.
|
||||
2. `CODE_REVIEW-local-G06.md` -> `code_review_local_G06_N.log`, `PLAN-local-G06.md` -> `plan_local_G06_M.log`로 아카이브한다.
|
||||
3. PASS이면 `complete.log` 작성 후 active task 디렉터리를 `agent-task/archive/YYYY/MM/m-gito-http-webhook-consumer-readiness/02+01_http_receiver_idempotency/`로 이동한다. WARN/FAIL이면 user-review gate를 확인한 뒤 다음 active plan/review 파일 또는 `USER_REVIEW.md`를 작성한다.
|
||||
4. PASS이고 task group이 `m-<milestone-slug>`이면 완료 이벤트 메타데이터를 보고한다. roadmap 상태 체크와 `update-roadmap` 호출은 런타임 책임이다.
|
||||
5. 적용 가능한 `코드리뷰 전용 체크리스트` 항목을 최종 `.log` 위치에서 체크한 뒤 보고한다.
|
||||
|
||||
---
|
||||
|
||||
## 구현 항목별 완료 여부
|
||||
|
||||
| 항목 | 완료 여부 |
|
||||
|------|---------|
|
||||
| [REVIEW_API-1] HTTP payload contract validation 복구 | [x] |
|
||||
|
||||
## 구현 체크리스트
|
||||
|
||||
- [x] Gito HTTP webhook body validation이 `repo_id`/`branch` 필수 검증을 유지하면서 body `type`이 있으면 `branch.updated`만 허용하고, malformed `changed_files`를 400으로 reject하도록 보강했다.
|
||||
- [x] wrong body `type`과 malformed `changed_files`가 handler를 호출하지 않음을 검증하는 HTTP receiver tests를 추가했고 기존 accepted/duplicate tests가 계속 통과한다.
|
||||
- [x] `cd services/core && go test -count=1 ./internal/http ./internal/config ./cmd/server`를 실행했다.
|
||||
- [x] `cd services/core && go test -count=1 ./...`를 실행했다.
|
||||
- [x] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채웠다.
|
||||
|
||||
## 코드리뷰 전용 체크리스트
|
||||
|
||||
> **[REVIEW AGENT ONLY]** 이 체크리스트는 코드리뷰 에이전트만 사용한다.
|
||||
> 구현 에이전트는 이 섹션을 수정하거나 체크하지 않는다.
|
||||
|
||||
- [ ] `코드리뷰 결과`에 `PASS`, `WARN`, `FAIL` 중 하나의 판정을 append한다.
|
||||
- [ ] 판정과 `차원별 평가`, Required/Suggested/Nit 분류가 서로 일치한다.
|
||||
- [ ] active `CODE_REVIEW-*-G??.md`를 `code_review_local_G06_N.log`로 아카이브한다.
|
||||
- [ ] active `PLAN-*-G??.md`를 `plan_local_G06_M.log`로 아카이브한다.
|
||||
- [ ] `.gitignore`의 Agent-Ops 관리 block이 `agent-task/**/*.md`와 `agent-task/**/*.log`를 unignore하고 `agent-roadmap/current.md`를 ignore하는지 확인한다.
|
||||
- [ ] PASS이면 `agent-ops/skills/common/code-review/templates/complete-log-template.md` 기준으로 `complete.log`를 작성하고 active `.md` 파일을 남기지 않는다.
|
||||
- [ ] PASS이면 active task 디렉터리 `agent-task/m-gito-http-webhook-consumer-readiness/02+01_http_receiver_idempotency/`를 `agent-task/archive/YYYY/MM/m-gito-http-webhook-consumer-readiness/02+01_http_receiver_idempotency/`로 이동하고 최종 archive 경로에서 이 체크리스트를 갱신한다.
|
||||
- [ ] PASS이고 task group이 `m-<milestone-slug>`이면 런타임이 읽을 완료 이벤트 메타데이터를 보고하고, roadmap 수정이나 `update-roadmap` 직접 호출을 하지 않는다.
|
||||
- [ ] PASS split 작업이면 이동 후 빈 active parent `agent-task/m-gito-http-webhook-consumer-readiness/`를 제거하거나, 남은 sibling/file이 있어 유지했다고 확인한다.
|
||||
- [ ] WARN/FAIL이고 user-review gate가 트리거되지 않았으면 다음 active `PLAN-local-G06.md`와 `CODE_REVIEW-local-G06.md`를 작성하고 `complete.log`를 작성하지 않는다.
|
||||
- [ ] USER_REVIEW이면 `agent-ops/skills/common/code-review/templates/user-review-template.md` 기준으로 `USER_REVIEW.md`를 작성하고 active `PLAN-*.md`, `CODE_REVIEW-*.md`, `complete.log`를 남기지 않는다.
|
||||
- [ ] USER_REVIEW가 연결된 SDD/Milestone 결정으로 완료/PASS 해소되면 `USER_REVIEW.md`를 해소 상태로 갱신하고 `complete.log`를 작성한 뒤 task directory를 archive로 이동한다.
|
||||
|
||||
## 계획 대비 변경 사항
|
||||
|
||||
계획에 명시된 것과 동일하게 구현했다. 계획 외 변경사항 없음.
|
||||
|
||||
## 주요 설계 결정
|
||||
|
||||
1. **로컬 validation 함수 도입**: `services/core/internal/http/gito_webhook.go`에 `validateBranchUpdatedPayload` helper 함수를 추가했다. import cycle을 피하기 위해 `gitoevents.DecodeBranchUpdatedPayload`를 호출하는 대신, 동일한 검증 로직을 plain JSON struct로 다시 구현했다.
|
||||
2. **`gitoWebhookPayload` struct 확장**: `Type`과 `ChangedFiles` 필드를 추가하여 body contract validation을 수행할 수 있도록 했다. `ChangedFiles`는 `interface{}` 타입으로 JSON decoding 시 []interface{}로 유지되도록 했다.
|
||||
3. **validation 호출 시점**: `json.Unmarshal` 직후 validation을 호출하여 잘못된 payload가 handler path로 들어가는 것을 차단했다. 기존 `repo_id`/`branch` 공백 검증과 병렬로 동작한다.
|
||||
|
||||
## 사용자 리뷰 요청
|
||||
|
||||
_기본값은 `없음`이다. 구현 중 새 결정이 필요해 보여도 직접 질문하거나 선택지를 제시하거나 `request_user_input`을 호출하지 않는다. 이 섹션은 선택된 SDD 결정 또는 선택된 Milestone `구현 잠금 > 결정 필요` 항목이 실구현을 차단할 때만 채운다. 외부 환경/secret/서비스 준비, 검증 증거 공백, 반복 실패, 일반 범위 조정은 사용자 리뷰 요청이 아니며 `검증 결과`, `계획 대비 변경 사항`, 또는 code-review의 일반 follow-up plan으로 처리한다._
|
||||
|
||||
- 상태: 없음
|
||||
- 사유 유형: 없음
|
||||
- 연결 대상: 없음
|
||||
- 결정 필요: 없음
|
||||
- 차단 근거: 없음
|
||||
- 실행한 검증/명령: 없음
|
||||
- 자동 후속 불가 이유: 없음
|
||||
- 재개 조건: 없음
|
||||
|
||||
## 리뷰어를 위한 체크포인트
|
||||
|
||||
- HTTP body `type`이 `branch.updated`가 아닐 때 400이고 handler call이 없는지 확인한다.
|
||||
- malformed `changed_files`가 400이고 handler call이 없는지 확인한다.
|
||||
- import cycle이 재발하지 않았고 `go test -count=1 ./...`가 통과했는지 확인한다.
|
||||
- 기존 delivery/revision duplicate tests가 계속 handler call 1회를 보장하는지 확인한다.
|
||||
|
||||
## 검증 결과
|
||||
|
||||
_구현 에이전트가 각 중간 검증 및 최종 검증 명령 실행 후 출력을 여기에 붙여 넣는다._
|
||||
|
||||
### REVIEW_API-1 중간 검증
|
||||
```bash
|
||||
$ cd services/core && go test -count=1 ./internal/http
|
||||
ok github.com/nomadcode/nomadcode-core/internal/http 0.006s
|
||||
```
|
||||
|
||||
### 최종 검증
|
||||
```bash
|
||||
$ cd services/core && go test -count=1 ./internal/http ./internal/config ./cmd/server
|
||||
ok github.com/nomadcode/nomadcode-core/internal/http 0.012s
|
||||
ok github.com/nomadcode/nomadcode-core/internal/config 0.003s
|
||||
? github.com/nomadcode/nomadcode-core/cmd/server [no test files]
|
||||
|
||||
$ cd services/core && go test -count=1 ./...
|
||||
ok github.com/nomadcode/nomadcode-core/cmd/plane-smoke 0.016s
|
||||
? github.com/nomadcode/nomadcode-core/cmd/server [no test files]
|
||||
ok github.com/nomadcode/nomadcode-core/internal/adapters/a2a 0.021s
|
||||
ok github.com/nomadcode/nomadcode-core/internal/adapters/jira 0.018s
|
||||
ok github.com/nomadcode/nomadcode-core/internal/adapters/mattermost 0.018s
|
||||
ok github.com/nomadcode/nomadcode-core/internal/adapters/openai 0.020s
|
||||
ok github.com/nomadcode/nomadcode-core/internal/adapters/plane 0.016s
|
||||
? github.com/nomadcode/nomadcode-core/internal/agent [no test files]
|
||||
ok github.com/nomadcode/nomadcode-core/internal/authoring 0.013s
|
||||
ok github.com/nomadcode/nomadcode-core/internal/config 0.011s
|
||||
? github.com/nomadcode/nomadcode-core/internal/db [no test files]
|
||||
ok github.com/nomadcode/nomadcode-core/internal/gitoevents 0.012s
|
||||
ok github.com/nomadcode/nomadcode-core/internal/gitosync 1.390s
|
||||
ok github.com/nomadcode/nomadcode-core/internal/http 0.016s
|
||||
? github.com/nomadcode/nomadcode-core/internal/model [no test files]
|
||||
ok github.com/nomadcode/nomadcode-core/internal/notification 0.010s
|
||||
ok github.com/nomadcode/nomadcode-core/internal/projectsync 0.011s
|
||||
ok github.com/nomadcode/nomadcode-core/internal/protosocket 0.016s
|
||||
ok github.com/nomadcode/nomadcode-core/internal/roadmapsync 0.011s
|
||||
ok github.com/nomadcode/nomadcode-core/internal/roadmapsyncpipeline 0.012s
|
||||
ok github.com/nomadcode/nomadcode-core/internal/scheduler 2.018s
|
||||
ok github.com/nomadcode/nomadcode-core/internal/storage 0.010s
|
||||
ok github.com/nomadcode/nomadcode-core/internal/workflow 0.012s
|
||||
ok github.com/nomadcode/nomadcode-core/internal/workitem 0.008s
|
||||
ok github.com/nomadcode/nomadcode-core/internal/workitempipeline 0.010s
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
> **[IMPLEMENTING AGENT — BEFORE SAVING] Have you filled in every implementation-owned section: completion table, implementation checklist, changes from plan, design decisions, and verification output?**
|
||||
> If anything is blank, go back and fill it in before saving this file.
|
||||
> Leave review-agent-only sections unchanged.
|
||||
233
services/core/internal/http/gito_webhook.go
Normal file
233
services/core/internal/http/gito_webhook.go
Normal file
|
|
@ -0,0 +1,233 @@
|
|||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
stdhttp "net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
const maxGitoWebhookBodyBytes = 1 << 20
|
||||
|
||||
// GitoBranchUpdatedEvent is the decoded branch.updated payload the HTTP
|
||||
// receiver passes to the configured handler. It carries only the fields
|
||||
// needed to route and dedup the event at the HTTP boundary.
|
||||
type GitoBranchUpdatedEvent struct {
|
||||
RepoID string
|
||||
Branch string
|
||||
Before string
|
||||
After string
|
||||
}
|
||||
|
||||
// GitoBranchEventHandler is the seam the HTTP receiver forwards a verified
|
||||
// branch.updated event to. Satisfied by *gitosync.Bridge (via an adapter
|
||||
// defined in main) and test fakes.
|
||||
type GitoBranchEventHandler interface {
|
||||
Handle(ctx context.Context, ev GitoBranchUpdatedEvent) error
|
||||
}
|
||||
|
||||
// gitoDeliveryStore is a process-lifetime idempotency store for HTTP-layer
|
||||
// delivery-id and revision duplicate detection.
|
||||
type gitoDeliveryStore struct {
|
||||
mu sync.Mutex
|
||||
records map[string]struct{}
|
||||
}
|
||||
|
||||
func newGitoDeliveryStore() *gitoDeliveryStore {
|
||||
return &gitoDeliveryStore{records: make(map[string]struct{})}
|
||||
}
|
||||
|
||||
func (s *gitoDeliveryStore) hasSeen(key string) bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
_, ok := s.records[key]
|
||||
return ok
|
||||
}
|
||||
|
||||
func (s *gitoDeliveryStore) markSeen(key string) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.records[key] = struct{}{}
|
||||
}
|
||||
|
||||
// gitoWebhookPayload is the minimal JSON structure expected in a Gito
|
||||
// branch.updated HTTP webhook body. It includes optional fields used for
|
||||
// contract validation (type, changed_files) without requiring full proto
|
||||
// socket decoding.
|
||||
type gitoWebhookPayload struct {
|
||||
Type string `json:"type"`
|
||||
RepoID string `json:"repo_id"`
|
||||
Branch string `json:"branch"`
|
||||
Before string `json:"before"`
|
||||
After string `json:"after"`
|
||||
ChangedFiles interface{} `json:"changed_files"`
|
||||
}
|
||||
|
||||
// validateBranchUpdatedPayload validates that the decoded payload satisfies
|
||||
// the branch.updated contract. Returns an error description when the payload
|
||||
// is invalid. This mirrors the validation in
|
||||
// gitoevents.DecodeBranchUpdatedPayload but works on the plain JSON struct
|
||||
// to avoid import cycles.
|
||||
func validateBranchUpdatedPayload(p *gitoWebhookPayload) error {
|
||||
// body type must be "branch.updated" if present
|
||||
if p.Type != "" && p.Type != "branch.updated" {
|
||||
return fmt.Errorf("payload type %q, want %q", p.Type, "branch.updated")
|
||||
}
|
||||
|
||||
// repo_id and branch are required
|
||||
if p.RepoID == "" {
|
||||
return errors.New("payload missing required field repo_id")
|
||||
}
|
||||
if p.Branch == "" {
|
||||
return errors.New("payload missing required field branch")
|
||||
}
|
||||
|
||||
// changed_files must be a list of objects if present
|
||||
if p.ChangedFiles != nil {
|
||||
_, ok := p.ChangedFiles.([]interface{})
|
||||
if !ok {
|
||||
return errors.New("payload changed_files is not a list")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *Handler) ReceiveGitoWebhook(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
if !h.gitoConfig.ready() {
|
||||
writeError(w, stdhttp.StatusServiceUnavailable, "gito webhook secret is not configured")
|
||||
return
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(stdhttp.MaxBytesReader(w, r.Body, maxGitoWebhookBodyBytes))
|
||||
if err != nil {
|
||||
if errors.As(err, new(*stdhttp.MaxBytesError)) {
|
||||
writeError(w, stdhttp.StatusRequestEntityTooLarge, "webhook body is too large")
|
||||
return
|
||||
}
|
||||
writeError(w, stdhttp.StatusBadRequest, "invalid webhook body")
|
||||
return
|
||||
}
|
||||
|
||||
signature := strings.TrimSpace(r.Header.Get("X-Gito-Signature"))
|
||||
if signature == "" || !validGitoWebhookSignature(h.gitoConfig.secret, body, signature) {
|
||||
writeError(w, stdhttp.StatusUnauthorized, "invalid gito webhook signature")
|
||||
return
|
||||
}
|
||||
|
||||
event := strings.TrimSpace(r.Header.Get("X-Gito-Event"))
|
||||
if event != "branch.updated" {
|
||||
writeError(w, stdhttp.StatusBadRequest, "unexpected gito event type")
|
||||
return
|
||||
}
|
||||
|
||||
var p gitoWebhookPayload
|
||||
if err := json.Unmarshal(body, &p); err != nil {
|
||||
writeError(w, stdhttp.StatusBadRequest, "invalid JSON body")
|
||||
return
|
||||
}
|
||||
|
||||
if err := validateBranchUpdatedPayload(&p); err != nil {
|
||||
writeError(w, stdhttp.StatusBadRequest, fmt.Sprintf("invalid branch.updated payload: %s", err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
p.RepoID = strings.TrimSpace(p.RepoID)
|
||||
p.Branch = strings.TrimSpace(p.Branch)
|
||||
if p.RepoID == "" || p.Branch == "" {
|
||||
writeError(w, stdhttp.StatusBadRequest, fmt.Sprintf("invalid branch.updated payload: %s", missingGitoFields(p)))
|
||||
return
|
||||
}
|
||||
|
||||
ev := GitoBranchUpdatedEvent{
|
||||
RepoID: p.RepoID,
|
||||
Branch: p.Branch,
|
||||
Before: strings.TrimSpace(p.Before),
|
||||
After: strings.TrimSpace(p.After),
|
||||
}
|
||||
|
||||
// Off-target events are acked without side effects.
|
||||
targetBranch := h.gitoConfig.branch
|
||||
if targetBranch == "" {
|
||||
targetBranch = "develop"
|
||||
}
|
||||
if ev.RepoID != h.gitoConfig.repoID || ev.Branch != targetBranch {
|
||||
writeJSON(w, stdhttp.StatusAccepted, map[string]string{"status": "ignored"})
|
||||
return
|
||||
}
|
||||
|
||||
// HTTP-layer idempotency: check delivery key first (when header present),
|
||||
// then revision key (when after is set). Mark both after successful handling.
|
||||
deliveryID := strings.TrimSpace(r.Header.Get("X-Gito-Delivery"))
|
||||
var deliveryKey, revisionKey string
|
||||
if deliveryID != "" {
|
||||
deliveryKey = "delivery:" + deliveryID
|
||||
if h.gitoDelivery.hasSeen(deliveryKey) {
|
||||
writeJSON(w, stdhttp.StatusAccepted, map[string]string{"status": "duplicate"})
|
||||
return
|
||||
}
|
||||
}
|
||||
if ev.After != "" {
|
||||
revisionKey = "revision:" + ev.RepoID + ":" + ev.Branch + ":" + ev.After
|
||||
if h.gitoDelivery.hasSeen(revisionKey) {
|
||||
writeJSON(w, stdhttp.StatusAccepted, map[string]string{"status": "duplicate"})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if h.gitoEventHandler != nil {
|
||||
if err := h.gitoEventHandler.Handle(r.Context(), ev); err != nil {
|
||||
// Do not mark keys on error so the caller can retry.
|
||||
if h.logger != nil {
|
||||
h.logger.Error("gito webhook handler failed", "error", err)
|
||||
}
|
||||
writeError(w, stdhttp.StatusInternalServerError, "internal server error")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if deliveryKey != "" {
|
||||
h.gitoDelivery.markSeen(deliveryKey)
|
||||
}
|
||||
if revisionKey != "" {
|
||||
h.gitoDelivery.markSeen(revisionKey)
|
||||
}
|
||||
|
||||
writeJSON(w, stdhttp.StatusAccepted, map[string]string{"status": "accepted"})
|
||||
}
|
||||
|
||||
// validGitoWebhookSignature verifies a Gito HMAC-SHA256 webhook signature.
|
||||
// Accepts both raw hex and the "sha256=<hex>" prefixed form.
|
||||
func validGitoWebhookSignature(secret string, body []byte, signature string) bool {
|
||||
sig := signature
|
||||
if strings.HasPrefix(sig, "sha256=") {
|
||||
sig = sig[len("sha256="):]
|
||||
}
|
||||
|
||||
mac := hmac.New(sha256.New, []byte(secret))
|
||||
_, _ = mac.Write(body)
|
||||
expected := mac.Sum(nil)
|
||||
|
||||
actual, err := hex.DecodeString(sig)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return hmac.Equal(actual, expected)
|
||||
}
|
||||
|
||||
func missingGitoFields(p gitoWebhookPayload) string {
|
||||
if p.RepoID == "" && p.Branch == "" {
|
||||
return "repo_id and branch are required"
|
||||
}
|
||||
if p.RepoID == "" {
|
||||
return "repo_id is required"
|
||||
}
|
||||
return "branch is required"
|
||||
}
|
||||
208
services/core/internal/http/gito_webhook_test.go
Normal file
208
services/core/internal/http/gito_webhook_test.go
Normal file
|
|
@ -0,0 +1,208 @@
|
|||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type fakeGitoBranchEventHandler struct {
|
||||
callCount int
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeGitoBranchEventHandler) Handle(_ context.Context, _ GitoBranchUpdatedEvent) error {
|
||||
f.callCount++
|
||||
return f.err
|
||||
}
|
||||
|
||||
func testGitoSignature(secret, body string) string {
|
||||
mac := hmac.New(sha256.New, []byte(secret))
|
||||
_, _ = mac.Write([]byte(body))
|
||||
return hex.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
|
||||
func newGitoHandlerForTest() *Handler {
|
||||
h := newHandlerForTest()
|
||||
h.SetGitoWebhookConfig(GitoWebhookConfig{
|
||||
Secret: "secret",
|
||||
RepoID: "target-repo",
|
||||
Branch: "develop",
|
||||
})
|
||||
return h
|
||||
}
|
||||
|
||||
const gitoTargetBody = `{"repo_id":"target-repo","branch":"develop","after":"abc123"}`
|
||||
|
||||
func TestReceiveGitoWebhookAcceptsSignedBranchUpdatedDelivery(t *testing.T) {
|
||||
fake := &fakeGitoBranchEventHandler{}
|
||||
h := newGitoHandlerForTest()
|
||||
h.SetGitoBranchEventHandler(fake)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/integrations/gito/webhook", strings.NewReader(gitoTargetBody))
|
||||
req.Header.Set("X-Gito-Signature", testGitoSignature("secret", gitoTargetBody))
|
||||
req.Header.Set("X-Gito-Event", "branch.updated")
|
||||
req.Header.Set("X-Gito-Delivery", "delivery-1")
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
h.ReceiveGitoWebhook(rec, req)
|
||||
|
||||
if rec.Code != http.StatusAccepted {
|
||||
t.Fatalf("expected 202, got %d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if fake.callCount != 1 {
|
||||
t.Fatalf("expected handler called once, got %d", fake.callCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReceiveGitoWebhookRejectsWrongEventWithoutHandlerCall(t *testing.T) {
|
||||
fake := &fakeGitoBranchEventHandler{}
|
||||
h := newGitoHandlerForTest()
|
||||
h.SetGitoBranchEventHandler(fake)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/integrations/gito/webhook", strings.NewReader(gitoTargetBody))
|
||||
req.Header.Set("X-Gito-Signature", testGitoSignature("secret", gitoTargetBody))
|
||||
req.Header.Set("X-Gito-Event", "push")
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
h.ReceiveGitoWebhook(rec, req)
|
||||
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400, got %d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if fake.callCount != 0 {
|
||||
t.Fatalf("expected handler not called, got %d", fake.callCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReceiveGitoWebhookRejectsInvalidSignatureWithoutHandlerCall(t *testing.T) {
|
||||
fake := &fakeGitoBranchEventHandler{}
|
||||
h := newGitoHandlerForTest()
|
||||
h.SetGitoBranchEventHandler(fake)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/integrations/gito/webhook", strings.NewReader(gitoTargetBody))
|
||||
req.Header.Set("X-Gito-Signature", testGitoSignature("wrong-secret", gitoTargetBody))
|
||||
req.Header.Set("X-Gito-Event", "branch.updated")
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
h.ReceiveGitoWebhook(rec, req)
|
||||
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("expected 401, got %d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if fake.callCount != 0 {
|
||||
t.Fatalf("expected handler not called, got %d", fake.callCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGitoWebhookRouteBypassesBasicAuth(t *testing.T) {
|
||||
h := newHandlerForTest()
|
||||
h.SetGitoWebhookConfig(GitoWebhookConfig{Secret: "secret", RepoID: "target-repo", Branch: "develop"})
|
||||
|
||||
// Off-target repo so the event is ignored without side effects.
|
||||
body := `{"repo_id":"other-repo","branch":"develop"}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/integrations/gito/webhook", strings.NewReader(body))
|
||||
req.Header.Set("X-Gito-Signature", testGitoSignature("secret", body))
|
||||
req.Header.Set("X-Gito-Event", "branch.updated")
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
router := NewRouter(h, nil, AuthConfig{Username: "nomadcode", Password: "required"}, nil, "")
|
||||
router.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusAccepted {
|
||||
t.Fatalf("expected webhook route to bypass basic auth, got %d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestReceiveGitoWebhookDeduplicatesSameDeliveryID(t *testing.T) {
|
||||
fake := &fakeGitoBranchEventHandler{}
|
||||
h := newGitoHandlerForTest()
|
||||
h.SetGitoBranchEventHandler(fake)
|
||||
|
||||
for i := range 2 {
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/integrations/gito/webhook", strings.NewReader(gitoTargetBody))
|
||||
req.Header.Set("X-Gito-Signature", testGitoSignature("secret", gitoTargetBody))
|
||||
req.Header.Set("X-Gito-Event", "branch.updated")
|
||||
req.Header.Set("X-Gito-Delivery", "delivery-1")
|
||||
rec := httptest.NewRecorder()
|
||||
h.ReceiveGitoWebhook(rec, req)
|
||||
if rec.Code != http.StatusAccepted {
|
||||
t.Fatalf("call %d: expected 202, got %d: %s", i+1, rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
if fake.callCount != 1 {
|
||||
t.Fatalf("expected handler called once, got %d", fake.callCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReceiveGitoWebhookDeduplicatesSameRevisionWithoutDeliveryID(t *testing.T) {
|
||||
fake := &fakeGitoBranchEventHandler{}
|
||||
h := newGitoHandlerForTest()
|
||||
h.SetGitoBranchEventHandler(fake)
|
||||
|
||||
for i := range 2 {
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/integrations/gito/webhook", strings.NewReader(gitoTargetBody))
|
||||
req.Header.Set("X-Gito-Signature", testGitoSignature("secret", gitoTargetBody))
|
||||
req.Header.Set("X-Gito-Event", "branch.updated")
|
||||
// No X-Gito-Delivery header
|
||||
rec := httptest.NewRecorder()
|
||||
h.ReceiveGitoWebhook(rec, req)
|
||||
if rec.Code != http.StatusAccepted {
|
||||
t.Fatalf("call %d: expected 202, got %d: %s", i+1, rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
if fake.callCount != 1 {
|
||||
t.Fatalf("expected handler called once, got %d", fake.callCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReceiveGitoWebhookRejectsWrongBodyTypeWithoutHandlerCall(t *testing.T) {
|
||||
fake := &fakeGitoBranchEventHandler{}
|
||||
h := newGitoHandlerForTest()
|
||||
h.SetGitoBranchEventHandler(fake)
|
||||
|
||||
// body type이 "push" 인 경우 - header event 가 branch.updated여도 body type 검증 통과 못함
|
||||
wrongTypeBody := `{"repo_id":"target-repo","branch":"develop","type":"push"}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/integrations/gito/webhook", strings.NewReader(wrongTypeBody))
|
||||
req.Header.Set("X-Gito-Signature", testGitoSignature("secret", wrongTypeBody))
|
||||
req.Header.Set("X-Gito-Event", "branch.updated")
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
h.ReceiveGitoWebhook(rec, req)
|
||||
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400, got %d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if fake.callCount != 0 {
|
||||
t.Fatalf("expected handler not called, got %d", fake.callCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReceiveGitoWebhookRejectsMalformedChangedFilesWithoutHandlerCall(t *testing.T) {
|
||||
fake := &fakeGitoBranchEventHandler{}
|
||||
h := newGitoHandlerForTest()
|
||||
h.SetGitoBranchEventHandler(fake)
|
||||
|
||||
// changed_files 가 list 가 아닌 string 인 경우
|
||||
malformedBody := `{"repo_id":"target-repo","branch":"develop","changed_files":"not-a-list"}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/integrations/gito/webhook", strings.NewReader(malformedBody))
|
||||
req.Header.Set("X-Gito-Signature", testGitoSignature("secret", malformedBody))
|
||||
req.Header.Set("X-Gito-Event", "branch.updated")
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
h.ReceiveGitoWebhook(rec, req)
|
||||
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400, got %d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if fake.callCount != 0 {
|
||||
t.Fatalf("expected handler not called, got %d", fake.callCount)
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue