diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..76675dd --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,46 @@ +name: release + +on: + workflow_dispatch: + push: + tags: + - "v*" + +jobs: + release: + runs-on: ubuntu-latest + steps: + - name: checkout + uses: actions/checkout@v4 + + - name: setup go dependencies + uses: actions/setup-go@v5 + with: + go-version: "1.22" + + - name: setup quemu + uses: docker/setup-qemu-action@v3 + + - name: setup docker buildx + uses: docker/setup-buildx-action@v3 + + - name: login to docker hub + uses: docker/login-action@v2 + with: + username: ${{ secrets.FLASHBOTS_DOCKERHUB_USERNAME }} + password: ${{ secrets.FLASHBOTS_DOCKERHUB_TOKEN }} + + - name: login to ghcr + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: build and publish backend release + uses: goreleaser/goreleaser-action@v5 + with: + args: release --clean + distribution: goreleaser + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.goreleaser.yml b/.goreleaser.yml new file mode 100644 index 0000000..af0f718 --- /dev/null +++ b/.goreleaser.yml @@ -0,0 +1,56 @@ +env: + - CGO_ENABLED=0 + +builds: + - main: ./cmd + ldflags: + - -s + - -w + - -X main.version={{ .Version }} + targets: + - linux_amd64 + - linux_arm64 + +archives: + - id: zip + format: zip + name_template: "{{ .ProjectName }}_{{ .Os }}_{{ .Arch }}" + files: + - none* + +checksum: + name_template: 'checksums.txt' + +release: + prerelease: auto + +dockers: + - dockerfile: Dockerfile.goreleaser + goarch: amd64 + goos: linux + use: buildx + build_flag_templates: + - --platform=linux/amd64 + image_templates: + - "flashbots/kube-sidecar-injector:{{ .Tag }}-amd64" + - "ghcr.io/flashbots/kube-sidecar-injector:{{ .Tag }}-amd64" + + - dockerfile: Dockerfile.goreleaser + goarch: arm64 + goos: linux + use: buildx + build_flag_templates: + - --platform=linux/arm64 + image_templates: + - "flashbots/kube-sidecar-injector:{{ .Tag }}-arm64" + - "ghcr.io/flashbots/kube-sidecar-injector:{{ .Tag }}-arm64" + +docker_manifests: + - name_template: "flashbots/kube-sidecar-injector:{{ .Tag }}" + image_templates: + - "flashbots/kube-sidecar-injector:{{ .Tag }}-amd64" + - "flashbots/kube-sidecar-injector:{{ .Tag }}-arm64" + - name_template: "ghcr.io/flashbots/kube-sidecar-injector:{{ .Tag }}" + image_templates: + - "ghcr.io/flashbots/kube-sidecar-injector:{{ .Tag }}-amd64" + - "ghcr.io/flashbots/kube-sidecar-injector:{{ .Tag }}-arm64" diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..1e61431 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,34 @@ +# stage: build --------------------------------------------------------- + +FROM golang:1.22-alpine as build + +RUN apk add --no-cache gcc musl-dev linux-headers + +WORKDIR /go/src/github.com/flashbots/kube-sidecar-injector + +COPY go.* ./ +RUN go mod download + +COPY . . + +ARG VERSION + +RUN --mount=type=cache,target=/root/.cache/go-build \ + go build \ + -o bin/kube-sidecar-injector \ + -ldflags "-s -w -X main.version=${VERSION}" \ + github.com/flashbots/kube-sidecar-injector/cmd + +# stage: run ----------------------------------------------------------- + +# TODO: change for distroless + +FROM alpine + +RUN apk add --no-cache ca-certificates + +WORKDIR /app + +COPY --from=build /go/src/github.com/flashbots/kube-sidecar-injector/bin/kube-sidecar-injector ./kube-sidecar-injector + +ENTRYPOINT ["/app/kube-sidecar-injector"] diff --git a/Dockerfile.goreleaser b/Dockerfile.goreleaser new file mode 100644 index 0000000..6fb2a22 --- /dev/null +++ b/Dockerfile.goreleaser @@ -0,0 +1,9 @@ +# stage: run + +FROM gcr.io/distroless/static-debian12 as runner + +WORKDIR /app + +COPY kube-sidecar-injector ./ + +ENTRYPOINT [ "./kube-sidecar-injector" ] diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..cd382dd --- /dev/null +++ b/Makefile @@ -0,0 +1,29 @@ +VERSION := $(shell git describe --tags --always --dirty="-dev" --match "v*.*.*" || echo "development" ) +VERSION := $(VERSION:v%=%) + +.PHONY: build +build: + @CGO_ENABLED=0 go build \ + -ldflags "-X main.version=${VERSION}" \ + -o ./bin/kube-sidecar-injector \ + github.com/flashbots/kube-sidecar-injector/cmd + +.PHONY: snapshot +snapshot: + @goreleaser release --snapshot --clean + +.PHONY: image +image: + @docker build \ + --build-arg VERSION=${VERSION} \ + --tag kube-sidecar-injector:${VERSION} \ + . + +.PHONY: deploy +deploy: + @kubectl \ + --context orbstack \ + apply \ + --filename deploy/cluster-role.yaml \ + --filename deploy/dummy.yaml \ + --filename deploy/deployment.yaml diff --git a/bin/.gitkeep b/bin/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/cert/cert.go b/cert/cert.go new file mode 100644 index 0000000..97efa8b --- /dev/null +++ b/cert/cert.go @@ -0,0 +1,22 @@ +package cert + +import ( + "crypto/tls" + "errors" +) + +type Bundle struct { + CA []byte + Pair *tls.Certificate +} + +type Source interface { + NewBundle() (*Bundle, error) +} + +var ( + ErrFailedToGenerateCert = errors.New("failed to generate certificate") + ErrFailedToGeneratePrivateKey = errors.New("failed to generate new private key") + ErrFailedToRegenerateCA = errors.New("failed to (re-)generate ca") + ErrUnspecifiedHosts = errors.New("no hosts specified for the certificate") +) diff --git a/cert/self_signer.go b/cert/self_signer.go new file mode 100644 index 0000000..5a0b35f --- /dev/null +++ b/cert/self_signer.go @@ -0,0 +1,170 @@ +package cert + +import ( + "bytes" + "crypto" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "fmt" + "math/big" + "net" + "time" +) + +type selfSigner struct { + organisation string + hosts []string + + serial *big.Int + + caCert []byte + caTemplate *x509.Certificate + caSigner crypto.Signer +} + +func NewSelfSigner(organisation string, hosts []string) (Source, error) { + if len(hosts) == 0 { + return nil, ErrUnspecifiedHosts + } + + serial, err := rand.Int(rand.Reader, (&big.Int{}).Exp(big.NewInt(2), big.NewInt(128), nil)) + if err != nil { + return nil, err + } + + return &selfSigner{ + organisation: organisation, + hosts: hosts, + + serial: serial, + }, nil +} + +func (s *selfSigner) NewBundle() (*Bundle, error) { + if s.caCert == nil { + if err := s.regenerateCA(); err != nil { + return nil, err + } + } + + cert, err := s.generateCert() + if err != nil { + return nil, err + } + + return &Bundle{ + CA: bytes.Clone(s.caCert), + Pair: cert, + }, nil +} + +func (s *selfSigner) newEcPrivateKey() (string, crypto.Signer, error) { + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + return "", nil, fmt.Errorf("%w: %w", ErrFailedToGeneratePrivateKey, err) + } + + bts, err := x509.MarshalECPrivateKey(key) + if err != nil { + return "", nil, fmt.Errorf("%w: %w", ErrFailedToGeneratePrivateKey, err) + } + + var buf bytes.Buffer + err = pem.Encode(&buf, &pem.Block{Type: "EC PRIVATE KEY", Bytes: bts}) + if err != nil { + return "", nil, fmt.Errorf("%w: %w", ErrFailedToGeneratePrivateKey, err) + } + + return buf.String(), key, nil +} + +func (s *selfSigner) regenerateCA() error { + recently := time.Now().AddDate(0, 0, -1).Round(time.Hour) + + _, sgn, err := s.newEcPrivateKey() + if err != nil { + return fmt.Errorf("%w: %w", ErrFailedToRegenerateCA, err) + } + + tpl := &x509.Certificate{ + BasicConstraintsValid: true, + IsCA: true, + SerialNumber: s.serial.Add(s.serial, big.NewInt(1)), + Subject: pkix.Name{Organization: []string{s.organisation}}, + + KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + + NotBefore: recently, + NotAfter: recently.AddDate(1, 0, 0), + } + + bts, err := x509.CreateCertificate(rand.Reader, tpl, tpl, sgn.Public(), sgn) + if err != nil { + return fmt.Errorf("%w: %w", ErrFailedToRegenerateCA, err) + } + + var buf bytes.Buffer + err = pem.Encode(&buf, &pem.Block{Type: "CERTIFICATE", Bytes: bts}) + if err != nil { + return fmt.Errorf("%w: %w", ErrFailedToRegenerateCA, err) + } + + s.caSigner = sgn + s.caCert = buf.Bytes() + s.caTemplate = tpl + + return nil +} + +func (s *selfSigner) generateCert() (*tls.Certificate, error) { + recently := time.Now().AddDate(0, 0, -1).Round(time.Hour) + + key, sgn, err := s.newEcPrivateKey() + if err != nil { + return nil, fmt.Errorf("%w: %w", ErrFailedToGenerateCert, err) + } + + cert := &x509.Certificate{ + BasicConstraintsValid: true, + SerialNumber: s.serial.Add(s.serial, big.NewInt(1)), + Subject: pkix.Name{CommonName: s.hosts[0], Organization: []string{s.organisation}}, + + KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + + NotBefore: recently, + NotAfter: recently.AddDate(1, 0, 0), + } + + for _, h := range s.hosts { + if ip := net.ParseIP(h); ip != nil { + cert.IPAddresses = append(cert.IPAddresses, ip) + } else { + cert.DNSNames = append(cert.DNSNames, h) + } + } + + bts, err := x509.CreateCertificate(rand.Reader, cert, s.caTemplate, sgn.Public(), s.caSigner) + if err != nil { + return nil, fmt.Errorf("%w: %w", ErrFailedToGenerateCert, err) + } + + var buf bytes.Buffer + err = pem.Encode(&buf, &pem.Block{Type: "CERTIFICATE", Bytes: bts}) + if err != nil { + return nil, fmt.Errorf("%w: %w", ErrFailedToGenerateCert, err) + } + + pair, err := tls.X509KeyPair(buf.Bytes(), []byte(key)) + if err != nil { + return nil, fmt.Errorf("%w: %w", ErrFailedToGenerateCert, err) + } + + return &pair, nil +} diff --git a/cmd/main.go b/cmd/main.go new file mode 100644 index 0000000..1c34fe3 --- /dev/null +++ b/cmd/main.go @@ -0,0 +1,81 @@ +package main + +import ( + "fmt" + "os" + + "github.com/flashbots/kube-sidecar-injector/config" + "github.com/flashbots/kube-sidecar-injector/global" + "github.com/flashbots/kube-sidecar-injector/logutils" + "github.com/urfave/cli/v2" + "go.uber.org/zap" +) + +const ( + envPrefix = "KUBE_SIDECAR_INJECTOR_" +) + +var ( + version = "development" +) + +func main() { + cfg := &config.Config{ + Version: version, + } + + flags := []cli.Flag{ + &cli.StringFlag{ + Destination: &cfg.Log.Level, + EnvVars: []string{envPrefix + "LOG_LEVEL"}, + Name: "log-level", + Usage: "logging level", + Value: "info", + }, + + &cli.StringFlag{ + Destination: &cfg.Log.Mode, + EnvVars: []string{envPrefix + "LOG_MODE"}, + Name: "log-mode", + Usage: "logging mode", + Value: "prod", + }, + } + + commands := []*cli.Command{ + CommandServe(cfg), + } + + app := &cli.App{ + Name: global.AppName, + Usage: "Inject sidecar containers into k8s pods", + Version: version, + + Flags: flags, + Commands: commands, + DefaultCommand: commands[0].Name, + + Before: func(_ *cli.Context) error { + // setup logger + l, err := logutils.NewLogger(&cfg.Log) + if err != nil { + return err + } + zap.ReplaceGlobals(l) + + return nil + }, + + Action: func(clictx *cli.Context) error { + return cli.ShowAppHelp(clictx) + }, + } + + defer func() { + zap.L().Sync() //nolint:errcheck + }() + if err := app.Run(os.Args); err != nil { + fmt.Fprintf(os.Stderr, "\nFailed with error:\n\n%s\n\n", err.Error()) + os.Exit(1) + } +} diff --git a/cmd/serve.go b/cmd/serve.go new file mode 100644 index 0000000..9edada1 --- /dev/null +++ b/cmd/serve.go @@ -0,0 +1,119 @@ +package main + +import ( + "fmt" + "slices" + + "github.com/flashbots/kube-sidecar-injector/config" + "github.com/flashbots/kube-sidecar-injector/global" + "github.com/flashbots/kube-sidecar-injector/server" + "github.com/urfave/cli/v2" +) + +const ( + categoryDebug = "DEBUG:" + categoryK8S = "KUBERNETES:" + categoryServer = "SERVER:" +) + +func CommandServe(cfg *config.Config) *cli.Command { + var rawServicePortNumber int64 + + debugFlags := []cli.Flag{} + + k8sFlags := []cli.Flag{ + &cli.StringFlag{ + Category: categoryK8S, + Destination: &cfg.K8S.Namespace, + EnvVars: []string{envPrefix + "NAMESPACE"}, + Name: "namespace", + Usage: "namespace in which the injector will run", + Value: "default", + }, + + &cli.StringFlag{ + Category: categoryK8S, + Destination: &cfg.K8S.ServiceName, + EnvVars: []string{envPrefix + "SERVICE_NAME"}, + Name: "service-name", + Usage: "`name` of service to use", + Value: global.AppName, + }, + + &cli.Int64Flag{ + Category: categoryK8S, + Destination: &rawServicePortNumber, + EnvVars: []string{envPrefix + "SERVICE_PORT_NUMBER"}, + Name: "service-port-number", + Usage: "the port `number` on which the k8s service listens on", + Value: 8443, + }, + + &cli.StringFlag{ + Category: categoryK8S, + Destination: &cfg.K8S.MutatingWebhookConfigurationName, + EnvVars: []string{envPrefix + "MUTATING_WEBHOOK_CONFIGURATION_NAME"}, + Name: "mutating-webhook-configuration-name", + Usage: "`name` of mutating webhook configuration to use", + Value: global.AppName, + }, + } + + serverFlags := []cli.Flag{ + &cli.StringFlag{ + Category: categoryServer, + Destination: &cfg.Server.ListenAddress, + EnvVars: []string{envPrefix + "LISTEN_ADDRESS"}, + Name: "listen-address", + Usage: "`host:port` for the server to listen on", + Value: "0.0.0.0:8443", + }, + + &cli.StringFlag{ + Category: categoryServer, + Destination: &cfg.Server.PathHealthcheck, + EnvVars: []string{envPrefix + "PATH_HEALTHCHECK"}, + Name: "path-healthcheck", + Usage: "`path` at which to serve the healthcheck", + Value: "/", + }, + + &cli.StringFlag{ + Category: categoryServer, + Destination: &cfg.Server.PathWebhook, + EnvVars: []string{envPrefix + "PATH_WEBHOOK"}, + Name: "path-webhook", + Usage: "`path` at which to serve the webhook", + Value: "/mutate", + }, + } + + flags := slices.Concat( + debugFlags, + k8sFlags, + serverFlags, + ) + + return &cli.Command{ + Name: "serve", + Usage: "run the monitor server", + Flags: flags, + + Before: func(ctx *cli.Context) error { + if rawServicePortNumber > 65535 { + return fmt.Errorf("invalid port service port number: %d", rawServicePortNumber) + } + cfg.K8S.ServicePortNumber = int32(rawServicePortNumber) + + return nil + }, + + Action: func(_ *cli.Context) error { + s, err := server.New(cfg) + if err != nil { + return err + } + return s.Run() + }, + } +} diff --git a/config/config.go b/config/config.go new file mode 100644 index 0000000..6955fff --- /dev/null +++ b/config/config.go @@ -0,0 +1,9 @@ +package config + +type Config struct { + K8S K8S `yaml:"k8s"` + Log Log `yaml:"log"` + Server Server `yaml:"server"` + + Version string +} diff --git a/config/k8s.go b/config/k8s.go new file mode 100644 index 0000000..e86def6 --- /dev/null +++ b/config/k8s.go @@ -0,0 +1,8 @@ +package config + +type K8S struct { + Namespace string `yaml:"namespace"` + ServiceName string `yaml:"service_name"` + ServicePortNumber int32 `yaml:"service_port_number"` + MutatingWebhookConfigurationName string `yaml:"mutating_webhook_configuration_name"` +} diff --git a/config/log.go b/config/log.go new file mode 100644 index 0000000..c57b2db --- /dev/null +++ b/config/log.go @@ -0,0 +1,6 @@ +package config + +type Log struct { + Level string `yaml:"level"` + Mode string `yaml:"mode"` +} diff --git a/config/server.go b/config/server.go new file mode 100644 index 0000000..278cac6 --- /dev/null +++ b/config/server.go @@ -0,0 +1,7 @@ +package config + +type Server struct { + ListenAddress string `yaml:"listen_address"` + PathHealthcheck string `yaml:"patch_healthcheck"` + PathWebhook string `yaml:"patch_webhook"` +} diff --git a/deploy/cluster-role.yaml b/deploy/cluster-role.yaml new file mode 100644 index 0000000..7ba5ed2 --- /dev/null +++ b/deploy/cluster-role.yaml @@ -0,0 +1,12 @@ +--- + +kind: ClusterRole +apiVersion: rbac.authorization.k8s.io/v1 +metadata: + name: kube-sidecar-injector + labels: + app.kubernetes.io/name: kube-sidecar-injector +rules: +- apiGroups: ["admissionregistration.k8s.io"] + resources: ["mutatingwebhookconfigurations"] + verbs: ["create", "get", "delete", "list", "patch", "update", "watch"] diff --git a/deploy/deployment.yaml b/deploy/deployment.yaml new file mode 100644 index 0000000..b385c44 --- /dev/null +++ b/deploy/deployment.yaml @@ -0,0 +1,67 @@ +--- + +kind: Deployment +apiVersion: apps/v1 +metadata: + name: kube-sidecar-injector + labels: + app.kubernetes.io/name: kube-sidecar-injector +spec: + replicas: 1 + selector: + matchLabels: + app.kubernetes.io/name: kube-sidecar-injector + template: + metadata: + labels: + app.kubernetes.io/name: kube-sidecar-injector + spec: + serviceAccountName: kube-sidecar-injector + containers: + - name: kube-sidecar-injector + image: kube-sidecar-injector:development + ports: + - name: https + containerPort: 8443 + +--- + +kind: Service +apiVersion: v1 +metadata: + name: kube-sidecar-injector + labels: + app.kubernetes.io/name: kube-sidecar-injector +spec: + selector: + app.kubernetes.io/name: kube-sidecar-injector + ports: + - name: https + port: 8443 + targetPort: 8443 + +--- + +kind: ServiceAccount +apiVersion: v1 +metadata: + name: kube-sidecar-injector + labels: + app.kubernetes.io/name: kube-sidecar-injector + +--- + +kind: ClusterRoleBinding +apiVersion: rbac.authorization.k8s.io/v1 +metadata: + name: kube-sidecar-injector + labels: + app.kubernetes.io/name: kube-sidecar-injector +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: kube-sidecar-injector +subjects: + - kind: ServiceAccount + name: kube-sidecar-injector + namespace: default diff --git a/deploy/dummy.yaml b/deploy/dummy.yaml new file mode 100644 index 0000000..e0fa396 --- /dev/null +++ b/deploy/dummy.yaml @@ -0,0 +1,44 @@ +--- + +kind: Pod +apiVersion: v1 +metadata: + name: dummy +spec: + containers: + - name: dummy + image: ubuntu + command: + - /bin/bash + - -c + - |- + stop() { + touch stop + } + trap stop SIGTERM + trap stop SIGINT + while [[ ! -f stop ]]; do sleep 1; done + +--- + +kind: Pod +apiVersion: v1 +metadata: + name: dummy-injected + labels: + eks.amazonaws.com/fargate-profile: default + +spec: + containers: + - name: dummy + image: ubuntu + command: + - /bin/bash + - -c + - |- + stop() { + touch stop + } + trap stop SIGTERM + trap stop SIGINT + while [[ ! -f stop ]]; do sleep 1; done diff --git a/global/global.go b/global/global.go new file mode 100644 index 0000000..7a45479 --- /dev/null +++ b/global/global.go @@ -0,0 +1,6 @@ +package global + +const ( + AppName = "kube-sidecar-injector" + OrgDomain = "flashbots.net" +) diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..fbfe7cb --- /dev/null +++ b/go.mod @@ -0,0 +1,54 @@ +module github.com/flashbots/kube-sidecar-injector + +go 1.22.0 + +require ( + github.com/evanphx/json-patch v4.12.0+incompatible + github.com/google/uuid v1.6.0 + github.com/urfave/cli/v2 v2.27.1 + go.uber.org/zap v1.27.0 + k8s.io/api v0.30.0 + k8s.io/apimachinery v0.30.0 + k8s.io/client-go v0.30.0 +) + +require ( + github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/emicklei/go-restful/v3 v3.11.0 // indirect + github.com/go-logr/logr v1.4.1 // indirect + github.com/go-openapi/jsonpointer v0.19.6 // indirect + github.com/go-openapi/jsonreference v0.20.2 // indirect + github.com/go-openapi/swag v0.22.3 // indirect + github.com/gogo/protobuf v1.3.2 // indirect + github.com/golang/protobuf v1.5.4 // indirect + github.com/google/gnostic-models v0.6.8 // indirect + github.com/google/gofuzz v1.2.0 // indirect + github.com/josharian/intern v1.0.0 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/mailru/easyjson v0.7.7 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/russross/blackfriday/v2 v2.1.0 // indirect + github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect + go.uber.org/multierr v1.10.0 // indirect + golang.org/x/net v0.23.0 // indirect + golang.org/x/oauth2 v0.10.0 // indirect + golang.org/x/sys v0.18.0 // indirect + golang.org/x/term v0.18.0 // indirect + golang.org/x/text v0.14.0 // indirect + golang.org/x/time v0.3.0 // indirect + google.golang.org/appengine v1.6.7 // indirect + google.golang.org/protobuf v1.33.0 // indirect + gopkg.in/inf.v0 v0.9.1 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect + k8s.io/klog/v2 v2.120.1 // indirect + k8s.io/kube-openapi v0.0.0-20240228011516-70dd3763d340 // indirect + k8s.io/utils v0.0.0-20230726121419-3b25d923346b // indirect + sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect + sigs.k8s.io/structured-merge-diff/v4 v4.4.1 // indirect + sigs.k8s.io/yaml v1.3.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..2939a9b --- /dev/null +++ b/go.sum @@ -0,0 +1,168 @@ +github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= +github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/emicklei/go-restful/v3 v3.11.0 h1:rAQeMHw1c7zTmncogyy8VvRZwtkmkZ4FxERmMY4rD+g= +github.com/emicklei/go-restful/v3 v3.11.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= +github.com/evanphx/json-patch v4.12.0+incompatible h1:4onqiflcdA9EOZ4RxV643DvftH5pOlLGNtQ5lPWQu84= +github.com/evanphx/json-patch v4.12.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= +github.com/go-logr/logr v1.4.1 h1:pKouT5E8xu9zeFC39JXRDukb6JFQPXM5p5I91188VAQ= +github.com/go-logr/logr v1.4.1/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-openapi/jsonpointer v0.19.6 h1:eCs3fxoIi3Wh6vtgmLTOjdhSpiqphQ+DaPn38N2ZdrE= +github.com/go-openapi/jsonpointer v0.19.6/go.mod h1:osyAmYz/mB/C3I+WsTTSgw1ONzaLJoLCyoi6/zppojs= +github.com/go-openapi/jsonreference v0.20.2 h1:3sVjiK66+uXK/6oQ8xgcRKcFgQ5KXa2KvnJRumpMGbE= +github.com/go-openapi/jsonreference v0.20.2/go.mod h1:Bl1zwGIM8/wsvqjsOQLJ/SH+En5Ap4rVB5KVcIDZG2k= +github.com/go-openapi/swag v0.22.3 h1:yMBqmnQ0gyZvEb/+KzuWZOXgllrXT4SADYbvDaXHv/g= +github.com/go-openapi/swag v0.22.3/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= +github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 h1:tfuBGBXKqDEevZMzYi5KSi8KkcZtzBcTgAUUtapy0OI= +github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572/go.mod h1:9Pwr4B2jHnOSGXyyzV8ROjYa2ojvAY6HCGYYfMoC3Ls= +github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/google/gnostic-models v0.6.8 h1:yo/ABAfM5IMRsS1VnXjTBvUb61tFIHozhlYvRgGre9I= +github.com/google/gnostic-models v0.6.8/go.mod h1:5n7qKqH0f5wFt+aWF8CW6pZLLNOfYuF5OpfBSENuI8U= +github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= +github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1 h1:K6RDEckDVWvDI9JAJYCmNdQXq6neHJOYx3V6jnqNEec= +github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= +github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= +github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= +github.com/onsi/ginkgo/v2 v2.15.0 h1:79HwNRBAZHOEwrczrgSOPy+eFTTlIGELKy5as+ClttY= +github.com/onsi/ginkgo/v2 v2.15.0/go.mod h1:HlxMHtYF57y6Dpf+mc5529KKmSq9h2FpCF+/ZkwUxKM= +github.com/onsi/gomega v1.31.0 h1:54UJxxj6cPInHS3a35wm6BK/F9nHYueZ1NVujHDrnXE= +github.com/onsi/gomega v1.31.0/go.mod h1:DW9aCi7U6Yi40wNVAvT6kzFnEVEI5n3DloYBiKiT6zk= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= +github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/urfave/cli/v2 v2.27.1 h1:8xSQ6szndafKVRmfyeUMxkNUJQMjL1F2zmsZ+qHpfho= +github.com/urfave/cli/v2 v2.27.1/go.mod h1:8qnjx1vcq5s2/wpsqoZFndg2CE5tNFyrTvS6SinrnYQ= +github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 h1:bAn7/zixMGCfxrRTfdpNzjtPYqr8smhKouy9mxVdGPU= +github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8= +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ= +go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= +go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.23.0 h1:7EYJ93RZ9vYSZAIb2x3lnuvqO5zneoD6IvWjuhfxjTs= +golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg= +golang.org/x/oauth2 v0.10.0 h1:zHCpF2Khkwy4mMB4bv0U37YtJdTGW8jI0glAApi0Kh8= +golang.org/x/oauth2 v0.10.0/go.mod h1:kTpgurOux7LqtuxjuyZa4Gj2gdezIt/jQtGnNFfypQI= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4= +golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/term v0.18.0 h1:FcHjZXDMxI8mM3nwhX9HlKop4C0YQvCVCdwYl2wOtE8= +golang.org/x/term v0.18.0/go.mod h1:ILwASektA3OnRv7amZ1xhE/KTR+u50pbXfZ03+6Nx58= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= +golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.18.0 h1:k8NLag8AGHnn+PHbl7g43CtqZAwG60vZkLqgyZgIHgQ= +golang.org/x/tools v0.18.0/go.mod h1:GL7B4CwcLLeo59yx/9UWWuNOW1n3VZ4f5axWfML7Lcg= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c= +google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI= +google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= +gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +k8s.io/api v0.30.0 h1:siWhRq7cNjy2iHssOB9SCGNCl2spiF1dO3dABqZ8niA= +k8s.io/api v0.30.0/go.mod h1:OPlaYhoHs8EQ1ql0R/TsUgaRPhpKNxIMrKQfWUp8QSE= +k8s.io/apimachinery v0.30.0 h1:qxVPsyDM5XS96NIh9Oj6LavoVFYff/Pon9cZeDIkHHA= +k8s.io/apimachinery v0.30.0/go.mod h1:iexa2somDaxdnj7bha06bhb43Zpa6eWH8N8dbqVjTUc= +k8s.io/client-go v0.30.0 h1:sB1AGGlhY/o7KCyCEQ0bPWzYDL0pwOZO4vAtTSh/gJQ= +k8s.io/client-go v0.30.0/go.mod h1:g7li5O5256qe6TYdAMyX/otJqMhIiGgTapdLchhmOaY= +k8s.io/klog/v2 v2.120.1 h1:QXU6cPEOIslTGvZaXvFWiP9VKyeet3sawzTOvdXb4Vw= +k8s.io/klog/v2 v2.120.1/go.mod h1:3Jpz1GvMt720eyJH1ckRHK1EDfpxISzJ7I9OYgaDtPE= +k8s.io/kube-openapi v0.0.0-20240228011516-70dd3763d340 h1:BZqlfIlq5YbRMFko6/PM7FjZpUb45WallggurYhKGag= +k8s.io/kube-openapi v0.0.0-20240228011516-70dd3763d340/go.mod h1:yD4MZYeKMBwQKVht279WycxKyM84kkAx2DPrTXaeb98= +k8s.io/utils v0.0.0-20230726121419-3b25d923346b h1:sgn3ZU783SCgtaSJjpcVVlRqd6GSnlTLKgpAAttJvpI= +k8s.io/utils v0.0.0-20230726121419-3b25d923346b/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= +sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd h1:EDPBXCAspyGV4jQlpZSudPeMmr1bNJefnuqLsRAsHZo= +sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd/go.mod h1:B8JuhiUyNFVKdsE8h686QcCxMaH6HrOAZj4vswFpcB0= +sigs.k8s.io/structured-merge-diff/v4 v4.4.1 h1:150L+0vs/8DA78h1u02ooW1/fFq/Lwr+sGiqlzvrtq4= +sigs.k8s.io/structured-merge-diff/v4 v4.4.1/go.mod h1:N8hJocpFajUSSeSJ9bOZ77VzejKZaXsTtZo4/u7Io08= +sigs.k8s.io/yaml v1.3.0 h1:a2VclLzOGrwOHDiV8EfBGhvjHvP46CtW5j6POvhYGGo= +sigs.k8s.io/yaml v1.3.0/go.mod h1:GeOyir5tyXNByN85N/dRIT9es5UQNerPYEKK56eTBm8= diff --git a/httplogger/middleware.go b/httplogger/middleware.go new file mode 100644 index 0000000..6f26d82 --- /dev/null +++ b/httplogger/middleware.go @@ -0,0 +1,59 @@ +package httplogger + +import ( + "encoding/base64" + "fmt" + "net/http" + "time" + + "github.com/flashbots/kube-sidecar-injector/logutils" + "github.com/google/uuid" + "go.uber.org/zap" +) + +func Middleware(logger *zap.Logger, next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Generate request ID (`base64` to shorten its string representation) + _uuid := [16]byte(uuid.New()) + httpRequestID := base64.RawStdEncoding.EncodeToString(_uuid[:]) + + l := logger.With( + zap.String("httpRequestID", httpRequestID), + zap.String("logType", "activity"), + ) + r = logutils.RequestWithLogger(r, l) + + // Handle panics + defer func() { + if msg := recover(); msg != nil { + w.WriteHeader(http.StatusInternalServerError) + var method, url string + if r != nil { + method = r.Method + url = r.URL.EscapedPath() + } + l.Error("HTTP request handler panicked", + zap.Any("error", msg), + zap.String("method", method), + zap.String("url", url), + ) + } + }() + + start := time.Now() + wrapped := wrapResponseWriter(w) + next.ServeHTTP(wrapped, r) + + // Passing request stats both in-message (for the human reader) + // as well as inside the structured log (for the machine parser) + logger.Debug(fmt.Sprintf("%s %s %d", r.Method, r.URL.EscapedPath(), wrapped.Status()), + zap.Int("durationMs", int(time.Since(start).Milliseconds())), + zap.Int("status", wrapped.Status()), + zap.String("httpRequestID", httpRequestID), + zap.String("logType", "access"), + zap.String("method", r.Method), + zap.String("path", r.URL.EscapedPath()), + zap.String("userAgent", r.Header.Get("user-agent")), + ) + }) +} diff --git a/httplogger/response_writer.go b/httplogger/response_writer.go new file mode 100644 index 0000000..0617e0d --- /dev/null +++ b/httplogger/response_writer.go @@ -0,0 +1,32 @@ +package httplogger + +import ( + "net/http" +) + +type responseWriter struct { + http.ResponseWriter + status int + wroteHeader bool +} + +func wrapResponseWriter(w http.ResponseWriter) *responseWriter { + return &responseWriter{ResponseWriter: w} +} + +func (rw *responseWriter) Status() int { + if rw.wroteHeader { + return rw.status + } + return http.StatusOK +} + +func (rw *responseWriter) WriteHeader(code int) { + if rw.wroteHeader { + return + } + + rw.status = code + rw.ResponseWriter.WriteHeader(code) + rw.wroteHeader = true +} diff --git a/logutils/context.go b/logutils/context.go new file mode 100644 index 0000000..3ec546a --- /dev/null +++ b/logutils/context.go @@ -0,0 +1,22 @@ +package logutils + +import ( + "context" + + "go.uber.org/zap" +) + +type contextKey string + +const loggerContextKey contextKey = "logger" + +func ContextWithLogger(parent context.Context, logger *zap.Logger) context.Context { + return context.WithValue(parent, loggerContextKey, logger) +} + +func LoggerFromContext(ctx context.Context) *zap.Logger { + if l, found := ctx.Value(loggerContextKey).(*zap.Logger); found { + return l + } + return zap.L() +} diff --git a/logutils/http_server_error_logger.go b/logutils/http_server_error_logger.go new file mode 100644 index 0000000..88cdfb5 --- /dev/null +++ b/logutils/http_server_error_logger.go @@ -0,0 +1,28 @@ +package logutils + +import ( + "errors" + "log" + "strings" + + "go.uber.org/zap" +) + +type httpServerErrorLogger struct { + logger *zap.Logger +} + +func (s *httpServerErrorLogger) Write(p []byte) (n int, err error) { + msg := strings.TrimSpace(string(p)) + s.logger.Warn("HTTP server encountered an error", + zap.Error(errors.New(msg)), + ) + return len(p), nil +} + +func NewHttpServerErrorLogger(logger *zap.Logger) *log.Logger { + wrapped := &httpServerErrorLogger{ + logger: logger, + } + return log.New(wrapped, "", 0) +} diff --git a/logutils/request.go b/logutils/request.go new file mode 100644 index 0000000..6e71cb4 --- /dev/null +++ b/logutils/request.go @@ -0,0 +1,17 @@ +package logutils + +import ( + "net/http" + + "go.uber.org/zap" +) + +func RequestWithLogger(parent *http.Request, logger *zap.Logger) *http.Request { + return parent.WithContext( + ContextWithLogger(parent.Context(), logger), + ) +} + +func LoggerFromRequest(request *http.Request) *zap.Logger { + return LoggerFromContext(request.Context()) +} diff --git a/logutils/setup.go b/logutils/setup.go new file mode 100644 index 0000000..f4dc546 --- /dev/null +++ b/logutils/setup.go @@ -0,0 +1,51 @@ +package logutils + +import ( + "errors" + "fmt" + "strings" + + "github.com/flashbots/kube-sidecar-injector/config" + "go.uber.org/zap" + "go.uber.org/zap/zapcore" +) + +var ( + ErrLoggerFailedToBuild = errors.New("failed to build the logger") + ErrLoggerInvalidLevel = errors.New("invalid log-level") + ErrLoggerInvalidMode = errors.New("invalid log-mode") +) + +func NewLogger(cfg *config.Log) ( + *zap.Logger, error, +) { + var config zap.Config + switch strings.ToLower(cfg.Mode) { + case "dev": + config = zap.NewDevelopmentConfig() + case "prod": + config = zap.NewProductionConfig() + default: + return nil, fmt.Errorf("%w: %s", + ErrLoggerInvalidMode, cfg.Mode, + ) + } + config.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder + + logLevel, err := zap.ParseAtomicLevel(cfg.Level) + if err != nil { + return nil, fmt.Errorf("%w: %s: %w", + ErrLoggerInvalidLevel, cfg.Level, err, + ) + } + config.Level = logLevel + + l, err := config.Build() + if err != nil { + return nil, fmt.Errorf("%w: %w", + ErrLoggerFailedToBuild, err, + ) + } + + return l, nil +} diff --git a/operation/operation.go b/operation/operation.go new file mode 100644 index 0000000..3f7c7ea --- /dev/null +++ b/operation/operation.go @@ -0,0 +1,63 @@ +package operation + +import ( + "encoding/json" + "strings" + + json_patch "github.com/evanphx/json-patch" +) + +var ( + rawAdd = json.RawMessage(`"add"`) + rawReplace = json.RawMessage(`"replace"`) +) + +func Escape(s string) string { + s = strings.ReplaceAll(s, "~", "~0") + s = strings.ReplaceAll(s, "/", "~1") + return s +} + +func Add(path string, value interface{}) ( + json_patch.Operation, error, +) { + bytesPath, err := json.Marshal(path) + if err != nil { + return nil, err + } + rawPath := json.RawMessage(bytesPath) + + bytesValue, err := json.Marshal(value) + if err != nil { + return nil, err + } + rawValue := json.RawMessage(bytesValue) + + return map[string]*json.RawMessage{ + "op": &rawAdd, + "path": &rawPath, + "value": &rawValue, + }, nil +} + +func Replace(path string, value interface{}) ( + json_patch.Operation, error, +) { + bytesPath, err := json.Marshal(path) + if err != nil { + return nil, err + } + rawPath := json.RawMessage(bytesPath) + + bytesValue, err := json.Marshal(value) + if err != nil { + return nil, err + } + rawValue := json.RawMessage(bytesValue) + + return map[string]*json.RawMessage{ + "op": &rawReplace, + "path": &rawPath, + "value": &rawValue, + }, nil +} diff --git a/patch/add_pod_containers.go b/patch/add_pod_containers.go new file mode 100644 index 0000000..56cbe53 --- /dev/null +++ b/patch/add_pod_containers.go @@ -0,0 +1,33 @@ +package patch + +import ( + json_patch "github.com/evanphx/json-patch" + "github.com/flashbots/kube-sidecar-injector/operation" + core_v1 "k8s.io/api/core/v1" +) + +func AddPodContainers(pod *core_v1.Pod, containers []core_v1.Container) (json_patch.Patch, error) { + res := make(json_patch.Patch, 0, len(containers)) + + notEmpty := len(pod.Spec.Containers) > 0 + for _, c := range containers { + var ( + op json_patch.Operation + err error + ) + + if notEmpty { + op, err = operation.Add("/spec/containers/-", c) + } else { + notEmpty = true + op, err = operation.Add("/spec/containers", []core_v1.Container{c}) + } + + if err != nil { + return nil, err + } + res = append(res, op) + } + + return res, nil +} diff --git a/patch/update_pod_annotations.go b/patch/update_pod_annotations.go new file mode 100644 index 0000000..1e245e8 --- /dev/null +++ b/patch/update_pod_annotations.go @@ -0,0 +1,40 @@ +package patch + +import ( + json_patch "github.com/evanphx/json-patch" + "github.com/flashbots/kube-sidecar-injector/operation" + core_v1 "k8s.io/api/core/v1" +) + +func UpdatePodAnnotations( + pod *core_v1.Pod, + annotations map[string]string, +) (json_patch.Patch, error) { + if len(pod.Annotations) == 0 { + op, err := operation.Add("/metadata/annotations", annotations) + if err != nil { + return nil, err + } + return []json_patch.Operation{op}, nil + } + + res := make(json_patch.Patch, 0, len(annotations)) + + for k, v := range annotations { + if _, exists := pod.Annotations[k]; exists { + op, err := operation.Replace("/metadata/annotations/"+operation.Escape(k), v) + if err != nil { + return nil, err + } + res = append(res, op) + } else { + op, err := operation.Add("/metadata/annotations/"+operation.Escape(k), v) + if err != nil { + return nil, err + } + res = append(res, op) + } + } + + return res, nil +} diff --git a/readme.md b/readme.md new file mode 100644 index 0000000..796267c --- /dev/null +++ b/readme.md @@ -0,0 +1,6 @@ +# kube-sidecar-injector + +Initial implementation of the sidecar injector for k8s. + +Currently, it's hardcoded for just one use case: injecting node-exporter +sidecars into fargate pods on EKS. diff --git a/server/handlers.go b/server/handlers.go new file mode 100644 index 0000000..3bf369e --- /dev/null +++ b/server/handlers.go @@ -0,0 +1,102 @@ +package server + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + + "github.com/flashbots/kube-sidecar-injector/logutils" + "go.uber.org/zap" + admission_v1 "k8s.io/api/admission/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/serializer" +) + +// unversionedAdmissionReview is used to decode both v1 and v1beta1 +// AdmissionReview types. +// +// See also: https://github.com/hashicorp/vault-k8s/blob/v1.4.1/agent-inject/handler.go#L114-L119 +type unversionedAdmissionReview struct { + admission_v1.AdmissionReview +} + +var ( + runtimeScheme = runtime.NewScheme() + codecs = serializer.NewCodecFactory(runtimeScheme) + deserializer = codecs.UniversalDeserializer() +) + +func (s *Server) handleHealthcheck(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) +} + +func (s *Server) handleWebhook(w http.ResponseWriter, r *http.Request) { + l := logutils.LoggerFromRequest(r) + + defer func() { + if _, err := io.ReadAll(r.Body); err != nil { + l.Error("Failed to read the full request body", zap.Error(err)) + } + }() + + if contentType := r.Header.Get("Content-Type"); contentType != "application/json" { + const msg = "Invalid content type" + l.Error(msg, zap.String("content_type", contentType)) + http.Error(w, fmt.Sprintf("%s: %s", msg, contentType), http.StatusBadRequest) + return + } + + var ( + body []byte + err error + ) + if r.Body != nil { + body, err = io.ReadAll(r.Body) + if err != nil { + const msg = "Failed to read request body" + l.Error(msg, zap.Error(err)) + http.Error(w, msg, http.StatusBadRequest) // shouldn't leak error details! + return + } + } + if len(body) == 0 { + const msg = "Empty request body" + l.Error(msg) + http.Error(w, msg, http.StatusBadRequest) + return + } + + admRequest := &unversionedAdmissionReview{} + admRequest.SetGroupVersionKind(admission_v1.SchemeGroupVersion.WithKind("AdmissionReview")) + _, gvk, err := deserializer.Decode(body, nil, admRequest) + if err != nil { + const msg = "Failed to decode admission request" + l.Error(msg, zap.Error(err)) + http.Error(w, fmt.Sprintf("%s: %s", msg, err), http.StatusBadRequest) + return + } + + admResponse := admission_v1.AdmissionReview{ + Response: s.mutate(r.Context(), admRequest.Request), + } + if gvk == nil || (gvk.Group == "" && gvk.Version == "" && gvk.Kind == "") { + admResponse.SetGroupVersionKind( + admission_v1.SchemeGroupVersion.WithKind("AdmissionReview"), + ) + } else { + admResponse.SetGroupVersionKind(*gvk) + } + + res, err := json.Marshal(&admResponse) + if err != nil { + const msg = "Failed to encode admission response" + l.Error(msg, zap.Error(err)) + http.Error(w, msg, http.StatusInternalServerError) + return + } + + if _, err := w.Write(res); err != nil { + l.Error("Failed to write response", zap.Error(err)) + } +} diff --git a/server/k8s.go b/server/k8s.go new file mode 100644 index 0000000..8bc75ca --- /dev/null +++ b/server/k8s.go @@ -0,0 +1,202 @@ +package server + +import ( + "context" + "encoding/json" + "errors" + "fmt" + + json_patch "github.com/evanphx/json-patch" + "github.com/flashbots/kube-sidecar-injector/global" + "github.com/flashbots/kube-sidecar-injector/logutils" + "github.com/flashbots/kube-sidecar-injector/patch" + "go.uber.org/zap" + admission_v1 "k8s.io/api/admission/v1" + admission_registration_v1 "k8s.io/api/admissionregistration/v1" + core_v1 "k8s.io/api/core/v1" + k8s_errors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/resource" + meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +var ( + ErrFailedToUpsertMutatingWebhookConfiguration = errors.New("failed to upsert mutating webhook configuration") + ErrUnexpectedPreExistingWebhook = errors.New("unexpected pre-existing webhook configuration") +) + +func (s *Server) upsertMutatingWebhookConfiguration(ctx context.Context) error { + l := logutils.LoggerFromContext(ctx) + + cli := s.k8s.AdmissionregistrationV1() + + l.Info("Fetching current mutating webhook configuration", + zap.String("mutating_webhook_configuration_name", s.cfg.K8S.MutatingWebhookConfigurationName), + ) + present, err := cli.MutatingWebhookConfigurations(). + Get(ctx, s.cfg.K8S.MutatingWebhookConfigurationName, meta_v1.GetOptions{}) + if err != nil { + if k8s_errors.IsNotFound(err) { + present = nil + } else { + return fmt.Errorf("%w: %s", ErrFailedToUpsertMutatingWebhookConfiguration, err) + } + } + + failurePolicyIgnore := admission_registration_v1.Ignore + sideEffectClassNone := admission_registration_v1.SideEffectClassNone + + desired := &admission_registration_v1.MutatingWebhookConfiguration{ + ObjectMeta: meta_v1.ObjectMeta{ + Name: s.cfg.K8S.MutatingWebhookConfigurationName, + }, + + Webhooks: []admission_registration_v1.MutatingWebhook{{ + Name: global.AppName + "." + global.OrgDomain, + + AdmissionReviewVersions: []string{"v1", "v1beta1"}, + FailurePolicy: &failurePolicyIgnore, + SideEffects: &sideEffectClassNone, + + ClientConfig: admission_registration_v1.WebhookClientConfig{ + CABundle: s.tls.CA, + + Service: &admission_registration_v1.ServiceReference{ + Name: s.cfg.K8S.ServiceName, + Namespace: s.cfg.K8S.Namespace, + Path: &s.cfg.Server.PathWebhook, + Port: &s.cfg.K8S.ServicePortNumber, + }, + }, + + Rules: []admission_registration_v1.RuleWithOperations{{ + Operations: []admission_registration_v1.OperationType{ + admission_registration_v1.Create, + admission_registration_v1.Update, + }, + + Rule: admission_registration_v1.Rule{ + APIGroups: []string{""}, + APIVersions: []string{"v1"}, + Resources: []string{"pods"}, + }, + }}, + + ObjectSelector: &meta_v1.LabelSelector{ + MatchExpressions: []meta_v1.LabelSelectorRequirement{{ + Key: "eks.amazonaws.com/fargate-profile", + Operator: "Exists", + }}, + }, + }}, + } + + if present != nil { + desired.ObjectMeta.ResourceVersion = present.ResourceVersion + l.Info("Updating existing mutating webhook configuration", + zap.String("mutating_webhook_configuration_name", s.cfg.K8S.MutatingWebhookConfigurationName), + ) + if _, err := cli.MutatingWebhookConfigurations().Update(ctx, desired, meta_v1.UpdateOptions{}); err != nil { + return fmt.Errorf("%w: %s", ErrFailedToUpsertMutatingWebhookConfiguration, err) + } + } else { + l.Info("Creating new mutating webhook configuration", + zap.String("mutating_webhook_configuration_name", s.cfg.K8S.MutatingWebhookConfigurationName), + ) + if _, err := cli.MutatingWebhookConfigurations().Create(ctx, desired, meta_v1.CreateOptions{}); err != nil { + return fmt.Errorf("%w: %s", ErrFailedToUpsertMutatingWebhookConfiguration, err) + } + } + + return nil +} + +func (s *Server) mutate(ctx context.Context, req *admission_v1.AdmissionRequest) *admission_v1.AdmissionResponse { + l := logutils.LoggerFromContext(ctx) + + res := &admission_v1.AdmissionResponse{ + Allowed: true, + UID: req.UID, + } + + pod := &core_v1.Pod{} + if err := json.Unmarshal(req.Object.Raw, pod); err != nil { + l.Error("Failed to decode raw object for pod", zap.Error(err)) + res.Result = &meta_v1.Status{Message: err.Error()} + return res + } + + l.Info("Handling admission request", + zap.String("kind", req.Kind.Kind), + zap.String("name", req.Name), + zap.String("namespace", req.Namespace), + zap.String("operation", string(req.Operation)), + zap.String("pod", pod.Name), + zap.String("uid", string(req.UID)), + zap.String("username", req.UserInfo.Username), + ) + + patches, err := s.mutatePod(pod) + if err != nil { + res.Result = &meta_v1.Status{Message: err.Error()} + return res + } + if len(patches) > 0 { + b, err := json.Marshal(patches) + if err != nil { + l.Error("Failed to encode pod patches", zap.Error(err)) + res.Result = &meta_v1.Status{Message: err.Error()} + return res + } + patchType := admission_v1.PatchTypeJSONPatch + res.Patch = b + res.PatchType = &patchType + } + + return res +} + +func (s *Server) mutatePod(pod *core_v1.Pod) (json_patch.Patch, error) { + res := make(json_patch.Patch, 0) + + { // inject sidecar + c := core_v1.Container{ + Name: "node-exporter", + Image: "prom/node-exporter:v1.7.0", + + Args: []string{ + "--log.format", "json", + "--web.listen-address", ":9001", + }, + + Ports: []core_v1.ContainerPort{{ + Name: "metrics", + ContainerPort: 9001, + }}, + + Resources: core_v1.ResourceRequirements{ + Requests: map[core_v1.ResourceName]resource.Quantity{ + "cpu": resource.MustParse("10m"), + "memory": resource.MustParse("64Mi"), + }, + }, + } + + p, err := patch.AddPodContainers(pod, []core_v1.Container{c}) + if err != nil { + return nil, err + } + res = append(res, p...) + } + + { // annotate + p, err := patch.UpdatePodAnnotations(pod, map[string]string{ + s.cfg.K8S.ServiceName + "." + global.OrgDomain + "/patched": "true", + }) + if err != nil { + return nil, err + } + res = append(res, p...) + } + + return res, nil +} diff --git a/server/server.go b/server/server.go new file mode 100644 index 0000000..6b0f4d9 --- /dev/null +++ b/server/server.go @@ -0,0 +1,144 @@ +package server + +import ( + "context" + "crypto/tls" + "errors" + "fmt" + "net/http" + "os" + "os/signal" + "syscall" + "time" + + "github.com/flashbots/kube-sidecar-injector/cert" + "github.com/flashbots/kube-sidecar-injector/config" + "github.com/flashbots/kube-sidecar-injector/global" + "github.com/flashbots/kube-sidecar-injector/httplogger" + "github.com/flashbots/kube-sidecar-injector/logutils" + "go.uber.org/zap" + "k8s.io/client-go/kubernetes" + k8s_config "k8s.io/client-go/rest" +) + +type Server struct { + cfg *config.Config + k8s *kubernetes.Clientset + log *zap.Logger + tls *cert.Bundle +} + +func New(cfg *config.Config) (*Server, error) { + l := zap.L() + + // k8s + + k8sConfig, err := k8s_config.InClusterConfig() + if err != nil { + return nil, err + } + k8sConfig.UserAgent = global.AppName + "/" + cfg.Version + + k8s, err := kubernetes.NewForConfig(k8sConfig) + if err != nil { + return nil, err + } + + // tls + + // TODO: implement renewal + src, err := cert.NewSelfSigner(global.OrgDomain, []string{ + fmt.Sprintf("%s.%s.svc", cfg.K8S.ServiceName, cfg.K8S.Namespace), + fmt.Sprintf("%s.%s.svc.cluster.local", cfg.K8S.ServiceName, cfg.K8S.Namespace), + }) + if err != nil { + return nil, err + } + bundle, err := src.NewBundle() + if err != nil { + return nil, err + } + + // done + + return &Server{ + tls: bundle, + cfg: cfg, + k8s: k8s, + log: l, + }, nil +} + +func (s *Server) Run() error { + l := s.log + ctx := logutils.ContextWithLogger(context.Background(), l) + + mux := http.NewServeMux() + mux.HandleFunc(s.cfg.Server.PathHealthcheck, s.handleHealthcheck) + mux.HandleFunc(s.cfg.Server.PathWebhook, s.handleWebhook) + handler := httplogger.Middleware(l, mux) + + srv := &http.Server{ + Addr: s.cfg.Server.ListenAddress, + ErrorLog: logutils.NewHttpServerErrorLogger(l), + Handler: handler, + MaxHeaderBytes: 1024, + ReadHeaderTimeout: 30 * time.Second, + ReadTimeout: 30 * time.Second, + WriteTimeout: 30 * time.Second, + TLSConfig: &tls.Config{Certificates: []tls.Certificate{*s.tls.Pair}}, + } + + l.Info("Kubernetes sidecar injector server is going up...", + zap.String("server_listen_address", s.cfg.Server.ListenAddress), + zap.String("version", s.cfg.Version), + ) + + // start up + + done := make(chan struct{}, 1) + go func() { + if err := srv.ListenAndServeTLS("", ""); err != nil && !errors.Is(err, http.ErrServerClosed) { + l.Error("Kubernetes sidecar injector server failed", zap.Error(err)) + } + l.Info("Kubernetes sidecar injector server is down") + }() + + // shut down + + fail := make(chan error, 1) + go func() { + terminator := make(chan os.Signal, 1) + signal.Notify(terminator, os.Interrupt, syscall.SIGTERM) + + select { + case stop := <-terminator: + l.Info("Stop signal received; shutting down...", zap.String("signal", stop.String())) + case err := <-fail: + l.Error("Internal failure; shutting down...", zap.Error(err)) + } + + ctx, cancel := context.WithTimeout(ctx, 30*time.Second) + defer cancel() + if err := srv.Shutdown(ctx); err != nil { + l.Error("Kubernetes sidecar injector server shutdown failed", + zap.Error(err), + ) + } + done <- struct{}{} + }() + + // register webhook + + ctx, cancel := context.WithTimeout(ctx, 30*time.Second) + defer cancel() + if err := s.upsertMutatingWebhookConfiguration(ctx); err != nil { + fail <- err + } + + // wait + + <-done + + return nil +}