main.go 2.4 KB

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