webhook.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. Copyright © The ESO 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. https://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 addon
  14. import (
  15. "bytes"
  16. "context"
  17. "crypto/tls"
  18. "fmt"
  19. "net/http"
  20. "strings"
  21. "time"
  22. "k8s.io/apimachinery/pkg/util/wait"
  23. . "github.com/onsi/ginkgo/v2"
  24. )
  25. const externalSecretValidationReview = `{"apiVersion":"admission.k8s.io/v1","kind":"AdmissionReview","request":{"uid":"test","kind":{"group":"external-secrets.io","version":"v1","kind":"ExternalSecret"},"resource":{"group":"external-secrets.io","version":"v1","resource":"externalsecrets"},"dryRun":true,"operation":"CREATE","userInfo":{"username":"test","uid":"test","groups":[],"extra":{}}}}`
  26. const externalSecretsChartName = "external-secrets"
  27. var (
  28. externalSecretWebhookURL = func(serviceName, namespace string) string {
  29. return fmt.Sprintf("https://%s.%s.svc.cluster.local/validate-external-secrets-io-v1-externalsecret", serviceName, namespace)
  30. }
  31. webhookReadyPollInterval = time.Second
  32. webhookReadyTimeout = 5 * time.Minute
  33. webhookReadyContext = func() context.Context { return GinkgoT().Context() }
  34. )
  35. func webhookServiceName(releaseName string) string {
  36. fullName := releaseName
  37. if !strings.Contains(releaseName, externalSecretsChartName) {
  38. fullName = fmt.Sprintf("%s-%s", releaseName, externalSecretsChartName)
  39. }
  40. return fmt.Sprintf("%s-webhook", fullName)
  41. }
  42. func waitForExternalSecretWebhookReady(serviceName, namespace string) error {
  43. tr := &http.Transport{
  44. // nolint:gosec
  45. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  46. }
  47. client := &http.Client{Transport: tr}
  48. url := externalSecretWebhookURL(serviceName, namespace)
  49. return wait.PollUntilContextTimeout(webhookReadyContext(), webhookReadyPollInterval, webhookReadyTimeout, true, func(ctx context.Context) (bool, error) {
  50. res, err := client.Post(url, "application/json", bytes.NewBufferString(externalSecretValidationReview))
  51. if err != nil {
  52. return false, nil
  53. }
  54. defer func() {
  55. _ = res.Body.Close()
  56. }()
  57. GinkgoWriter.Printf("webhook res: %d", res.StatusCode)
  58. return res.StatusCode == http.StatusOK, nil
  59. })
  60. }