github.com/Racer159/jackal@v0.32.7-0.20240401174413-0bd2339e4f2e/src/internal/agent/http/server.go (about) 1 // SPDX-License-Identifier: Apache-2.0 2 // SPDX-FileCopyrightText: 2021-Present The Jackal Authors 3 4 // Package http provides a http server for the webhook and proxy. 5 package http 6 7 import ( 8 "fmt" 9 "net/http" 10 "time" 11 12 "github.com/Racer159/jackal/src/internal/agent/hooks" 13 "github.com/Racer159/jackal/src/pkg/message" 14 "github.com/prometheus/client_golang/prometheus/promhttp" 15 ) 16 17 // NewAdmissionServer creates a http.Server for the mutating webhook admission handler. 18 func NewAdmissionServer(port string) *http.Server { 19 message.Debugf("http.NewServer(%s)", port) 20 21 // Instances hooks 22 podsMutation := hooks.NewPodMutationHook() 23 fluxGitRepositoryMutation := hooks.NewGitRepositoryMutationHook() 24 argocdApplicationMutation := hooks.NewApplicationMutationHook() 25 argocdRepositoryMutation := hooks.NewRepositoryMutationHook() 26 27 // Routers 28 ah := newAdmissionHandler() 29 mux := http.NewServeMux() 30 mux.Handle("/healthz", healthz()) 31 mux.Handle("/mutate/pod", ah.Serve(podsMutation)) 32 mux.Handle("/mutate/flux-gitrepository", ah.Serve(fluxGitRepositoryMutation)) 33 mux.Handle("/mutate/argocd-application", ah.Serve(argocdApplicationMutation)) 34 mux.Handle("/mutate/argocd-repository", ah.Serve(argocdRepositoryMutation)) 35 mux.Handle("/metrics", promhttp.Handler()) 36 37 return &http.Server{ 38 Addr: fmt.Sprintf(":%s", port), 39 Handler: mux, 40 ReadHeaderTimeout: 5 * time.Second, // Set ReadHeaderTimeout to avoid Slowloris attacks 41 } 42 } 43 44 // NewProxyServer creates and returns an http proxy server. 45 func NewProxyServer(port string) *http.Server { 46 message.Debugf("http.NewHTTPProxy(%s)", port) 47 48 mux := http.NewServeMux() 49 mux.Handle("/healthz", healthz()) 50 mux.Handle("/", ProxyHandler()) 51 mux.Handle("/metrics", promhttp.Handler()) 52 53 return &http.Server{ 54 Addr: fmt.Sprintf(":%s", port), 55 Handler: mux, 56 ReadHeaderTimeout: 5 * time.Second, // Set ReadHeaderTimeout to avoid Slowloris attacks 57 } 58 } 59 60 func healthz() http.HandlerFunc { 61 return func(w http.ResponseWriter, _ *http.Request) { 62 w.WriteHeader(http.StatusOK) 63 w.Write([]byte("ok")) 64 } 65 }