webhook.go 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. . "github.com/onsi/ginkgo/v2"
  23. "k8s.io/apimachinery/pkg/util/wait"
  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. var (
  27. externalSecretWebhookURL = func(namespace, releaseName string) string {
  28. return fmt.Sprintf("https://%s.%s.svc.cluster.local/validate-external-secrets-io-v1-externalsecret", externalSecretWebhookServiceName(releaseName), namespace)
  29. }
  30. webhookReadyPollInterval = time.Second
  31. webhookReadyTimeout = 5 * time.Minute
  32. webhookReadyContext = func() context.Context { return GinkgoT().Context() }
  33. )
  34. func externalSecretWebhookServiceName(releaseName string) string {
  35. const chartName = "external-secrets"
  36. fullName := releaseName
  37. if !strings.Contains(releaseName, chartName) {
  38. fullName = releaseName + "-" + chartName
  39. }
  40. return fullName + "-webhook"
  41. }
  42. func waitForExternalSecretWebhookReady(namespace, releaseName 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(namespace, releaseName)
  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. }