diff --git a/crd/crd.yaml b/crd/crd.yaml index d269aeaa7f..783d3f6b28 100644 --- a/crd/crd.yaml +++ b/crd/crd.yaml @@ -1,9 +1,9 @@ apiVersion: apiextensions.k8s.io/v1beta1 kind: CustomResourceDefinition metadata: - name: policies.policy.nirmata.io + name: policies.nirmata.io spec: - group: policy.nirmata.io + group: nirmata.io names: kind: Policy plural: policies diff --git a/main.go b/main.go index 6e9a6a8569..b65bd38667 100644 --- a/main.go +++ b/main.go @@ -2,23 +2,31 @@ package main import ( - "fmt" + "flag" + "log" + "os" "time" "github.com/nirmata/kube-policy/server" ) -var ( - kubeConfigFile string -) - func main() { - server := server.NewWebhookServer() - fmt.Println("WebHook server is running!") + var cert = flag.String("cert", "", "TLS certificate") + var key = flag.String("key", "", "TLS key in PEM format") + flag.Parse() + + if *cert == "" || *key == "" { + log.Fatal("TLS certificate or/and key is not set") + } + + logger := log.New(os.Stdout, "http: ", log.LstdFlags|log.Lshortfile) + logger.Printf("! Server is starting...") + server := server.NewWebhookServer(*cert, *key, logger) + logger.Printf("! WebHook server is running!") server.RunAsync() - time.Sleep(5 * time.Second) + time.Sleep(500500 * time.Second) server.Stop() - fmt.Println("WebHook server is stopped.") + logger.Printf("! WebHook server is stopped.") } diff --git a/server/server.go b/server/server.go index 1389d8e369..ab8e75a478 100644 --- a/server/server.go +++ b/server/server.go @@ -2,28 +2,26 @@ package server import ( "context" + "crypto/tls" "fmt" "log" "net/http" + "net/http/httputil" "time" ) -const ( // TODO: read these files from ~/.kube/config - clientCertFile = "/home/quest/.minikube/client.crt" - clientKeyFile = "/home/quest/.minikube/client.key" -) - type WebhookServer struct { server http.Server } func (ws *WebhookServer) serve(w http.ResponseWriter, r *http.Request) { fmt.Println("/mutate is called!") + httputil.DumpRequest(r, true) } func (ws *WebhookServer) RunAsync() { go func(server http.Server) { - err := server.ListenAndServeTLS(clientCertFile, clientKeyFile) + err := server.ListenAndServeTLS("", "") if err != nil { log.Fatal(err) } @@ -39,13 +37,23 @@ func (ws *WebhookServer) Stop() { } } -func NewWebhookServer() WebhookServer { +func NewWebhookServer(certFile string, keyFile string, logger *log.Logger) WebhookServer { var ws WebhookServer mux := http.NewServeMux() mux.HandleFunc("/mutate", ws.serve) + + var config tls.Config + pair, err := tls.LoadX509KeyPair(certFile, keyFile) + if err != nil { + log.Fatal("Unable to load certificate and key: ", err) + } + config.Certificates = []tls.Certificate{pair} + ws.server = http.Server{ - Addr: ":443", + Addr: ":443", // Listen on port for HTTPS requests + TLSConfig: &config, Handler: mux, + ErrorLog: logger, ReadTimeout: 5 * time.Second, WriteTimeout: 5 * time.Second} return ws