170 lines
4.2 KiB
Go
170 lines
4.2 KiB
Go
package main
|
|
|
|
import (
|
|
"crypto/hmac"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"os/exec"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
var (
|
|
deployMutex sync.Mutex
|
|
lastDeploy time.Time
|
|
)
|
|
|
|
type GiteaPayload struct {
|
|
Ref string `json:"ref"`
|
|
Repository struct {
|
|
Name string `json:"name"`
|
|
FullName string `json:"full_name"`
|
|
} `json:"repository"`
|
|
Pusher struct {
|
|
Username string `json:"username"`
|
|
} `json:"pusher"`
|
|
}
|
|
|
|
func main() {
|
|
port := os.Getenv("WEBHOOK_PORT")
|
|
if port == "" {
|
|
port = "9110"
|
|
}
|
|
|
|
secret := os.Getenv("WEBHOOK_SECRET")
|
|
deployScript := os.Getenv("DEPLOY_SCRIPT")
|
|
if deployScript == "" {
|
|
deployScript = "/docker/web-hosts/domains/test.coppertone.tech/deploy.sh"
|
|
}
|
|
targetBranch := os.Getenv("TARGET_BRANCH")
|
|
if targetBranch == "" {
|
|
targetBranch = "testing"
|
|
}
|
|
|
|
// Log all incoming requests
|
|
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
|
log.Printf("[REQUEST] %s %s from %s", r.Method, r.URL.Path, r.RemoteAddr)
|
|
log.Printf("[HEADERS] %v", r.Header)
|
|
|
|
// Only handle specific paths
|
|
if r.URL.Path != "/deploy" && r.URL.Path != "/health" {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
|
|
if r.URL.Path == "/health" {
|
|
w.Write([]byte("OK"))
|
|
return
|
|
}
|
|
|
|
// /deploy handler
|
|
if r.Method != http.MethodPost {
|
|
log.Printf("[REJECTED] Method %s not allowed", r.Method)
|
|
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
|
|
body, err := io.ReadAll(r.Body)
|
|
if err != nil {
|
|
log.Printf("[ERROR] Failed to read body: %v", err)
|
|
http.Error(w, "Failed to read body", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
log.Printf("[PAYLOAD] %s", string(body))
|
|
|
|
// Verify signature if secret is set
|
|
if secret != "" {
|
|
sig := r.Header.Get("X-Gitea-Signature")
|
|
if sig == "" {
|
|
sig = r.Header.Get("X-Hub-Signature-256")
|
|
if sig != "" {
|
|
sig = strings.TrimPrefix(sig, "sha256=")
|
|
}
|
|
}
|
|
if !verifySignature(body, sig, secret) {
|
|
log.Printf("Invalid signature from %s", r.RemoteAddr)
|
|
http.Error(w, "Invalid signature", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
}
|
|
|
|
// Parse payload
|
|
var payload GiteaPayload
|
|
if len(body) > 0 {
|
|
if err := json.Unmarshal(body, &payload); err != nil {
|
|
log.Printf("Failed to parse payload: %v", err)
|
|
}
|
|
}
|
|
|
|
// Check branch (allow force deploy with query param)
|
|
force := r.URL.Query().Get("force") == "true"
|
|
expectedRef := "refs/heads/" + targetBranch
|
|
if payload.Ref != "" && payload.Ref != expectedRef && !force {
|
|
log.Printf("Skipping deploy - branch %s != %s", payload.Ref, expectedRef)
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(map[string]string{
|
|
"status": "skipped",
|
|
"message": fmt.Sprintf("Not %s branch", targetBranch),
|
|
})
|
|
return
|
|
}
|
|
|
|
// Rate limit - no more than once per 30 seconds
|
|
deployMutex.Lock()
|
|
if time.Since(lastDeploy) < 30*time.Second {
|
|
deployMutex.Unlock()
|
|
log.Printf("Rate limited - last deploy was %v ago", time.Since(lastDeploy))
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(map[string]string{
|
|
"status": "rate_limited",
|
|
"message": "Please wait before deploying again",
|
|
})
|
|
return
|
|
}
|
|
lastDeploy = time.Now()
|
|
deployMutex.Unlock()
|
|
|
|
log.Printf("Triggering deploy for %s (pusher: %s)", payload.Repository.FullName, payload.Pusher.Username)
|
|
|
|
// Run deploy script
|
|
go func() {
|
|
cmd := exec.Command(deployScript)
|
|
cmd.Dir = "/docker/web-hosts/domains/test.coppertone.tech"
|
|
output, err := cmd.CombinedOutput()
|
|
if err != nil {
|
|
log.Printf("Deploy failed: %v\n%s", err, output)
|
|
} else {
|
|
log.Printf("Deploy successful:\n%s", output)
|
|
}
|
|
}()
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(map[string]string{
|
|
"status": "success",
|
|
"message": "Deployment triggered",
|
|
})
|
|
})
|
|
|
|
|
|
log.Printf("Webhook receiver listening on :%s (branch: %s)", port, targetBranch)
|
|
log.Fatal(http.ListenAndServe(":"+port, nil))
|
|
}
|
|
|
|
func verifySignature(payload []byte, signature, secret string) bool {
|
|
if signature == "" {
|
|
return false
|
|
}
|
|
mac := hmac.New(sha256.New, []byte(secret))
|
|
mac.Write(payload)
|
|
expected := hex.EncodeToString(mac.Sum(nil))
|
|
return hmac.Equal([]byte(expected), []byte(signature))
|
|
}
|