k8s.io/kubernetes@v1.29.3/test/images/agnhost/audit-proxy/main.go (about) 1 /* 2 Copyright 2019 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package auditproxy 18 19 import ( 20 "io" 21 "log" 22 "net/http" 23 "os" 24 25 "github.com/spf13/cobra" 26 27 "k8s.io/apimachinery/pkg/runtime" 28 "k8s.io/apimachinery/pkg/runtime/serializer/json" 29 auditinstall "k8s.io/apiserver/pkg/apis/audit/install" 30 auditv1 "k8s.io/apiserver/pkg/apis/audit/v1" 31 "k8s.io/apiserver/pkg/audit" 32 ) 33 34 // CmdAuditProxy is used by agnhost Cobra. 35 var CmdAuditProxy = &cobra.Command{ 36 Use: "audit-proxy", 37 Short: "Listens on port 8080 for incoming audit events", 38 Long: "Used to test dynamic auditing. It listens on port 8080 for incoming audit events and writes them in a uniform manner to stdout.", 39 Args: cobra.MaximumNArgs(0), 40 Run: main, 41 } 42 43 var ( 44 encoder runtime.Encoder 45 decoder runtime.Decoder 46 ) 47 48 func main(cmd *cobra.Command, args []string) { 49 scheme := runtime.NewScheme() 50 auditinstall.Install(scheme) 51 serializer := json.NewSerializerWithOptions(json.DefaultMetaFactory, scheme, scheme, json.SerializerOptions{Pretty: false}) 52 encoder = audit.Codecs.EncoderForVersion(serializer, auditv1.SchemeGroupVersion) 53 decoder = audit.Codecs.UniversalDecoder(auditv1.SchemeGroupVersion) 54 55 http.HandleFunc("/", handler) 56 log.Fatal(http.ListenAndServe(":8080", nil)) 57 } 58 59 func handler(w http.ResponseWriter, req *http.Request) { 60 body, err := io.ReadAll(req.Body) 61 if err != nil { 62 log.Printf("could not read request body: %v", err) 63 w.WriteHeader(http.StatusInternalServerError) 64 return 65 } 66 el := &auditv1.EventList{} 67 68 if err := runtime.DecodeInto(decoder, body, el); err != nil { 69 log.Printf("failed decoding buf: %b, apiVersion: %s", body, auditv1.SchemeGroupVersion) 70 w.WriteHeader(http.StatusInternalServerError) 71 return 72 } 73 defer req.Body.Close() 74 75 // write events to stdout 76 for _, event := range el.Items { 77 err := encoder.Encode(&event, os.Stdout) 78 if err != nil { 79 log.Printf("could not encode audit event: %v", err) 80 w.WriteHeader(http.StatusInternalServerError) 81 return 82 } 83 } 84 w.WriteHeader(http.StatusOK) 85 }