Files
web-hosts/webhook/main.go
2025-12-26 13:17:19 +01:00

270 lines
6.8 KiB
Go

package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"time"
)
const (
domainsDir = "/docker/web-hosts/domains"
logsDir = "/docker/web-hosts/logs"
)
var (
deployMutex sync.Mutex
lastDeploys = make(map[string]time.Time)
domainConfig = make(map[string]DomainConfig)
)
type DomainConfig struct {
Secret string
TargetBranch string
DeployScript string
}
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 loadConfig() {
// Load domain configurations from environment
// Format: WEBHOOK_<DOMAIN_UNDERSCORE>_SECRET, WEBHOOK_<DOMAIN_UNDERSCORE>_BRANCH
// e.g., WEBHOOK_TEST_COPPERTONE_TECH_SECRET
domains := []string{
"test.coppertone.tech",
"chuckie.coppertone.tech",
"dev.coppertone.tech",
"games.coppertone.tech",
"coppertone.tech",
}
globalSecret := os.Getenv("WEBHOOK_SECRET")
for _, domain := range domains {
envKey := strings.ReplaceAll(strings.ReplaceAll(domain, ".", "_"), "-", "_")
envKey = strings.ToUpper(envKey)
secret := os.Getenv("WEBHOOK_" + envKey + "_SECRET")
if secret == "" {
secret = globalSecret
}
branch := os.Getenv("WEBHOOK_" + envKey + "_BRANCH")
if branch == "" {
branch = "main"
}
deployScript := filepath.Join(domainsDir, domain, "deploy.sh")
if _, err := os.Stat(deployScript); os.IsNotExist(err) {
altDeploy := filepath.Join(domainsDir, domain, "scripts", "deploy.sh")
if _, altErr := os.Stat(altDeploy); altErr == nil {
deployScript = altDeploy
}
}
domainConfig[domain] = DomainConfig{
Secret: secret,
TargetBranch: branch,
DeployScript: deployScript,
}
log.Printf("Configured domain: %s (branch: %s, secret: %v)", domain, branch, secret != "")
}
}
func main() {
port := os.Getenv("WEBHOOK_PORT")
if port == "" {
port = "9090"
}
loadConfig()
http.HandleFunc("/health", healthHandler)
http.HandleFunc("/deploy/", deployHandler)
http.HandleFunc("/", rootHandler)
log.Printf("Webhook service listening on :%s", port)
log.Fatal(http.ListenAndServe("127.0.0.1:"+port, nil))
}
func rootHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("[REQUEST] %s %s from %s", r.Method, r.URL.Path, r.RemoteAddr)
if r.URL.Path == "/" {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"service": "web-hosts-webhook",
"status": "running",
"domains": getDomainList(),
})
return
}
http.NotFound(w, r)
}
func healthHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("OK"))
}
func deployHandler(w http.ResponseWriter, r *http.Request) {
// Extract domain from path: /deploy/<domain>
path := strings.TrimPrefix(r.URL.Path, "/deploy/")
domain := strings.TrimSuffix(path, "/")
log.Printf("[DEPLOY] Request for domain: %s from %s", domain, r.RemoteAddr)
log.Printf("[HEADERS] %v", r.Header)
config, exists := domainConfig[domain]
if !exists {
log.Printf("[ERROR] Unknown domain: %s", domain)
http.Error(w, "Unknown domain", http.StatusNotFound)
return
}
// Check deploy script exists
if _, err := os.Stat(config.DeployScript); os.IsNotExist(err) {
log.Printf("[ERROR] Deploy script not found: %s", config.DeployScript)
http.Error(w, "Deploy script not found", http.StatusNotFound)
return
}
if r.Method != http.MethodPost {
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 configured
if config.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, config.Secret) {
log.Printf("[REJECTED] Invalid signature for %s", domain)
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("[WARN] Failed to parse payload: %v", err)
}
}
// Check branch
force := r.URL.Query().Get("force") == "true"
expectedRef := "refs/heads/" + config.TargetBranch
if payload.Ref != "" && payload.Ref != expectedRef && !force {
log.Printf("[SKIP] Branch %s != %s for %s", payload.Ref, expectedRef, domain)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"status": "skipped",
"message": fmt.Sprintf("Not %s branch", config.TargetBranch),
})
return
}
// Rate limit per domain
deployMutex.Lock()
if last, ok := lastDeploys[domain]; ok && time.Since(last) < 30*time.Second {
deployMutex.Unlock()
log.Printf("[RATE_LIMITED] %s - last deploy %v ago", domain, time.Since(last))
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"status": "rate_limited",
"message": "Please wait before deploying again",
})
return
}
lastDeploys[domain] = time.Now()
deployMutex.Unlock()
log.Printf("[DEPLOY] Triggering deploy for %s (repo: %s, pusher: %s)",
domain, payload.Repository.FullName, payload.Pusher.Username)
// Run deploy in background
go runDeploy(domain, config)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"status": "success",
"message": fmt.Sprintf("Deployment triggered for %s", domain),
})
}
func runDeploy(domain string, config DomainConfig) {
logFile := filepath.Join(logsDir, domain+"-webhook.log")
cmd := exec.Command(config.DeployScript)
cmd.Dir = filepath.Dir(config.DeployScript)
output, err := cmd.CombinedOutput()
if err != nil {
log.Printf("[DEPLOY_FAILED] %s: %v\n%s", domain, err, output)
} else {
log.Printf("[DEPLOY_SUCCESS] %s:\n%s", domain, output)
}
// Append to log file
f, _ := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if f != nil {
fmt.Fprintf(f, "\n=== Deploy %s ===\n%s\n", time.Now().Format(time.RFC3339), output)
f.Close()
}
}
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))
}
func getDomainList() []string {
domains := make([]string, 0, len(domainConfig))
for d := range domainConfig {
domains = append(domains, d)
}
return domains
}