diff --git a/CODEOWNERS b/CODEOWNERS index 86783212e7d6..d1b817700255 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -20,20 +20,10 @@ # Logging library /common/logging @kyma-project/Framefrog -/components/central-application-connectivity-validator @kyma-project/Framefrog -/components/central-application-gateway @kyma-project/Framefrog -/components/compass-runtime-agent @kyma-project/Framefrog - - # All files and subdirectories in /docs /docs @kyma-project/technical-writers /installation @kyma-project/Jellyfish -/installation/resources/crds/compass-runtime-agent @kyma-project/Framefrog - -/resources/compass-runtime-agent @kyma-project/Framefrog - -/tests/components/application-connector @kyma-project/Framefrog # Config files for markdownlint .markdownlint.yaml @kyma-project/technical-writers diff --git a/components/README.md b/components/README.md deleted file mode 100644 index 825ecd16f150..000000000000 --- a/components/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# Components - -## Overview - -The `components` directory contains the sources of all Kyma components. -A Kyma component is any Pod, container, or image deployed with and referenced in a Kyma module or chart to provide the module's functionality. -Each subdirectory in the `components` directory defines one component. - -## Details - -Every Kyma component resides in a dedicated folder which contains its sources and a `README.md` file. This file provides instructions on how to build and develop the component. - -The component's name consists of a term describing the component, followed by the **component type**. The first part of the name may differ depending on the component's purpose. -This table lists the available types: - -| Type | Description | Example | -|---|---|---| -| **controller** | A [Kubernetes Controller](https://kubernetes.io/docs/concepts/workloads/controllers/) which reacts to a standard Kubernetes resource or manages [CustomResourceDefinition](https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions/) resources. The component's name reflects the name of the primary resource it controls. | Function-controller | -| **controller-manager** | A daemon that embeds all [Kubernetes Controllers](https://kubernetes.io/docs/concepts/workloads/controllers/) of a domain. Such an approach brings operational benefits in comparison to shipping all controllers separately. A `controller-manager` takes the name of the domain it belongs to. | - | -| **operator** | A [Kubernetes Operator](https://kubernetes.io/docs/concepts/extend-kubernetes/operator/) which covers the application-specific logic behind the operation of the application, such as steps to upscale a stateful application. It reacts on changes made to custom resources derived from a given [CustomResourceDefinition](https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions/). It uses the name of the application it operates. | telemetry-operator | -| **job** | A [Kubernetes Job](https://kubernetes.io/docs/tasks/job/) which performs a task once or periodically. It uses the name of the task it performs. |istio-patch-job (not renamed yet)| -| **proxy** | Acts as a proxy for an existing component, usually introducing a security model for this component. It uses the component's name. | - | -| **service** | Serves an HTTP/S-based API, usually securely exposed to the public. It uses the domain name and the API it serves. | - | -| **broker** | Implements the [Open Service Broker](https://www.openservicebrokerapi.org/) specification to enrich the Kyma Service Catalog with the services of a provider. It uses the name of the provider it integrates with. | azure-broker | -| **configurer** | A one-time task which usually runs as an [Init Container](https://kubernetes.io/docs/concepts/workloads/pods/init-containers/) in order to configure the application. | - | - -## Development - -Follow [this](https://github.com/kyma-project/kyma/blob/main/resources/README.md) development guide when you add a new component to the `kyma` repository. diff --git a/components/central-application-connectivity-validator/.gitignore b/components/central-application-connectivity-validator/.gitignore deleted file mode 100644 index 2cb965c5e69b..000000000000 --- a/components/central-application-connectivity-validator/.gitignore +++ /dev/null @@ -1,16 +0,0 @@ -# Editors and IDEs -/.idea -*.iml -*~ -*.swp -*.swo - -# Binaries -/centralapplicationconnectivityvalidator -bin - -# Output of the go coverage tool, specifically when used with LiteIDE -*.out - -# Software licenses -/licenses diff --git a/components/central-application-connectivity-validator/Dockerfile b/components/central-application-connectivity-validator/Dockerfile deleted file mode 100644 index 1305eaeaf87e..000000000000 --- a/components/central-application-connectivity-validator/Dockerfile +++ /dev/null @@ -1,23 +0,0 @@ -FROM golang:1.22.2-alpine3.18 as builder - -ARG DOCK_PKG_DIR=/go/src/github.com/kyma-project/kyma/components/central-application-connectivity-validator -WORKDIR $DOCK_PKG_DIR - -COPY . $DOCK_PKG_DIR - -RUN echo "nobody:x:65534:65534:nobody:/:" > /etc_passwd - -RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o centralapplicationconnectivityvalidator ./cmd/centralapplicationconnectivityvalidator - - -FROM scratch -LABEL source=git@github.com:kyma-project/kyma.git - -WORKDIR /app - -COPY --from=builder /go/src/github.com/kyma-project/kyma/components/central-application-connectivity-validator/centralapplicationconnectivityvalidator . - -COPY --from=builder /etc_passwd /etc/passwd -USER nobody - -CMD ["/app/centralapplicationconnectivityvalidator"] diff --git a/components/central-application-connectivity-validator/Makefile b/components/central-application-connectivity-validator/Makefile deleted file mode 100644 index f98cd6808763..000000000000 --- a/components/central-application-connectivity-validator/Makefile +++ /dev/null @@ -1,42 +0,0 @@ -APP_NAME = central-application-connectivity-validator -APP_PATH = components/$(APP_NAME) -SCRIPTS_DIR = $(realpath $(shell pwd)/../..)/common/makefiles - -# ENVTEST_K8S_VERSION refers to the version of kubebuilder assets to be downloaded by envtest binary. -ENVTEST_K8S_VERSION = 1.25.0 - -override ENTRYPOINT = cmd/centralapplicationconnectivityvalidator/ - -include $(SCRIPTS_DIR)/generic-make-go.mk - -VERIFY_IGNORE := /vendor\|/mocks - -release: - $(MAKE) gomod-release-local - - -## Location to install dependencies to -LOCALBIN ?= $(shell pwd)/bin -$(LOCALBIN): - mkdir -p $(LOCALBIN) - -COVERPROFILE ?= cover.out - -.PHONY: fmt -fmt: ## Run go fmt against code. - go fmt ./... - -.PHONY: vet -vet: ## Run go vet against code. - go vet ./... - -ENVTEST ?= $(LOCALBIN)/setup-envtest - -.PHONY: envtest -envtest: $(ENVTEST) ## Download envtest-setup locally if necessary. -$(ENVTEST): $(LOCALBIN) - test -s $(LOCALBIN)/setup-envtest || GOBIN=$(LOCALBIN) go install sigs.k8s.io/controller-runtime/tools/setup-envtest@latest - -.PHONY: test -test: fmt vet envtest ## Run tests. - KUBEBUILDER_ASSETS="$(shell $(ENVTEST) use $(ENVTEST_K8S_VERSION) -p path)" go test ./... -coverprofile $(COVERPROFILE) diff --git a/components/central-application-connectivity-validator/README.md b/components/central-application-connectivity-validator/README.md deleted file mode 100644 index 1d502a74ec47..000000000000 --- a/components/central-application-connectivity-validator/README.md +++ /dev/null @@ -1,66 +0,0 @@ -# Central Application Connectivity Validator - -## Overview - -Central Application Connectivity Validator validates client certificate subjects in the Compass mode of Kyma. -It proxies the requests to the Eventing Publisher Proxy. - -## Usage - -Central Application Connectivity Validator has the following parameters: -- **proxyPort** is the port on which the reverse proxy is exposed. The default port is `8081`. -- **externalAPIPort** is the port on which the external API is exposed. The default port is `8080`. -- **eventingPathPrefixV1** is the path prefix for which requests are forwarded to the Eventing Publisher V1 API. The default value is `/v1/events`. -- **eventingPathPrefixV2** is the path prefix for which requests are forwarded to the Eventing Publisher V2 API. The default value is `/v2/events`. -- **eventingPublisherHost** is the host and the port of the Eventing Publisher Proxy. The default value is `events-api:8080`. -- **eventingDestinationPath** is the destination path for the requests coming to the Eventing. The default value is `/`. -- **eventingPathPrefixEvents** is the prefix of paths that is directed to the CloudEvents-based Eventing. The default value is `/events`. -- **appNamePlaceholder** is the path URL placeholder used for the application name. The default value is `%%APP_NAME%%`. -- **cacheExpirationSeconds** is the expiration time for client IDs stored in cache expressed in seconds. The default value is `90`. -- **cacheCleanupIntervalSeconds** is the clean-up interval controlling how often the client IDs stored in cache are removed. The default value is `15`. -- **syncPeriod** is the time in seconds after which the controller should reconcile the Application resource. The default value is `60 seconds`. - -### Application Name Placeholder - -If the **appNamePlaceholder** parameter is not empty, it defines a placeholder for the application name in the parameters **eventingPathPrefixV1**, **eventingPathPrefixV2**, and **eventingPathPrefixEvents**. This placeholder is replaced on every proxy request with the value from the certificate Common Name (CN). - -### Local Cache Refresh - -The application **clientIDs** are read from Application resources and cached locally with the TTL (Time to live) defined by the **cacheExpirationSeconds** parameter. -The cache refresh is performed by the controller during reconciliation in intervals defined by the **syncPeriod**. -To prevent cache entries eviction, the value of the **syncPeriod** should be smaller than that of **cacheExpirationSeconds**. - -## Details - -The certificate subjects are validated using the `X-Forwarded-Client-Cert` header. -After successful client certificate verification defined in the Istio Gateway, the Envoy Proxy adds the header to the request. -The service to which the header is added must have mutual TLS between Istio sidecar Pods enabled. -This is an example `X-Forwarded-Client-Cert` header: -```bash -Hash=f4cf22fb633d4df500e371daf703d4b4d14a0ea9d69cd631f95f9e6ba840f8ad;Subject="CN=test-application,OU=OrgUnit,O=Organization,L=Waldorf,ST=Waldorf,C=DE";URI=,By=spiffe://cluster.local/ns/kyma-system/sa/default;Hash=6d1f9f3a6ac94ff925841aeb9c15bb3323014e3da2c224ea7697698acf413226;Subject="";URI=spiffe://cluster.local/ns/istio-system/sa/istio-ingressgateway-service-account -``` - -Central Application Connectivity Validator forwards only the requests with the `X-Forwarded-Client-Cert` header that contains **Subject** with the following fields corresponding to the Application custom resource: -- **CommonName** is the name of the Application custom resource. -- **Organization** (optional) is the tenant. -- **OrganizationalUnit** (optional) is the group. - -## Development - -### Generate Mocks - -Prerequisites: - -- [Mockery](https://github.com/vektra/mockery) 2.0 or higher - -To generate mocks, run: - -```sh -go generate ./... -``` - -When adding a new interface to be mocked or when a mock of an existing interface is not being generated, add the following line directly above the interface declaration: - -``` -//go:generate mockery --name {INTERFACE_NAME} -``` \ No newline at end of file diff --git a/components/central-application-connectivity-validator/cmd/centralapplicationconnectivityvalidator/centralapplicationconnectivityvalidator.go b/components/central-application-connectivity-validator/cmd/centralapplicationconnectivityvalidator/centralapplicationconnectivityvalidator.go deleted file mode 100644 index 2c8419d0c77b..000000000000 --- a/components/central-application-connectivity-validator/cmd/centralapplicationconnectivityvalidator/centralapplicationconnectivityvalidator.go +++ /dev/null @@ -1,197 +0,0 @@ -package main - -import ( - "context" - "fmt" - "net" - "net/http" - "os" - "os/signal" - "syscall" - "time" - - "sigs.k8s.io/controller-runtime/pkg/client" - - "sigs.k8s.io/controller-runtime/pkg/manager" - - "github.com/kyma-project/kyma/common/logging/logger" - "github.com/kyma-project/kyma/common/logging/tracing" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" - - "github.com/kyma-project/kyma/components/central-application-connectivity-validator/internal/controller" - "github.com/kyma-project/kyma/components/central-application-connectivity-validator/internal/externalapi" - "github.com/kyma-project/kyma/components/central-application-connectivity-validator/internal/validationproxy" - "github.com/oklog/run" - "github.com/patrickmn/go-cache" - - "k8s.io/apimachinery/pkg/runtime" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" - clientgoscheme "k8s.io/client-go/kubernetes/scheme" - ctrl "sigs.k8s.io/controller-runtime" -) - -const ( - shutdownTimeout = 2 * time.Second -) - -var ( - scheme = runtime.NewScheme() -) - -func init() { - utilruntime.Must(clientgoscheme.AddToScheme(scheme)) - utilruntime.Must(v1alpha1.AddToScheme(scheme)) -} - -func main() { - options, err := parseOptions() - if err != nil { - if logErr := logger.LogFatalError("Failed to parse options: %s", err.Error()); logErr != nil { - fmt.Printf("Failed to initializie default fatal error logger: %s,Failed to parse options: %s", logErr, err) - } - os.Exit(1) - } - if err = options.validate(); err != nil { - if logErr := logger.LogFatalError("Failed to validate options: %s", err.Error()); logErr != nil { - fmt.Printf("Failed to initializie default fatal error logger: %s,Failed to validate options: %s", logErr, err) - } - os.Exit(1) - } - level, err := logger.MapLevel(options.LogLevel) - if err != nil { - if logErr := logger.LogFatalError("Failed to map log level from options: %s", err.Error()); logErr != nil { - fmt.Printf("Failed to initializie default fatal error logger: %s, Failed to map log level from options: %s", logErr, err) - } - - os.Exit(2) - } - format, err := logger.MapFormat(options.LogFormat) - if err != nil { - if logErr := logger.LogFatalError("Failed to map log format from options: %s", err.Error()); logErr != nil { - fmt.Printf("Failed to initializie default fatal error logger: %s, Failed to map log format from options: %s", logErr, err) - } - os.Exit(3) - } - log, err := logger.New(format, level) - if err != nil { - if logErr := logger.LogFatalError("Failed to initialize logger: %s", err.Error()); logErr != nil { - fmt.Printf("Failed to initializie default fatal error logger: %s, Failed to initialize logger: %s", logErr, err) - } - os.Exit(4) - } - if err := logger.InitKlog(log, level); err != nil { - log.WithContext().Error("While initializing klog logger: %s", err.Error()) - os.Exit(5) - } - - log.WithContext().With("options", options).Info("Starting Validation Proxy.") - - idCache := cache.New( - cache.NoExpiration, - cache.NoExpiration, - ) - idCache.OnEvicted(func(key string, i interface{}) { - log.WithContext(). - With("controller", "cache_janitor"). - With("name", key). - Warnf("Deleted the application from the cache with values %v.", i) - }) - - proxyHandler := validationproxy.NewProxyHandler( - options.eventingPublisherHost, - options.eventingDestinationPath, - idCache, - log) - - tracingMiddleware := tracing.NewTracingMiddleware(proxyHandler.ProxyAppConnectorRequests) - - proxyServer := http.Server{ - Handler: validationproxy.NewHandler(tracingMiddleware), - Addr: fmt.Sprintf(":%d", options.proxyPort), - } - - externalServer := http.Server{ - Handler: externalapi.NewHandler(), - Addr: fmt.Sprintf(":%d", options.externalAPIPort), - } - - mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{ - Scheme: scheme, - MetricsBindAddress: "0", - SyncPeriod: &options.syncPeriod, - ClientDisableCacheFor: []client.Object{ - &v1alpha1.Application{}, - }, - }) - if err != nil { - log.WithContext().Error("Unable to start manager: %s", err.Error()) - os.Exit(1) - } - if err = controller.NewController( - log, - mgr.GetClient(), - idCache, - options.appNamePlaceholder, - options.eventingPathPrefixV1, - options.eventingPathPrefixV2, - options.eventingPathPrefixEvents).SetupWithManager(mgr); err != nil { - log.WithContext().Error("Unable to create reconciler: %s", err.Error()) - os.Exit(1) - } - - ctx, cancel := context.WithCancel(context.Background()) - var g run.Group - addInterruptSignalToRunGroup(ctx, cancel, log, &g) - addManagerToRunGroup(ctx, log, &g, mgr) - addHttpServerToRunGroup(log, "proxy-server", &g, &proxyServer) - addHttpServerToRunGroup(log, "external-server", &g, &externalServer) - - err = g.Run() - if err != nil && err != http.ErrServerClosed { - log.WithContext().Fatal(err) - } -} - -func addHttpServerToRunGroup(log *logger.Logger, name string, g *run.Group, srv *http.Server) { - log.WithContext().Infof("Starting %s HTTP server on %s", name, srv.Addr) - ln, err := net.Listen("tcp", srv.Addr) - if err != nil { - log.WithContext().Fatalf("Unable to start %s HTTP server: '%s'", name, err.Error()) - } - g.Add(func() error { - defer log.WithContext().Infof("Server %s finished", name) - return srv.Serve(ln) - }, func(error) { - log.WithContext().Infof("Shutting down %s HTTP server on %s", name, srv.Addr) - - ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout) - defer cancel() - err = srv.Shutdown(ctx) - if err != nil && err != http.ErrServerClosed { - log.WithContext().Warnf("HTTP server shutdown %s failed: %s", name, err.Error()) - } - }) -} - -func addManagerToRunGroup(ctx context.Context, log *logger.Logger, g *run.Group, mgr manager.Manager) { - g.Add(func() error { - defer log.WithContext().Infof("Manager finished") - return mgr.Start(ctx) - }, func(error) { - }) -} - -func addInterruptSignalToRunGroup(ctx context.Context, cancel context.CancelFunc, log *logger.Logger, g *run.Group) { - g.Add(func() error { - c := make(chan os.Signal, 1) - signal.Notify(c, syscall.SIGINT, syscall.SIGTERM) - select { - case <-ctx.Done(): - case sig := <-c: - log.WithContext().Infof("received signal %s", sig) - } - return nil - }, func(error) { - cancel() - }) -} diff --git a/components/central-application-connectivity-validator/cmd/centralapplicationconnectivityvalidator/options.go b/components/central-application-connectivity-validator/cmd/centralapplicationconnectivityvalidator/options.go deleted file mode 100644 index c7346586601b..000000000000 --- a/components/central-application-connectivity-validator/cmd/centralapplicationconnectivityvalidator/options.go +++ /dev/null @@ -1,97 +0,0 @@ -package main - -import ( - "flag" - "fmt" - "github.com/vrischmann/envconfig" - "k8s.io/client-go/tools/clientcmd" - "os" - "strings" - "time" -) - -type args struct { - proxyPort int - externalAPIPort int - eventingPathPrefixV1 string - eventingPathPrefixV2 string - eventingPublisherHost string - eventingPathPrefixEvents string - eventingDestinationPath string - appNamePlaceholder string - syncPeriod time.Duration -} - -type config struct { - LogFormat string `default:"json"` - LogLevel string `default:"warn"` -} - -type options struct { - args - config -} - -func parseOptions() (*options, error) { - proxyPort := flag.Int("proxyPort", 8081, "Proxy port.") - externalAPIPort := flag.Int("externalAPIPort", 8080, "External API port.") - eventingPathPrefixV1 := flag.String("eventingPathPrefixV1", "/v1/events", "Prefix of paths that is directed to Kyma Eventing V1") - eventingPathPrefixV2 := flag.String("eventingPathPrefixV2", "/v2/events", "Prefix of paths that is directed to Kyma Eventing V2") - eventingPublisherHost := flag.String("eventingPublisherHost", "eventing-event-publisher-proxy.kyma-system", "Host (and port) of the Eventing Publisher") - eventingDestinationPath := flag.String("eventingDestinationPath", "/publish", "Path of the destination of the requests to the Eventing") - eventingPathPrefixEvents := flag.String("eventingPathPrefixEvents", "/events", "Prefix of paths that is directed to the Cloud Events based Eventing") - appNamePlaceholder := flag.String("appNamePlaceholder", "%%APP_NAME%%", "Path URL placeholder used for an application name") - syncPeriod := flag.Duration("syncPeriod", 45*time.Second, "Sync period in seconds how often controller should periodically reconcile Application resource.") - - flag.Parse() - - var c config - if err := envconfig.InitWithPrefix(&c, "APP"); err != nil { - return nil, err - } - - return &options{ - args: args{ - proxyPort: *proxyPort, - externalAPIPort: *externalAPIPort, - eventingPathPrefixV1: *eventingPathPrefixV1, - eventingPathPrefixV2: *eventingPathPrefixV2, - eventingPublisherHost: *eventingPublisherHost, - eventingPathPrefixEvents: *eventingPathPrefixEvents, - eventingDestinationPath: *eventingDestinationPath, - appNamePlaceholder: *appNamePlaceholder, - syncPeriod: *syncPeriod, - }, - config: c, - }, nil -} - -func (o *options) String() string { - return fmt.Sprintf("--proxyPort=%d --externalAPIPort=%d "+ - "--eventingPathPrefixV1=%s --eventingPathPrefixV2=%s "+ - "--eventingPathPrefixEvents=%s --eventingPublisherHost=%s "+ - "--eventingDestinationPath=%s "+ - "--appNamePlaceholder=%s "+ - "--syncPeriod=%d APP_LOG_FORMAT=%s APP_LOG_LEVEL=%s KUBECONFIG=%s", - o.proxyPort, o.externalAPIPort, - o.eventingPathPrefixV1, o.eventingPathPrefixV2, o.eventingPathPrefixEvents, - o.eventingPublisherHost, o.eventingDestinationPath, - o.appNamePlaceholder, - o.syncPeriod, o.LogFormat, o.LogLevel, os.Getenv(clientcmd.RecommendedConfigPathEnvVar)) -} - -func (o *options) validate() error { - if o.appNamePlaceholder == "" { - return nil - } - if !strings.Contains(o.eventingPathPrefixV1, o.appNamePlaceholder) { - return fmt.Errorf("eventingPathPrefixV1 '%s' should contain appNamePlaceholder '%s'", o.eventingPathPrefixV1, o.appNamePlaceholder) - } - if !strings.Contains(o.eventingPathPrefixV2, o.appNamePlaceholder) { - return fmt.Errorf("eventingPathPrefixV2 '%s' should contain appNamePlaceholder '%s'", o.eventingPathPrefixV2, o.appNamePlaceholder) - } - if !strings.Contains(o.eventingPathPrefixEvents, o.appNamePlaceholder) { - return fmt.Errorf("eventingPathPrefixEvents '%s' should contain appNamePlaceholder '%s'", o.eventingPathPrefixEvents, o.appNamePlaceholder) - } - return nil -} diff --git a/components/central-application-connectivity-validator/cmd/centralapplicationconnectivityvalidator/options_test.go b/components/central-application-connectivity-validator/cmd/centralapplicationconnectivityvalidator/options_test.go deleted file mode 100644 index a57eaaa1283b..000000000000 --- a/components/central-application-connectivity-validator/cmd/centralapplicationconnectivityvalidator/options_test.go +++ /dev/null @@ -1,89 +0,0 @@ -package main - -import ( - "testing" - "time" - - "github.com/stretchr/testify/assert" -) - -func TestOptionsValidation(t *testing.T) { - tests := []struct { - name string - args args - valid bool - }{ - { - name: "default arguments", - valid: true, - args: args{ - appNamePlaceholder: "%%APP_NAME%%", - eventingPathPrefixV1: "/%%APP_NAME%%/v1/events", - eventingPathPrefixV2: "/%%APP_NAME%%/v2/events", - eventingPathPrefixEvents: "/%%APP_NAME%%/events", - }, - }, - { - name: "skip validation when appNamePlaceholder is empty", - valid: true, - args: args{ - appNamePlaceholder: "", - eventingPathPrefixV1: "/app1/v1/events", - eventingPathPrefixV2: "/app1/v2/events", - eventingPathPrefixEvents: "//events", - }, - }, - { - name: "missing app name prefix in eventingPathPrefixV1", - valid: false, - args: args{ - appNamePlaceholder: "%%APP_NAME%%", - eventingPathPrefixV1: "/v1/events", - eventingPathPrefixV2: "/%%APP_NAME%%/v2/events", - eventingPathPrefixEvents: "/%%APP_NAME%%/events", - }, - }, - { - name: "missing app name prefix in eventingPathPrefixV2", - valid: false, - args: args{ - appNamePlaceholder: "%%APP_NAME%%", - eventingPathPrefixV1: "/%%APP_NAME%%/v1/events", - eventingPathPrefixV2: "//v2/events", - eventingPathPrefixEvents: "/%%APP_NAME%%/events", - }, - }, - { - name: "missing app name prefix in eventingPathPrefixEvents", - valid: false, - args: args{ - appNamePlaceholder: "%%APP_NAME%%", - eventingPathPrefixV1: "/%%APP_NAME%%/v1/events", - eventingPathPrefixV2: "/%%APP_NAME%%/v2/events", - eventingPathPrefixEvents: "//events", - }, - }, - { - name: "syncPeriod is set", - valid: true, - args: args{ - appNamePlaceholder: "%%APP_NAME%%", - eventingPathPrefixV1: "/%%APP_NAME%%/v1/events", - eventingPathPrefixV2: "/%%APP_NAME%%/v2/events", - eventingPathPrefixEvents: "/%%APP_NAME%%/events", - syncPeriod: 121 * time.Second, - }, - }, - } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - opts := options{ - args: tc.args, - config: config{}, - } - err := opts.validate() - b := (err == nil && tc.valid) || (err != nil && !tc.valid) - assert.Truef(t, b, "Parsing validation error: %v, valid: %v", err, tc.valid) - }) - } -} diff --git a/components/central-application-connectivity-validator/go.mod b/components/central-application-connectivity-validator/go.mod deleted file mode 100644 index 39792b5b0102..000000000000 --- a/components/central-application-connectivity-validator/go.mod +++ /dev/null @@ -1,93 +0,0 @@ -module github.com/kyma-project/kyma/components/central-application-connectivity-validator - -go 1.21 - -require ( - github.com/gorilla/mux v1.8.1 - github.com/kyma-project/kyma/common/logging v0.0.0-20230130154909-4c81ab2cee61 - github.com/kyma-project/kyma/components/central-application-gateway v0.0.0-20230130154909-4c81ab2cee61 - github.com/oklog/run v1.1.0 - github.com/onsi/ginkgo/v2 v2.17.3 - github.com/onsi/gomega v1.33.1 - github.com/patrickmn/go-cache v2.1.0+incompatible - github.com/stretchr/testify v1.9.0 - github.com/vrischmann/envconfig v1.3.0 - go.uber.org/zap v1.27.0 - k8s.io/apimachinery v0.27.4 - k8s.io/client-go v0.26.7 - k8s.io/utils v0.0.0-20230209194617-a36077c30491 - sigs.k8s.io/controller-runtime v0.14.6 -) - -require ( - github.com/beorn7/perks v1.0.1 // indirect - github.com/cespare/xxhash/v2 v2.1.2 // indirect - github.com/davecgh/go-spew v1.1.1 // indirect - github.com/emicklei/go-restful/v3 v3.9.0 // indirect - github.com/evanphx/json-patch v4.12.0+incompatible // indirect - github.com/evanphx/json-patch/v5 v5.6.0 // indirect - github.com/fsnotify/fsnotify v1.6.0 // indirect - github.com/go-logr/logr v1.4.1 // indirect - github.com/go-logr/zapr v1.2.3 // indirect - github.com/go-openapi/jsonpointer v0.19.6 // indirect - github.com/go-openapi/jsonreference v0.20.1 // indirect - github.com/go-openapi/swag v0.22.3 // indirect - github.com/go-task/slim-sprig/v3 v3.0.0 // indirect - github.com/gogo/protobuf v1.3.2 // indirect - github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect - github.com/golang/protobuf v1.5.3 // indirect - github.com/google/gnostic v0.5.7-v3refs // indirect - github.com/google/go-cmp v0.6.0 // indirect - github.com/google/gofuzz v1.1.0 // indirect - github.com/google/pprof v0.0.0-20240424215950-a892ee059fd6 // indirect - github.com/google/uuid v1.3.0 // indirect - github.com/imdario/mergo v0.3.12 // indirect - github.com/josharian/intern v1.0.0 // indirect - github.com/json-iterator/go v1.1.12 // indirect - github.com/kr/pretty v0.3.1 // indirect - github.com/mailru/easyjson v0.7.7 // indirect - github.com/matttproud/golang_protobuf_extensions v1.0.2 // 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/pmezard/go-difflib v1.0.0 // indirect - github.com/prometheus/client_golang v1.14.0 // indirect - github.com/prometheus/client_model v0.3.0 // indirect - github.com/prometheus/common v0.37.0 // indirect - github.com/prometheus/procfs v0.8.0 // indirect - github.com/rogpeppe/go-internal v1.10.0 // indirect - github.com/spf13/pflag v1.0.5 // indirect - go.uber.org/multierr v1.10.0 // indirect - golang.org/x/net v0.24.0 // indirect - golang.org/x/oauth2 v0.0.0-20220223155221-ee480838109b // indirect - golang.org/x/sys v0.19.0 // indirect - golang.org/x/term v0.15.0 // indirect - golang.org/x/text v0.14.0 // indirect - golang.org/x/time v0.3.0 // indirect - golang.org/x/tools v0.20.0 // indirect - gomodules.xyz/jsonpatch/v2 v2.2.0 // indirect - google.golang.org/appengine v1.6.8 // 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/api v0.26.7 // indirect - k8s.io/apiextensions-apiserver v0.26.1 // indirect - k8s.io/component-base v0.26.1 // indirect - k8s.io/klog/v2 v2.90.1 // indirect - k8s.io/kube-openapi v0.0.0-20230501164219-8b0f38b5fd1f // indirect - sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect - sigs.k8s.io/structured-merge-diff/v4 v4.2.3 // indirect - sigs.k8s.io/yaml v1.3.0 // indirect -) - -replace ( - github.com/containerd/containerd => github.com/containerd/containerd v1.4.11 - github.com/docker/docker => github.com/docker/docker v20.10.8+incompatible - github.com/opencontainers/runc => github.com/opencontainers/runc v1.1.12 - golang.org/x/crypto => golang.org/x/crypto v0.16.0 - golang.org/x/net => golang.org/x/net v0.19.0 - golang.org/x/sys => golang.org/x/sys v0.15.0 - golang.org/x/text => golang.org/x/text v0.14.0 -) diff --git a/components/central-application-connectivity-validator/go.sum b/components/central-application-connectivity-validator/go.sum deleted file mode 100644 index d8d7363f58c2..000000000000 --- a/components/central-application-connectivity-validator/go.sum +++ /dev/null @@ -1,566 +0,0 @@ -cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= -cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU= -cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= -cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc= -cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0= -cloud.google.com/go v0.50.0/go.mod h1:r9sluTvynVuxRIOHXQEHMFffphuXHOMZMycpNR5e6To= -cloud.google.com/go v0.52.0/go.mod h1:pXajvRH/6o3+F9jDHZWQ5PbGhn+o8w9qiu/CffaVdO4= -cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6M= -cloud.google.com/go v0.54.0/go.mod h1:1rq2OEkV3YMf6n/9ZvGWI3GWw0VoqH/1x2nd8Is/bPc= -cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKVk= -cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs= -cloud.google.com/go v0.62.0/go.mod h1:jmCYTdRCQuc1PHIIJ/maLInMho30T/Y0M4hTdTShOYc= -cloud.google.com/go v0.65.0/go.mod h1:O5N8zS7uWy9vkA9vayVHs65eM1ubvY4h553ofrNHObY= -cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= -cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE= -cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc= -cloud.google.com/go/bigquery v1.5.0/go.mod h1:snEHRnqQbz117VIFhE8bmtwIDY80NLUZUMb4Nv6dBIg= -cloud.google.com/go/bigquery v1.7.0/go.mod h1://okPTzCYNXSlb24MZs83e2Do+h+VXtc4gLoIoXIAPc= -cloud.google.com/go/bigquery v1.8.0/go.mod h1:J5hqkt3O0uAFnINi6JXValWIb1v0goeZM77hZzJN/fQ= -cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= -cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk= -cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= -cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw= -cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA= -cloud.google.com/go/pubsub v1.3.1/go.mod h1:i+ucay31+CNRpDW4Lu78I4xXG+O1r/MAHgjpRVR+TSU= -cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= -cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos= -cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk= -cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= -cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= -dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= -github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= -github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= -github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= -github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= -github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= -github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= -github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= -github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= -github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= -github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= -github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= -github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 h1:DDGfHa7BWjL4YnC6+E63dPcxHo2sUxDIu8g3QgEJdRY= -github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869/go.mod h1:Ekp36dRnpXw/yCqJaO+ZrUyxD+3VXMFFr56k5XYrpB4= -github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= -github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE= -github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= -github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= -github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= -github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= -github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= -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/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815/go.mod h1:WwZ+bS3ebgob9U8Nd0kOddGdZWjyMGR8Wziv+TBNwSE= -github.com/emicklei/go-restful/v3 v3.9.0 h1:XwGDlfxEnQZzuopoqxwSEllNcCOM9DhhFyhFIIGKwxE= -github.com/emicklei/go-restful/v3 v3.9.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= -github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= -github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= -github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= -github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/evanphx/json-patch v0.5.2/go.mod h1:ZWS5hhDbVDyob71nXKNL0+PWn6ToqBHMikGIFbs31qQ= -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/evanphx/json-patch/v5 v5.6.0 h1:b91NhWfaz02IuVxO9faSllyAtNXHMPkC5J8sJCLunww= -github.com/evanphx/json-patch/v5 v5.6.0/go.mod h1:G79N1coSVB93tBe7j6PhzjmR3/2VvlbKOFpnXhI9Bw4= -github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= -github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= -github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= -github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= -github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= -github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= -github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= -github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY= -github.com/go-kit/log v0.2.0/go.mod h1:NwTd00d/i8cPZ3xOwwiv2PO5MOcx78fFErGNcVmBjv0= -github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= -github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= -github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= -github.com/go-logfmt/logfmt v0.5.1/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs= -github.com/go-logr/logr v1.2.0/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -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-logr/zapr v1.2.3 h1:a9vnzlIBPQBBkeaR9IuMUfmVOrQlkoC4YfPoFkX3T7A= -github.com/go-logr/zapr v1.2.3/go.mod h1:eIauM6P8qSvTw5o2ez6UEAfGjQKrxQTl5EoK+Qa2oG4= -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.1 h1:FBLnyygC4/IZZr893oiomc9XaghoveYTrLC1F86HID8= -github.com/go-openapi/jsonreference v0.20.1/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-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= -github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= -github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= -github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= -github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= -github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= -github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= -github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE= -github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= -github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= -github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= -github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= -github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= -github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= -github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= -github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= -github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= -github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= -github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= -github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= -github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= -github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= -github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= -github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= -github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= -github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= -github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= -github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= -github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= -github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= -github.com/google/gnostic v0.5.7-v3refs h1:FhTMOKj2VhjpouxvWJAV1TL304uMlb9zcDqkl6cEI54= -github.com/google/gnostic v0.5.7-v3refs/go.mod h1:73MKFl6jIHelAJNaBGFzt3SPtZULs9dYrGFt8OiIsHQ= -github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= -github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -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.1.0 h1:Hsa8mG0dQ46ij8Sl2AYJDUv1oA9/d6Vk+3LG99Oe02g= -github.com/google/gofuzz v1.1.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= -github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= -github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= -github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= -github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20240424215950-a892ee059fd6 h1:k7nVchz72niMH6YLQNvHSdIE7iqsQxK1P41mySCvssg= -github.com/google/pprof v0.0.0-20240424215950-a892ee059fd6/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw= -github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= -github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= -github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= -github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= -github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= -github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= -github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= -github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= -github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= -github.com/imdario/mergo v0.3.12 h1:b6R2BslTbIEToALKP7LxUvijTsNI9TAe80pLWN2g/HU= -github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= -github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= -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/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= -github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= -github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= -github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= -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/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= -github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= -github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= -github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= -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/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= -github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= -github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= -github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= -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/kyma-project/kyma/common/logging v0.0.0-20230130154909-4c81ab2cee61 h1:BwQJGDfg0IqI8ltfRGHHPXfPHArzexpDFOhMZGhk92Y= -github.com/kyma-project/kyma/common/logging v0.0.0-20230130154909-4c81ab2cee61/go.mod h1:JGb5RBi8Uz+RZ/jf54+qA+RqY6uPQBJ8pO1w3KSwm1Q= -github.com/kyma-project/kyma/components/central-application-gateway v0.0.0-20230130154909-4c81ab2cee61 h1:iviPUIyUTMKA322amhFURlXbIbj9NrojpvJFDI+DtnQ= -github.com/kyma-project/kyma/components/central-application-gateway v0.0.0-20230130154909-4c81ab2cee61/go.mod h1:NL5E+cv7oyD8xJtDywLrHnkublvqifMBt5HFdw94adc= -github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= -github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= -github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= -github.com/matttproud/golang_protobuf_extensions v1.0.2 h1:hAHbPm5IJGijwng3PWk09JkG9WeqChjprR5s9bBZ+OM= -github.com/matttproud/golang_protobuf_extensions v1.0.2/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4= -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 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= -github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= -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/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= -github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= -github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= -github.com/oklog/run v1.1.0 h1:GEenZ1cK0+q0+wsJew9qUg/DyD8k3JzYsZAi5gYi2mA= -github.com/oklog/run v1.1.0/go.mod h1:sVPdnTZT1zYwAJeCMu2Th4T21pA3FPOQRfWjQlk7DVU= -github.com/onsi/ginkgo/v2 v2.17.3 h1:oJcvKpIb7/8uLpDDtnQuf18xVnwKp8DTD7DQ6gTd/MU= -github.com/onsi/ginkgo/v2 v2.17.3/go.mod h1:nP2DPOQoNsQmsVyv5rDA8JkXQoCs6goXIvr/PRJ1eCc= -github.com/onsi/gomega v1.33.1 h1:dsYjIxxSR755MDmKVsaFQTE22ChNBcuuTWgkUDSubOk= -github.com/onsi/gomega v1.33.1/go.mod h1:U4R44UsT+9eLIaYRB2a5qajjtQYn0hauxvRm16AVYg0= -github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc= -github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ= -github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= -github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -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/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= -github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= -github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= -github.com/prometheus/client_golang v1.11.0/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqroYurpAkEiz0P2BEV0= -github.com/prometheus/client_golang v1.12.1/go.mod h1:3Z9XVyYiZYEO+YQWt3RD2R3jrbd179Rt297l4aS6nDY= -github.com/prometheus/client_golang v1.14.0 h1:nJdhIvne2eSX/XRAFV9PcvFFRbrjbcTUj0VP62TMhnw= -github.com/prometheus/client_golang v1.14.0/go.mod h1:8vpkKitgIVNcqrRBWh1C4TIUQgYNtG/XQE4E/Zae36Y= -github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= -github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/client_model v0.3.0 h1:UBgGFHqYdG/TPFD1B1ogZywDqEkwp3fBMvqdiQ7Xew4= -github.com/prometheus/client_model v0.3.0/go.mod h1:LDGWKZIo7rky3hgvBe+caln+Dr3dPggB5dvjtD7w9+w= -github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= -github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= -github.com/prometheus/common v0.26.0/go.mod h1:M7rCNAaPfAosfx8veZJCuw84e35h3Cfd9VFqTh1DIvc= -github.com/prometheus/common v0.32.1/go.mod h1:vu+V0TpY+O6vW9J44gczi3Ap/oXXR10b+M/gUGO4Hls= -github.com/prometheus/common v0.37.0 h1:ccBbHCgIiT9uSoFY0vX8H3zsNR5eLt17/RQLUvn8pXE= -github.com/prometheus/common v0.37.0/go.mod h1:phzohg0JFMnBEFGxTDbfu3QyL5GI8gTQJFhYO5B3mfA= -github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= -github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= -github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= -github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= -github.com/prometheus/procfs v0.7.3/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= -github.com/prometheus/procfs v0.8.0 h1:ODq8ZFEaYeCaZOJlZZdJA2AbQR98dSHSM1KW/You5mo= -github.com/prometheus/procfs v0.8.0/go.mod h1:z7EfXMXOkbkqb9IINtpCn86r/to3BnA0uaxHdg830/4= -github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= -github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= -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/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= -github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= -github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= -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/stoewer/go-strcase v1.2.0/go.mod h1:IBiWB2sKIp3wVVQ3Y035++gc+knqhUQag1KpM8ahLw8= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.1.1/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.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= -github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -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.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= -github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= -github.com/vrischmann/envconfig v1.3.0 h1:4XIvQTXznxmWMnjouj0ST5lFo/WAYf5Exgl3x82crEk= -github.com/vrischmann/envconfig v1.3.0/go.mod h1:bbvxFYJdRSpXrhS63mBFtKJzkDiNkyArOLXtY6q0kuI= -github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= -go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= -go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= -go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= -go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= -go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= -go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= -go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A= -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.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= -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.19.0/go.mod h1:xg/QME4nWcxGxrpdeYfq7UvYrLh66cuVKdrbD1XF/NI= -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.16.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4= -golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= -golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek= -golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY= -golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= -golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= -golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= -golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= -golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= -golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= -golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= -golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= -golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= -golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= -golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= -golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= -golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= -golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= -golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= -golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= -golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= -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/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/net v0.19.0 h1:zTwKpTd2XuCqf8huc7Fo2iSy+4RHPd10s4KzeTnVr1c= -golang.org/x/net v0.19.0/go.mod h1:CfAk/cbD4CthTvqiEl8NpboMuiuOYsAr/7NOjZJtv1U= -golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20220223155221-ee480838109b h1:clP8eMhB30EHdc0bd2Twtq6kgU7yl5ub2cQLSdrv1Dg= -golang.org/x/oauth2 v0.0.0-20220223155221-ee480838109b/go.mod h1:DAh4E804XQdzx2j+YRIaUnCqCV2RuMz24cGBJ5QYIrc= -golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -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-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc= -golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/term v0.15.0 h1:y/Oo/a/q3IXu26lQgl04j/gjuBDOBlx7X6Om1j2CPW4= -golang.org/x/term v0.15.0/go.mod h1:BDl952bC7+uMoWR75FIrCDx79TPU9oHkTZ9yRbYOrX0= -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.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -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-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= -golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191108193012-7d206e10da11/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200204074204-1cc6d1ef6c74/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200224181240-023911ca70b2/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200304193943-95d2e580d8eb/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= -golang.org/x/tools v0.0.0-20200312045724-11d5b4c81c7d/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= -golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= -golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/tools v0.20.0 h1:hz/CVckiOxybQvFw6h7b/q80NTr9IUQb4s1IIzW7KNY= -golang.org/x/tools v0.20.0/go.mod h1:WvitBU7JJf6A4jOdg4S1tviW9bhUxkgeCui/0JHctQg= -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= -gomodules.xyz/jsonpatch/v2 v2.2.0 h1:4pT439QV83L+G9FkcCriY6EkpcK6r6bK+A5FBUMI7qY= -gomodules.xyz/jsonpatch/v2 v2.2.0/go.mod h1:WXp+iVDkoLQqPudfQ9GBlwB2eZ5DKOnjQZCYdOS8GPY= -google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= -google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= -google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= -google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= -google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= -google.golang.org/api v0.14.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= -google.golang.org/api v0.15.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= -google.golang.org/api v0.17.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.18.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.19.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.20.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.22.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.24.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= -google.golang.org/api v0.28.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= -google.golang.org/api v0.29.0/go.mod h1:Lcubydp8VUV7KeIHD9z2Bys/sm/vGKnG1UHuDBSrHWM= -google.golang.org/api v0.30.0/go.mod h1:QGmEvQ87FHZNiUVJkT14jQNYJ4ZJjdRF23ZXz5138Fc= -google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= -google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= -google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/appengine v1.6.8 h1:IhEN5q69dyKagZPYMSdIjS2HqprW324FRQZJcGqPAsM= -google.golang.org/appengine v1.6.8/go.mod h1:1jJ3jBArFh5pcgW8gCtRJnepW8FzD1V44FJffLiz/Ds= -google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= -google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= -google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= -google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= -google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20191115194625-c23dd37a84c9/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20191216164720-4f79533eabd1/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20191230161307-f3c370f40bfb/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20200115191322-ca5a22157cba/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20200204135345-fa8e72b47b90/go.mod h1:GmwEX6Z4W5gMy59cAlVYjN9JhxgbQH6Gn+gFDQe2lzA= -google.golang.org/genproto v0.0.0-20200212174721-66ed5ce911ce/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200224152610-e50cd9704f63/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200228133532-8c2c7df3a383/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200305110556-506484158171/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200312145019-da6875a35672/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200331122359-1ee6d9798940/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200430143042-b979b6f78d84/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200511104702-f5ebc3bea380/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200515170657-fc4c6c6a6587/go.mod h1:YsZOwe1myG/8QRHRsmBRE1LrgQY60beZKjly0O1fX9U= -google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= -google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7FcilCzHH/e9qn6dsT145K34l5v+OpcnNgKAAA= -google.golang.org/genproto v0.0.0-20200729003335-053ba62fc06f/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20201019141844-1ed22bb0c154/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= -google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= -google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= -google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= -google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= -google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= -google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= -google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= -google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= -google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= -google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= -google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= -google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= -google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= -google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= -google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= -google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= -google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -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/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/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/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= -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.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.3.0/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.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/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= -honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= -honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= -honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= -k8s.io/api v0.26.7 h1:Lf4iEBEJb5OFNmawtBfSZV/UNi9riSJ0t1qdhyZqI40= -k8s.io/api v0.26.7/go.mod h1:Vk9bMadzA49UHPmHB//lX7VRCQSXGoVwfLd3Sc1SSXI= -k8s.io/apiextensions-apiserver v0.26.1 h1:cB8h1SRk6e/+i3NOrQgSFij1B2S0Y0wDoNl66bn8RMI= -k8s.io/apiextensions-apiserver v0.26.1/go.mod h1:AptjOSXDGuE0JICx/Em15PaoO7buLwTs0dGleIHixSM= -k8s.io/apimachinery v0.27.4 h1:CdxflD4AF61yewuid0fLl6bM4a3q04jWel0IlP+aYjs= -k8s.io/apimachinery v0.27.4/go.mod h1:XNfZ6xklnMCOGGFNqXG7bUrQCoR04dh/E7FprV6pb+E= -k8s.io/client-go v0.26.7 h1:hyU9aKHlwVOykgyxzGYkrDSLCc4+mimZVyUJjPyUn1E= -k8s.io/client-go v0.26.7/go.mod h1:okYjy0jtq6sdeztALDvCh24tg4opOQS1XNvsJlERDAo= -k8s.io/component-base v0.26.1 h1:4ahudpeQXHZL5kko+iDHqLj/FSGAEUnSVO0EBbgDd+4= -k8s.io/component-base v0.26.1/go.mod h1:VHrLR0b58oC035w6YQiBSbtsf0ThuSwXP+p5dD/kAWU= -k8s.io/klog/v2 v2.90.1 h1:m4bYOKall2MmOiRaR1J+We67Do7vm9KiQVlT96lnHUw= -k8s.io/klog/v2 v2.90.1/go.mod h1:y1WjHnz7Dj687irZUWR/WLkLc5N1YHtjLdmgWjndZn0= -k8s.io/kube-openapi v0.0.0-20230501164219-8b0f38b5fd1f h1:2kWPakN3i/k81b0gvD5C5FJ2kxm1WrQFanWchyKuqGg= -k8s.io/kube-openapi v0.0.0-20230501164219-8b0f38b5fd1f/go.mod h1:byini6yhqGC14c3ebc/QwanvYwhuMWF6yz2F8uwW8eg= -k8s.io/utils v0.0.0-20230209194617-a36077c30491 h1:r0BAOLElQnnFhE/ApUsg3iHdVYYPBjNSSOMowRZxxsY= -k8s.io/utils v0.0.0-20230209194617-a36077c30491/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= -rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= -rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= -rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= -sigs.k8s.io/controller-runtime v0.14.6 h1:oxstGVvXGNnMvY7TAESYk+lzr6S3V5VFxQ6d92KcwQA= -sigs.k8s.io/controller-runtime v0.14.6/go.mod h1:WqIdsAY6JBsjfc/CqO0CORmNtoCtE4S6qbPc9s68h+0= -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.2.3 h1:PRbqxJClWWYMNV1dhaG4NsibJbArud9kFxnAMREiWFE= -sigs.k8s.io/structured-merge-diff/v4 v4.2.3/go.mod h1:qjx8mGObPmV2aSZepjQjbmb2ihdVs8cGKBraizNC69E= -sigs.k8s.io/yaml v1.3.0 h1:a2VclLzOGrwOHDiV8EfBGhvjHvP46CtW5j6POvhYGGo= -sigs.k8s.io/yaml v1.3.0/go.mod h1:GeOyir5tyXNByN85N/dRIT9es5UQNerPYEKK56eTBm8= diff --git a/components/central-application-connectivity-validator/hack/applications.applicationconnector.crd.yaml b/components/central-application-connectivity-validator/hack/applications.applicationconnector.crd.yaml deleted file mode 100644 index 1a7b6518af71..000000000000 --- a/components/central-application-connectivity-validator/hack/applications.applicationconnector.crd.yaml +++ /dev/null @@ -1,183 +0,0 @@ -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - annotations: - "helm.sh/resource-policy": keep - name: applications.applicationconnector.kyma-project.io -spec: - group: applicationconnector.kyma-project.io - preserveUnknownFields: false - versions: - - name: v1alpha1 - served: true - storage: true - schema: - openAPIV3Schema: - type: object - properties: - spec: - properties: - compassMetadata: - type: object - required: - - "authentication" - properties: - applicationId: - type: string - authentication: - type: object - required: - - "clientIds" - properties: - clientIds: - type: array - items: - type: string - accessLabel: - type: string - maxLength: 63 - pattern: '^([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9]$' - description: - type: string - skipInstallation: - type: boolean - skipVerify: - type: boolean - encodeUrl: - type: boolean - default: true - labels: - nullable: true - additionalProperties: - type: string - type: object - tenant: - type: string - group: - type: string - tags: - nullable: true - description: New fields used by V2 version - items: - type: string - type: array - displayName: - type: string - providerDisplayName: - type: string - longDescription: - type: string - services: - type: array - items: - type: object - required: - - "id" - - "name" - - "displayName" - - "providerDisplayName" - - "description" - - "entries" - properties: - id: - type: string - name: - type: string - identifier: - type: string - labels: - nullable: true - additionalProperties: - type: string - description: Deprecated - type: object - displayName: - type: string - description: - type: string - longDescription: - type: string - providerDisplayName: - type: string - authCreateParameterSchema: - description: New fields used by V2 version - type: string - entries: - type: array - items: - type: object - required: - - "type" - properties: - apiType: - type: string - type: - type: string - enum: - - "API" - - "Events" - gatewayUrl: - type: string - centralGatewayUrl: - type: string - accessLabel: - type: string - maxLength: 63 - pattern: '^([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9]$' - targetUrl: - type: string - id: - type: string - name: - description: New fields used by V2 version - type: string - requestParametersSecretName: - type: string - specificationUrl: - type: string - credentials: - type: object - required: - - "type" - - "secretName" - properties: - type: - type: string - secretName: - type: string - authenticationUrl: - type: string - csrfInfo: - type: object - required: - - "tokenEndpointURL" - properties: - tokenEndpointURL: - type: string - tags: - type: array - items: - type: string - type: object - status: - properties: - installationStatus: - description: Represents the status of Application release installation - properties: - description: - type: string - status: - type: string - required: - - status - type: object - required: - - installationStatus - type: object - scope: Cluster - names: - plural: applications - singular: application - kind: Application - shortNames: - - app diff --git a/components/central-application-connectivity-validator/internal/apperrors/apperrors.go b/components/central-application-connectivity-validator/internal/apperrors/apperrors.go deleted file mode 100755 index 2d62744215e1..000000000000 --- a/components/central-application-connectivity-validator/internal/apperrors/apperrors.go +++ /dev/null @@ -1,58 +0,0 @@ -package apperrors - -import "fmt" - -const ( - CodeInternal = 1 - CodeNotFound = 2 - CodeAlreadyExists = 3 - CodeWrongInput = 4 - CodeForbidden = 5 - CodeBadRequest = 6 -) - -type AppError interface { - Code() int - Error() string -} - -type appError struct { - code int - message string -} - -func errorf(code int, format string, a ...interface{}) AppError { - return appError{code: code, message: fmt.Sprintf(format, a...)} -} - -func Internal(format string, a ...interface{}) AppError { - return errorf(CodeInternal, format, a...) -} - -func NotFound(format string, a ...interface{}) AppError { - return errorf(CodeNotFound, format, a...) -} - -func AlreadyExists(format string, a ...interface{}) AppError { - return errorf(CodeAlreadyExists, format, a...) -} - -func WrongInput(format string, a ...interface{}) AppError { - return errorf(CodeWrongInput, format, a...) -} - -func Forbidden(format string, a ...interface{}) AppError { - return errorf(CodeForbidden, format, a...) -} - -func BadRequest(format string, a ...interface{}) AppError { - return errorf(CodeBadRequest, format, a...) -} - -func (ae appError) Code() int { - return ae.code -} - -func (ae appError) Error() string { - return ae.message -} diff --git a/components/central-application-connectivity-validator/internal/apperrors/apperrors_test.go b/components/central-application-connectivity-validator/internal/apperrors/apperrors_test.go deleted file mode 100755 index 2233c20104f1..000000000000 --- a/components/central-application-connectivity-validator/internal/apperrors/apperrors_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package apperrors - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestAppError(t *testing.T) { - - t.Run("should create error with proper code", func(t *testing.T) { - assert.Equal(t, CodeInternal, Internal("error").Code()) - assert.Equal(t, CodeNotFound, NotFound("error").Code()) - assert.Equal(t, CodeAlreadyExists, AlreadyExists("error").Code()) - assert.Equal(t, CodeWrongInput, WrongInput("error").Code()) - assert.Equal(t, CodeForbidden, Forbidden("error").Code()) - }) - - t.Run("should create error with simple message", func(t *testing.T) { - assert.Equal(t, "error", Internal("error").Error()) - assert.Equal(t, "error", NotFound("error").Error()) - assert.Equal(t, "error", AlreadyExists("error").Error()) - assert.Equal(t, "error", WrongInput("error").Error()) - assert.Equal(t, "error", Forbidden("error").Error()) - }) - - t.Run("should create error with formatted message", func(t *testing.T) { - assert.Equal(t, "code: 1, error: bug", Internal("code: %d, error: %s", 1, "bug").Error()) - assert.Equal(t, "code: 1, error: bug", NotFound("code: %d, error: %s", 1, "bug").Error()) - assert.Equal(t, "code: 1, error: bug", AlreadyExists("code: %d, error: %s", 1, "bug").Error()) - assert.Equal(t, "code: 1, error: bug", WrongInput("code: %d, error: %s", 1, "bug").Error()) - assert.Equal(t, "code: 1, error: bug", Forbidden("code: %d, error: %s", 1, "bug").Error()) - }) -} diff --git a/components/central-application-connectivity-validator/internal/controller/cache_sync_controller_test.go b/components/central-application-connectivity-validator/internal/controller/cache_sync_controller_test.go deleted file mode 100644 index d253013bc93e..000000000000 --- a/components/central-application-connectivity-validator/internal/controller/cache_sync_controller_test.go +++ /dev/null @@ -1,102 +0,0 @@ -package controller_test - -import ( - "fmt" - "net/http" - - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" - - "context" - "time" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -type testResult struct { - err error - statusCode int -} - -var _ = Describe("Cache synchronization controller", func() { - Context("When controller is running", func() { - - appCount := 1000 - - It("should not fail with cache miss", func() { - ctx, cancel := context.WithTimeout(context.Background(), time.Second*60) - defer cancel() - - for i := 0; i < appCount; i++ { - testApplication := fmt.Sprintf("ta%d", i) - app := application(testApplication) - Expect(k8sClient.Create(ctx, &app)).To(BeNil()) - - Eventually(func() bool { - _, found := idCache.Get(testApplication) - return found - }, 5*time.Second).Should(BeTrue()) - } - - counter := 0 - client := http.Client{} - - Consistently(func() testResult { - if counter == appCount { - counter = 0 - } - ta := fmt.Sprintf("ta%d", counter) - URL := fmt.Sprintf("http://localhost:%s/%s/v2/events", testProxyServerPort, ta) - req, err := http.NewRequest(http.MethodGet, URL, nil) - Expect(err).Should(BeNil()) - - req.Header.Add("X-Forwarded-Client-Cert", fmt.Sprintf(`Subject="CN=%s"`, ta)) - - resp, err := client.Do(req) - counter++ - return testResult{ - err: err, - statusCode: resp.StatusCode, - } - }, time.Second*10, time.Millisecond*25).Should(Equal(testResult{ - statusCode: http.StatusOK, - })) - }) - - It("should delete application cache when cr is deleted", func() { - ctx, cancel := context.WithTimeout(context.Background(), time.Second*60) - defer cancel() - - appName := "deleteme" - app := application(appName) - Expect(k8sClient.Create(ctx, &app)).To(BeNil()) - - Eventually(func() bool { - _, found := idCache.Get(appName) - return found - }).Should(BeTrue()) - - Expect(k8sClient.Delete(ctx, &app)).Should(BeNil()) - - Eventually(func() bool { - _, found := idCache.Get(appName) - return found - }).Should(BeFalse()) - }) - - }) -}) - -func application(name string) v1alpha1.Application { - return v1alpha1.Application{ - TypeMeta: metav1.TypeMeta{ - Kind: "Application", - APIVersion: "applicationconnector.kyma-project.io/v1alpha1", - }, - ObjectMeta: metav1.ObjectMeta{ - Name: name, - }, - Spec: v1alpha1.ApplicationSpec{}, - } -} diff --git a/components/central-application-connectivity-validator/internal/controller/cachesync.go b/components/central-application-connectivity-validator/internal/controller/cachesync.go deleted file mode 100644 index 6196b937a770..000000000000 --- a/components/central-application-connectivity-validator/internal/controller/cachesync.go +++ /dev/null @@ -1,139 +0,0 @@ -package controller - -import ( - "context" - "github.com/kyma-project/kyma/common/logging/logger" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" - gocache "github.com/patrickmn/go-cache" - apierrors "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/client" - "strings" -) - -type CacheSync interface { - Sync(ctx context.Context, applicationName string) error - Init(ctx context.Context) -} - -type cacheSync struct { - client client.Reader - appCache *gocache.Cache - log *logger.Logger - controllerName string - eventingPathPrefixV1 string - eventingPathPrefixV2 string - eventingPathPrefixEvents string - appNamePlaceholder string -} - -type CachedAppData struct { - ClientIDs []string - AppPathPrefixV1 string - AppPathPrefixV2 string - AppPathPrefixEvents string -} - -func NewCacheSync( - log *logger.Logger, - client client.Reader, - appCache *gocache.Cache, - controllerName, - appNamePlaceholder, - eventingPathPrefixV1, - eventingPathPrefixV2, - eventingPathPrefixEvents string) CacheSync { - return &cacheSync{ - client: client, - appCache: appCache, - log: log, - controllerName: controllerName, - appNamePlaceholder: appNamePlaceholder, - eventingPathPrefixV1: eventingPathPrefixV1, - eventingPathPrefixV2: eventingPathPrefixV2, - eventingPathPrefixEvents: eventingPathPrefixEvents, - } -} - -func (c *cacheSync) Init(ctx context.Context) { - - c.log.WithContext().With("controller", c.controllerName).Infof("Cache initialisation") - - var applicationList v1alpha1.ApplicationList - err := c.client.List(ctx, &applicationList) - - if apierrors.IsNotFound(err) { - c.log.WithContext().Infof("No application are present on the cluster") - } - - if err != nil { - c.log.WithContext().Warnf("Unable to read applications") - } - - for _, app := range applicationList.Items { - c.syncApplication(&app) - } -} - -func (c *cacheSync) Sync(ctx context.Context, applicationName string) error { - var application v1alpha1.Application - if err := c.client.Get(ctx, types.NamespacedName{Name: applicationName}, &application); err != nil { - err = client.IgnoreNotFound(err) - if err != nil { - c.log.WithContext(). - With("controller", c.controllerName). - With("name", applicationName). - Error("Unable to fetch application: %s", err.Error()) - } else { - c.appCache.Delete(applicationName) - c.log.WithContext(). - With("controller", c.controllerName). - With("name", applicationName). - Infof("Application not found, deleting from the cache.") - } - return err - } - c.syncApplication(&application) - return nil -} - -func (c *cacheSync) syncApplication(application *v1alpha1.Application) { - key := application.Name - if !application.DeletionTimestamp.IsZero() { - c.appCache.Delete(key) - c.log.WithContext(). - With("controller", c.controllerName). - With("name", application.Name). - Infof("Deleted the application from the cache on graceful deletion.") - return - } - - applicationInfo := c.getAppDataFromResource(application) - c.appCache.Set(key, applicationInfo, gocache.DefaultExpiration) - c.log.WithContext(). - With("controller", c.controllerName). - With("name", application.Name). - Infof("Added/Updated the application in the cache with values %v.", applicationInfo) -} - -func (c *cacheSync) getAppDataFromResource(application *v1alpha1.Application) CachedAppData { - - appData := CachedAppData{ClientIDs: []string{}} - - appData.AppPathPrefixV1 = c.getApplicationPrefix(c.eventingPathPrefixV1, application.Name) - appData.AppPathPrefixV2 = c.getApplicationPrefix(c.eventingPathPrefixV2, application.Name) - appData.AppPathPrefixEvents = c.getApplicationPrefix(c.eventingPathPrefixEvents, application.Name) - - if application.Spec.CompassMetadata != nil { - appData.ClientIDs = append(appData.ClientIDs, application.Spec.CompassMetadata.Authentication.ClientIds...) - } - - return appData -} - -func (c *cacheSync) getApplicationPrefix(path string, applicationName string) string { - if c.appNamePlaceholder != "" { - return strings.ReplaceAll(path, c.appNamePlaceholder, applicationName) - } - return path -} diff --git a/components/central-application-connectivity-validator/internal/controller/cachesync_test.go b/components/central-application-connectivity-validator/internal/controller/cachesync_test.go deleted file mode 100644 index 63e7a179930f..000000000000 --- a/components/central-application-connectivity-validator/internal/controller/cachesync_test.go +++ /dev/null @@ -1,272 +0,0 @@ -package controller - -import ( - "context" - "testing" - "time" - - "github.com/kyma-project/kyma/common/logging/logger" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/client/clientset/versioned/fake" - applicationconnectorv1alpha1 "github.com/kyma-project/kyma/components/central-application-gateway/pkg/client/clientset/versioned/typed/applicationconnector/v1alpha1" - "github.com/patrickmn/go-cache" - "github.com/stretchr/testify/require" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "sigs.k8s.io/controller-runtime/pkg/client" -) - -var ( - emptyAppData = CachedAppData{} - - appDataNoClients = CachedAppData{ - ClientIDs: []string{}, - AppPathPrefixV1: "/my-app/v1/events", - AppPathPrefixV2: "/my-app/v2/events", - AppPathPrefixEvents: "/my-app/events", - } - - appData2Clients = CachedAppData{ - ClientIDs: []string{"client-1", "client-2"}, - AppPathPrefixV1: "/my-app/v1/events", - AppPathPrefixV2: "/my-app/v2/events", - AppPathPrefixEvents: "/my-app/events", - } - - appData1Client = CachedAppData{ - ClientIDs: []string{"client-1"}, - AppPathPrefixV1: "/my-app/v1/events", - AppPathPrefixV2: "/my-app/v2/events", - AppPathPrefixEvents: "/my-app/events", - } -) - -func TestCacheSync(t *testing.T) { - const name = "my-app" - type setup func(t *testing.T, applicationName string, fc *fakeClient, cache *cache.Cache) - type check func(t *testing.T, applicationName string, cache *cache.Cache) - - notFoundInCache := func(t *testing.T, applicationName string, appCache *cache.Cache) { - _, found := appCache.Get(applicationName) - require.False(t, found) - } - - tests := []struct { - name string - setup setup - check check - }{ - { - name: "Application already removed from cache", - check: notFoundInCache, - }, - { - name: "Remove application from cache", - setup: func(t *testing.T, applicationName string, fc *fakeClient, appCache *cache.Cache) { - appCache.Set(applicationName, emptyAppData, cache.DefaultExpiration) - }, - check: notFoundInCache, - }, - { - name: "Add new application to cache without compass metadata and generate endpoints", - setup: func(t *testing.T, applicationName string, fc *fakeClient, appCache *cache.Cache) { - require.NoError(t, fc.Create(&v1alpha1.Application{ - ObjectMeta: v1.ObjectMeta{ - Name: applicationName, - }, - })) - }, - check: func(t *testing.T, applicationName string, appCache *cache.Cache) { - v, found := appCache.Get(applicationName) - require.True(t, found) - require.Equal(t, appDataNoClients, v) - }, - }, - { - name: "Overwrite authentication clients in cache", - setup: func(t *testing.T, applicationName string, fc *fakeClient, appCache *cache.Cache) { - appCache.Set(applicationName, appData1Client, cache.DefaultExpiration) - require.NoError(t, fc.Create(&v1alpha1.Application{ - ObjectMeta: v1.ObjectMeta{ - Name: applicationName, - }, - })) - }, - check: func(t *testing.T, applicationName string, appCache *cache.Cache) { - v, found := appCache.Get(applicationName) - require.True(t, found) - require.Equal(t, appDataNoClients, v) - }, - }, - { - name: "Add new application to cache with authentication clients and generate endpoints", - setup: func(t *testing.T, applicationName string, fc *fakeClient, appCache *cache.Cache) { - require.NoError(t, fc.Create(&v1alpha1.Application{ - ObjectMeta: v1.ObjectMeta{ - Name: applicationName, - }, - Spec: v1alpha1.ApplicationSpec{ - CompassMetadata: &v1alpha1.CompassMetadata{ - Authentication: v1alpha1.Authentication{ - ClientIds: []string{"client-1", "client-2"}, - }, - }, - }, - })) - }, - check: func(t *testing.T, applicationName string, appCache *cache.Cache) { - v, found := appCache.Get(applicationName) - require.True(t, found) - require.Equal(t, appData2Clients, v) - }, - }, - { - name: "Delete application from cache", - setup: func(t *testing.T, applicationName string, fc *fakeClient, appCache *cache.Cache) { - appCache.Set(applicationName, emptyAppData, cache.DefaultExpiration) - - now := v1.NewTime(time.Now()) - require.NoError(t, fc.Create(&v1alpha1.Application{ - ObjectMeta: v1.ObjectMeta{ - Name: applicationName, - DeletionTimestamp: &now, - }, - })) - }, - check: notFoundInCache, - }, - } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - applicationName := name - - log, err := logger.New(logger.TEXT, logger.DEBUG) - require.NoError(t, err) - appCache := cache.New(60*time.Second, 60*time.Second) - fc := NewFakeClient() - - if tc.setup != nil { - tc.setup(t, applicationName, fc, appCache) - } - - cacheSync := NewCacheSync(log, fc, appCache, "test-controller", "%%APP_NAME%%", "/%%APP_NAME%%/v1/events", "/%%APP_NAME%%/v2/events", "/%%APP_NAME%%/events") - err = cacheSync.Sync(context.Background(), applicationName) - require.NoError(t, err) - - tc.check(t, applicationName, appCache) - }) - } -} - -func TestCacheInit(t *testing.T) { - const name = "my-app" - type setup func(t *testing.T, applicationName string, fc *fakeClient, cache *cache.Cache) - type check func(t *testing.T, applicationName string, cache *cache.Cache) - - notFoundInCache := func(t *testing.T, applicationName string, appCache *cache.Cache) { - _, found := appCache.Get(applicationName) - require.False(t, found) - } - - tests := []struct { - name string - setup setup - check check - }{ - { - name: "Application will not be added to cache", - check: notFoundInCache, - }, - { - name: "Add application to cache without compass metadata and generate endpoints", - setup: func(t *testing.T, applicationName string, fc *fakeClient, appCache *cache.Cache) { - require.NoError(t, fc.Create(&v1alpha1.Application{ - ObjectMeta: v1.ObjectMeta{ - Name: applicationName, - }, - })) - }, - check: func(t *testing.T, applicationName string, appCache *cache.Cache) { - v, found := appCache.Get(applicationName) - require.True(t, found) - require.Equal(t, appDataNoClients, v) - }, - }, - { - name: "Add new application to cache with authentication clients and generate endpoints", - setup: func(t *testing.T, applicationName string, fc *fakeClient, appCache *cache.Cache) { - require.NoError(t, fc.Create(&v1alpha1.Application{ - ObjectMeta: v1.ObjectMeta{ - Name: applicationName, - }, - Spec: v1alpha1.ApplicationSpec{ - CompassMetadata: &v1alpha1.CompassMetadata{ - Authentication: v1alpha1.Authentication{ - ClientIds: []string{"client-1", "client-2"}, - }, - }, - }, - })) - }, - check: func(t *testing.T, applicationName string, appCache *cache.Cache) { - v, found := appCache.Get(applicationName) - require.True(t, found) - require.Equal(t, appData2Clients, v) - }, - }, - } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - applicationName := name - - log, err := logger.New(logger.TEXT, logger.DEBUG) - require.NoError(t, err) - appCache := cache.New(60*time.Second, 60*time.Second) - fc := NewFakeClient() - - if tc.setup != nil { - tc.setup(t, applicationName, fc, appCache) - } - - cacheSync := NewCacheSync(log, fc, appCache, "test-controller", "%%APP_NAME%%", "/%%APP_NAME%%/v1/events", "/%%APP_NAME%%/v2/events", "/%%APP_NAME%%/events") - cacheSync.Init(context.Background()) - - tc.check(t, applicationName, appCache) - }) - } -} - -type fakeClient struct { - client.Reader - intf applicationconnectorv1alpha1.ApplicationInterface -} - -func NewFakeClient() *fakeClient { - return &fakeClient{ - intf: fake.NewSimpleClientset(&v1alpha1.Application{}).ApplicationconnectorV1alpha1().Applications(), - } -} - -func (c fakeClient) Get(ctx context.Context, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { - target := obj.(*v1alpha1.Application) - app, err := c.intf.Get(ctx, key.Name, v1.GetOptions{}) - if err != nil { - return err - } - *target = *app - return nil -} - -func (c fakeClient) List(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error { - target := list.(*v1alpha1.ApplicationList) - appList, err := c.intf.List(ctx, v1.ListOptions{}) - if err != nil { - return err - } - *target = *appList - return nil -} - -func (c fakeClient) Create(application *v1alpha1.Application) error { - _, err := c.intf.Create(context.Background(), application, v1.CreateOptions{}) - return err -} diff --git a/components/central-application-connectivity-validator/internal/controller/cachesynccontroller.go b/components/central-application-connectivity-validator/internal/controller/cachesynccontroller.go deleted file mode 100644 index 0ea01f09d7c4..000000000000 --- a/components/central-application-connectivity-validator/internal/controller/cachesynccontroller.go +++ /dev/null @@ -1,47 +0,0 @@ -package controller - -import ( - "context" - - "github.com/kyma-project/kyma/common/logging/logger" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" - gocache "github.com/patrickmn/go-cache" - ctrl "sigs.k8s.io/controller-runtime" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/reconcile" -) - -type Controller interface { - Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) - SetupWithManager(mgr ctrl.Manager) error -} - -type controller struct { - cacheSync CacheSync -} - -func NewController( - log *logger.Logger, - client client.Client, - appCache *gocache.Cache, - appNamePlaceholder, - eventingPathPrefixV1, - eventingPathPrefixV2, - eventingPathPrefixEvents string) Controller { - return &controller{ - cacheSync: NewCacheSync(log, client, appCache, "cache_sync_controller", appNamePlaceholder, eventingPathPrefixV1, eventingPathPrefixV2, eventingPathPrefixEvents), - } -} - -func (c *controller) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) { - return ctrl.Result{}, c.cacheSync.Sync(ctx, request.Name) -} - -func (c *controller) SetupWithManager(mgr ctrl.Manager) error { - - c.cacheSync.Init(context.Background()) - - return ctrl.NewControllerManagedBy(mgr). - For(&v1alpha1.Application{}). - Complete(c) -} diff --git a/components/central-application-connectivity-validator/internal/controller/controller_suite_test.go b/components/central-application-connectivity-validator/internal/controller/controller_suite_test.go deleted file mode 100644 index ff9b1c1a965c..000000000000 --- a/components/central-application-connectivity-validator/internal/controller/controller_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package controller_test - -import ( - "testing" - - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" -) - -func TestController(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Controller Suite") -} diff --git a/components/central-application-connectivity-validator/internal/controller/suite_test.go b/components/central-application-connectivity-validator/internal/controller/suite_test.go deleted file mode 100644 index 23f78afea59a..000000000000 --- a/components/central-application-connectivity-validator/internal/controller/suite_test.go +++ /dev/null @@ -1,161 +0,0 @@ -package controller_test - -import ( - "fmt" - "time" - - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" - - "context" - "io" - "net" - "net/http" - "path/filepath" - "strings" - - "github.com/kyma-project/kyma/common/logging/logger" - "github.com/kyma-project/kyma/common/logging/tracing" - "github.com/kyma-project/kyma/components/central-application-connectivity-validator/internal/controller" - "github.com/kyma-project/kyma/components/central-application-connectivity-validator/internal/validationproxy" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" - "github.com/patrickmn/go-cache" - "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/rest" - "k8s.io/utils/pointer" - ctrl "sigs.k8s.io/controller-runtime" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/envtest" - logf "sigs.k8s.io/controller-runtime/pkg/log" - "sigs.k8s.io/controller-runtime/pkg/log/zap" -) - -var ( - testEnv *envtest.Environment - config *rest.Config - k8sClient client.Client - suiteCtx context.Context - cancelSuiteCtx context.CancelFunc - - idCache *cache.Cache - appNamePlaceholder = "%%APP_NAME%%" - eventingPathPrefixV1 = "/%%APP_NAME%%/v1/events" - eventingPathPrefixV2 = "/%%APP_NAME%%/v2/events" - eventingPathPrefix = "/%%APP_NAME%%/events" - eventingPublisherHost = "eventing-event-publisher-proxy.kyma-system" - eventingDestinationPath = "/publish" - testProxyServerPort = "8078" -) - -type testTransport struct { -} - -func (t testTransport) RoundTrip(req *http.Request) (*http.Response, error) { - responseBody := "eventing-event-publisher-proxy.kyma-system: [OK]" - respReader := io.NopCloser(strings.NewReader(responseBody)) - resp := http.Response{ - StatusCode: http.StatusOK, - Body: respReader, - ContentLength: int64(len(responseBody)), - Header: map[string][]string{ - "Content-Type": {"text/plain"}, - }, - } - return &resp, nil -} - -var _ = BeforeSuite(func() { - logf.SetLogger(zap.New(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true))) - - suiteCtx, cancelSuiteCtx = context.WithCancel(context.Background()) - - By("bootstrapping test environment") - testEnv = &envtest.Environment{ - CRDDirectoryPaths: []string{filepath.Join("..", "..", "hack")}, - ErrorIfCRDPathMissing: true, - } - - var err error - // config is defined in this file globally. - config, err = testEnv.Start() - Expect(err).NotTo(HaveOccurred()) - Expect(config).NotTo(BeNil()) - - err = v1alpha1.AddToScheme(scheme.Scheme) - Expect(err).To(BeNil()) - - k8sClient, err = client.New(config, client.Options{Scheme: scheme.Scheme}) - Expect(err).NotTo(HaveOccurred()) - Expect(k8sClient).NotTo(BeNil()) - - k8sManager, err := ctrl.NewManager(config, ctrl.Options{ - Scheme: scheme.Scheme, - SyncPeriod: pointer.Duration(time.Second * 2), - }) - Expect(err).ToNot(HaveOccurred()) - - idCache = cache.New( - cache.NoExpiration, - cache.NoExpiration, - ) - - log, err := logger.New(logger.TEXT, logger.DEBUG) - Expect(err).Should(BeNil()) - - controller := controller.NewController( - log, - k8sClient, - idCache, - appNamePlaceholder, - eventingPathPrefixV1, - eventingPathPrefixV2, - eventingPathPrefix, - ) - err = controller.SetupWithManager(k8sManager) - Expect(err).To(BeNil()) - - ceProxyTransport := &testTransport{} - - proxyHandler := validationproxy.NewProxyHandler( - eventingPublisherHost, - eventingDestinationPath, - idCache, - log, - validationproxy.WithCEProxyTransport(ceProxyTransport)) - - tracingMiddleware := tracing.NewTracingMiddleware(proxyHandler.ProxyAppConnectorRequests) - - go func() { - defer GinkgoRecover() - - srv := http.Server{ - Handler: validationproxy.NewHandler(tracingMiddleware), - Addr: fmt.Sprintf(":%s", testProxyServerPort), - } - - defer func() { - if err := srv.Shutdown(suiteCtx); err != nil { - logf.Log.Error(err, "while shutting down http server") - } - }() - - ln, err := net.Listen("tcp", srv.Addr) - Expect(err).Should(BeNil()) - - err = srv.Serve(ln) - Expect(err).Should(BeNil()) - }() - - go func() { - err = k8sManager.Start(suiteCtx) - Expect(err).ToNot(HaveOccurred(), "failed to run manager") - }() -}) - -var _ = AfterSuite(func() { - By("tearing down the test environment") - cancelSuiteCtx() - - err := testEnv.Stop() - Expect(err).NotTo(HaveOccurred()) -}) diff --git a/components/central-application-connectivity-validator/internal/externalapi/externalapi.go b/components/central-application-connectivity-validator/internal/externalapi/externalapi.go deleted file mode 100644 index c5679880cdc0..000000000000 --- a/components/central-application-connectivity-validator/internal/externalapi/externalapi.go +++ /dev/null @@ -1,16 +0,0 @@ -package externalapi - -import ( - "net/http" - - "github.com/gorilla/mux" -) - -func NewHandler() http.Handler { - - router := mux.NewRouter() - - router.Path("/v1/health").Handler(NewHealthCheckHandler()) - - return router -} diff --git a/components/central-application-connectivity-validator/internal/externalapi/healthcheckhandler.go b/components/central-application-connectivity-validator/internal/externalapi/healthcheckhandler.go deleted file mode 100644 index 3a7ea2cc324f..000000000000 --- a/components/central-application-connectivity-validator/internal/externalapi/healthcheckhandler.go +++ /dev/null @@ -1,12 +0,0 @@ -package externalapi - -import ( - "net/http" -) - -// NewHealthCheckHandler creates handler for performing health check -func NewHealthCheckHandler() http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusOK) - }) -} diff --git a/components/central-application-connectivity-validator/internal/externalapi/healthcheckhandler_test.go b/components/central-application-connectivity-validator/internal/externalapi/healthcheckhandler_test.go deleted file mode 100644 index 80d250f72350..000000000000 --- a/components/central-application-connectivity-validator/internal/externalapi/healthcheckhandler_test.go +++ /dev/null @@ -1,27 +0,0 @@ -package externalapi - -import ( - "net/http" - "net/http/httptest" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestHealthCheckHandler_HandleRequest(t *testing.T) { - t.Run("should always respond with 200 status code", func(t *testing.T) { - // given - req, err := http.NewRequest(http.MethodGet, "/v1/health", nil) - require.NoError(t, err) - rr := httptest.NewRecorder() - - handler := NewHealthCheckHandler() - - // when - handler.ServeHTTP(rr, req) - - // then - assert.Equal(t, http.StatusOK, rr.Code) - }) -} diff --git a/components/central-application-connectivity-validator/internal/httpconsts/httpconsts.go b/components/central-application-connectivity-validator/internal/httpconsts/httpconsts.go deleted file mode 100755 index 0536bf1968ef..000000000000 --- a/components/central-application-connectivity-validator/internal/httpconsts/httpconsts.go +++ /dev/null @@ -1,9 +0,0 @@ -package httpconsts - -const ( - HeaderContentType = "Content-Type" -) - -const ( - ContentTypeApplicationJson = "application/json;charset=UTF-8" -) diff --git a/components/central-application-connectivity-validator/internal/httperrors/httperrors.go b/components/central-application-connectivity-validator/internal/httperrors/httperrors.go deleted file mode 100755 index 2c37893398cb..000000000000 --- a/components/central-application-connectivity-validator/internal/httperrors/httperrors.go +++ /dev/null @@ -1,36 +0,0 @@ -package httperrors - -import ( - "net/http" - - "github.com/kyma-project/kyma/components/central-application-connectivity-validator/internal/apperrors" -) - -type ErrorResponse struct { - Code int `json:"code"` - Error string `json:"error"` -} - -func errorCodeToHttpStatus(code int) int { - switch code { - case apperrors.CodeInternal: - return http.StatusInternalServerError - case apperrors.CodeNotFound: - return http.StatusNotFound - case apperrors.CodeAlreadyExists: - return http.StatusConflict - case apperrors.CodeWrongInput: - return http.StatusBadRequest - case apperrors.CodeForbidden: - return http.StatusForbidden - case apperrors.CodeBadRequest: - return http.StatusBadRequest - default: - return http.StatusInternalServerError - } -} - -func AppErrorToResponse(appError apperrors.AppError) (status int, body ErrorResponse) { - httpCode := errorCodeToHttpStatus(appError.Code()) - return httpCode, ErrorResponse{httpCode, appError.Error()} -} diff --git a/components/central-application-connectivity-validator/internal/httptools/response.go b/components/central-application-connectivity-validator/internal/httptools/response.go deleted file mode 100644 index 9f1342c371a2..000000000000 --- a/components/central-application-connectivity-validator/internal/httptools/response.go +++ /dev/null @@ -1,32 +0,0 @@ -package httptools - -import ( - "encoding/json" - "net/http" - - "go.uber.org/zap" - - "github.com/kyma-project/kyma/components/central-application-connectivity-validator/internal/httpconsts" - "github.com/kyma-project/kyma/components/central-application-connectivity-validator/internal/httperrors" - - "github.com/kyma-project/kyma/components/central-application-connectivity-validator/internal/apperrors" -) - -func RespondWithError(log *zap.SugaredLogger, w http.ResponseWriter, apperr apperrors.AppError) { - log.Errorf("Error: %s", apperr.Error()) - - statusCode, responseBody := httperrors.AppErrorToResponse(apperr) - - Respond(w, statusCode) - json.NewEncoder(w).Encode(responseBody) -} - -func Respond(w http.ResponseWriter, statusCode int) { - w.Header().Set(httpconsts.HeaderContentType, httpconsts.ContentTypeApplicationJson) - w.WriteHeader(statusCode) -} - -func RespondWithBody(w http.ResponseWriter, statusCode int, responseBody interface{}) { - Respond(w, statusCode) - json.NewEncoder(w).Encode(responseBody) -} diff --git a/components/central-application-connectivity-validator/internal/validationproxy/handler.go b/components/central-application-connectivity-validator/internal/validationproxy/handler.go deleted file mode 100644 index 928abfd1fed5..000000000000 --- a/components/central-application-connectivity-validator/internal/validationproxy/handler.go +++ /dev/null @@ -1,307 +0,0 @@ -package validationproxy - -import ( - "crypto/x509/pkix" - "github.com/gorilla/mux" - "github.com/kyma-project/kyma/components/central-application-connectivity-validator/internal/controller" - "github.com/kyma-project/kyma/components/central-application-connectivity-validator/internal/httptools" - "net" - "net/http" - "net/http/httputil" - "regexp" - "strconv" - "strings" - "time" - - "github.com/kyma-project/kyma/common/logging/logger" - "github.com/kyma-project/kyma/components/central-application-connectivity-validator/internal/apperrors" -) - -const ( - CertificateInfoHeader = "X-Forwarded-Client-Cert" - - handlerName = "validation_proxy_handler" -) - -type ProxyHandler interface { - ProxyAppConnectorRequests(w http.ResponseWriter, r *http.Request) -} - -type Cache interface { - Get(k string) (interface{}, bool) - Set(k string, x interface{}, d time.Duration) -} - -type proxyHandler struct { - eventingPublisherHost string - - legacyEventsProxy *httputil.ReverseProxy - cloudEventsProxy *httputil.ReverseProxy - - log *logger.Logger - subjectRegex *regexp.Regexp - - cache Cache -} - -type option func(*proxyHandler) - -func WithCEProxyTransport(t http.RoundTripper) func(*proxyHandler) { - return func(p *proxyHandler) { - p.cloudEventsProxy.Transport = t - } -} - -func NewProxyHandler( - eventingPublisherHost string, - eventingDestinationPath string, - cache Cache, - log *logger.Logger, - ops ...option) ProxyHandler { - - out := proxyHandler{ - eventingPublisherHost: eventingPublisherHost, - - legacyEventsProxy: createReverseProxy(log, eventingPublisherHost, withEmptyRequestHost, withEmptyXFwdClientCert, withHTTPScheme), - cloudEventsProxy: createReverseProxy(log, eventingPublisherHost, withRewriteBaseURL(eventingDestinationPath), withEmptyRequestHost, withEmptyXFwdClientCert, withHTTPScheme), - - cache: cache, - log: log, - subjectRegex: regexp.MustCompile(`Subject="(.*?)"`), - } - - for _, f := range ops { - f(&out) - } - - return &out -} - -func (ph *proxyHandler) ProxyAppConnectorRequests(w http.ResponseWriter, r *http.Request) { - certInfoData := r.Header.Get(CertificateInfoHeader) - if certInfoData == "" { - httptools.RespondWithError(ph.log.WithTracing(r.Context()).With("handler", handlerName), w, apperrors.Internal("%s header not found", CertificateInfoHeader)) - return - } - - applicationName := mux.Vars(r)["application"] - if applicationName == "" { - httptools.RespondWithError(ph.log.WithTracing(r.Context()).With("handler", handlerName), w, apperrors.BadRequest("application name not specified")) - return - } - - ph.log.WithTracing(r.Context()).With("handler", handlerName).With("application", applicationName).With("proxyPath", r.URL.Path).Infof("Proxying request for application...") - - applicationClientIDs, err := ph.getCompassMetadataClientIDs(applicationName) - if err != nil { - httptools.RespondWithError(ph.log.WithTracing(r.Context()).With("handler", handlerName).With("applicationName", applicationName), w, apperrors.NotFound("while getting application ClientIds: %s", err)) - return - } - - subjects := ph.extractSubjects(certInfoData) - - if !hasValidSubject(subjects, applicationClientIDs, applicationName) { - httptools.RespondWithError(ph.log.WithTracing(r.Context()).With("handler", handlerName).With("applicationName", applicationName), w, apperrors.Forbidden("no valid subject found")) - return - } - - reverseProxy, err := ph.mapRequestToProxy(r.URL.Path, applicationName) - if err != nil { - httptools.RespondWithError(ph.log.WithTracing(r.Context()).With("handler", handlerName).With("applicationName", applicationName), w, err) - return - } - - reverseProxy.ServeHTTP(w, r) -} - -func (ph *proxyHandler) getCompassMetadataClientIDs(applicationName string) ([]string, apperrors.AppError) { - applicationClientIDs, found := ph.getClientIDsFromCache(applicationName) - if !found { - err := apperrors.NotFound("application data for name %s is not found in the cache. Please retry", applicationName) - return nil, err - } - return applicationClientIDs, nil -} - -func (ph *proxyHandler) getClientIDsFromCache(applicationName string) ([]string, bool) { - appData, found := ph.cache.Get(applicationName) - if !found { - return []string{}, found - } - - appInfo := appData.(controller.CachedAppData) - - return appInfo.ClientIDs, found -} - -func (ph *proxyHandler) mapRequestToProxy(path string, applicationName string) (*httputil.ReverseProxy, apperrors.AppError) { - - appData, found := ph.cache.Get(applicationName) - - if !found { - return nil, apperrors.NotFound("application data for name %s is not found in the cache. Please retry", applicationName) - } - - appInfo := appData.(controller.CachedAppData) - - switch { - - // legacy-events reaching /{application}/v1/events are routed to /{application}/v1/events endpoint of event-publisher-proxy - case strings.HasPrefix(path, appInfo.AppPathPrefixV1): - return ph.legacyEventsProxy, nil - - // cloud-events reaching /{application}/v2/events or /{application}/events are routed to /publish endpoint of event-publisher-proxy - case strings.HasPrefix(path, appInfo.AppPathPrefixV2): - return ph.cloudEventsProxy, nil - - // cloud-events reaching /{application}/events are routed to /publish endpoint of event-publisher-proxy - case strings.HasPrefix(path, appInfo.AppPathPrefixEvents): - return ph.cloudEventsProxy, nil - } - - return nil, apperrors.NotFound("could not determine destination host, requested resource not found") -} - -func hasValidSubject(subjects, applicationClientIDs []string, appName string) bool { - subjectValidator := newSubjectValidator(applicationClientIDs, appName) - - for _, s := range subjects { - parsedSubject := parseSubject(s) - - if subjectValidator(parsedSubject) { - return true - } - } - - return false -} - -func newSubjectValidator(applicationClientIDs []string, appName string) func(subject pkix.Name) bool { - validateCommonNameWithAppName := func(subject pkix.Name) bool { - return appName == subject.CommonName - } - validateCommonNameWithClientIDs := func(subject pkix.Name) bool { - for _, id := range applicationClientIDs { - if subject.CommonName == id { - return true - } - } - return false - } - if len(applicationClientIDs) == 0 { - return validateCommonNameWithAppName - } else { - return validateCommonNameWithClientIDs - } -} - -func (ph *proxyHandler) extractSubjects(certInfoData string) []string { - var subjects []string - - subjectMatches := ph.subjectRegex.FindAllStringSubmatch(certInfoData, -1) - - for _, subjectMatch := range subjectMatches { - subject := get(subjectMatch, 1) - - if subject != "" { - subjects = append(subjects, subject) - } - } - - return subjects -} - -func get(array []string, index int) string { - if len(array) > index { - return array[index] - } - - return "" -} - -func parseSubject(rawSubject string) pkix.Name { - subjectInfo := extractSubject(rawSubject) - - return pkix.Name{ - CommonName: subjectInfo["CN"], - Country: []string{subjectInfo["C"]}, - Organization: []string{subjectInfo["O"]}, - OrganizationalUnit: []string{subjectInfo["OU"]}, - Locality: []string{subjectInfo["L"]}, - Province: []string{subjectInfo["ST"]}, - } -} - -func extractSubject(subject string) map[string]string { - result := map[string]string{} - - segments := strings.Split(subject, ",") - - for _, segment := range segments { - parts := strings.Split(segment, "=") - result[parts[0]] = parts[1] - } - - return result -} - -func createReverseProxy(log *logger.Logger, destinationHost string, reqOpts ...requestOption) *httputil.ReverseProxy { - - return &httputil.ReverseProxy{ - Director: func(request *http.Request) { - request.URL.Host = destinationHost - for _, opt := range reqOpts { - opt(request) - } - - log.WithTracing(request.Context()).With("handler", handlerName).With("targetURL", request.URL).Infof("Proxying request to target URL...") - }, - ModifyResponse: func(res *http.Response) error { - log.WithContext().With("handler", handlerName).Infof("Host responded with status %s", res.Status) - if res.StatusCode >= 500 && res.StatusCode < 600 { - res.Header.Set("Target-System-Status", strconv.Itoa(res.StatusCode)) - res.StatusCode = http.StatusBadGateway - } - return nil - }, - Transport: &http.Transport{ - DialContext: (&net.Dialer{ - Timeout: 30 * time.Second, - KeepAlive: 30 * time.Second, - }).DialContext, - MaxIdleConns: 400, - DisableKeepAlives: false, - MaxIdleConnsPerHost: 200, - MaxConnsPerHost: 200, - ForceAttemptHTTP2: false, - IdleConnTimeout: 10 * time.Second, - TLSHandshakeTimeout: 10 * time.Second, - ExpectContinueTimeout: 1 * time.Second, - }, - } -} - -type requestOption func(req *http.Request) - -// withRewriteBaseURL rewrites the Request's Path. -func withRewriteBaseURL(path string) requestOption { - return func(req *http.Request) { - req.URL.Path = path - } -} - -// withEmptyRequestHost clears the Request's Host field to ensure -// the 'Host' HTTP header is set to the host name defined in the Request's URL. -func withEmptyRequestHost(req *http.Request) { - req.Host = "" -} - -// withHTTPScheme sets the URL scheme to HTTP -func withHTTPScheme(req *http.Request) { - req.URL.Scheme = "http" -} - -// withEmptyXFwdClientCert clears the value of X-Forwarded-Client-Cert header -func withEmptyXFwdClientCert(req *http.Request) { - req.Header.Del("X-Forwarded-Client-Cert") -} diff --git a/components/central-application-connectivity-validator/internal/validationproxy/handler_test.go b/components/central-application-connectivity-validator/internal/validationproxy/handler_test.go deleted file mode 100644 index 80bc60b29603..000000000000 --- a/components/central-application-connectivity-validator/internal/validationproxy/handler_test.go +++ /dev/null @@ -1,601 +0,0 @@ -package validationproxy - -import ( - "bytes" - "encoding/json" - "fmt" - "github.com/kyma-project/kyma/components/central-application-connectivity-validator/internal/controller" - "net/http" - "net/http/httptest" - "strings" - "testing" - "time" - - "github.com/kyma-project/kyma/common/logging/logger" - - "github.com/gorilla/mux" - "github.com/patrickmn/go-cache" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - appconnv1alpha1 "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" -) - -const ( - applicationName = "test-application" - applicationMetaName = "test-application-meta" - applicationID = "test-application-id" - - eventingPathPrefixEvents = "/%%APP_NAME%%/events" - eventingDestinationPathPublish = "/publish" -) - -type event struct { - Title string `json:"title"` -} - -type testCase struct { - caseDescription string - tenant string - group string - certInfoHeader string - expectedStatus int - application *appconnv1alpha1.Application -} - -var ( - applicationManagedByCompass = &appconnv1alpha1.Application{ - TypeMeta: metav1.TypeMeta{ - Kind: "Application", - APIVersion: "applicationconnector.kyma-project.io/v1alpha1", - }, - ObjectMeta: metav1.ObjectMeta{ - Name: applicationMetaName, - }, - Spec: appconnv1alpha1.ApplicationSpec{ - Description: "Description", - Services: []appconnv1alpha1.Service{}, - CompassMetadata: &appconnv1alpha1.CompassMetadata{Authentication: appconnv1alpha1.Authentication{ClientIds: []string{applicationID}}}, - }, - } - applicationNotManagedByCompass = &appconnv1alpha1.Application{ - TypeMeta: metav1.TypeMeta{ - Kind: "Application", - APIVersion: "applicationconnector.kyma-project.io/v1alpha1", - }, - ObjectMeta: metav1.ObjectMeta{ - Name: applicationName, - }, - Spec: appconnv1alpha1.ApplicationSpec{ - Description: "Description", - Services: []appconnv1alpha1.Service{}, - }, - } -) - -func TestProxyHandler_ProxyAppConnectorRequests(t *testing.T) { - - log, err := logger.New(logger.TEXT, logger.ERROR) - require.NoError(t, err) - positiveCases := []testCase{ - { - caseDescription: "Application without group and tenant", - certInfoHeader: `Hash=f4cf22fb633d4df500e371daf703d4b4d14a0ea9d69cd631f95f9e6ba840f8ad;Subject="CN=test-application-id,OU=OrgUnit,O=Organization,L=Waldorf,ST=Waldorf,C=DE";` + - `URI=,By=spiffe://cluster.local/ns/kyma-system/sa/default;` + - `Hash=6d1f9f3a6ac94ff925841aeb9c15bb3323014e3da2c224ea7697698acf413226;Subject="";` + - `URI=spiffe://cluster.local/ns/istio-system/sa/istio-ingressgateway-service-account`, - expectedStatus: http.StatusOK, - application: applicationManagedByCompass, - }, - { - caseDescription: "Application with group and tenant", - certInfoHeader: `Hash=f4cf22fb633d4df500e371daf703d4b4d14a0ea9d69cd631f95f9e6ba840f8ad;Subject="CN=test-application-id,OU=group,O=tenant,L=Waldorf,ST=Waldorf,C=DE";` + - `URI=,By=spiffe://cluster.local/ns/kyma-system/sa/default;` + - `Hash=6d1f9f3a6ac94ff925841aeb9c15bb3323014e3da2c224ea7697698acf413226;Subject="";` + - `URI=spiffe://cluster.local/ns/istio-system/sa/istio-ingressgateway-service-account`, - expectedStatus: http.StatusOK, - application: applicationManagedByCompass, - }, - { - caseDescription: "Application not managed by Compass Runtime Agent without group and tenant", - certInfoHeader: `Hash=f4cf22fb633d4df500e371daf703d4b4d14a0ea9d69cd631f95f9e6ba840f8ad;Subject="CN=test-application,OU=OrgUnit,O=Organization,L=Waldorf,ST=Waldorf,C=DE";` + - `URI=,By=spiffe://cluster.local/ns/kyma-system/sa/default;` + - `Hash=6d1f9f3a6ac94ff925841aeb9c15bb3323014e3da2c224ea7697698acf413226;Subject="";` + - `URI=spiffe://cluster.local/ns/istio-system/sa/istio-ingressgateway-service-account`, - expectedStatus: http.StatusOK, - application: applicationNotManagedByCompass, - }, - { - caseDescription: "Application not managed by Compass Runtime Agent with group and tenant", - certInfoHeader: `Hash=f4cf22fb633d4df500e371daf703d4b4d14a0ea9d69cd631f95f9e6ba840f8ad;Subject="CN=test-application,OU=group,O=tenant,L=Waldorf,ST=Waldorf,C=DE";` + - `URI=,By=spiffe://cluster.local/ns/kyma-system/sa/default;` + - `Hash=6d1f9f3a6ac94ff925841aeb9c15bb3323014e3da2c224ea7697698acf413226;Subject="";` + - `URI=spiffe://cluster.local/ns/istio-system/sa/istio-ingressgateway-service-account`, - expectedStatus: http.StatusOK, - application: applicationNotManagedByCompass, - }, - } - negativeCases := []testCase{ - { - caseDescription: "Application without group and tenant and with invalid Common Name", - certInfoHeader: `Hash=f4cf22fb633d4df500e371daf703d4b4d14a0ea9d69cd631f95f9e6ba840f8ad;Subject="CN=invalid-cn,OU=OrgUnit,O=Organization,L=Waldorf,ST=Waldorf,C=DE";` + - `URI=,By=spiffe://cluster.local/ns/kyma-system/sa/default;` + - `Hash=6d1f9f3a6ac94ff925841aeb9c15bb3323014e3da2c224ea7697698acf413226;Subject="";` + - `URI=spiffe://cluster.local/ns/istio-system/sa/istio-ingressgateway-service-account`, - expectedStatus: http.StatusForbidden, - application: applicationManagedByCompass, - }, - { - caseDescription: "Application with group, tenant and invalid Common Name", - certInfoHeader: `Hash=f4cf22fb633d4df500e371daf703d4b4d14a0ea9d69cd631f95f9e6ba840f8ad;Subject="CN=invalid-application,OU=group,O=tenant,L=Waldorf,ST=Waldorf,C=DE";` + - `URI=,By=spiffe://cluster.local/ns/kyma-system/sa/default;` + - `Hash=6d1f9f3a6ac94ff925841aeb9c15bb3323014e3da2c224ea7697698acf413226;Subject="";` + - `URI=spiffe://cluster.local/ns/istio-system/sa/istio-ingressgateway-service-account`, - expectedStatus: http.StatusForbidden, - application: applicationManagedByCompass, - }, - { - caseDescription: "X-Forwarded-Client-Cert header not specified", - expectedStatus: http.StatusInternalServerError, - application: applicationManagedByCompass, - }, - { - caseDescription: "Application not managed by Compass Runtime Agent without group and tenant and with invalid Common Name", - certInfoHeader: `Hash=f4cf22fb633d4df500e371daf703d4b4d14a0ea9d69cd631f95f9e6ba840f8ad;Subject="CN=invalid-cn,OU=OrgUnit,O=Organization,L=Waldorf,ST=Waldorf,C=DE";` + - `URI=,By=spiffe://cluster.local/ns/kyma-system/sa/default;` + - `Hash=6d1f9f3a6ac94ff925841aeb9c15bb3323014e3da2c224ea7697698acf413226;Subject="";` + - `URI=spiffe://cluster.local/ns/istio-system/sa/istio-ingressgateway-service-account`, - expectedStatus: http.StatusForbidden, - application: applicationNotManagedByCompass, - }, - { - caseDescription: "Application not managed by Compass Runtime Agent with group, tenant and invalid Common Name", - certInfoHeader: `Hash=f4cf22fb633d4df500e371daf703d4b4d14a0ea9d69cd631f95f9e6ba840f8ad;Subject="CN=invalid-application,OU=group,O=tenant,L=Waldorf,ST=Waldorf,C=DE";` + - `URI=,By=spiffe://cluster.local/ns/kyma-system/sa/default;` + - `Hash=6d1f9f3a6ac94ff925841aeb9c15bb3323014e3da2c224ea7697698acf413226;Subject="";` + - `URI=spiffe://cluster.local/ns/istio-system/sa/istio-ingressgateway-service-account`, - expectedStatus: http.StatusForbidden, - application: applicationNotManagedByCompass, - }, - } - testCases := append(positiveCases, negativeCases...) - - t.Run("should proxy requests", func(t *testing.T) { - const mockIncomingRequestHost = "fake.istio.gateway" - const eventTitle = "my-event" - eventPublisherProxyHandler := mux.NewRouter() - eventPublisherProxyServer := httptest.NewServer(eventPublisherProxyHandler) - eventPublisherProxyHost := strings.TrimPrefix(eventPublisherProxyServer.URL, "http://") - - // publish handler which are overwritten in the tests - var publishHandler http.HandlerFunc - eventPublisherProxyHandler.Path(eventingPathPrefixEvents).HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { - publishHandler.ServeHTTP(writer, request) - }) - - eventPublisherProxyHandler.PathPrefix(eventingDestinationPathPublish).HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - var receivedEvent event - - err := json.NewDecoder(r.Body).Decode(&receivedEvent) - require.NoError(t, err) - assert.Equal(t, eventTitle, receivedEvent.Title) - - assert.NotEqual(t, mockIncomingRequestHost, r.Host, "proxy should rewrite Host field") - - w.WriteHeader(http.StatusOK) - }) - - for _, testCase := range testCases { - // given - appData := controller.CachedAppData{ - AppPathPrefixV1: fmt.Sprintf("/%s/v1/events", testCase.application.Name), - AppPathPrefixV2: fmt.Sprintf("/%s/v2/events", testCase.application.Name), - AppPathPrefixEvents: fmt.Sprintf("/%s/events", testCase.application.Name), - } - - idCache := cache.New(time.Minute, time.Minute) - if testCase.application.Spec.CompassMetadata != nil { - appData.ClientIDs = []string{applicationID} - } else { - appData.ClientIDs = []string{} - } - - idCache.Set(testCase.application.Name, appData, cache.NoExpiration) - - proxyHandler := NewProxyHandler( - eventPublisherProxyHost, - eventingDestinationPathPublish, - idCache, - log) - - t.Run("should proxy eventing V1 request when "+testCase.caseDescription, func(t *testing.T) { - eventTitle := "my-event-1" - - eventPublisherProxyHandler.PathPrefix("/{application}/v1/events").HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - appName := mux.Vars(r)["application"] - assert.Equal(t, testCase.application.Name, appName, `Error reading "application" route variable from request context`) - - var receivedEvent event - - err := json.NewDecoder(r.Body).Decode(&receivedEvent) - require.NoError(t, err) - assert.Equal(t, eventTitle, receivedEvent.Title) - - w.WriteHeader(http.StatusOK) - }) - - body, err := json.Marshal(event{Title: eventTitle}) - require.NoError(t, err) - - req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("/%s/v1/events", testCase.application.Name), bytes.NewReader(body)) - require.NoError(t, err) - req.Header.Set(CertificateInfoHeader, testCase.certInfoHeader) - req = mux.SetURLVars(req, map[string]string{"application": testCase.application.Name}) - - recorder := httptest.NewRecorder() - - // when - proxyHandler.ProxyAppConnectorRequests(recorder, req) - - // then - assert.Equal(t, testCase.expectedStatus, recorder.Code) - }) - - t.Run("should proxy eventing V2 request when "+testCase.caseDescription, func(t *testing.T) { - body, err := json.Marshal(event{Title: eventTitle}) - require.NoError(t, err) - - req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("/%s/v2/events", testCase.application.Name), bytes.NewReader(body)) - require.NoError(t, err) - req.Header.Set(CertificateInfoHeader, testCase.certInfoHeader) - req = mux.SetURLVars(req, map[string]string{"application": testCase.application.Name}) - - recorder := httptest.NewRecorder() - - // when - proxyHandler.ProxyAppConnectorRequests(recorder, req) - - // then - assert.Equal(t, testCase.expectedStatus, recorder.Code) - }) - - t.Run("should proxy eventing request when "+testCase.caseDescription, func(t *testing.T) { - - body, err := json.Marshal(event{Title: eventTitle}) - require.NoError(t, err) - - req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("/%s/events", testCase.application.Name), bytes.NewReader(body)) - require.NoError(t, err) - req.Header.Set(CertificateInfoHeader, testCase.certInfoHeader) - req = mux.SetURLVars(req, map[string]string{"application": testCase.application.Name}) - - // mock request Host to assert it gets rewritten by the proxy - req.Host = mockIncomingRequestHost - - recorder := httptest.NewRecorder() - - // when - proxyHandler.ProxyAppConnectorRequests(recorder, req) - - // then - assert.Equal(t, testCase.expectedStatus, recorder.Code) - }) - } - }) - - t.Run("should rewrite 5xx codes", func(t *testing.T) { - eventPublisherProxyHandler := mux.NewRouter() - eventPublisherProxyServer := httptest.NewServer(eventPublisherProxyHandler) - eventPublisherProxyHost := strings.TrimPrefix(eventPublisherProxyServer.URL, "http://") - - application := applicationNotManagedByCompass - - cert := `Hash=f4cf22fb633d4df500e371daf703d4b4d14a0ea9d69cd631f95f9e6ba840f8ad;Subject="CN=test-application,OU=OrgUnit,O=Organization,L=Waldorf,ST=Waldorf,C=DE";` + - `URI=,By=spiffe://cluster.local/ns/kyma-system/sa/default;` + - `Hash=6d1f9f3a6ac94ff925841aeb9c15bb3323014e3da2c224ea7697698acf413226;Subject="";` + - `URI=spiffe://cluster.local/ns/istio-system/sa/istio-ingressgateway-service-account` - - // publish handler which are overwritten in the tests - var publishHandler http.HandlerFunc - eventPublisherProxyHandler.Path(eventingPathPrefixEvents).HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { - publishHandler.ServeHTTP(writer, request) - }) - - eventPublisherProxyHandler.PathPrefix(eventingDestinationPathPublish).HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusInternalServerError) - }) - - // given - appData := controller.CachedAppData{ - AppPathPrefixV1: fmt.Sprintf("/%s/v1/events", application.Name), - } - - idCache := cache.New(time.Minute, time.Minute) - if application.Spec.CompassMetadata != nil { - appData.ClientIDs = []string{applicationID} - } else { - appData.ClientIDs = []string{} - } - - idCache.Set(application.Name, appData, cache.NoExpiration) - - proxyHandler := NewProxyHandler( - eventPublisherProxyHost, - eventingDestinationPathPublish, - idCache, - log) - - req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("/%s/v2/events", application.Name), nil) - require.NoError(t, err) - req.Header.Set(CertificateInfoHeader, cert) - req = mux.SetURLVars(req, map[string]string{"application": application.Name}) - - recorder := httptest.NewRecorder() - - // when - proxyHandler.ProxyAppConnectorRequests(recorder, req) - - // then - assert.Equal(t, http.StatusBadGateway, recorder.Code) - }) - - t.Run("should return 404 failed when cache doesn't contain the element", func(t *testing.T) { - eventPublisherProxyHandler := mux.NewRouter() - eventPublisherProxyServer := httptest.NewServer(eventPublisherProxyHandler) - eventingPublisherHost := strings.TrimPrefix(eventPublisherProxyServer.URL, "http://") - - for _, testCase := range positiveCases { - // given - idCache := cache.New(time.Minute, time.Minute) - - proxyHandler := NewProxyHandler( - eventingPublisherHost, - eventingDestinationPathPublish, - idCache, - log) - - req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("/%s/v1/metadata/services", testCase.application.Name), nil) - require.NoError(t, err) - req.Header.Set(CertificateInfoHeader, testCase.certInfoHeader) - req = mux.SetURLVars(req, map[string]string{"application": testCase.application.Name}) - recorder := httptest.NewRecorder() - - // when - proxyHandler.ProxyAppConnectorRequests(recorder, req) - - // then - assert.Equal(t, http.StatusNotFound, recorder.Code, fmt.Sprintf("%s case has failed", testCase.caseDescription)) - } - }) - - t.Run("should return 400 when application not specified in path", func(t *testing.T) { - eventPublisherProxyHandler := mux.NewRouter() - eventPublisherProxyServer := httptest.NewServer(eventPublisherProxyHandler) - eventingPublisherHost := strings.TrimPrefix(eventPublisherProxyServer.URL, "http://") - - // given - certInfoHeader := - `Hash=f4cf22fb633d4df500e371daf703d4b4d14a0ea9d69cd631f95f9e6ba840f8ad;Subject="CN=test-application,OU=OrgUnit,O=Organization,L=Waldorf,ST=Waldorf,C=DE";URI=` - - appData := controller.CachedAppData{ - ClientIDs: []string{}, - AppPathPrefixV1: fmt.Sprintf("/%s/v1/events", applicationName), - AppPathPrefixV2: fmt.Sprintf("/%s/v2/events", applicationName), - AppPathPrefixEvents: fmt.Sprintf("/%s/events", applicationName), - } - - idCache := cache.New(time.Minute, time.Minute) - idCache.Set(applicationName, appData, cache.NoExpiration) - - proxyHandler := NewProxyHandler( - eventingPublisherHost, - eventingDestinationPathPublish, - idCache, - log) - - req, err := http.NewRequest(http.MethodGet, "/path", nil) - require.NoError(t, err) - req.Header.Set(CertificateInfoHeader, certInfoHeader) - recorder := httptest.NewRecorder() - - // when - proxyHandler.ProxyAppConnectorRequests(recorder, req) - - // then - assert.Equal(t, http.StatusBadRequest, recorder.Code) - }) - - t.Run("should return 404 when path is invalid", func(t *testing.T) { - eventPublisherProxyHandler := mux.NewRouter() - eventPublisherProxyServer := httptest.NewServer(eventPublisherProxyHandler) - eventingPublisherHost := strings.TrimPrefix(eventPublisherProxyServer.URL, "http://") - - // given - certInfoHeader := - `Hash=f4cf22fb633d4df500e371daf703d4b4d14a0ea9d69cd631f95f9e6ba840f8ad;Subject="CN=test-application-id,OU=OrgUnit,O=Organization,L=Waldorf,ST=Waldorf,C=DE";` + - `URI=,By=spiffe://cluster.local/ns/kyma-system/sa/default;` + - `Hash=6d1f9f3a6ac94ff925841aeb9c15bb3323014e3da2c224ea7697698acf413226;Subject="";` + - `URI=spiffe://cluster.local/ns/istio-system/sa/istio-ingressgateway-service-account` - - // mock cache sync controller that it fills cache - idCache := cache.New(time.Minute, time.Minute) - - appData := controller.CachedAppData{ - ClientIDs: []string{applicationID}, - AppPathPrefixV1: fmt.Sprintf("/%s/v1/events", applicationName), - AppPathPrefixV2: fmt.Sprintf("/%s/v2/events", applicationName), - AppPathPrefixEvents: fmt.Sprintf("/%s/events", applicationName), - } - - idCache.Set(applicationName, appData, cache.NoExpiration) - - proxyHandler := NewProxyHandler( - eventingPublisherHost, - eventingDestinationPathPublish, - idCache, - log) - - req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("/%s/v1/bad/path", applicationMetaName), nil) - require.NoError(t, err) - req.Header.Set(CertificateInfoHeader, certInfoHeader) - req = mux.SetURLVars(req, map[string]string{"application": applicationMetaName}) - recorder := httptest.NewRecorder() - - // when - proxyHandler.ProxyAppConnectorRequests(recorder, req) - - // then - assert.Equal(t, http.StatusNotFound, recorder.Code) - }) - - t.Run("should proxy requests to Event Publisher Proxy(EPP) when BEB is enabled", func(t *testing.T) { - - eventPublisherProxyHandler := mux.NewRouter() - eventPublisherProxyServer := httptest.NewServer(eventPublisherProxyHandler) - eventingPublisherHost := strings.TrimPrefix(eventPublisherProxyServer.URL, "http://") - - for _, testCase := range testCases { - // given - idCache := cache.New(time.Minute, time.Minute) - - appData := controller.CachedAppData{ - AppPathPrefixV1: fmt.Sprintf("/%s/v1/events", testCase.application.Name), - AppPathPrefixV2: fmt.Sprintf("/%s/v2/events", testCase.application.Name), - AppPathPrefixEvents: fmt.Sprintf("/%s/events", testCase.application.Name), - } - - if testCase.application.Spec.CompassMetadata != nil { - appData.ClientIDs = []string{applicationID} - } else { - appData.ClientIDs = []string{} - } - idCache.Set(testCase.application.Name, appData, cache.NoExpiration) - - t.Run("should proxy requests in V1 to V1 endpoint of EPP when "+testCase.caseDescription, func(t *testing.T) { - - proxyHandlerBEB := NewProxyHandler( - eventingPublisherHost, - eventingDestinationPathPublish, - idCache, - log) - eventTitle := "my-event-1" - - eventPublisherProxyHandler.PathPrefix("/{application}/v1/events").HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - appName := mux.Vars(r)["application"] - assert.Equal(t, testCase.application.Name, appName, `Error reading "application" route variable from request context`) - - var receivedEvent event - - err := json.NewDecoder(r.Body).Decode(&receivedEvent) - require.NoError(t, err) - assert.Equal(t, eventTitle, receivedEvent.Title) - - w.WriteHeader(http.StatusOK) - }) - - body, err := json.Marshal(event{Title: eventTitle}) - require.NoError(t, err) - - req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("/%s/v1/events", testCase.application.Name), bytes.NewReader(body)) - require.NoError(t, err) - req.Header.Set(CertificateInfoHeader, testCase.certInfoHeader) - req = mux.SetURLVars(req, map[string]string{"application": testCase.application.Name}) - - recorder := httptest.NewRecorder() - - // when - proxyHandlerBEB.ProxyAppConnectorRequests(recorder, req) - - // then - assert.Equal(t, testCase.expectedStatus, recorder.Code) - }) - - t.Run("should proxy requests in V2 to /publish endpoint of EPP when "+testCase.caseDescription, func(t *testing.T) { - eventTitle := "my-event-2" - - eventPublisherProxyHandler := mux.NewRouter() - eventPublisherProxyServer := httptest.NewServer(eventPublisherProxyHandler) - eventPublisherProxyHost := strings.TrimPrefix(eventPublisherProxyServer.URL, "http://") - - proxyHandlerBEB := NewProxyHandler( - eventPublisherProxyHost, // For a BEB enabled cluster requests to /v2 and /events should be forwarded to Event Publisher Proxy - eventingDestinationPathPublish, - idCache, - log) - - eventPublisherProxyHandler.PathPrefix("/publish").HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - var receivedEvent event - - err := json.NewDecoder(r.Body).Decode(&receivedEvent) - require.NoError(t, err) - assert.Equal(t, eventTitle, receivedEvent.Title) - - w.WriteHeader(http.StatusOK) - }) - - body, err := json.Marshal(event{Title: eventTitle}) - require.NoError(t, err) - - req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("/%s/v2/events", testCase.application.Name), bytes.NewReader(body)) - require.NoError(t, err) - req.Header.Set(CertificateInfoHeader, testCase.certInfoHeader) - req = mux.SetURLVars(req, map[string]string{"application": testCase.application.Name}) - - recorder := httptest.NewRecorder() - - // when - proxyHandlerBEB.ProxyAppConnectorRequests(recorder, req) - - // then - assert.Equal(t, testCase.expectedStatus, recorder.Code) - }) - - t.Run("should proxy requests in /events to /publish endpoint of EPP when "+testCase.caseDescription, func(t *testing.T) { - const eventTitle = "my-event" - const mockIncomingRequestHost = "fake.istio.gateway" - - eventPublisherProxyHandler := mux.NewRouter() - eventPublisherProxyServer := httptest.NewServer(eventPublisherProxyHandler) - eventPublisherProxyHost := strings.TrimPrefix(eventPublisherProxyServer.URL, "http://") - proxyHandlerBEB := NewProxyHandler( - eventPublisherProxyHost, // For a BEB enabled cluster requests to /v2 and /events should be forwarded to Event Publisher Proxy - eventingDestinationPathPublish, - idCache, - log) - - eventPublisherProxyHandler.Path("/publish").HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - var receivedEvent event - - err := json.NewDecoder(r.Body).Decode(&receivedEvent) - require.NoError(t, err) - assert.Equal(t, eventTitle, receivedEvent.Title) - - assert.NotEqual(t, mockIncomingRequestHost, r.Host, "proxy should rewrite Host field") - - w.WriteHeader(http.StatusOK) - }) - - body, err := json.Marshal(event{Title: eventTitle}) - require.NoError(t, err) - - req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("/%s/events", testCase.application.Name), bytes.NewReader(body)) - require.NoError(t, err) - req.Header.Set(CertificateInfoHeader, testCase.certInfoHeader) - req = mux.SetURLVars(req, map[string]string{"application": testCase.application.Name}) - - // mock request Host to assert it gets rewritten by the proxy - req.Host = mockIncomingRequestHost - - recorder := httptest.NewRecorder() - - // when - proxyHandlerBEB.ProxyAppConnectorRequests(recorder, req) - - // then - assert.Equal(t, testCase.expectedStatus, recorder.Code) - }) - } - }) -} diff --git a/components/central-application-connectivity-validator/internal/validationproxy/proxy.go b/components/central-application-connectivity-validator/internal/validationproxy/proxy.go deleted file mode 100644 index 8cb3b75196cf..000000000000 --- a/components/central-application-connectivity-validator/internal/validationproxy/proxy.go +++ /dev/null @@ -1,16 +0,0 @@ -package validationproxy - -import ( - "net/http" - - "github.com/gorilla/mux" -) - -func NewHandler(proxyHandler http.Handler) http.Handler { - - router := mux.NewRouter() - - router.PathPrefix("/{application}/").HandlerFunc(proxyHandler.ServeHTTP) - - return router -} diff --git a/components/central-application-gateway/.gitignore b/components/central-application-gateway/.gitignore deleted file mode 100644 index e1903162da1a..000000000000 --- a/components/central-application-gateway/.gitignore +++ /dev/null @@ -1,31 +0,0 @@ -# Binaries for programs and plugins -*.exe -*.exe~ -*.dll -*.so -*.dylib -bin -/applicationgateway - -# Test binary, build with `go test -c` -*.test - -# Output of the go coverage tool, specifically when used with LiteIDE -*.out - -# Kubernetes Generated files - skip generated files, except for vendored files - -!vendor/**/zz_generated.* - -# editor and IDE paraphernalia -.idea -*.swp -*.swo -*~ - -# Licenses -licenses - -/skaffold.yaml -/app.yaml - diff --git a/components/central-application-gateway/Dockerfile b/components/central-application-gateway/Dockerfile deleted file mode 100644 index 8edce1912711..000000000000 --- a/components/central-application-gateway/Dockerfile +++ /dev/null @@ -1,31 +0,0 @@ -FROM golang:1.21.5-alpine3.18 as builder - -ARG DOCK_PKG_DIR=/go/src/github.com/kyma-project/kyma/components/central-application-gateway -WORKDIR $DOCK_PKG_DIR - -COPY go.mod . -COPY go.sum . -RUN go mod download - -COPY . $DOCK_PKG_DIR - -RUN echo "nobody:x:65534:5534:nobody:/:" > /etc_passwd - -RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o applicationgateway ./cmd/applicationgateway - - -FROM eu.gcr.io/kyma-project/external/alpine:3.17.3 as certs -RUN apk add -U --no-cache ca-certificates - -FROM scratch -LABEL source=git@github.com:kyma-project/kyma.git - -WORKDIR /app - -COPY --from=certs /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ -COPY --from=builder /go/src/github.com/kyma-project/kyma/components/central-application-gateway/applicationgateway . - -COPY --from=builder /etc_passwd /etc/passwd -USER nobody - -CMD ["/app/applicationgateway"] diff --git a/components/central-application-gateway/Makefile b/components/central-application-gateway/Makefile deleted file mode 100644 index 31176a6a32bc..000000000000 --- a/components/central-application-gateway/Makefile +++ /dev/null @@ -1,20 +0,0 @@ -APP_NAME = central-application-gateway -APP_PATH = components/$(APP_NAME) -BUILDPACK = eu.gcr.io/kyma-project/test-infra/buildpack-golang:v20220914-d77fdc09 -SCRIPTS_DIR = $(realpath $(shell pwd)/../..)/common/makefiles - -override ENTRYPOINT = cmd/applicationgateway/ - -include $(SCRIPTS_DIR)/generic-make-go.mk - -VERIFY_IGNORE := /vendor\|/mocks - -release: - $(MAKE) gomod-release-local - -resolve-local: - GO111MODULE=on go mod vendor -v - -test-local: - GO111MODULE=on go test ./... - diff --git a/components/central-application-gateway/README.md b/components/central-application-gateway/README.md deleted file mode 100644 index 0c7511b29273..000000000000 --- a/components/central-application-gateway/README.md +++ /dev/null @@ -1,166 +0,0 @@ -# Central Application Gateway - -## Overview - -This is the repository for Central Application Gateway. - -## Prerequisites - -Central Application Gateway requires Go 1.8 or higher. - -## Installation - -To install Central Application Gateway, follow these steps: - -1. Clone the repository to your local machine: - ```bash - git clone git@github.com:kyma-project/kyma.git - ``` -2. Navigate to the directory with Central Application Gateway: - ```bash - cd kyma/components/central-application-gateway - ``` -3. Build the component: - ```bash - CGO_ENABLED=0 go build ./cmd/applicationgateway - ``` - -## Usage - -This section explains how to use Central Application Gateway. - -### Start Central Application Gateway - -To start Central Application Gateway, run this command: - -```bash -./applicationgateway -``` - -Central Application Gateway has the following parameters: - -- **apiServerURL** - The address of the Kubernetes API server. Overrides any value in a kubeconfig. Only required if out-of-cluster. -- **applicationSecretsNamespace** - Namespace where Application secrets used by the Application Gateway exist. The default is `kymasystem` -- **externalAPIPort** - Port that exposes the API which allows checking the component status and exposes log configuration. The default is `8081` -- **kubeConfig** - Path to a kubeconfig. Only required if out-of-cluster -- **logLevel** - Log level: `panic` | `fatal` | `error` | `warn` | `info` | `debug`. Can't be lower than `info`. The default is `zapInfoLevel` -- **proxyCacheTTL** - TTL, in seconds, for proxy cache of Remote API information. The default is `120` -- **proxyPort** - Port that acts as a proxy for the calls from services and Functions to an external solution in the default standalone mode or Compass bundles with a single API definition. The default is `8080` -- **proxyPortCompass** - Port that acts as a proxy for the calls from services and Functions to an external solution in the Compass mode. The default is `8082` -- **proxyTimeout** - Timeout for requests sent through the proxy, expressed in seconds. The default is `10` -- **requestTimeout** - Timeout for requests sent through Central Application Gateway, expressed in seconds. The defaultis `1` - -## API - -Central Application Gateway exposes: -- an external API implementing a health endpoint for liveness and readiness probes -- 2 internal APIs implementing a proxy handler accessible via a service of type `ClusterIP` -- an endpoint for changing the log level - -Application Gateway also supports redirects for the request flows in which the URL host remains unchanged. For more details, see [Response rewriting](https://kyma-project.io/#/application-connector-manager/user/technical-reference/07-10-application-gateway-details?id=response-rewriting). - -### Standalone Mode - -The proxy API exposes the following endpoint: -```bash -{APPLICATION_NAME}/{SERVICE_NAME}/{TARGET_API_PATH} -``` - -For instance, if there's a `cc-occ-commerce-webservices` service in the `ec` Application CR, the user can send a request to the following URL: -```bash -http://central-application-gateway.kyma-system:8080/ec/cc-occ-commerce-webservices/basesites -``` - -As a result, Central Application Gateway: -1. Looks for the `cc-occ-commerce-webservices` service in the `ec` Application CR and extracts the target URL path along with the authentication configuration. -2. Modifies the request to include the authentication data. -3. Sends the request to the following path: - ```bash - {TARGET_URL_EXTRACTED_FROM_APPLICATION_CR}/basesites - ``` - -#### Standalone Mode for Compass - Simplified API - -The standalone mode can also be used for Compass bundles with a single API definition. -In this case, `{API_DEFINITION_NAME}` is removed from the URL and the pattern looks as follows: -```bash -{APPLICATION_NAME}/{API_BUNDLE_NAME}/{TARGET_API_PATH} -``` -> **NOTE:** Invocation of service bundles configured with multiple API definitions results in a `400 Bad Request` failure. - -### Compass Mode - -The proxy API exposes the following endpoint: -```bash -{APPLICATION_NAME}/{API_BUNDLE_NAME}/{API_DEFINITION_NAME}/{TARGET_API_PATH} -``` - -For instance, if the user registered the `cc-occ` API bundle with the `commerce-webservices` API definition in the `ec` application, they can send a request to the following URL: -```bash -http://central-application-gateway.kyma-system:8082/ec/cc-occ/commerce-webservices/basesites -``` - -As a result, Central Application Gateway: -1. Looks for the `cc-occ` service and the `commerce-webservices` entry in the `ec` Application CR and extracts the target URL path along with the authentication configuration. -2. Modifies the request to include the authentication data. -3. Sends the request to the following path: - ```bash - {TARGET_URL_EXTRACTED_FROM_APPLICATION_CRD}/basesites - ``` - -#### Handling Ambiguous API Definition Names - -A combination of `{API_BUNDLE_NAME}` and `{API_DEFINITION_NAME}` which are extracted from an Application CR must be unique for a given application. -Invocation of endpoints with duplicate names results in a `400 Bad Request` failure. In such a case, you must change one of the names to avoid ambiguity. - -### Status Codes for Errors Returned by Application Gateway - -- `404 Not Found` - returned when the Application specified in the path doesn't exist. -- `400 Bad Request` - returned when an Application, service, or entry for the [Compass mode](https://kyma-project.io/#/application-connector-manager/user/README) is not specified in the path. -- `504 Gateway Timeout` - returned when a call to the target API times out. - -### Debugging - -The log level can be changed using `zap.AtomicLevel`. -The endpoint is exposed at `http://central-application-gateway.kyma-system:8081/v1/loglevel`. - -https://pkg.go.dev/go.uber.org/zap#AtomicLevel.ServeHTTP - - -## Development - -This section explains the development process. - -### Generate Mocks - -Prerequisites: - - - [Mockery](https://github.com/vektra/mockery) 2.0 or higher - -To generate mocks, run: - -```bash -go generate ./... -``` - -When adding a new interface to be mocked or when a mock of an existing interface is not being generated, add the following line directly above the interface declaration: - -```bash -//go:generate mockery --name {INTERFACE_NAME} -``` - -### Tests - -This section outlines the testing details. - -#### Unit Tests - -To run the unit tests, run this command: - -```bash -go test./... -``` - -### Contribution - -To learn how you can contribute to this project, see the [Contributing](/CONTRIBUTING.md) document. diff --git a/components/central-application-gateway/cmd/applicationgateway/applicationproxy.go b/components/central-application-gateway/cmd/applicationgateway/applicationproxy.go deleted file mode 100644 index d69925a0286b..000000000000 --- a/components/central-application-gateway/cmd/applicationgateway/applicationproxy.go +++ /dev/null @@ -1,226 +0,0 @@ -package main - -import ( - "context" - "net" - "net/http" - "os" - "os/signal" - "strconv" - "syscall" - "time" - - "github.com/kyma-project/kyma/components/central-application-gateway/internal/csrf" - csrfClient "github.com/kyma-project/kyma/components/central-application-gateway/internal/csrf/client" - csrfStrategy "github.com/kyma-project/kyma/components/central-application-gateway/internal/csrf/strategy" - "github.com/kyma-project/kyma/components/central-application-gateway/internal/externalapi" - "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata" - "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata/applications" - "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata/secrets" - "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata/serviceapi" - "github.com/kyma-project/kyma/components/central-application-gateway/internal/proxy" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/client/clientset/versioned" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/httptools" - "github.com/oklog/run" - "go.uber.org/zap" - "k8s.io/client-go/kubernetes" - restclient "k8s.io/client-go/rest" - "k8s.io/client-go/tools/clientcmd" -) - -const ( - shutdownTimeout = 2 * time.Second -) - -func main() { - setupLogger := zap.Must(zap.NewProduction()) - defer func(setupLogger *zap.Logger) { - err := setupLogger.Sync() - if err != nil { - panic(err) - } - }(setupLogger) - - setupLogger.Info("Starting Application Gateway") - - options := parseArgs(setupLogger) - - logCfg := zap.NewProductionConfig() - logCfg.Level.SetLevel(*options.logLevel) - - log, err := logCfg.Build() - zap.ReplaceGlobals(log) - defer func(log *zap.Logger) { - err := log.Sync() - if err != nil { - panic(err) - } - }(log) - - if err != nil { - setupLogger.Fatal("Couldn't initiate logger", zap.Error(err)) - } - - k8sConfig, err := clientcmd.BuildConfigFromFlags(options.apiServerURL, options.kubeConfig) - if err != nil { - log.Fatal("Error reading in cluster config", zap.Error(err)) - } - - coreClientset, err := kubernetes.NewForConfig(k8sConfig) - if err != nil { - log.Fatal("Error creating core clientset", zap.Error(err)) - } - - serviceDefinitionService, err := newServiceDefinitionService( - k8sConfig, - coreClientset, - options.applicationSecretsNamespace, - ) - if err != nil { - log.Fatal("Unable to create ServiceDefinitionService:'", zap.Error(err)) - } - - internalHandler := newInternalHandler(serviceDefinitionService, options) - internalHandlerForCompass := newInternalHandlerForCompass(serviceDefinitionService, options) - externalHandler := externalapi.NewHandler(logCfg.Level) - - internalHandler = httptools.RequestLogger("Internal handler: ", internalHandler) - internalHandlerForCompass = httptools.RequestLogger("Internal handler: ", internalHandlerForCompass) - externalHandler = httptools.RequestLogger("External handler: ", externalHandler) - - externalSrv := &http.Server{ - Addr: ":" + strconv.Itoa(options.externalAPIPort), - Handler: externalHandler, - ReadTimeout: time.Duration(options.requestTimeout) * time.Second, - WriteTimeout: time.Duration(options.requestTimeout) * time.Second, - } - - internalSrv := &http.Server{ - Addr: ":" + strconv.Itoa(options.proxyPort), - Handler: internalHandler, - ReadTimeout: time.Duration(options.requestTimeout) * time.Second, - } - - internalSrvCompass := &http.Server{ - Addr: ":" + strconv.Itoa(options.proxyPortCompass), - Handler: internalHandlerForCompass, - ReadTimeout: time.Duration(options.requestTimeout) * time.Second, - } - - var g run.Group - - addHttpServerToRunGroup("external-api", &g, externalSrv) - addHttpServerToRunGroup("proxy-kyma-os", &g, internalSrv) - addHttpServerToRunGroup("proxy-kyma-mps", &g, internalSrvCompass) - addInterruptSignalToRunGroup(&g) - - err = g.Run() - if err != nil && err != http.ErrServerClosed { - log.Fatal("Servers encountered error", zap.Error(err)) - } -} - -func addHttpServerToRunGroup(name string, g *run.Group, srv *http.Server) { - log := zap.L().Sugar() - - log.Infof("Starting %s HTTP server on %s", name, srv.Addr) - ln, err := net.Listen("tcp", srv.Addr) - if err != nil { - log.Fatalf("Unable to start %s HTTP server: '%s'", name, err) - } - g.Add(func() error { - defer log.Infof("Server %s finished", name) - return srv.Serve(ln) - }, func(error) { - log.Infof("Shutting down %s HTTP server on %s", name, srv.Addr) - - ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout) - defer cancel() - err = srv.Shutdown(ctx) - if err != nil && err != http.ErrServerClosed { - log.Warnf("HTTP server shutdown %s failed: %s", name, err) - } - }) -} - -func addInterruptSignalToRunGroup(g *run.Group) { - cancelInterrupt := make(chan struct{}) - g.Add(func() error { - c := make(chan os.Signal, 1) - signal.Notify(c, syscall.SIGINT, syscall.SIGTERM) - select { - case <-cancelInterrupt: - case sig := <-c: - zap.L().Sugar().Infof("received signal %s", sig) - } - return nil - }, func(error) { - close(cancelInterrupt) - }) -} - -func newInternalHandler(serviceDefinitionService metadata.ServiceDefinitionService, options options) http.Handler { - authStrategyFactory := newAuthenticationStrategyFactory(options.proxyTimeout) - csrfCl := newCSRFClient(options.proxyTimeout) - csrfTokenStrategyFactory := csrfStrategy.NewTokenStrategyFactory(csrfCl) - - return proxy.New(serviceDefinitionService, authStrategyFactory, csrfTokenStrategyFactory, getProxyConfig(options)) -} - -func newInternalHandlerForCompass(serviceDefinitionService metadata.ServiceDefinitionService, options options) http.Handler { - authStrategyFactory := newAuthenticationStrategyFactory(options.proxyTimeout) - csrfCl := newCSRFClient(options.proxyTimeout) - csrfTokenStrategyFactory := csrfStrategy.NewTokenStrategyFactory(csrfCl) - - return proxy.NewForCompass(serviceDefinitionService, authStrategyFactory, csrfTokenStrategyFactory, getProxyConfig(options)) -} - -func getProxyConfig(options options) proxy.Config { - return proxy.Config{ - ProxyTimeout: options.proxyTimeout, - ProxyCacheTTL: options.proxyCacheTTL, - } -} - -func newAuthenticationStrategyFactory(oauthClientTimeout int) authorization.StrategyFactory { - return authorization.NewStrategyFactory(authorization.FactoryConfiguration{ - OAuthClientTimeout: oauthClientTimeout, - }) -} - -func newServiceDefinitionService(k8sConfig *restclient.Config, coreClientset kubernetes.Interface, namespace string) (metadata.ServiceDefinitionService, error) { - applicationServiceRepository, apperror := newApplicationRepository(k8sConfig) - if apperror != nil { - return nil, apperror - } - - secretsRepository := newSecretsRepository(coreClientset, namespace) - - serviceAPIService := serviceapi.NewService(secretsRepository) - - return metadata.NewServiceDefinitionService(serviceAPIService, applicationServiceRepository), nil -} - -func newApplicationRepository(config *restclient.Config) (applications.ServiceRepository, apperrors.AppError) { - applicationClientset, err := versioned.NewForConfig(config) - if err != nil { - return nil, apperrors.Internal("failed to create k8s application client, %s", err) - } - - rei := applicationClientset.ApplicationconnectorV1alpha1().Applications() - - return applications.NewServiceRepository(rei), nil -} - -func newSecretsRepository(coreClientset kubernetes.Interface, namespace string) secrets.Repository { - sei := coreClientset.CoreV1().Secrets(namespace) - - return secrets.NewRepository(sei) -} - -func newCSRFClient(timeout int) csrf.Client { - cache := csrfClient.NewTokenCache() - return csrfClient.New(timeout, cache) -} diff --git a/components/central-application-gateway/cmd/applicationgateway/options.go b/components/central-application-gateway/cmd/applicationgateway/options.go deleted file mode 100644 index ab5df0f5e788..000000000000 --- a/components/central-application-gateway/cmd/applicationgateway/options.go +++ /dev/null @@ -1,55 +0,0 @@ -package main - -import ( - "flag" - - "go.uber.org/zap" - "go.uber.org/zap/zapcore" -) - -type options struct { - apiServerURL string - applicationSecretsNamespace string - externalAPIPort int - kubeConfig string - logLevel *zapcore.Level - proxyCacheTTL int - proxyPort int - proxyPortCompass int - proxyTimeout int - requestTimeout int -} - -func parseArgs(log *zap.Logger) (opts options) { - flag.StringVar(&opts.apiServerURL, "apiServerURL", "", "The address of the Kubernetes API server. Overrides any value in kubeconfig. Only required if out-of-cluster.") - flag.StringVar(&opts.applicationSecretsNamespace, "applicationSecretsNamespace", "kyma-system", "Namespace where Application secrets used by the Application Gateway exist") - flag.IntVar(&opts.externalAPIPort, "externalAPIPort", 8081, "Port that exposes the API which allows checking the component status and exposes log configuration") - flag.StringVar(&opts.kubeConfig, "kubeConfig", "", "Path to a kubeconfig. Only required if out-of-cluster") - opts.logLevel = zap.LevelFlag("logLevel", zap.InfoLevel, "Log level: panic | fatal | error | warn | info | debug. Can't be lower than info") - flag.IntVar(&opts.proxyCacheTTL, "proxyCacheTTL", 120, "TTL, in seconds, for proxy cache of Remote API information") - flag.IntVar(&opts.proxyPort, "proxyPort", 8080, "Port that acts as a proxy for the calls from services and Functions to an external solution in the default standalone mode or Compass bundles with a single API definition") - flag.IntVar(&opts.proxyPortCompass, "proxyPortCompass", 8082, "Port that acts as a proxy for the calls from services and Functions to an external solution in the Compass mode") - flag.IntVar(&opts.proxyTimeout, "proxyTimeout", 10, "Timeout for requests sent through the proxy, expressed in seconds") - flag.IntVar(&opts.requestTimeout, "requestTimeout", 10, "Timeout for requests sent through Central Application Gateway, expressed in seconds") - - flag.Parse() - - opts.Log(log) - - return -} - -func (o options) Log(log *zap.Logger) { - log.Info("Parsed flags", - zap.String("-apiServerURL", o.apiServerURL), - zap.String("-applicationSecretsNamespace", o.applicationSecretsNamespace), - zap.Int("-externalAPIPort", o.externalAPIPort), - zap.String("-kubeConfig", o.kubeConfig), - zap.String("-logLevel", o.logLevel.String()), - zap.Int("-proxyCacheTTL", o.proxyCacheTTL), - zap.Int("-proxyPort", o.proxyPort), - zap.Int("-proxyPortCompass", o.proxyPortCompass), - zap.Int("-proxyTimeout", o.proxyTimeout), - zap.Int("-requestTimeout", o.requestTimeout), - ) -} diff --git a/components/central-application-gateway/go.mod b/components/central-application-gateway/go.mod deleted file mode 100644 index d9995975b83b..000000000000 --- a/components/central-application-gateway/go.mod +++ /dev/null @@ -1,66 +0,0 @@ -module github.com/kyma-project/kyma/components/central-application-gateway - -go 1.21 - -require ( - github.com/gorilla/mux v1.8.1 - github.com/oklog/run v1.1.0 - github.com/patrickmn/go-cache v2.1.0+incompatible - github.com/stretchr/testify v1.8.4 - go.uber.org/zap v1.27.0 - k8s.io/api v0.27.4 - k8s.io/apimachinery v0.27.4 - k8s.io/client-go v0.27.4 -) - -require ( - github.com/davecgh/go-spew v1.1.1 // indirect - github.com/emicklei/go-restful/v3 v3.9.0 // indirect - github.com/evanphx/json-patch v4.12.0+incompatible // indirect - github.com/go-logr/logr v1.2.3 // indirect - github.com/go-openapi/jsonpointer v0.19.6 // indirect - github.com/go-openapi/jsonreference v0.20.1 // indirect - github.com/go-openapi/swag v0.22.3 // indirect - github.com/gogo/protobuf v1.3.2 // indirect - github.com/golang/protobuf v1.5.3 // indirect - github.com/google/gnostic v0.5.7-v3refs // indirect - github.com/google/go-cmp v0.5.9 // indirect - github.com/google/gofuzz v1.1.0 // indirect - github.com/google/uuid v1.3.0 // indirect - github.com/imdario/mergo v0.3.12 // 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/pmezard/go-difflib v1.0.0 // indirect - github.com/spf13/pflag v1.0.5 // indirect - github.com/stretchr/objx v0.5.0 // indirect - go.uber.org/multierr v1.10.0 // indirect - golang.org/x/net v0.19.0 // indirect - golang.org/x/oauth2 v0.0.0-20220223155221-ee480838109b // indirect - golang.org/x/sys v0.15.0 // indirect - golang.org/x/term v0.15.0 // indirect - golang.org/x/text v0.14.0 // indirect - golang.org/x/time v0.0.0-20220210224613-90d013bbcef8 // indirect - google.golang.org/appengine v1.6.7 // indirect - google.golang.org/protobuf v1.28.1 // 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.90.1 // indirect - k8s.io/kube-openapi v0.0.0-20230501164219-8b0f38b5fd1f // indirect - k8s.io/utils v0.0.0-20230209194617-a36077c30491 // indirect - sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect - sigs.k8s.io/structured-merge-diff/v4 v4.2.3 // indirect - sigs.k8s.io/yaml v1.3.0 // indirect -) - -replace ( - golang.org/x/crypto => golang.org/x/crypto v0.16.0 - golang.org/x/net => golang.org/x/net v0.19.0 - golang.org/x/sys => golang.org/x/sys v0.15.0 - golang.org/x/text => golang.org/x/text v0.14.0 -) diff --git a/components/central-application-gateway/go.sum b/components/central-application-gateway/go.sum deleted file mode 100644 index cf87712bd051..000000000000 --- a/components/central-application-gateway/go.sum +++ /dev/null @@ -1,449 +0,0 @@ -cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= -cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU= -cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= -cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc= -cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0= -cloud.google.com/go v0.50.0/go.mod h1:r9sluTvynVuxRIOHXQEHMFffphuXHOMZMycpNR5e6To= -cloud.google.com/go v0.52.0/go.mod h1:pXajvRH/6o3+F9jDHZWQ5PbGhn+o8w9qiu/CffaVdO4= -cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6M= -cloud.google.com/go v0.54.0/go.mod h1:1rq2OEkV3YMf6n/9ZvGWI3GWw0VoqH/1x2nd8Is/bPc= -cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKVk= -cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs= -cloud.google.com/go v0.62.0/go.mod h1:jmCYTdRCQuc1PHIIJ/maLInMho30T/Y0M4hTdTShOYc= -cloud.google.com/go v0.65.0/go.mod h1:O5N8zS7uWy9vkA9vayVHs65eM1ubvY4h553ofrNHObY= -cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= -cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE= -cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc= -cloud.google.com/go/bigquery v1.5.0/go.mod h1:snEHRnqQbz117VIFhE8bmtwIDY80NLUZUMb4Nv6dBIg= -cloud.google.com/go/bigquery v1.7.0/go.mod h1://okPTzCYNXSlb24MZs83e2Do+h+VXtc4gLoIoXIAPc= -cloud.google.com/go/bigquery v1.8.0/go.mod h1:J5hqkt3O0uAFnINi6JXValWIb1v0goeZM77hZzJN/fQ= -cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= -cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk= -cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= -cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw= -cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA= -cloud.google.com/go/pubsub v1.3.1/go.mod h1:i+ucay31+CNRpDW4Lu78I4xXG+O1r/MAHgjpRVR+TSU= -cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= -cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos= -cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk= -cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= -cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= -dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= -github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= -github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= -github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= -github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= -github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= -github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= -github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= -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/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815/go.mod h1:WwZ+bS3ebgob9U8Nd0kOddGdZWjyMGR8Wziv+TBNwSE= -github.com/emicklei/go-restful/v3 v3.9.0 h1:XwGDlfxEnQZzuopoqxwSEllNcCOM9DhhFyhFIIGKwxE= -github.com/emicklei/go-restful/v3 v3.9.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= -github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= -github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= -github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= -github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -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-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= -github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= -github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= -github.com/go-logr/logr v1.2.0/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.2.3 h1:2DntVwHkVopvECVRSlL5PSo9eG+cAkDCuckLubN+rq0= -github.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -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.1 h1:FBLnyygC4/IZZr893oiomc9XaghoveYTrLC1F86HID8= -github.com/go-openapi/jsonreference v0.20.1/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-20210107165309-348f09dbbbc0 h1:p104kn46Q8WdvHunIJ9dAyjPVtrBPhSr3KT2yUst43I= -github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= -github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= -github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= -github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= -github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= -github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= -github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= -github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= -github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= -github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= -github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= -github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= -github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= -github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= -github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= -github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= -github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= -github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= -github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= -github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= -github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= -github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= -github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= -github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= -github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= -github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= -github.com/google/gnostic v0.5.7-v3refs h1:FhTMOKj2VhjpouxvWJAV1TL304uMlb9zcDqkl6cEI54= -github.com/google/gnostic v0.5.7-v3refs/go.mod h1:73MKFl6jIHelAJNaBGFzt3SPtZULs9dYrGFt8OiIsHQ= -github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= -github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= -github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/gofuzz v1.1.0 h1:Hsa8mG0dQ46ij8Sl2AYJDUv1oA9/d6Vk+3LG99Oe02g= -github.com/google/gofuzz v1.1.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= -github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= -github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= -github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= -github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -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/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= -github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= -github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= -github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= -github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= -github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= -github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= -github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= -github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= -github.com/imdario/mergo v0.3.12 h1:b6R2BslTbIEToALKP7LxUvijTsNI9TAe80pLWN2g/HU= -github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= -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/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= -github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= -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.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= -github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= -github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= -github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= -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/oklog/run v1.1.0 h1:GEenZ1cK0+q0+wsJew9qUg/DyD8k3JzYsZAi5gYi2mA= -github.com/oklog/run v1.1.0/go.mod h1:sVPdnTZT1zYwAJeCMu2Th4T21pA3FPOQRfWjQlk7DVU= -github.com/onsi/ginkgo/v2 v2.9.1 h1:zie5Ly042PD3bsCvsSOPvRnFwyo3rKe64TJlD6nu0mk= -github.com/onsi/ginkgo/v2 v2.9.1/go.mod h1:FEcmzVcCHl+4o9bQZVab+4dC9+j+91t2FHSzmGAPfuo= -github.com/onsi/gomega v1.27.4 h1:Z2AnStgsdSayCMDiCU42qIz+HLqEPcgiOCXjAU/w+8E= -github.com/onsi/gomega v1.27.4/go.mod h1:riYq/GJKh8hhoM01HN6Vmuy93AarCXCBGpvFDK3q3fQ= -github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc= -github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ= -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/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= -github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= -github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= -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/stoewer/go-strcase v1.2.0/go.mod h1:IBiWB2sKIp3wVVQ3Y035++gc+knqhUQag1KpM8ahLw8= -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 h1:1zr/of2m5FGMsad5YfcqgdqdWrIhu+EBEJRhR1U7z/c= -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.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= -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/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= -go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= -go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= -go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= -go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= -go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= -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.16.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4= -golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= -golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek= -golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY= -golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= -golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= -golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= -golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= -golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= -golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= -golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= -golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= -golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= -golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= -golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= -golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= -golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= -golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= -golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= -golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= -golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= -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/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/net v0.19.0 h1:zTwKpTd2XuCqf8huc7Fo2iSy+4RHPd10s4KzeTnVr1c= -golang.org/x/net v0.19.0/go.mod h1:CfAk/cbD4CthTvqiEl8NpboMuiuOYsAr/7NOjZJtv1U= -golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20220223155221-ee480838109b h1:clP8eMhB30EHdc0bd2Twtq6kgU7yl5ub2cQLSdrv1Dg= -golang.org/x/oauth2 v0.0.0-20220223155221-ee480838109b/go.mod h1:DAh4E804XQdzx2j+YRIaUnCqCV2RuMz24cGBJ5QYIrc= -golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -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-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc= -golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/term v0.15.0 h1:y/Oo/a/q3IXu26lQgl04j/gjuBDOBlx7X6Om1j2CPW4= -golang.org/x/term v0.15.0/go.mod h1:BDl952bC7+uMoWR75FIrCDx79TPU9oHkTZ9yRbYOrX0= -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.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.0.0-20220210224613-90d013bbcef8 h1:vVKdlvoWBphwdxWKrFZEuM0kGgGLxUOYcY4U/2Vjg44= -golang.org/x/time v0.0.0-20220210224613-90d013bbcef8/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= -golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200204074204-1cc6d1ef6c74/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200224181240-023911ca70b2/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200304193943-95d2e580d8eb/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= -golang.org/x/tools v0.0.0-20200312045724-11d5b4c81c7d/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= -golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= -golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/tools v0.7.0 h1:W4OVu8VVOaIO0yzWMNdepAulS7YfoS3Zabrm8DOXXU4= -golang.org/x/tools v0.7.0/go.mod h1:4pg6aUX35JBAogB10C9AtvVL+qowtN4pT3CGSQex14s= -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/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= -google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= -google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= -google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= -google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= -google.golang.org/api v0.14.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= -google.golang.org/api v0.15.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= -google.golang.org/api v0.17.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.18.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.19.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.20.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.22.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.24.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= -google.golang.org/api v0.28.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= -google.golang.org/api v0.29.0/go.mod h1:Lcubydp8VUV7KeIHD9z2Bys/sm/vGKnG1UHuDBSrHWM= -google.golang.org/api v0.30.0/go.mod h1:QGmEvQ87FHZNiUVJkT14jQNYJ4ZJjdRF23ZXz5138Fc= -google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= -google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= -google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -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/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= -google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= -google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= -google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= -google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20191115194625-c23dd37a84c9/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20191216164720-4f79533eabd1/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20191230161307-f3c370f40bfb/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20200115191322-ca5a22157cba/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20200204135345-fa8e72b47b90/go.mod h1:GmwEX6Z4W5gMy59cAlVYjN9JhxgbQH6Gn+gFDQe2lzA= -google.golang.org/genproto v0.0.0-20200212174721-66ed5ce911ce/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200224152610-e50cd9704f63/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200228133532-8c2c7df3a383/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200305110556-506484158171/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200312145019-da6875a35672/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200331122359-1ee6d9798940/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200430143042-b979b6f78d84/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200511104702-f5ebc3bea380/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200515170657-fc4c6c6a6587/go.mod h1:YsZOwe1myG/8QRHRsmBRE1LrgQY60beZKjly0O1fX9U= -google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= -google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7FcilCzHH/e9qn6dsT145K34l5v+OpcnNgKAAA= -google.golang.org/genproto v0.0.0-20200729003335-053ba62fc06f/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20201019141844-1ed22bb0c154/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= -google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= -google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= -google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= -google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= -google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= -google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= -google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= -google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= -google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= -google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= -google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= -google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= -google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= -google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= -google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= -google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= -google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.28.1 h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w= -google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/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/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= -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.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.3.0/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.0-20200615113413-eeeca48fe776/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= -honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= -honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= -honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= -k8s.io/api v0.27.4 h1:0pCo/AN9hONazBKlNUdhQymmnfLRbSZjd5H5H3f0bSs= -k8s.io/api v0.27.4/go.mod h1:O3smaaX15NfxjzILfiln1D8Z3+gEYpjEpiNA/1EVK1Y= -k8s.io/apimachinery v0.27.4 h1:CdxflD4AF61yewuid0fLl6bM4a3q04jWel0IlP+aYjs= -k8s.io/apimachinery v0.27.4/go.mod h1:XNfZ6xklnMCOGGFNqXG7bUrQCoR04dh/E7FprV6pb+E= -k8s.io/client-go v0.27.4 h1:vj2YTtSJ6J4KxaC88P4pMPEQECWMY8gqPqsTgUKzvjk= -k8s.io/client-go v0.27.4/go.mod h1:ragcly7lUlN0SRPk5/ZkGnDjPknzb37TICq07WhI6Xc= -k8s.io/klog/v2 v2.90.1 h1:m4bYOKall2MmOiRaR1J+We67Do7vm9KiQVlT96lnHUw= -k8s.io/klog/v2 v2.90.1/go.mod h1:y1WjHnz7Dj687irZUWR/WLkLc5N1YHtjLdmgWjndZn0= -k8s.io/kube-openapi v0.0.0-20230501164219-8b0f38b5fd1f h1:2kWPakN3i/k81b0gvD5C5FJ2kxm1WrQFanWchyKuqGg= -k8s.io/kube-openapi v0.0.0-20230501164219-8b0f38b5fd1f/go.mod h1:byini6yhqGC14c3ebc/QwanvYwhuMWF6yz2F8uwW8eg= -k8s.io/utils v0.0.0-20230209194617-a36077c30491 h1:r0BAOLElQnnFhE/ApUsg3iHdVYYPBjNSSOMowRZxxsY= -k8s.io/utils v0.0.0-20230209194617-a36077c30491/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= -rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= -rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= -rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= -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.2.3 h1:PRbqxJClWWYMNV1dhaG4NsibJbArud9kFxnAMREiWFE= -sigs.k8s.io/structured-merge-diff/v4 v4.2.3/go.mod h1:qjx8mGObPmV2aSZepjQjbmb2ihdVs8cGKBraizNC69E= -sigs.k8s.io/yaml v1.3.0 h1:a2VclLzOGrwOHDiV8EfBGhvjHvP46CtW5j6POvhYGGo= -sigs.k8s.io/yaml v1.3.0/go.mod h1:GeOyir5tyXNByN85N/dRIT9es5UQNerPYEKK56eTBm8= diff --git a/components/central-application-gateway/internal/csrf/client/csrfclient.go b/components/central-application-gateway/internal/csrf/client/csrfclient.go deleted file mode 100644 index 6eacd14d7c6a..000000000000 --- a/components/central-application-gateway/internal/csrf/client/csrfclient.go +++ /dev/null @@ -1,111 +0,0 @@ -package client - -import ( - "context" - "crypto/tls" - "net/http" - "strings" - "time" - - "go.uber.org/zap" - - "github.com/kyma-project/kyma/components/central-application-gateway/internal/csrf" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/clientcert" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/httpconsts" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/httptools" -) - -func New(timeoutDuration int, tokenCache TokenCache) csrf.Client { - clientCertificate := clientcert.NewClientCertificate(nil) - - return &client{ - timeoutDuration: timeoutDuration, - tokenCache: tokenCache, - clientCertificate: clientCertificate, - } -} - -type client struct { - timeoutDuration int - tokenCache TokenCache - clientCertificate clientcert.ClientCertificate -} - -func (c *client) GetTokenEndpointResponse(tokenEndpointURL string, strategy authorization.Strategy, skipTLSVerify bool) (*csrf.Response, apperrors.AppError) { - - resp, found := c.tokenCache.Get(tokenEndpointURL) - if found { - return resp, nil - } - - zap.L().Info("CSRF Token not found in cache, fetching", - zap.String("tokenEndpoint", tokenEndpointURL)) - - tokenResponse, err := c.requestToken(tokenEndpointURL, strategy, c.timeoutDuration, skipTLSVerify) - if err != nil { - return nil, err - } - - c.tokenCache.Add(tokenEndpointURL, tokenResponse) - - return tokenResponse, nil - -} - -func (c *client) InvalidateTokenCache(tokenEndpointURL string) { - zap.L().Info("Invalidating token for endpoint", - zap.String("tokenEndpoint", tokenEndpointURL)) - c.tokenCache.Remove(tokenEndpointURL) -} - -func (c *client) requestToken(csrfEndpointURL string, strategy authorization.Strategy, timeoutDuration int, skipTLSVerify bool) (*csrf.Response, apperrors.AppError) { - - tokenRequest, err := http.NewRequest(http.MethodGet, csrfEndpointURL, strings.NewReader("")) - if err != nil { - return nil, apperrors.Internal("failed to create token request: %s", err.Error()) - } - - err = addAuthorization(tokenRequest, c.clientCertificate, strategy, skipTLSVerify) - if err != nil { - return nil, apperrors.Internal("failed to create token request: %s", err.Error()) - } - - setCSRFSpecificHeaders(tokenRequest) - - ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeoutDuration)*time.Second) - defer cancel() - requestWithContext := tokenRequest.WithContext(ctx) - - httpClient := &http.Client{ - Transport: httptools.NewRoundTripper(httptools.WithGetClientCertificate(c.clientCertificate.GetClientCertificate), httptools.WithTLSSkipVerify(skipTLSVerify)), - } - resp, err := httpClient.Do(requestWithContext) - if err != nil { - return nil, apperrors.UpstreamServerCallFailed("failed to make a request to '%s': %s", csrfEndpointURL, err.Error()) - } - - if resp.StatusCode != http.StatusOK { - return nil, apperrors.UpstreamServerCallFailed("incorrect response code '%d' while getting token from %s", resp.StatusCode, csrfEndpointURL) - } - - tokenRes := &csrf.Response{ - CSRFToken: resp.Header.Get(httpconsts.HeaderCSRFToken), - Cookies: resp.Cookies(), - } - - return tokenRes, nil -} - -func addAuthorization(r *http.Request, clientCertificate clientcert.ClientCertificate, strategy authorization.Strategy, skipTLSVerify bool) apperrors.AppError { - return strategy.AddAuthorization(r, func(cert *tls.Certificate) { - clientCertificate.SetCertificate(cert) - }, skipTLSVerify) -} - -func setCSRFSpecificHeaders(r *http.Request) { - r.Header.Add(httpconsts.HeaderCSRFToken, httpconsts.HeaderCSRFTokenVal) - r.Header.Add(httpconsts.HeaderAccept, httpconsts.HeaderAcceptVal) - r.Header.Add(httpconsts.HeaderCacheControl, httpconsts.HeaderCacheControlVal) -} diff --git a/components/central-application-gateway/internal/csrf/client/csrfclient_test.go b/components/central-application-gateway/internal/csrf/client/csrfclient_test.go deleted file mode 100644 index 0eb4ad1dfb9c..000000000000 --- a/components/central-application-gateway/internal/csrf/client/csrfclient_test.go +++ /dev/null @@ -1,290 +0,0 @@ -package client - -import ( - "encoding/base64" - "net/http" - "net/http/httptest" - "strings" - "testing" - - "github.com/stretchr/testify/mock" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/clientcert" - - "github.com/kyma-project/kyma/components/central-application-gateway/internal/csrf" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization" - authorizationMocks "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/mocks" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/testconsts" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/httpconsts" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -const ( - timeoutDuration = 5 - testURL = "test.io/token" - - cachedTestToken = "someToken" - cachedTestCookieName = "someCookie" - endpointTestToken = "someEndpointToken" - endpointResponseCookieName = "someOtherCookie" - - testUsername = "someUser" - testPassword = "somePassword" - expectedAuthHeaderVal = "Basic c29tZVVzZXI6c29tZVBhc3N3b3Jk" -) - -var ( - certificate = []byte(testconsts.Certificate) - privateKey = []byte(testconsts.PrivateKey) -) - -func TestClient_GetTokenEndpointResponse(t *testing.T) { - - sf := authorization.NewStrategyFactory(authorization.FactoryConfiguration{OAuthClientTimeout: timeoutDuration}) - - strategy := sf.Create(&authorization.Credentials{BasicAuth: &authorization.BasicAuth{ - Username: testUsername, - Password: testPassword, - }}) - - t.Run("Should fetch the token from cache if it is present", func(t *testing.T) { - - // given - r := &csrf.Response{ - CSRFToken: cachedTestToken, - Cookies: []*http.Cookie{{Name: cachedTestCookieName}}, - } - - fakeCache := NewTokenCache() - fakeCache.Add(testURL, r) - - c := New(timeoutDuration, fakeCache) - - // when - response, appError := c.GetTokenEndpointResponse(testURL, nil, false) - - // then - require.Nil(t, appError) - require.NotNil(t, response) - - assert.Equal(t, cachedTestToken, response.CSRFToken) - assert.Equal(t, cachedTestCookieName, response.Cookies[0].Name) - }) - - t.Run("Should fetch the token from endpoint and add it to cache if it is not there", func(t *testing.T) { - - // given - fakeCache := NewTokenCache() - - c := New(timeoutDuration, fakeCache) - - srv := startTLSTestServer(t) - mockURL := srv.URL - - // when - response, appError := c.GetTokenEndpointResponse(mockURL, strategy, true) - item, found := fakeCache.Get(mockURL) - - // then - require.Nil(t, appError) - require.NotNil(t, response) - - assert.Equal(t, endpointTestToken, response.CSRFToken) - assert.Equal(t, endpointResponseCookieName, response.Cookies[0].Name) - - assert.True(t, found) - require.NotNil(t, item) - assert.Equal(t, endpointTestToken, item.CSRFToken) - assert.Equal(t, endpointResponseCookieName, item.Cookies[0].Name) - }) - - t.Run("Should return error if the token requested is not in the cache and can't be retrieved", func(t *testing.T) { - - // given - fakeCache := NewTokenCache() - - c := New(timeoutDuration, fakeCache) - - srv := startFailingTestServer(t) - mockURL := srv.URL - - // when - response, appError := c.GetTokenEndpointResponse(mockURL, strategy, false) - item, found := fakeCache.Get(mockURL) - - // then - require.NotNil(t, appError) - require.Nil(t, response) - - require.Nil(t, item) - assert.False(t, found) - }) - - t.Run("Should return error if the token requested is not in the cache and can't be retrieved since the server certificate cannot be verified", func(t *testing.T) { - - // given - fakeCache := NewTokenCache() - - c := New(timeoutDuration, fakeCache) - - srv := startTLSTestServer(t) - mockURL := srv.URL - - // when - response, appError := c.GetTokenEndpointResponse(mockURL, strategy, false) - item, found := fakeCache.Get(mockURL) - - // then - require.NotNil(t, appError) - require.Nil(t, response) - - require.Nil(t, item) - assert.False(t, found) - }) - - t.Run("Should pass skipTLSVerify flag to authorization strategy", func(t *testing.T) { - - // given - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - })) - mockURL := srv.URL - - { - // given - fakeCache := NewTokenCache() - - c := New(timeoutDuration, fakeCache) - - // when - mockStrategy := &authorizationMocks.Strategy{} - mockStrategy.On("AddAuthorization", mock.Anything, mock.Anything, true).Return(nil) - - response, appError := c.GetTokenEndpointResponse(mockURL, mockStrategy, true) - - // then - require.Nil(t, appError) - require.NotNil(t, response) - } - - { - // given - fakeCache := NewTokenCache() - - c := New(timeoutDuration, fakeCache) - - // when - mockStrategy := &authorizationMocks.Strategy{} - mockStrategy.On("AddAuthorization", mock.Anything, mock.Anything, false).Return(nil) - - response, appError := c.GetTokenEndpointResponse(mockURL, mockStrategy, false) - - // then - require.Nil(t, appError) - require.NotNil(t, response) - } - }) -} - -func TestAddAuthorization(t *testing.T) { - - sf := authorization.NewStrategyFactory(authorization.FactoryConfiguration{OAuthClientTimeout: timeoutDuration}) - - t.Run("Should update request with authorization headers in case of basicAuth strategy", func(t *testing.T) { - - // given - strategy := sf.Create(&authorization.Credentials{BasicAuth: &authorization.BasicAuth{ - Username: testUsername, - Password: testPassword, - }}) - - clientCertificate := clientcert.NewClientCertificate(nil) - request := getNewEmptyRequest() - - // when - err := addAuthorization(request, clientCertificate, strategy, false) - assert.NoError(t, err) - // then - assert.Len(t, request.Header, 1) - assert.NotEmpty(t, request.Header.Get(httpconsts.HeaderAuthorization)) - assert.Equal(t, expectedAuthHeaderVal, request.Header.Get(httpconsts.HeaderAuthorization)) - }) - - t.Run("Should update httpClient with transport in case of certificateGen strategy", func(t *testing.T) { - - // given - strategy := sf.Create(&authorization.Credentials{CertificateGen: &authorization.CertificateGen{ - PrivateKey: privateKey, - Certificate: certificate, - }}) - - clientCertificate := clientcert.NewClientCertificate(nil) - request := getNewEmptyRequest() - - // when - err := addAuthorization(request, clientCertificate, strategy, false) - assert.NoError(t, err) - - // then - assert.NotNil(t, clientCertificate.GetCertificate()) - }) -} - -func TestSetCSRFSpecificHeaders(t *testing.T) { - - t.Run("Should add CSRF specific headers to the request", func(t *testing.T) { - - // given - r := getNewEmptyRequest() - - // when - setCSRFSpecificHeaders(r) - - // then - assert.Len(t, r.Header, 3) - assert.NotEmpty(t, r.Header.Get(httpconsts.HeaderCSRFToken)) - assert.NotEmpty(t, r.Header.Get(httpconsts.HeaderAccept)) - assert.NotEmpty(t, r.Header.Get(httpconsts.HeaderCacheControl)) - }) -} - -func getNewEmptyRequest() *http.Request { - return &http.Request{ - Header: make(map[string][]string), - } -} - -func startTLSTestServer(t *testing.T) *httptest.Server { - ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - checkRequest(t, r) - w.Header().Add("x-csrf-token", endpointTestToken) - http.SetCookie(w, &http.Cookie{Name: endpointResponseCookieName}) - w.WriteHeader(http.StatusOK) - })) - ts.StartTLS() - - return ts -} - -func startFailingTestServer(t *testing.T) *httptest.Server { - return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - checkRequest(t, r) - w.WriteHeader(http.StatusNotFound) - })) -} - -func checkRequest(t *testing.T, r *http.Request) { - authHeader := r.Header.Get(httpconsts.HeaderAuthorization) - encodedCredentials := strings.TrimPrefix(string(authHeader), "Basic ") - decoded, err := base64.StdEncoding.DecodeString(encodedCredentials) - require.NoError(t, err) - credentials := strings.Split(string(decoded), ":") - - assert.Equal(t, testUsername, credentials[0]) - assert.Equal(t, testPassword, credentials[1]) - - assert.NotEmpty(t, r.Header.Get(httpconsts.HeaderCSRFToken)) - assert.NotEmpty(t, r.Header.Get(httpconsts.HeaderAccept)) - assert.NotEmpty(t, r.Header.Get(httpconsts.HeaderCacheControl)) -} diff --git a/components/central-application-gateway/internal/csrf/client/csrftokencache.go b/components/central-application-gateway/internal/csrf/client/csrftokencache.go deleted file mode 100644 index b4a8ea548ede..000000000000 --- a/components/central-application-gateway/internal/csrf/client/csrftokencache.go +++ /dev/null @@ -1,44 +0,0 @@ -package client - -import ( - "time" - - "github.com/kyma-project/kyma/components/central-application-gateway/internal/csrf" - - cache "github.com/patrickmn/go-cache" -) - -// Cache for CSRF data items -type TokenCache interface { - Get(itemID string) (resp *csrf.Response, found bool) - Add(itemID string, resp *csrf.Response) - Remove(itemID string) -} - -// Creates a new TokenCache instance -func NewTokenCache() TokenCache { - return &tokenCache{ - cache: cache.New(cache.NoExpiration, cache.NoExpiration), - } -} - -type tokenCache struct { - cache *cache.Cache -} - -func (tc *tokenCache) Get(itemID string) (resp *csrf.Response, found bool) { - res, found := tc.cache.Get(itemID) - if !found { - return nil, false - } - - return res.(*csrf.Response), found -} - -func (tc *tokenCache) Add(itemID string, resp *csrf.Response) { - tc.cache.Set(itemID, resp, time.Duration(-1)*time.Second) -} - -func (tc *tokenCache) Remove(itemID string) { - tc.cache.Delete(itemID) -} diff --git a/components/central-application-gateway/internal/csrf/client/csrftokencache_test.go b/components/central-application-gateway/internal/csrf/client/csrftokencache_test.go deleted file mode 100644 index 60ca97281781..000000000000 --- a/components/central-application-gateway/internal/csrf/client/csrftokencache_test.go +++ /dev/null @@ -1,66 +0,0 @@ -package client - -import ( - "net/http" - "testing" - - "github.com/kyma-project/kyma/components/central-application-gateway/internal/csrf" - "github.com/stretchr/testify/assert" -) - -const ( - itemId = "someEndpointURL" - cachedToken = "someToken" - cachedCookieName = "someCookie" -) - -func TestTokenCache(t *testing.T) { - - testCookie := http.Cookie{Name: cachedCookieName} - - resp := &csrf.Response{ - CSRFToken: cachedToken, - Cookies: []*http.Cookie{&testCookie}, - } - - t.Run("should add and retrieve the response from the cache", func(t *testing.T) { - // given - tokenCache := NewTokenCache() - tokenCache.Add(itemId, resp) - - // when - response, found := tokenCache.Get(itemId) - - // then - assert.Equal(t, true, found) - assert.Equal(t, cachedToken, response.CSRFToken) - assert.Equal(t, cachedCookieName, response.Cookies[0].Name) - }) - - t.Run("should return false if the response was not found", func(t *testing.T) { - // given - tokenCache := NewTokenCache() - - // when - resp, found := tokenCache.Get(itemId) - - // then - assert.Equal(t, false, found) - assert.Nil(t, resp) - }) - - t.Run("should remove a response from the cache", func(t *testing.T) { - // given - tokenCache := NewTokenCache() - tokenCache.Add(itemId, resp) - tokenCache.Remove(itemId) - - // when - resp, found := tokenCache.Get(itemId) - - // then - assert.Equal(t, false, found) - assert.Nil(t, resp) - }) - -} diff --git a/components/central-application-gateway/internal/csrf/mocks/Client.go b/components/central-application-gateway/internal/csrf/mocks/Client.go deleted file mode 100644 index b8a1213eaa1d..000000000000 --- a/components/central-application-gateway/internal/csrf/mocks/Client.go +++ /dev/null @@ -1,62 +0,0 @@ -// Code generated by mockery v2.16.0. DO NOT EDIT. - -package mocks - -import ( - apperrors "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - authorization "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization" - - csrf "github.com/kyma-project/kyma/components/central-application-gateway/internal/csrf" - - mock "github.com/stretchr/testify/mock" -) - -// Client is an autogenerated mock type for the Client type -type Client struct { - mock.Mock -} - -// GetTokenEndpointResponse provides a mock function with given fields: csrfEndpointURL, strategy, skipTLSVerify -func (_m *Client) GetTokenEndpointResponse(csrfEndpointURL string, strategy authorization.Strategy, skipTLSVerify bool) (*csrf.Response, apperrors.AppError) { - ret := _m.Called(csrfEndpointURL, strategy, skipTLSVerify) - - var r0 *csrf.Response - if rf, ok := ret.Get(0).(func(string, authorization.Strategy, bool) *csrf.Response); ok { - r0 = rf(csrfEndpointURL, strategy, skipTLSVerify) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*csrf.Response) - } - } - - var r1 apperrors.AppError - if rf, ok := ret.Get(1).(func(string, authorization.Strategy, bool) apperrors.AppError); ok { - r1 = rf(csrfEndpointURL, strategy, skipTLSVerify) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(apperrors.AppError) - } - } - - return r0, r1 -} - -// InvalidateTokenCache provides a mock function with given fields: csrfEndpointURL -func (_m *Client) InvalidateTokenCache(csrfEndpointURL string) { - _m.Called(csrfEndpointURL) -} - -type mockConstructorTestingTNewClient interface { - mock.TestingT - Cleanup(func()) -} - -// NewClient creates a new instance of Client. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewClient(t mockConstructorTestingTNewClient) *Client { - mock := &Client{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/components/central-application-gateway/internal/csrf/mocks/TokenStrategy.go b/components/central-application-gateway/internal/csrf/mocks/TokenStrategy.go deleted file mode 100644 index e553dc010f85..000000000000 --- a/components/central-application-gateway/internal/csrf/mocks/TokenStrategy.go +++ /dev/null @@ -1,52 +0,0 @@ -// Code generated by mockery v2.16.0. DO NOT EDIT. - -package mocks - -import ( - apperrors "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - - http "net/http" - - mock "github.com/stretchr/testify/mock" -) - -// TokenStrategy is an autogenerated mock type for the TokenStrategy type -type TokenStrategy struct { - mock.Mock -} - -// AddCSRFToken provides a mock function with given fields: apiRequest, skipTLSVerify -func (_m *TokenStrategy) AddCSRFToken(apiRequest *http.Request, skipTLSVerify bool) apperrors.AppError { - ret := _m.Called(apiRequest, skipTLSVerify) - - var r0 apperrors.AppError - if rf, ok := ret.Get(0).(func(*http.Request, bool) apperrors.AppError); ok { - r0 = rf(apiRequest, skipTLSVerify) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(apperrors.AppError) - } - } - - return r0 -} - -// Invalidate provides a mock function with given fields: -func (_m *TokenStrategy) Invalidate() { - _m.Called() -} - -type mockConstructorTestingTNewTokenStrategy interface { - mock.TestingT - Cleanup(func()) -} - -// NewTokenStrategy creates a new instance of TokenStrategy. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewTokenStrategy(t mockConstructorTestingTNewTokenStrategy) *TokenStrategy { - mock := &TokenStrategy{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/components/central-application-gateway/internal/csrf/mocks/TokenStrategyFactory.go b/components/central-application-gateway/internal/csrf/mocks/TokenStrategyFactory.go deleted file mode 100644 index 0feb8e575d55..000000000000 --- a/components/central-application-gateway/internal/csrf/mocks/TokenStrategyFactory.go +++ /dev/null @@ -1,46 +0,0 @@ -// Code generated by mockery v2.16.0. DO NOT EDIT. - -package mocks - -import ( - csrf "github.com/kyma-project/kyma/components/central-application-gateway/internal/csrf" - authorization "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization" - - mock "github.com/stretchr/testify/mock" -) - -// TokenStrategyFactory is an autogenerated mock type for the TokenStrategyFactory type -type TokenStrategyFactory struct { - mock.Mock -} - -// Create provides a mock function with given fields: authorizationStrategy, csrfTokenEndpointURL -func (_m *TokenStrategyFactory) Create(authorizationStrategy authorization.Strategy, csrfTokenEndpointURL string) csrf.TokenStrategy { - ret := _m.Called(authorizationStrategy, csrfTokenEndpointURL) - - var r0 csrf.TokenStrategy - if rf, ok := ret.Get(0).(func(authorization.Strategy, string) csrf.TokenStrategy); ok { - r0 = rf(authorizationStrategy, csrfTokenEndpointURL) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(csrf.TokenStrategy) - } - } - - return r0 -} - -type mockConstructorTestingTNewTokenStrategyFactory interface { - mock.TestingT - Cleanup(func()) -} - -// NewTokenStrategyFactory creates a new instance of TokenStrategyFactory. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewTokenStrategyFactory(t mockConstructorTestingTNewTokenStrategyFactory) *TokenStrategyFactory { - mock := &TokenStrategyFactory{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/components/central-application-gateway/internal/csrf/strategy/csrf.go b/components/central-application-gateway/internal/csrf/strategy/csrf.go deleted file mode 100644 index 4d99a4d87dc8..000000000000 --- a/components/central-application-gateway/internal/csrf/strategy/csrf.go +++ /dev/null @@ -1,90 +0,0 @@ -package strategy - -import ( - "net/http" - - "go.uber.org/zap" - - "github.com/kyma-project/kyma/components/central-application-gateway/internal/csrf" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/httpconsts" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization" -) - -func NewTokenStrategyFactory(csrfClient csrf.Client) csrf.TokenStrategyFactory { - return &strategyFactory{csrfClient} -} - -type strategyFactory struct { - csrfClient csrf.Client -} - -func (tsf *strategyFactory) Create(authorizationStrategy authorization.Strategy, csrfTokenEndpointURL string) csrf.TokenStrategy { - if csrfTokenEndpointURL == "" { - return &noTokenStrategy{} - } - return &strategy{authorizationStrategy, csrfTokenEndpointURL, tsf.csrfClient} -} - -type strategy struct { - authorizationStrategy authorization.Strategy - csrfTokenURL string - csrfClient csrf.Client -} - -func (s *strategy) AddCSRFToken(apiRequest *http.Request, skipTLSVerify bool) apperrors.AppError { - - tokenResponse, err := s.csrfClient.GetTokenEndpointResponse(s.csrfTokenURL, s.authorizationStrategy, skipTLSVerify) - if err != nil { - zap.L().Error("failed to get CSRF token", - zap.Error(err)) - return err - } - - apiRequest.Header.Set(httpconsts.HeaderCSRFToken, tokenResponse.CSRFToken) - - mergeCookiesWithOverride(apiRequest, tokenResponse.Cookies) - - return nil -} - -func (s *strategy) Invalidate() { - s.csrfClient.InvalidateTokenCache(s.csrfTokenURL) -} - -type noTokenStrategy struct{} - -func (nts *noTokenStrategy) AddCSRFToken(apiRequest *http.Request, skipTLSVerify bool) apperrors.AppError { - return nil -} - -func (nts *noTokenStrategy) Invalidate() { -} - -// Adds newCookies to the request. If the cookie is already present, overrides it. -func mergeCookiesWithOverride(request *http.Request, newCookies []*http.Cookie) { - existingCookies := request.Cookies() - - for _, exCookie := range existingCookies { - if !containsCookie(exCookie.Name, newCookies) { - newCookies = append(newCookies, exCookie) - } - } - - request.Header.Del(httpconsts.HeaderCookie) - - for _, c := range newCookies { - request.AddCookie(c) - } -} - -func containsCookie(name string, cookies []*http.Cookie) bool { - for _, c := range cookies { - if c.Name == name { - return true - } - } - - return false -} diff --git a/components/central-application-gateway/internal/csrf/strategy/csrf_test.go b/components/central-application-gateway/internal/csrf/strategy/csrf_test.go deleted file mode 100644 index 39db41ca5bd0..000000000000 --- a/components/central-application-gateway/internal/csrf/strategy/csrf_test.go +++ /dev/null @@ -1,175 +0,0 @@ -package strategy - -import ( - "net/http" - "testing" - - "github.com/kyma-project/kyma/components/central-application-gateway/internal/csrf/mocks" - - "github.com/kyma-project/kyma/components/central-application-gateway/internal/csrf" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - authmocks "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/mocks" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/httpconsts" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -const ( - TestTokenEndpointURL = "myapp.com/csrf/token" - noURL = "" -) - -func TestStrategyFactory_Create(t *testing.T) { - - // given - factory := NewTokenStrategyFactory(nil) - authStrategy := &authmocks.Strategy{} - - t.Run("Should create strategy if the CSRF token endpoint URL has been provided", func(t *testing.T) { - - // when - tokenStrategy := factory.Create(authStrategy, TestTokenEndpointURL) - - // then - require.NotNil(t, tokenStrategy) - assert.IsType(t, &strategy{}, tokenStrategy) - }) - - t.Run("Should create noTokenStrategy if the CSRF token has not been provided", func(t *testing.T) { - - // when - tokenStrategy := factory.Create(authStrategy, noURL) - - // then - require.NotNil(t, tokenStrategy) - assert.IsType(t, &noTokenStrategy{}, tokenStrategy) - }) -} - -const ( - cachedToken = "someToken" - cachedCookieName = "someCookieName" - testCSRFTokenEndpointURL = "app.com/token" -) - -func TestStrategy_AddCSRFToken(t *testing.T) { - - t.Run("In case CSRF is enabled", func(t *testing.T) { - - authStrategy := &authmocks.Strategy{} - - t.Run("Should set CSRF header and copy all Cookies into the request if it is possible to fetch the CSRF token", func(t *testing.T) { - // given - req := getNewEmptyRequest() - - c := &mocks.Client{} - sf := NewTokenStrategyFactory(c) - - s := sf.Create(authStrategy, testCSRFTokenEndpointURL) - - cachedItem := &csrf.Response{ - CSRFToken: cachedToken, - Cookies: []*http.Cookie{ - {Name: cachedCookieName, Value: cachedToken}, - }, - } - - c.On("GetTokenEndpointResponse", testCSRFTokenEndpointURL, authStrategy, false).Return(cachedItem, nil) - - // when - err := s.AddCSRFToken(req, false) - - //then - require.Nil(t, err) - cachedCookie, cookieErr := req.Cookie(cachedCookieName) - require.NoError(t, cookieErr) - assert.Equal(t, cachedToken, cachedCookie.Value) - - }) - - t.Run("Should set CSRF header and merge new Cookies into the request overriding existing cookies", func(t *testing.T) { - // given - req := getNewEmptyRequest() - req.AddCookie(&http.Cookie{Name: cachedCookieName, Value: "oldInvalidCookie"}) - req.AddCookie(&http.Cookie{Name: "custom-user-cookie", Value: "customValue"}) - - c := &mocks.Client{} - sf := NewTokenStrategyFactory(c) - - s := sf.Create(authStrategy, testCSRFTokenEndpointURL) - - cachedItem := &csrf.Response{ - CSRFToken: cachedToken, - Cookies: []*http.Cookie{ - {Name: cachedCookieName, Value: cachedToken}, - }, - } - - c.On("GetTokenEndpointResponse", testCSRFTokenEndpointURL, authStrategy, false).Return(cachedItem, nil) - - // when - err := s.AddCSRFToken(req, false) - - //then - require.Nil(t, err) - assert.Equal(t, cachedToken, req.Header.Get(httpconsts.HeaderCSRFToken)) - - cachedCookie, cookieErr := req.Cookie(cachedCookieName) - require.NoError(t, cookieErr) - assert.Equal(t, cachedToken, cachedCookie.Value) - - customUserCookie, cookieErr := req.Cookie("custom-user-cookie") - require.NoError(t, cookieErr) - assert.Equal(t, "customValue", customUserCookie.Value) - - }) - - t.Run("Should return error if it is not possible to fetch the CSRF token", func(t *testing.T) { - - // given - req := getNewEmptyRequest() - - c := &mocks.Client{} - sf := NewTokenStrategyFactory(c) - - s := sf.Create(authStrategy, testCSRFTokenEndpointURL) - - c.On("GetTokenEndpointResponse", testCSRFTokenEndpointURL, authStrategy, false).Return(nil, apperrors.NotFound("error")) - - //when - err := s.AddCSRFToken(req, false) - - //then - require.NotNil(t, err) - }) - }) - - t.Run("In case CSRF is disabled", func(t *testing.T) { - - t.Run("Should not modify the original request", func(t *testing.T) { - - // given - req := getNewEmptyRequest() - - c := &mocks.Client{} - sf := NewTokenStrategyFactory(c) - - s := sf.Create(nil, "") - - // when - err := s.AddCSRFToken(req, false) - - //then - require.Nil(t, err) - assert.Empty(t, req.Header) - assert.Empty(t, req.Cookies()) - - }) - }) -} - -func getNewEmptyRequest() *http.Request { - return &http.Request{ - Header: make(map[string][]string), - } -} diff --git a/components/central-application-gateway/internal/csrf/types.go b/components/central-application-gateway/internal/csrf/types.go deleted file mode 100644 index ab2b94c403d7..000000000000 --- a/components/central-application-gateway/internal/csrf/types.go +++ /dev/null @@ -1,43 +0,0 @@ -package csrf - -import ( - "net/http" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization" -) - -// CSRF Client is an HTTP client responsible for fetching and caching CSRF Tokens. -// -//go:generate mockery --name=Client -type Client interface { - //Fetches data from CSRF Token Endpoint - GetTokenEndpointResponse(csrfEndpointURL string, strategy authorization.Strategy, skipTLSVerify bool) (*Response, apperrors.AppError) - - //Invalidates cached data - InvalidateTokenCache(csrfEndpointURL string) -} - -// CSFR Endpoint response data -type Response struct { - CSRFToken string //Opaque value - Cookies []*http.Cookie //Must be included in API requests along with the token for CSFR verification to succeed -} - -// Creates new instances of TokenStrategy -// -//go:generate mockery --name=TokenStrategyFactory -type TokenStrategyFactory interface { - Create(authorizationStrategy authorization.Strategy, csrfTokenEndpointURL string) TokenStrategy -} - -// Augments upstream API requests with CSRF data. -// -//go:generate mockery --name=TokenStrategy -type TokenStrategy interface { - //Sets CSRF Token into requests to external APIs - AddCSRFToken(apiRequest *http.Request, skipTLSVerify bool) apperrors.AppError - - //Invalidates cached CSRF Token - Invalidate() -} diff --git a/components/central-application-gateway/internal/externalapi/errorhandler.go b/components/central-application-gateway/internal/externalapi/errorhandler.go deleted file mode 100644 index 393e6ef504ad..000000000000 --- a/components/central-application-gateway/internal/externalapi/errorhandler.go +++ /dev/null @@ -1,26 +0,0 @@ -package externalapi - -import ( - "encoding/json" - "net/http" - - "github.com/kyma-project/kyma/components/central-application-gateway/internal/httperrors" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/httpconsts" -) - -type ErrorHandler struct { - Message string - Code int -} - -func NewErrorHandler(code int, message string) *ErrorHandler { - return &ErrorHandler{Message: message, Code: code} -} - -func (eh *ErrorHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - responseBody := httperrors.ErrorResponse{Code: eh.Code, Error: eh.Message} - - w.Header().Set(httpconsts.HeaderContentType, httpconsts.ContentTypeApplicationJson) - w.WriteHeader(eh.Code) - json.NewEncoder(w).Encode(responseBody) -} diff --git a/components/central-application-gateway/internal/externalapi/errorhandler_test.go b/components/central-application-gateway/internal/externalapi/errorhandler_test.go deleted file mode 100644 index d448eb8f0fc7..000000000000 --- a/components/central-application-gateway/internal/externalapi/errorhandler_test.go +++ /dev/null @@ -1,43 +0,0 @@ -package externalapi - -import ( - "encoding/json" - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" - - "github.com/gorilla/mux" - "github.com/kyma-project/kyma/components/central-application-gateway/internal/httperrors" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestErrorHandler_ServeHTTP(t *testing.T) { - t.Run("Should always respond with given error and status code", func(t *testing.T) { - - r := mux.NewRouter() - - r.NotFoundHandler = NewErrorHandler(404, "Requested resource could not be found.") - ts := httptest.NewServer(r) - defer ts.Close() - - // when - res, err := http.Get(ts.URL + "/wrong/path") - - responseBody, err := ioutil.ReadAll(res.Body) - if err != nil { - assert.Fail(t, "Failure while reading response body.") - } - defer res.Body.Close() - - var errResponse httperrors.ErrorResponse - - json.Unmarshal(responseBody, &errResponse) - - // then - require.NoError(t, err) - assert.Equal(t, http.StatusNotFound, errResponse.Code) - assert.Equal(t, http.StatusNotFound, res.StatusCode) - }) -} diff --git a/components/central-application-gateway/internal/externalapi/externalapi.go b/components/central-application-gateway/internal/externalapi/externalapi.go deleted file mode 100644 index 3ad453852afd..000000000000 --- a/components/central-application-gateway/internal/externalapi/externalapi.go +++ /dev/null @@ -1,20 +0,0 @@ -package externalapi - -import ( - "go.uber.org/zap" - "net/http" - - "github.com/gorilla/mux" -) - -func NewHandler(lvl zap.AtomicLevel) http.Handler { - router := mux.NewRouter() - - router.Path("/v1/health").Handler(NewHealthCheckHandler()).Methods(http.MethodGet) - router.Path("/v1/loglevel").Handler(lvl).Methods(http.MethodGet, http.MethodPut) - - router.NotFoundHandler = NewErrorHandler(404, "Requested resource could not be found.") - router.MethodNotAllowedHandler = NewErrorHandler(405, "Method not allowed.") - - return router -} diff --git a/components/central-application-gateway/internal/externalapi/healthcheckhandler.go b/components/central-application-gateway/internal/externalapi/healthcheckhandler.go deleted file mode 100644 index 3a7ea2cc324f..000000000000 --- a/components/central-application-gateway/internal/externalapi/healthcheckhandler.go +++ /dev/null @@ -1,12 +0,0 @@ -package externalapi - -import ( - "net/http" -) - -// NewHealthCheckHandler creates handler for performing health check -func NewHealthCheckHandler() http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusOK) - }) -} diff --git a/components/central-application-gateway/internal/externalapi/healthcheckhandler_test.go b/components/central-application-gateway/internal/externalapi/healthcheckhandler_test.go deleted file mode 100644 index 80d250f72350..000000000000 --- a/components/central-application-gateway/internal/externalapi/healthcheckhandler_test.go +++ /dev/null @@ -1,27 +0,0 @@ -package externalapi - -import ( - "net/http" - "net/http/httptest" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestHealthCheckHandler_HandleRequest(t *testing.T) { - t.Run("should always respond with 200 status code", func(t *testing.T) { - // given - req, err := http.NewRequest(http.MethodGet, "/v1/health", nil) - require.NoError(t, err) - rr := httptest.NewRecorder() - - handler := NewHealthCheckHandler() - - // when - handler.ServeHTTP(rr, req) - - // then - assert.Equal(t, http.StatusOK, rr.Code) - }) -} diff --git a/components/central-application-gateway/internal/httperrors/httperrors.go b/components/central-application-gateway/internal/httperrors/httperrors.go deleted file mode 100644 index 3d2dfd90384a..000000000000 --- a/components/central-application-gateway/internal/httperrors/httperrors.go +++ /dev/null @@ -1,34 +0,0 @@ -package httperrors - -import ( - "net/http" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" -) - -type ErrorResponse struct { - Code int `json:"code"` - Error string `json:"error"` -} - -func errorCodeToHttpStatus(code int) int { - switch code { - case apperrors.CodeInternal: - return http.StatusInternalServerError - case apperrors.CodeNotFound: - return http.StatusNotFound - case apperrors.CodeAlreadyExists: - return http.StatusConflict - case apperrors.CodeWrongInput: - return http.StatusBadRequest - case apperrors.CodeUpstreamServerCallFailed: - return http.StatusBadGateway - default: - return http.StatusInternalServerError - } -} - -func AppErrorToResponse(appError apperrors.AppError) (status int, body ErrorResponse) { - httpCode := errorCodeToHttpStatus(appError.Code()) - return httpCode, ErrorResponse{httpCode, appError.Error()} -} diff --git a/components/central-application-gateway/internal/k8sconsts/k8sconsts.go b/components/central-application-gateway/internal/k8sconsts/k8sconsts.go deleted file mode 100644 index 557592f8b0eb..000000000000 --- a/components/central-application-gateway/internal/k8sconsts/k8sconsts.go +++ /dev/null @@ -1,7 +0,0 @@ -package k8sconsts - -const ( - LabelApplication = "app" - LabelServiceId = "serviceId" - LabelApp = "app" -) diff --git a/components/central-application-gateway/internal/metadata/applications/mocks/Manager.go b/components/central-application-gateway/internal/metadata/applications/mocks/Manager.go deleted file mode 100644 index 03752247c46e..000000000000 --- a/components/central-application-gateway/internal/metadata/applications/mocks/Manager.go +++ /dev/null @@ -1,55 +0,0 @@ -// Code generated by mockery v2.16.0. DO NOT EDIT. - -package mocks - -import ( - context "context" - - mock "github.com/stretchr/testify/mock" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - v1alpha1 "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" -) - -// Manager is an autogenerated mock type for the Manager type -type Manager struct { - mock.Mock -} - -// Get provides a mock function with given fields: ctx, name, options -func (_m *Manager) Get(ctx context.Context, name string, options v1.GetOptions) (*v1alpha1.Application, error) { - ret := _m.Called(ctx, name, options) - - var r0 *v1alpha1.Application - if rf, ok := ret.Get(0).(func(context.Context, string, v1.GetOptions) *v1alpha1.Application); ok { - r0 = rf(ctx, name, options) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*v1alpha1.Application) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(context.Context, string, v1.GetOptions) error); ok { - r1 = rf(ctx, name, options) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -type mockConstructorTestingTNewManager interface { - mock.TestingT - Cleanup(func()) -} - -// NewManager creates a new instance of Manager. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewManager(t mockConstructorTestingTNewManager) *Manager { - mock := &Manager{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/components/central-application-gateway/internal/metadata/applications/mocks/ServiceRepository.go b/components/central-application-gateway/internal/metadata/applications/mocks/ServiceRepository.go deleted file mode 100644 index f4cbccd3925e..000000000000 --- a/components/central-application-gateway/internal/metadata/applications/mocks/ServiceRepository.go +++ /dev/null @@ -1,76 +0,0 @@ -// Code generated by mockery v2.16.0. DO NOT EDIT. - -package mocks - -import ( - applications "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata/applications" - apperrors "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - - mock "github.com/stretchr/testify/mock" -) - -// ServiceRepository is an autogenerated mock type for the ServiceRepository type -type ServiceRepository struct { - mock.Mock -} - -// GetByEntryName provides a mock function with given fields: appName, serviceName, entryName -func (_m *ServiceRepository) GetByEntryName(appName string, serviceName string, entryName string) (applications.Service, apperrors.AppError) { - ret := _m.Called(appName, serviceName, entryName) - - var r0 applications.Service - if rf, ok := ret.Get(0).(func(string, string, string) applications.Service); ok { - r0 = rf(appName, serviceName, entryName) - } else { - r0 = ret.Get(0).(applications.Service) - } - - var r1 apperrors.AppError - if rf, ok := ret.Get(1).(func(string, string, string) apperrors.AppError); ok { - r1 = rf(appName, serviceName, entryName) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(apperrors.AppError) - } - } - - return r0, r1 -} - -// GetByServiceName provides a mock function with given fields: appName, serviceName -func (_m *ServiceRepository) GetByServiceName(appName string, serviceName string) (applications.Service, apperrors.AppError) { - ret := _m.Called(appName, serviceName) - - var r0 applications.Service - if rf, ok := ret.Get(0).(func(string, string) applications.Service); ok { - r0 = rf(appName, serviceName) - } else { - r0 = ret.Get(0).(applications.Service) - } - - var r1 apperrors.AppError - if rf, ok := ret.Get(1).(func(string, string) apperrors.AppError); ok { - r1 = rf(appName, serviceName) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(apperrors.AppError) - } - } - - return r0, r1 -} - -type mockConstructorTestingTNewServiceRepository interface { - mock.TestingT - Cleanup(func()) -} - -// NewServiceRepository creates a new instance of ServiceRepository. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewServiceRepository(t mockConstructorTestingTNewServiceRepository) *ServiceRepository { - mock := &ServiceRepository{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/components/central-application-gateway/internal/metadata/applications/repository.go b/components/central-application-gateway/internal/metadata/applications/repository.go deleted file mode 100644 index 5153ffc48c01..000000000000 --- a/components/central-application-gateway/internal/metadata/applications/repository.go +++ /dev/null @@ -1,187 +0,0 @@ -// Package applications contains components for accessing/modifying Application CRD -package applications - -import ( - "context" - "fmt" - "strings" - - "go.uber.org/zap" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/normalization" - k8serrors "k8s.io/apimachinery/pkg/api/errors" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" -) - -const ( - specAPIType = "API" - specEventsType = "Events" -) - -// Manager contains operations for managing Application CRD -// -//go:generate mockery --name=Manager -type Manager interface { - Get(ctx context.Context, name string, options v1.GetOptions) (*v1alpha1.Application, error) -} - -type repository struct { - appManager Manager -} - -// Credentials stores information about credentials needed to call an API -type Credentials struct { - Type string - SecretName string - URL string - CSRFTokenEndpointURL string -} - -// ServiceAPI stores information needed to call an API -type ServiceAPI struct { - TargetURL string - Credentials *Credentials - RequestParametersSecretName string - SkipVerify bool - EncodeURL bool -} - -type predicateFunc func(service v1alpha1.Service, entry v1alpha1.Entry) bool - -// Service represents a service stored in Application -type Service struct { - // Mapped to id in Application CRD - ID string - // Mapped to name in Application CRD - Name string - // Mapped to displayName in Application CRD - DisplayName string - // Mapped to longDescription in Application CRD - LongDescription string - // Mapped to providerDisplayName in Application CRD - ProviderDisplayName string - // Mapped to tags in Application CRD - Tags []string - // Mapped to type property under entries element (type: API) - API *ServiceAPI -} - -// ServiceRepository contains operations for managing services stored in Application CRD -// -//go:generate mockery --name=ServiceRepository -type ServiceRepository interface { - GetByServiceName(appName, serviceName string) (Service, apperrors.AppError) - GetByEntryName(appName, serviceName, entryName string) (Service, apperrors.AppError) -} - -// NewServiceRepository creates a new ApplicationServiceRepository -func NewServiceRepository(appManager Manager) ServiceRepository { - return &repository{appManager: appManager} -} - -// Get reads Service from Application by service name (bundle SKR mode) and apiName (entry -func (r *repository) GetByServiceName(appName, serviceName string) (Service, apperrors.AppError) { - return r.get(appName, getMatchFunction(serviceName)) -} - -func (r *repository) GetByEntryName(appName, serviceName, entryName string) (Service, apperrors.AppError) { - - matchServiceAndEntry := func(service v1alpha1.Service, entry v1alpha1.Entry) bool { - serviceMatchFunc := getMatchFunction(serviceName) - return serviceMatchFunc(service, entry) && entryName == normalization.NormalizeName(entry.Name) - } - return r.get(appName, matchServiceAndEntry) -} - -func getMatchFunction(serviceName string) predicateFunc { - return func(service v1alpha1.Service, entry v1alpha1.Entry) bool { - return serviceName == normalization.NormalizeName(service.DisplayName) && entry.Type == specAPIType - } -} - -func (r *repository) get(appName string, predicate func(service v1alpha1.Service, entry v1alpha1.Entry) bool) (Service, apperrors.AppError) { - app, err := r.getApplication(appName) - if err != nil { - return Service{}, err - } - services := make([]Service, 0) - infos := make([]string, 0) - for _, service := range app.Spec.Services { - for _, entry := range service.Entries { - if predicate(service, entry) { - services = append(services, convert(service, entry, app.Spec.SkipVerify, app.Spec.EncodeURL)) - infos = append(infos, fmt.Sprintf("service.ID: '%s', service.DisplayName: '%s', entry.Name: '%s'", service.ID, service.DisplayName, entry.Name)) - } - } - } - - if len(services) == 1 { - return services[0], nil - } else if len(services) > 1 { - return Service{}, apperrors.WrongInput("multiple services found: %s", strings.Join(infos, " | ")) - } else { - return Service{}, apperrors.NotFound("service not found") - } -} - -func (r *repository) getApplication(appName string) (*v1alpha1.Application, apperrors.AppError) { - app, err := r.appManager.Get(context.Background(), appName, v1.GetOptions{}) - if err != nil { - if k8serrors.IsNotFound(err) { - message := fmt.Sprintf("Application: %s not found.", appName) - zap.L().Warn(message, - zap.String("appName", appName)) - return nil, apperrors.NotFound(message) - } - - message := fmt.Sprintf("failed to get Application '%s' : %s", appName, err) - zap.L().Error(message, - zap.String("appName", appName), - zap.Error(err)) - return nil, apperrors.Internal(message) - } - - return app, nil -} - -func convert(service v1alpha1.Service, entry v1alpha1.Entry, skipVerify, encodeURL bool) Service { - api := &ServiceAPI{ - TargetURL: entry.TargetUrl, - Credentials: convertCredentialsFromK8sType(entry.Credentials), - RequestParametersSecretName: entry.RequestParametersSecretName, - SkipVerify: skipVerify, - EncodeURL: encodeURL, - } - - return Service{ - ID: service.ID, - Name: service.Name, - DisplayName: service.DisplayName, - LongDescription: service.LongDescription, - ProviderDisplayName: service.ProviderDisplayName, - Tags: service.Tags, - API: api, - } -} - -func convertCredentialsFromK8sType(credentials v1alpha1.Credentials) *Credentials { - emptyCredentials := v1alpha1.Credentials{} - if credentials == emptyCredentials { - return nil - } - - csrfTokenEndpointURL := "" - if credentials.CSRFInfo != nil { - csrfTokenEndpointURL = credentials.CSRFInfo.TokenEndpointURL - } - - return &Credentials{ - Type: credentials.Type, - SecretName: credentials.SecretName, - URL: credentials.AuthenticationUrl, - CSRFTokenEndpointURL: csrfTokenEndpointURL, - } -} diff --git a/components/central-application-gateway/internal/metadata/applications/repository_test.go b/components/central-application-gateway/internal/metadata/applications/repository_test.go deleted file mode 100644 index 3c98db88ec36..000000000000 --- a/components/central-application-gateway/internal/metadata/applications/repository_test.go +++ /dev/null @@ -1,296 +0,0 @@ -package applications_test - -import ( - "context" - "testing" - - "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata/applications" - "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata/applications/mocks" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func TestGetServices(t *testing.T) { - - type testFunc func(applications.ServiceRepository) (applications.Service, apperrors.AppError) - - type testcase struct { - description string - application *v1alpha1.Application - testFunc testFunc - expectedServiceAPI applications.ServiceAPI - } - - expectedServiceAPI := applications.ServiceAPI{ - TargetURL: "https://192.168.1.2", - SkipVerify: false, - Credentials: &applications.Credentials{ - Type: "OAuth", - SecretName: "SecretName", - URL: "www.example.com/token", - }, - } - - expectedServiceAPISkipVerify := applications.ServiceAPI{ - TargetURL: "https://192.168.1.2", - SkipVerify: true, - Credentials: &applications.Credentials{ - Type: "OAuth", - SecretName: "SecretName", - URL: "www.example.com/token", - }, - } - - for _, testCase := range []testcase{ - { - description: "should get service by service name", - application: createApplication("production", false), - testFunc: func(repository applications.ServiceRepository) (applications.Service, apperrors.AppError) { - return repository.GetByServiceName("production", "service-1") - }, - expectedServiceAPI: expectedServiceAPI, - }, - { - description: "should get service by service and entry name", - application: createApplication("production", false), - testFunc: func(repository applications.ServiceRepository) (applications.Service, apperrors.AppError) { - return repository.GetByEntryName("production", "service-1", "service-entry-1") - }, - expectedServiceAPI: expectedServiceAPI, - }, - { - description: "should get service by service name in no-TLS verification mode", - application: createApplication("production", true), - testFunc: func(repository applications.ServiceRepository) (applications.Service, apperrors.AppError) { - return repository.GetByServiceName("production", "service-1") - }, - expectedServiceAPI: expectedServiceAPISkipVerify, - }, - { - description: "should get service by service and entry name in no-TLS verification mode", - application: createApplication("production", true), - testFunc: func(repository applications.ServiceRepository) (applications.Service, apperrors.AppError) { - return repository.GetByEntryName("production", "service-1", "service-entry-1") - }, - expectedServiceAPI: expectedServiceAPISkipVerify, - }, - } { - t.Run(testCase.description, func(t *testing.T) { - // given - managerMock := &mocks.Manager{} - managerMock.On("Get", context.Background(), "production", metav1.GetOptions{}). - Return(testCase.application, nil) - - repository := applications.NewServiceRepository(managerMock) - require.NotNil(t, repository) - - // when - service, err := testCase.testFunc(repository) - - // then - require.NotNil(t, service) - require.NoError(t, err) - - assert.Equal(t, service.ProviderDisplayName, "SAP Hybris") - assert.Equal(t, service.DisplayName, "Service 1") - assert.Equal(t, service.LongDescription, "This is Orders API") - assert.Equal(t, service.API, &testCase.expectedServiceAPI) - }) - } - - for _, testCase := range []testcase{ - { - description: "should return not found error if service doesn't exist", - application: createApplication("production", false), - testFunc: func(repository applications.ServiceRepository) (applications.Service, apperrors.AppError) { - return repository.GetByServiceName("production", "not-exists") - }, - }, - { - description: "should return not found error if service doesn't exist", - application: createApplication("production", false), - testFunc: func(repository applications.ServiceRepository) (applications.Service, apperrors.AppError) { - return repository.GetByEntryName("production", "not-exists", "service-entry-1") - }, - expectedServiceAPI: expectedServiceAPI, - }, - { - description: "should return not found error if service entry doesn't exist", - application: createApplication("production", false), - testFunc: func(repository applications.ServiceRepository) (applications.Service, apperrors.AppError) { - return repository.GetByEntryName("production", "service-1", "not-exists") - }, - expectedServiceAPI: expectedServiceAPI, - }, - } { - t.Run("should return not found error if service doesn't exist", func(t *testing.T) { - // given - managerMock := &mocks.Manager{} - managerMock.On("Get", context.Background(), "production", metav1.GetOptions{}). - Return(testCase.application, nil) - - repository := applications.NewServiceRepository(managerMock) - require.NotNil(t, repository) - - // when - service, err := testCase.testFunc(repository) - - // then - assert.Equal(t, applications.Service{}, service) - assert.Equal(t, apperrors.CodeNotFound, err.Code()) - }) - } - - for _, testCase := range []testcase{ - - { - description: "should return bad request error if service has multiple entries with the same names", - application: createApplication("production", false), - testFunc: func(repository applications.ServiceRepository) (applications.Service, apperrors.AppError) { - return repository.GetByEntryName("production", "service-3", "service-entry-duplicate") - }, - }, - { - description: "should return bad request error if there are multiple services with the same name", - application: createApplication("production", false), - testFunc: func(repository applications.ServiceRepository) (applications.Service, apperrors.AppError) { - return repository.GetByServiceName("production", "service-4") - }, - }, - } { - t.Run("should return bad request error if multiple services were found", func(t *testing.T) { - // given - managerMock := &mocks.Manager{} - managerMock.On("Get", context.Background(), "production", metav1.GetOptions{}). - Return(testCase.application, nil) - - repository := applications.NewServiceRepository(managerMock) - require.NotNil(t, repository) - - // when - service, err := testCase.testFunc(repository) - - // then - assert.Equal(t, applications.Service{}, service) - assert.Equal(t, apperrors.CodeWrongInput, err.Code()) - }) - } - -} - -func createApplication(name string, skipVerify bool) *v1alpha1.Application { - - service1Entry := v1alpha1.Entry{ - Type: "API", - Name: "Service entry 1", - TargetUrl: "https://192.168.1.2", - Credentials: v1alpha1.Credentials{ - Type: "OAuth", - SecretName: "SecretName", - AuthenticationUrl: "www.example.com/token", - }, - } - service1 := v1alpha1.Service{ - ID: "id1", - Name: "service-1", - DisplayName: "Service 1", - LongDescription: "This is Orders API", - ProviderDisplayName: "SAP Hybris", - Tags: []string{"orders"}, - Entries: []v1alpha1.Entry{service1Entry}, - } - - service2Entry := v1alpha1.Entry{ - Type: "API", - TargetUrl: "https://192.168.1.3", - Credentials: v1alpha1.Credentials{ - Type: "OAuth", - SecretName: "SecretName", - AuthenticationUrl: "www.example.com/token", - }, - } - - service2 := v1alpha1.Service{ - ID: "id2", - DisplayName: "Products API", - LongDescription: "This is Products API", - ProviderDisplayName: "SAP Hybris", - Tags: []string{"products"}, - Entries: []v1alpha1.Entry{service2Entry}, - } - - service3Entry1 := v1alpha1.Entry{ - Name: "Service entry duplicate", - Type: "API", - TargetUrl: "https://192.168.1.3", - Credentials: v1alpha1.Credentials{ - Type: "OAuth", - SecretName: "SecretName", - AuthenticationUrl: "www.example.com/token", - }, - } - - service3Entry2 := v1alpha1.Entry{ - Name: "Service entry duplicate", - Type: "API", - TargetUrl: "https://192.168.1.3", - Credentials: v1alpha1.Credentials{ - Type: "OAuth", - SecretName: "SecretName", - AuthenticationUrl: "www.example.com/token", - }, - } - service3Entry3 := v1alpha1.Entry{ - Name: "Service entry 3", - Type: "API", - TargetUrl: "https://192.168.1.3", - Credentials: v1alpha1.Credentials{ - Type: "OAuth", - SecretName: "SecretName", - AuthenticationUrl: "www.example.com/token", - }, - } - - service3 := v1alpha1.Service{ - Name: "service-3", - DisplayName: "Service 3", - Entries: []v1alpha1.Entry{service3Entry1, service3Entry2, service3Entry3}, - } - - service4Entry := v1alpha1.Entry{ - Name: "Service entry 4", - Type: "API", - TargetUrl: "https://192.168.1.3", - Credentials: v1alpha1.Credentials{ - Type: "OAuth", - SecretName: "SecretName", - AuthenticationUrl: "www.example.com/token", - }, - } - service4 := v1alpha1.Service{ - Name: "service-4", - DisplayName: "Service 4", - Entries: []v1alpha1.Entry{service4Entry}, - } - - spec1 := v1alpha1.ApplicationSpec{ - Description: "test_1", - SkipVerify: skipVerify, - Services: []v1alpha1.Service{ - service1, - service2, - service3, - // duplicate services - service4, - service4, - }, - } - - return &v1alpha1.Application{ - ObjectMeta: metav1.ObjectMeta{Name: name}, - Spec: spec1, - } -} diff --git a/components/central-application-gateway/internal/metadata/mocks/ServiceDefinitionService.go b/components/central-application-gateway/internal/metadata/mocks/ServiceDefinitionService.go deleted file mode 100644 index d5318ca0d85a..000000000000 --- a/components/central-application-gateway/internal/metadata/mocks/ServiceDefinitionService.go +++ /dev/null @@ -1,63 +0,0 @@ -// Code generated by mockery v1.0.0. DO NOT EDIT. - -package mocks - -import apperrors "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - -import mock "github.com/stretchr/testify/mock" -import model "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata/model" - -// ServiceDefinitionService is an autogenerated mock type for the ServiceDefinitionService type -type ServiceDefinitionService struct { - mock.Mock -} - -// GetAPIByEntryName provides a mock function with given fields: appName, serviceName, entryName -func (_m *ServiceDefinitionService) GetAPIByEntryName(appName string, serviceName string, entryName string) (*model.API, apperrors.AppError) { - ret := _m.Called(appName, serviceName, entryName) - - var r0 *model.API - if rf, ok := ret.Get(0).(func(string, string, string) *model.API); ok { - r0 = rf(appName, serviceName, entryName) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*model.API) - } - } - - var r1 apperrors.AppError - if rf, ok := ret.Get(1).(func(string, string, string) apperrors.AppError); ok { - r1 = rf(appName, serviceName, entryName) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(apperrors.AppError) - } - } - - return r0, r1 -} - -// GetAPIByServiceName provides a mock function with given fields: appName, serviceName -func (_m *ServiceDefinitionService) GetAPIByServiceName(appName string, serviceName string) (*model.API, apperrors.AppError) { - ret := _m.Called(appName, serviceName) - - var r0 *model.API - if rf, ok := ret.Get(0).(func(string, string) *model.API); ok { - r0 = rf(appName, serviceName) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*model.API) - } - } - - var r1 apperrors.AppError - if rf, ok := ret.Get(1).(func(string, string) apperrors.AppError); ok { - r1 = rf(appName, serviceName) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(apperrors.AppError) - } - } - - return r0, r1 -} diff --git a/components/central-application-gateway/internal/metadata/model/model.go b/components/central-application-gateway/internal/metadata/model/model.go deleted file mode 100644 index 282d87a57203..000000000000 --- a/components/central-application-gateway/internal/metadata/model/model.go +++ /dev/null @@ -1,50 +0,0 @@ -package model - -import "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization" - -// ServiceDefinition is an internal representation of a service. -type ServiceDefinition struct { - // ID of service - ID string - // Name of a service - Name string - // Provider of a service - Provider string - // Description of a service - Description string - // Api of a service - Api *API - // Events of a service - Events *Events - // Documentation of service - Documentation []byte -} - -// API is an internal representation of a service's API. -type API struct { - // TargetUrl points to API. - TargetUrl string - // Credentials is a credentials of API. - Credentials *authorization.Credentials - // Spec contains specification of an API. - Spec []byte - // RequestParameters will be used with request send by the Application Gateway - RequestParameters *authorization.RequestParameters - // skipVerify is flag set on Application CRD - SkipVerify bool - // encodeUrl is flag set on Application CRD - EncodeUrl bool -} - -// Events contains specification for events. -type Events struct { - // Spec contains data of events specification. - Spec []byte -} - -// API key -type APIIdentifier struct { - Application string - Service string - Entry string -} diff --git a/components/central-application-gateway/internal/metadata/secrets/mocks/Manager.go b/components/central-application-gateway/internal/metadata/secrets/mocks/Manager.go deleted file mode 100644 index 38c61cbdee94..000000000000 --- a/components/central-application-gateway/internal/metadata/secrets/mocks/Manager.go +++ /dev/null @@ -1,56 +0,0 @@ -// Code generated by mockery v2.16.0. DO NOT EDIT. - -package mocks - -import ( - context "context" - - corev1 "k8s.io/api/core/v1" - - mock "github.com/stretchr/testify/mock" - - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// Manager is an autogenerated mock type for the Manager type -type Manager struct { - mock.Mock -} - -// Get provides a mock function with given fields: ctx, name, options -func (_m *Manager) Get(ctx context.Context, name string, options v1.GetOptions) (*corev1.Secret, error) { - ret := _m.Called(ctx, name, options) - - var r0 *corev1.Secret - if rf, ok := ret.Get(0).(func(context.Context, string, v1.GetOptions) *corev1.Secret); ok { - r0 = rf(ctx, name, options) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*corev1.Secret) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(context.Context, string, v1.GetOptions) error); ok { - r1 = rf(ctx, name, options) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -type mockConstructorTestingTNewManager interface { - mock.TestingT - Cleanup(func()) -} - -// NewManager creates a new instance of Manager. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewManager(t mockConstructorTestingTNewManager) *Manager { - mock := &Manager{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/components/central-application-gateway/internal/metadata/secrets/mocks/Repository.go b/components/central-application-gateway/internal/metadata/secrets/mocks/Repository.go deleted file mode 100644 index 9f140206d5e2..000000000000 --- a/components/central-application-gateway/internal/metadata/secrets/mocks/Repository.go +++ /dev/null @@ -1,53 +0,0 @@ -// Code generated by mockery v2.16.0. DO NOT EDIT. - -package mocks - -import ( - apperrors "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - mock "github.com/stretchr/testify/mock" -) - -// Repository is an autogenerated mock type for the Repository type -type Repository struct { - mock.Mock -} - -// Get provides a mock function with given fields: name -func (_m *Repository) Get(name string) (map[string][]byte, apperrors.AppError) { - ret := _m.Called(name) - - var r0 map[string][]byte - if rf, ok := ret.Get(0).(func(string) map[string][]byte); ok { - r0 = rf(name) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(map[string][]byte) - } - } - - var r1 apperrors.AppError - if rf, ok := ret.Get(1).(func(string) apperrors.AppError); ok { - r1 = rf(name) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(apperrors.AppError) - } - } - - return r0, r1 -} - -type mockConstructorTestingTNewRepository interface { - mock.TestingT - Cleanup(func()) -} - -// NewRepository creates a new instance of Repository. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewRepository(t mockConstructorTestingTNewRepository) *Repository { - mock := &Repository{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/components/central-application-gateway/internal/metadata/secrets/repository.go b/components/central-application-gateway/internal/metadata/secrets/repository.go deleted file mode 100644 index 9a014f865482..000000000000 --- a/components/central-application-gateway/internal/metadata/secrets/repository.go +++ /dev/null @@ -1,54 +0,0 @@ -// Package secrets contains components for accessing/modifying client secrets -package secrets - -import ( - "context" - - "go.uber.org/zap" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - v1 "k8s.io/api/core/v1" - k8serrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// Repository contains operations for managing client credentials -// -//go:generate mockery --name=Repository -type Repository interface { - Get(name string) (map[string][]byte, apperrors.AppError) -} - -type repository struct { - secretsManager Manager - application string -} - -// Manager contains operations for managing k8s secrets -// -//go:generate mockery --name=Manager -type Manager interface { - Get(ctx context.Context, name string, options metav1.GetOptions) (*v1.Secret, error) -} - -// NewRepository creates a new secrets repository -func NewRepository(secretsManager Manager) Repository { - return &repository{ - secretsManager: secretsManager, - } -} - -func (r *repository) Get(name string) (map[string][]byte, apperrors.AppError) { - secret, err := r.secretsManager.Get(context.Background(), name, metav1.GetOptions{}) - if err != nil { - zap.L().Error("failed to read secret", - zap.String("secretName", name), - zap.Error(err)) - if k8serrors.IsNotFound(err) { - return nil, apperrors.NotFound("secret '%s' not found", name) - } - return nil, apperrors.Internal("failed to get '%s' secret, %s", name, err) - } - - return secret.Data, nil -} diff --git a/components/central-application-gateway/internal/metadata/secrets/repository_test.go b/components/central-application-gateway/internal/metadata/secrets/repository_test.go deleted file mode 100644 index fd2c448d7866..000000000000 --- a/components/central-application-gateway/internal/metadata/secrets/repository_test.go +++ /dev/null @@ -1,97 +0,0 @@ -package secrets - -import ( - "context" - "errors" - "testing" - - "github.com/kyma-project/kyma/components/central-application-gateway/internal/k8sconsts" - "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata/secrets/mocks" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - "github.com/stretchr/testify/assert" - v1 "k8s.io/api/core/v1" - k8serrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -func TestRepository_Get(t *testing.T) { - t.Run("should get given secret", func(t *testing.T) { - // given - secretsManagerMock := &mocks.Manager{} - repository := NewRepository(secretsManagerMock) - - secret := makeSecret("new-secret", "CLIENT_ID", "CLIENT_SECRET", "secretId", "default-ec") - secretsManagerMock.On("Get", context.Background(), "new-secret", metav1.GetOptions{}).Return(secret, nil) - - // when - secrets, err := repository.Get("new-secret") - - // then - assert.NoError(t, err) - assert.NotNil(t, secrets["clientId"]) - assert.NotNil(t, secrets["clientSecret"]) - - secretsManagerMock.AssertExpectations(t) - }) - - t.Run("should return an error in case fetching fails", func(t *testing.T) { - // given - secretsManagerMock := &mocks.Manager{} - repository := NewRepository(secretsManagerMock) - - secretsManagerMock.On("Get", context.Background(), "secret-name", metav1.GetOptions{}).Return( - nil, - errors.New("some error")) - - // when - cacheData, err := repository.Get("secret-name") - - // then - assert.Error(t, err) - assert.Equal(t, apperrors.CodeInternal, err.Code()) - assert.NotEmpty(t, err.Error()) - assert.Nil(t, cacheData) - - secretsManagerMock.AssertExpectations(t) - }) - - t.Run("should return not found if secret does not exist", func(t *testing.T) { - // given - secretsManagerMock := &mocks.Manager{} - repository := NewRepository(secretsManagerMock) - - secretsManagerMock.On("Get", context.Background(), "secret-name", metav1.GetOptions{}).Return( - nil, - k8serrors.NewNotFound(schema.GroupResource{}, - "")) - - // when - secrets, err := repository.Get("secret-name") - - // then - assert.Error(t, err) - assert.Equal(t, apperrors.CodeNotFound, err.Code()) - assert.NotEmpty(t, err.Error()) - - assert.Nil(t, secrets) - secretsManagerMock.AssertExpectations(t) - }) -} - -func makeSecret(name, clientID, clientSecret, serviceID, application string) *v1.Secret { - secretMap := make(map[string][]byte) - secretMap["clientId"] = []byte(clientID) - secretMap["clientSecret"] = []byte(clientSecret) - - return &v1.Secret{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - Labels: map[string]string{ - k8sconsts.LabelApplication: application, - k8sconsts.LabelServiceId: serviceID, - }, - }, - Data: secretMap, - } -} diff --git a/components/central-application-gateway/internal/metadata/serviceapi/mocks/Service.go b/components/central-application-gateway/internal/metadata/serviceapi/mocks/Service.go deleted file mode 100644 index 1effaa16f7be..000000000000 --- a/components/central-application-gateway/internal/metadata/serviceapi/mocks/Service.go +++ /dev/null @@ -1,42 +0,0 @@ -// Code generated by mockery v1.0.0. DO NOT EDIT. - -package mocks - -import ( - applications "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata/applications" - apperrors "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - - mock "github.com/stretchr/testify/mock" - - model "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata/model" -) - -// Service is an autogenerated mock type for the Service type -type Service struct { - mock.Mock -} - -// Read provides a mock function with given fields: _a0 -func (_m *Service) Read(_a0 *applications.ServiceAPI) (*model.API, apperrors.AppError) { - ret := _m.Called(_a0) - - var r0 *model.API - if rf, ok := ret.Get(0).(func(*applications.ServiceAPI) *model.API); ok { - r0 = rf(_a0) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*model.API) - } - } - - var r1 apperrors.AppError - if rf, ok := ret.Get(1).(func(*applications.ServiceAPI) apperrors.AppError); ok { - r1 = rf(_a0) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(apperrors.AppError) - } - } - - return r0, r1 -} diff --git a/components/central-application-gateway/internal/metadata/serviceapi/serviceapiservice.go b/components/central-application-gateway/internal/metadata/serviceapi/serviceapiservice.go deleted file mode 100644 index d7e2741e64fd..000000000000 --- a/components/central-application-gateway/internal/metadata/serviceapi/serviceapiservice.go +++ /dev/null @@ -1,198 +0,0 @@ -package serviceapi - -import ( - "encoding/json" - - "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata/applications" - "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata/model" - "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata/secrets" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization" -) - -const ( - ClientIDKey = "clientId" - ClientSecretKey = "clientSecret" - UsernameKey = "username" - PasswordKey = "password" - TypeOAuth = "OAuth" - TypeOAuthWithCert = "OAuthWithCert" - TypeBasic = "Basic" - TypeCertificateGen = "CertificateGen" - PrivateKeyKey = "key" - CertificateKey = "crt" - - HeadersKey = "headers" - QueryParametersKey = "queryParameters" -) - -// Service manages API definition of a service -type Service interface { - // Read reads API from Application API definition. It also reads all additional information. - Read(*applications.ServiceAPI) (*model.API, apperrors.AppError) -} - -type defaultService struct { - secretsRepository secrets.Repository -} - -func NewService(secretsRepository secrets.Repository) Service { - - return defaultService{ - secretsRepository: secretsRepository, - } -} - -func (sas defaultService) Read(applicationAPI *applications.ServiceAPI) (*model.API, apperrors.AppError) { - api := &model.API{ - TargetUrl: applicationAPI.TargetURL, - SkipVerify: applicationAPI.SkipVerify, - EncodeUrl: applicationAPI.EncodeURL, - } - - if applicationAPI.Credentials != nil { - credentialsSecretName := applicationAPI.Credentials.SecretName - - secret, err := sas.secretsRepository.Get(credentialsSecretName) - if err != nil { - return nil, err - } - - api.Credentials, err = sas.readCredentials(secret, applicationAPI) - if err != nil { - return nil, err - } - } - - if applicationAPI.RequestParametersSecretName != "" { - secret, err := sas.secretsRepository.Get(applicationAPI.RequestParametersSecretName) - if err != nil { - return nil, err - } - - requestParameters, err := getRequestParameters(secret) - if err != nil { - return nil, err - } - - api.RequestParameters = requestParameters - } - - return api, nil -} - -func (sas defaultService) readCredentials(secret map[string][]byte, applicationAPI *applications.ServiceAPI) (*authorization.Credentials, apperrors.AppError) { - var credentials *authorization.Credentials - - credentialsType := applicationAPI.Credentials.Type - - if credentialsType == TypeOAuth { - oAuthCredentials, err := getOAuthCredentials(secret, applicationAPI.Credentials.URL) - if err != nil { - return nil, err - } - credentials = &authorization.Credentials{ - OAuth: oAuthCredentials, - } - } else if credentialsType == TypeOAuthWithCert { - oAuthWithCredentials, err := getOAuthWithCertCredentials(secret, applicationAPI.Credentials.URL) - if err != nil { - return nil, err - } - credentials = &authorization.Credentials{ - OAuthWithCert: oAuthWithCredentials, - } - } else if credentialsType == TypeBasic { - credentials = &authorization.Credentials{ - BasicAuth: getBasicAuthCredentials(secret), - } - } else if credentialsType == TypeCertificateGen { - credentials = &authorization.Credentials{ - CertificateGen: getCertificateGenCredentials(secret), - } - } else { - credentials = nil - } - - if credentials != nil { - credentials.CSRFTokenEndpointURL = applicationAPI.Credentials.CSRFTokenEndpointURL - } - - return credentials, nil -} - -func getRequestParameters(secret map[string][]byte) (*authorization.RequestParameters, apperrors.AppError) { - requestParameters := &authorization.RequestParameters{} - - headersData := secret[HeadersKey] - if headersData != nil { - var headers = &map[string][]string{} - err := json.Unmarshal(headersData, headers) - if err != nil { - return nil, apperrors.Internal("Failed to unmarshal headers, %s", err.Error()) - } - - requestParameters.Headers = headers - } - - queryParamsData := secret[QueryParametersKey] - if queryParamsData != nil { - var queryParameters = &map[string][]string{} - err := json.Unmarshal(queryParamsData, queryParameters) - if err != nil { - return nil, apperrors.Internal("Failed to unmarshal query parameters, %s", err.Error()) - } - - requestParameters.QueryParameters = queryParameters - } - - if requestParameters.Headers == nil && requestParameters.QueryParameters == nil { - return nil, nil - } - - return requestParameters, nil -} - -func getOAuthCredentials(secret map[string][]byte, url string) (*authorization.OAuth, apperrors.AppError) { - requestParameters, err := getRequestParameters(secret) - if err != nil { - return nil, err - } - - return &authorization.OAuth{ - ClientID: string(secret[ClientIDKey]), - ClientSecret: string(secret[ClientSecretKey]), - URL: url, - RequestParameters: requestParameters, - }, nil -} - -func getOAuthWithCertCredentials(secret map[string][]byte, url string) (*authorization.OAuthWithCert, apperrors.AppError) { - requestParameters, err := getRequestParameters(secret) - if err != nil { - return nil, err - } - - return &authorization.OAuthWithCert{ - ClientID: string(secret[ClientIDKey]), - ClientSecret: string(secret[ClientSecretKey]), - Certificate: secret[CertificateKey], - PrivateKey: secret[PrivateKeyKey], - URL: url, - RequestParameters: requestParameters, - }, nil -} - -func getBasicAuthCredentials(secret map[string][]byte) *authorization.BasicAuth { - return &authorization.BasicAuth{ - Username: string(secret[UsernameKey]), - Password: string(secret[PasswordKey]), - } -} - -func getCertificateGenCredentials(secret map[string][]byte) *authorization.CertificateGen { - return &authorization.CertificateGen{ - Certificate: secret[CertificateKey], - PrivateKey: secret[PrivateKeyKey], - } -} diff --git a/components/central-application-gateway/internal/metadata/serviceapi/serviceapiservice_test.go b/components/central-application-gateway/internal/metadata/serviceapi/serviceapiservice_test.go deleted file mode 100644 index 49855daa2c8a..000000000000 --- a/components/central-application-gateway/internal/metadata/serviceapi/serviceapiservice_test.go +++ /dev/null @@ -1,288 +0,0 @@ -package serviceapi - -import ( - "testing" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization" - - "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata/model" - - secretsmocks "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata/secrets/mocks" - - "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata/applications" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - "github.com/stretchr/testify/assert" -) - -const ( - targetUrl = "http://target.com" - clientId = "clientId" - clientSecret = "clientSecret" - oauthUrl = "http://oauth.com" - secretName = "credentialsSecret-name" - username = "username" - password = "password" -) - -var ( - certificate = []byte("certificate") - privateKey = []byte("privateKey") -) - -func TestDefaultService_Read(t *testing.T) { - testCases := []struct { - description string - applicationAPI *applications.ServiceAPI - credentialsSecret map[string][]byte - requestParamsSecretName string - requestParamsSecret map[string][]byte - resultingAPI *model.API - }{ - { - description: "api with oauth credentials", - applicationAPI: &applications.ServiceAPI{ - TargetURL: targetUrl, - Credentials: &applications.Credentials{ - Type: TypeOAuth, - SecretName: secretName, - URL: oauthUrl, - }, - }, - credentialsSecret: map[string][]byte{ - ClientIDKey: []byte(clientId), - ClientSecretKey: []byte(clientSecret), - }, - resultingAPI: &model.API{ - TargetUrl: targetUrl, - Credentials: &authorization.Credentials{ - OAuth: &authorization.OAuth{ - ClientID: clientId, - ClientSecret: clientSecret, - URL: oauthUrl, - }, - }, - }, - }, - { - description: "api with oauth with certificate credentials", - applicationAPI: &applications.ServiceAPI{ - TargetURL: targetUrl, - Credentials: &applications.Credentials{ - Type: TypeOAuthWithCert, - SecretName: secretName, - URL: oauthUrl, - }, - }, - credentialsSecret: map[string][]byte{ - ClientIDKey: []byte(clientId), - CertificateKey: certificate, - PrivateKeyKey: privateKey, - }, - resultingAPI: &model.API{ - TargetUrl: targetUrl, - Credentials: &authorization.Credentials{ - OAuthWithCert: &authorization.OAuthWithCert{ - ClientID: clientId, - Certificate: certificate, - PrivateKey: privateKey, - URL: oauthUrl, - }, - }, - }, - }, - { - description: "api with basic auth credentials", - applicationAPI: &applications.ServiceAPI{ - TargetURL: targetUrl, - Credentials: &applications.Credentials{ - Type: TypeBasic, - SecretName: secretName, - URL: "", - }, - }, - credentialsSecret: map[string][]byte{ - UsernameKey: []byte(username), - PasswordKey: []byte(password), - }, - resultingAPI: &model.API{ - TargetUrl: targetUrl, - Credentials: &authorization.Credentials{ - BasicAuth: &authorization.BasicAuth{ - Username: username, - Password: password, - }, - }, - }, - }, - { - description: "api with certificate gen credentials", - applicationAPI: &applications.ServiceAPI{ - TargetURL: targetUrl, - Credentials: &applications.Credentials{ - Type: TypeCertificateGen, - SecretName: secretName, - URL: "", - }, - }, - credentialsSecret: map[string][]byte{ - CertificateKey: certificate, - PrivateKeyKey: privateKey, - }, - resultingAPI: &model.API{ - TargetUrl: targetUrl, - Credentials: &authorization.Credentials{ - CertificateGen: &authorization.CertificateGen{ - Certificate: certificate, - PrivateKey: privateKey, - }, - }, - }, - }, - { - description: "api without credentials", - applicationAPI: &applications.ServiceAPI{ - TargetURL: targetUrl, - }, - credentialsSecret: map[string][]byte{}, - resultingAPI: &model.API{ - TargetUrl: targetUrl, - }, - }, - { - description: "api with headers and query parameters", - applicationAPI: &applications.ServiceAPI{ - TargetURL: targetUrl, - RequestParametersSecretName: "params-secret", - }, - credentialsSecret: map[string][]byte{}, - requestParamsSecretName: "params-secret", - requestParamsSecret: map[string][]byte{ - HeadersKey: []byte(`{"header":["headerValue"]}`), - QueryParametersKey: []byte(`{"query":["queryValue"]}`), - }, - resultingAPI: &model.API{ - TargetUrl: targetUrl, - RequestParameters: &authorization.RequestParameters{ - Headers: &map[string][]string{ - "header": {"headerValue"}, - }, - QueryParameters: &map[string][]string{ - "query": {"queryValue"}, - }, - }, - }, - }, - { - description: "api with query parameters only", - applicationAPI: &applications.ServiceAPI{ - TargetURL: targetUrl, - RequestParametersSecretName: "params-secret", - }, - credentialsSecret: map[string][]byte{}, - requestParamsSecretName: "params-secret", - requestParamsSecret: map[string][]byte{ - QueryParametersKey: []byte(`{"query":["queryValue"]}`), - }, - resultingAPI: &model.API{ - TargetUrl: targetUrl, - RequestParameters: &authorization.RequestParameters{ - QueryParameters: &map[string][]string{ - "query": {"queryValue"}, - }, - }, - }, - }, - { - description: "api with headers only", - applicationAPI: &applications.ServiceAPI{ - TargetURL: targetUrl, - RequestParametersSecretName: "params-secret", - }, - credentialsSecret: map[string][]byte{}, - requestParamsSecretName: "params-secret", - requestParamsSecret: map[string][]byte{ - HeadersKey: []byte(`{"header":["headerValue"]}`), - }, - resultingAPI: &model.API{ - TargetUrl: targetUrl, - RequestParameters: &authorization.RequestParameters{ - Headers: &map[string][]string{ - "header": {"headerValue"}, - }, - }, - }, - }, - } - - for _, test := range testCases { - t.Run("should read "+test.description, func(t *testing.T) { - // given - secretsRepository := new(secretsmocks.Repository) - secretsRepository.On("Get", secretName).Return(test.credentialsSecret, nil) - if test.requestParamsSecretName != "" { - secretsRepository.On("Get", test.requestParamsSecretName).Return(test.requestParamsSecret, nil) - } - - service := NewService(secretsRepository) - - // when - api, err := service.Read(test.applicationAPI) - - // then - assert.NoError(t, err) - assert.Equal(t, test.resultingAPI, api) - }) - } - - t.Run("should return error when reading credentialsSecret fails", func(t *testing.T) { - // given - applicationServiceAPI := &applications.ServiceAPI{ - TargetURL: "http://target.com", - Credentials: &applications.Credentials{ - Type: "OAuth", - SecretName: "credentialsSecret-name", - URL: "http://oauth.com", - }, - } - - secretsRepository := new(secretsmocks.Repository) - secretsRepository.On("Get", "credentialsSecret-name"). - Return(nil, apperrors.Internal("credentialsSecret error")) - - service := NewService(secretsRepository) - - // when - api, err := service.Read(applicationServiceAPI) - - // then - assert.Error(t, err) - assert.Nil(t, api) - assert.Contains(t, err.Error(), "credentialsSecret error") - - secretsRepository.AssertExpectations(t) - }) - - t.Run("should return error when reading request parameters fails", func(t *testing.T) { - // given - applicationServiceAPI := &applications.ServiceAPI{ - TargetURL: "http://target.com", - RequestParametersSecretName: secretName, - } - - secretsRepository := new(secretsmocks.Repository) - secretsRepository.On("Get", secretName). - Return(nil, apperrors.Internal("request params error")) - - service := NewService(secretsRepository) - - // when - api, err := service.Read(applicationServiceAPI) - - // then - assert.Error(t, err) - assert.Nil(t, api) - assert.Contains(t, err.Error(), "request params error") - - secretsRepository.AssertExpectations(t) - }) -} diff --git a/components/central-application-gateway/internal/metadata/servicedefservice.go b/components/central-application-gateway/internal/metadata/servicedefservice.go deleted file mode 100644 index 3fecd9c66aef..000000000000 --- a/components/central-application-gateway/internal/metadata/servicedefservice.go +++ /dev/null @@ -1,90 +0,0 @@ -// Package metadata contains components for accessing Kyma Application -package metadata - -import ( - "fmt" - - "go.uber.org/zap" - - "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata/applications" - "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata/model" - "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata/serviceapi" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" -) - -// ServiceDefinitionService is a service that manages ServiceDefinition objects. -// -//go:generate mockery -name=ServiceDefinitionService -type ServiceDefinitionService interface { - // GetAPI gets API of a service with given ID - GetAPIByServiceName(appName, serviceName string) (*model.API, apperrors.AppError) - GetAPIByEntryName(appName, serviceName, entryName string) (*model.API, apperrors.AppError) -} - -type serviceDefinitionService struct { - serviceAPIService serviceapi.Service - applicationRepository applications.ServiceRepository -} - -// NewServiceDefinitionService creates new ServiceDefinitionService with provided dependencies. -func NewServiceDefinitionService(serviceAPIService serviceapi.Service, applicationRepository applications.ServiceRepository) ServiceDefinitionService { - return &serviceDefinitionService{ - serviceAPIService: serviceAPIService, - applicationRepository: applicationRepository, - } -} - -// GetAPI gets API of a service with given name -func (sds *serviceDefinitionService) GetAPIByServiceName(appName, serviceName string) (*model.API, apperrors.AppError) { - service, err := sds.applicationRepository.GetByServiceName(appName, serviceName) - - if err != nil { - notFoundMessage := fmt.Sprintf("service with name %s not found", serviceName) - internalErrMessage := fmt.Sprintf("failed to get service with name '%s': %s", serviceName, err.Error()) - - return nil, handleError(err, notFoundMessage, internalErrMessage) - } - - return sds.getAPI(service) -} - -func (sds *serviceDefinitionService) GetAPIByEntryName(appName, serviceName, entryName string) (*model.API, apperrors.AppError) { - service, err := sds.applicationRepository.GetByEntryName(appName, serviceName, entryName) - - if err != nil { - notFoundMessage := fmt.Sprintf("service with name %s and entry name %s not found", serviceName, entryName) - internalErrMessage := fmt.Sprintf("failed to get service with name '%s' and entry name '%s': %s", serviceName, entryName, err.Error()) - - return nil, handleError(err, notFoundMessage, internalErrMessage) - } - - return sds.getAPI(service) -} - -func (sds *serviceDefinitionService) getAPI(service applications.Service) (*model.API, apperrors.AppError) { - - if service.API == nil { - return nil, apperrors.WrongInput("service '%s' has no API", service.Name) - } - - api, err := sds.serviceAPIService.Read(service.API) - if err != nil { - zap.L().Error("failed to read api for serviceID", - zap.String("serviceID", service.Name), - zap.Error(err)) - return nil, apperrors.Internal("failed to read API for %s service, %s", service.Name, err) - } - return api, nil -} - -func handleError(err apperrors.AppError, notFoundMessage, internalErrorMEssage string) apperrors.AppError { - if err.Code() == apperrors.CodeNotFound { - return apperrors.NotFound(notFoundMessage) - } - zap.L().Error(internalErrorMEssage) - - if err.Code() == apperrors.CodeWrongInput { - return apperrors.WrongInput(internalErrorMEssage) - } - return apperrors.Internal(internalErrorMEssage) -} diff --git a/components/central-application-gateway/internal/metadata/servicedefservice_test.go b/components/central-application-gateway/internal/metadata/servicedefservice_test.go deleted file mode 100644 index 7f5256505da0..000000000000 --- a/components/central-application-gateway/internal/metadata/servicedefservice_test.go +++ /dev/null @@ -1,223 +0,0 @@ -package metadata - -import ( - "testing" - - "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata/applications" - applicationmocks "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata/applications/mocks" - "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata/model" - serviceapimocks "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata/serviceapi/mocks" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestServiceDefinitionService_GetAPI(t *testing.T) { - - type testFunc func(ServiceDefinitionService) (*model.API, apperrors.AppError) - type getRepositoryMockFunction func() *applicationmocks.ServiceRepository - - type testcase struct { - description string - application *v1alpha1.Application - testFunc testFunc - getRepositoryMockFunction getRepositoryMockFunction - checkExpectedErrorMessage bool - expectedError apperrors.AppError - } - - applicationServiceAPI := &applications.ServiceAPI{} - applicationService := applications.Service{API: applicationServiceAPI} - - for _, testCase := range []testcase{ - { - description: "should get API by service name", - testFunc: func(serviceDefService ServiceDefinitionService) (*model.API, apperrors.AppError) { - return serviceDefService.GetAPIByServiceName("app", "service") - }, - getRepositoryMockFunction: func() *applicationmocks.ServiceRepository { - serviceRepository := applicationmocks.ServiceRepository{} - serviceRepository.On("GetByServiceName", "app", "service").Return(applicationService, nil) - - return &serviceRepository - }, - }, - { - description: "should get API by entry name", - testFunc: func(serviceDefService ServiceDefinitionService) (*model.API, apperrors.AppError) { - return serviceDefService.GetAPIByEntryName("app", "service", "entry") - }, - getRepositoryMockFunction: func() *applicationmocks.ServiceRepository { - serviceRepository := applicationmocks.ServiceRepository{} - serviceRepository.On("GetByEntryName", "app", "service", "entry").Return(applicationService, nil) - - return &serviceRepository - }, - }, - } { - t.Run(testCase.description, func(t *testing.T) { - // given - serviceAPI := &model.API{} - - serviceAPIService := new(serviceapimocks.Service) - serviceAPIService.On("Read", applicationServiceAPI).Return(serviceAPI, nil) - - service := NewServiceDefinitionService(serviceAPIService, testCase.getRepositoryMockFunction()) - - // when - result, err := testCase.testFunc(service) - - // then - require.NoError(t, err) - - assert.Equal(t, serviceAPI, result) - }) - } - - testGetByServiceNameFunc := func(serviceDefService ServiceDefinitionService) (*model.API, apperrors.AppError) { - return serviceDefService.GetAPIByServiceName("app", "service") - } - - testGetByEntryNameFunc := func(serviceDefService ServiceDefinitionService) (*model.API, apperrors.AppError) { - return serviceDefService.GetAPIByEntryName("app", "service", "entry") - } - - for _, testCase := range []testcase{ - { - description: "should return not found error if service does not exist", - testFunc: testGetByServiceNameFunc, - getRepositoryMockFunction: func() *applicationmocks.ServiceRepository { - serviceRepository := applicationmocks.ServiceRepository{} - serviceRepository.On("GetByServiceName", "app", "service").Return(applications.Service{}, apperrors.NotFound("missing")) - - return &serviceRepository - }, - checkExpectedErrorMessage: false, - expectedError: apperrors.NotFound("missing"), - }, - { - description: "should return not found error if service entry does not exist", - testFunc: testGetByEntryNameFunc, - getRepositoryMockFunction: func() *applicationmocks.ServiceRepository { - serviceRepository := applicationmocks.ServiceRepository{} - serviceRepository.On("GetByEntryName", "app", "service", "entry").Return(applications.Service{}, apperrors.NotFound("missing")) - - return &serviceRepository - }, - checkExpectedErrorMessage: false, - expectedError: apperrors.NotFound("missing"), - }, - { - description: "should return internal error if failed to get service", - testFunc: testGetByServiceNameFunc, - getRepositoryMockFunction: func() *applicationmocks.ServiceRepository { - serviceRepository := applicationmocks.ServiceRepository{} - serviceRepository.On("GetByServiceName", "app", "service").Return(applications.Service{}, apperrors.Internal("some error")) - - return &serviceRepository - }, - checkExpectedErrorMessage: true, - expectedError: apperrors.Internal("some error"), - }, - { - description: "should return internal error if failed to get service entry", - testFunc: testGetByEntryNameFunc, - getRepositoryMockFunction: func() *applicationmocks.ServiceRepository { - serviceRepository := applicationmocks.ServiceRepository{} - serviceRepository.On("GetByEntryName", "app", "service", "entry").Return(applications.Service{}, apperrors.Internal("some error")) - - return &serviceRepository - }, - checkExpectedErrorMessage: true, - expectedError: apperrors.Internal("some error"), - }, - { - description: "should return bad request if service does not have API", - testFunc: testGetByServiceNameFunc, - getRepositoryMockFunction: func() *applicationmocks.ServiceRepository { - serviceRepository := applicationmocks.ServiceRepository{} - serviceRepository.On("GetByServiceName", "app", "service").Return(applications.Service{}, nil) - - return &serviceRepository - }, - checkExpectedErrorMessage: false, - expectedError: apperrors.WrongInput("some error"), - }, - { - description: "should return bad request if service entry does not have API", - testFunc: testGetByEntryNameFunc, - getRepositoryMockFunction: func() *applicationmocks.ServiceRepository { - serviceRepository := applicationmocks.ServiceRepository{} - serviceRepository.On("GetByEntryName", "app", "service", "entry").Return(applications.Service{}, nil) - - return &serviceRepository - }, - checkExpectedErrorMessage: false, - expectedError: apperrors.WrongInput("some error"), - }, - } { - t.Run(testCase.description, func(t *testing.T) { - // given - service := NewServiceDefinitionService(nil, testCase.getRepositoryMockFunction()) - - // when - result, err := testCase.testFunc(service) - - // then - assert.Error(t, err) - assert.Nil(t, result) - assert.Equal(t, testCase.expectedError.Code(), err.Code()) - - if testCase.checkExpectedErrorMessage { - assert.Contains(t, err.Error(), testCase.expectedError.Error()) - } - }) - } - - for _, testCase := range []testcase{ - { - description: "should return internal error if reading service API fails", - testFunc: func(serviceDefService ServiceDefinitionService) (*model.API, apperrors.AppError) { - return serviceDefService.GetAPIByServiceName("app", "service") - }, - getRepositoryMockFunction: func() *applicationmocks.ServiceRepository { - serviceRepository := applicationmocks.ServiceRepository{} - serviceRepository.On("GetByServiceName", "app", "service").Return(applicationService, nil) - - return &serviceRepository - }, - }, - { - description: "should return internal error if reading service API fails", - testFunc: func(serviceDefService ServiceDefinitionService) (*model.API, apperrors.AppError) { - return serviceDefService.GetAPIByEntryName("app", "service", "entry") - }, - getRepositoryMockFunction: func() *applicationmocks.ServiceRepository { - serviceRepository := applicationmocks.ServiceRepository{} - serviceRepository.On("GetByEntryName", "app", "service", "entry").Return(applicationService, nil) - - return &serviceRepository - }, - }, - } { - t.Run("should return internal error if reading service API fails", func(t *testing.T) { - // given - applicationServiceAPI := &applications.ServiceAPI{} - - serviceAPIService := new(serviceapimocks.Service) - serviceAPIService.On("Read", applicationServiceAPI).Return(nil, apperrors.Internal("some error")) - - service := NewServiceDefinitionService(serviceAPIService, testCase.getRepositoryMockFunction()) - - // when - result, err := testCase.testFunc(service) - - // then - assert.Error(t, err) - assert.Nil(t, result) - assert.Equal(t, apperrors.CodeInternal, err.Code()) - assert.Contains(t, err.Error(), "some error") - }) - } -} diff --git a/components/central-application-gateway/internal/proxy/cache.go b/components/central-application-gateway/internal/proxy/cache.go deleted file mode 100644 index ada552b2a399..000000000000 --- a/components/central-application-gateway/internal/proxy/cache.go +++ /dev/null @@ -1,73 +0,0 @@ -package proxy - -import ( - "net/http" - "net/http/httputil" - "time" - - "github.com/kyma-project/kyma/components/central-application-gateway/internal/csrf" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/clientcert" - gocache "github.com/patrickmn/go-cache" -) - -const cleanupInterval = 60 - -// CacheEntry stores information about proxy configuration in cache -type CacheEntry struct { - Proxy *httputil.ReverseProxy - AuthorizationStrategy *authorizationStrategyWrapper - CSRFTokenStrategy csrf.TokenStrategy -} - -type authorizationStrategyWrapper struct { - actualStrategy authorization.Strategy - proxy *httputil.ReverseProxy - clientCertificate clientcert.ClientCertificate -} - -func (ce *authorizationStrategyWrapper) AddAuthorization(r *http.Request, skipTLSVerify bool) apperrors.AppError { - return ce.actualStrategy.AddAuthorization(r, ce.clientCertificate.SetCertificate, skipTLSVerify) -} - -func (ce *authorizationStrategyWrapper) Invalidate() { - ce.actualStrategy.Invalidate() -} - -// Cache is an interface for caching Proxies -type Cache interface { - // Get returns entry from the cache - Get(appName, serviceName, apiName string) (*CacheEntry, bool) - // Put adds entry to the cache - Put(appName, serviceName, apiName string, reverseProxy *httputil.ReverseProxy, authorizationStrategy authorization.Strategy, csrfTokenStrategy csrf.TokenStrategy, clientCertificate clientcert.ClientCertificate) *CacheEntry -} - -type cache struct { - proxyCache *gocache.Cache -} - -// NewCache creates new cache with specified TTL -func NewCache(proxyCacheTTL int) Cache { - return &cache{ - proxyCache: gocache.New(time.Duration(proxyCacheTTL)*time.Second, cleanupInterval*time.Second), - } -} - -func (p *cache) Get(appName, serviceName, apiName string) (*CacheEntry, bool) { - key := appName + serviceName + apiName - proxy, found := p.proxyCache.Get(key) - if !found { - return nil, false - } - - return proxy.(*CacheEntry), found -} - -func (p *cache) Put(appName, serviceName, apiName string, reverseProxy *httputil.ReverseProxy, authorizationStrategy authorization.Strategy, csrfTokenStrategy csrf.TokenStrategy, clientCertificate clientcert.ClientCertificate) *CacheEntry { - key := appName + serviceName + apiName - proxy := &CacheEntry{Proxy: reverseProxy, AuthorizationStrategy: &authorizationStrategyWrapper{authorizationStrategy, reverseProxy, clientCertificate}, CSRFTokenStrategy: csrfTokenStrategy} - p.proxyCache.Set(key, proxy, gocache.DefaultExpiration) - - return proxy -} diff --git a/components/central-application-gateway/internal/proxy/cache_test.go b/components/central-application-gateway/internal/proxy/cache_test.go deleted file mode 100644 index cf8f863b9db9..000000000000 --- a/components/central-application-gateway/internal/proxy/cache_test.go +++ /dev/null @@ -1,58 +0,0 @@ -package proxy - -import ( - "net/http/httputil" - "testing" - - csrfmocks "github.com/kyma-project/kyma/components/central-application-gateway/internal/csrf/mocks" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/clientcert" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/mocks" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "k8s.io/apimachinery/pkg/util/net" -) - -func TestCache(t *testing.T) { - - t.Run("should return false if not found", func(t *testing.T) { - // given - cache := NewCache(60) - - // when - cacheEntry, found := cache.Get("app1", "service1", "api1") - - // then - assert.Nil(t, cacheEntry) - assert.False(t, found) - }) - - t.Run("should put cache entry", func(t *testing.T) { - // given - cache := NewCache(60) - - // when - authorizationStrategyMock := &mocks.Strategy{} - csrfTokenStrategy := &csrfmocks.TokenStrategy{} - clientCertificate := clientcert.NewClientCertificate(nil) - url := net.FormatURL("http", "www.example.com", 8080, "") - proxy := httputil.NewSingleHostReverseProxy(url) - - cacheEntry := cache.Put("app1", "service1", "api1", proxy, authorizationStrategyMock, csrfTokenStrategy, clientCertificate) - - // then - require.NotNil(t, cacheEntry) - assert.Equal(t, proxy, cacheEntry.Proxy) - assert.Equal(t, authorizationStrategyMock, cacheEntry.AuthorizationStrategy.actualStrategy) - assert.Equal(t, csrfTokenStrategy, cacheEntry.CSRFTokenStrategy) - - // when - cacheEntry, found := cache.Get("app1", "service1", "api1") - - // then - require.NotNil(t, cacheEntry) - assert.True(t, found) - assert.Equal(t, proxy, cacheEntry.Proxy) - assert.Equal(t, authorizationStrategyMock, cacheEntry.AuthorizationStrategy.actualStrategy) - assert.Equal(t, csrfTokenStrategy, cacheEntry.CSRFTokenStrategy) - }) -} diff --git a/components/central-application-gateway/internal/proxy/factory.go b/components/central-application-gateway/internal/proxy/factory.go deleted file mode 100644 index 6c34bf3d9e0a..000000000000 --- a/components/central-application-gateway/internal/proxy/factory.go +++ /dev/null @@ -1,130 +0,0 @@ -package proxy - -import ( - "net/http" - "net/url" - "strings" - - "github.com/kyma-project/kyma/components/central-application-gateway/internal/csrf" - "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata" - "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata/model" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization" -) - -type pathExtractorFunc func(*url.URL) (model.APIIdentifier, *url.URL, *url.URL, apperrors.AppError) -type gatewayURLExtractorFunc func(*url.URL) (*url.URL, apperrors.AppError) - -// New creates proxy for handling user's services calls -func New( - serviceDefService metadata.ServiceDefinitionService, - authorizationStrategyFactory authorization.StrategyFactory, - csrfTokenStrategyFactory csrf.TokenStrategyFactory, - config Config) http.Handler { - - pathExtractor := func(u *url.URL) (model.APIIdentifier, *url.URL, *url.URL, apperrors.AppError) { - path := u.EscapedPath() - - trimmed := strings.Trim(path, "/") - split := strings.Split(trimmed, "/") - - if len(split) < 2 || split[0] == path { - return model.APIIdentifier{}, nil, nil, apperrors.WrongInput("path must contain Application and Service name") - } - - apiIdentifier := model.APIIdentifier{ - Application: split[0], - Service: split[1], - } - - targetAPIPath := strings.Join(split[2:], "/") - - gwURL := *u - gwURL.Path = "/" + strings.Join(split[:2], "/") - - targetURL, err := url.Parse(targetAPIPath) - - if err != nil { - return model.APIIdentifier{}, nil, nil, apperrors.WrongInput("Path has to be a valid path") - } - - return apiIdentifier, targetURL, &gwURL, nil - } - - apiExtractor := apiExtractor{ - serviceDefService: serviceDefService, - } - - return &proxy{ - cache: NewCache(config.ProxyCacheTTL), - proxyTimeout: config.ProxyTimeout, - authorizationStrategyFactory: authorizationStrategyFactory, - csrfTokenStrategyFactory: csrfTokenStrategyFactory, - extractPathFunc: pathExtractor, - apiExtractor: apiExtractor, - } -} - -func NewForCompass( - serviceDefService metadata.ServiceDefinitionService, - authorizationStrategyFactory authorization.StrategyFactory, - csrfTokenStrategyFactory csrf.TokenStrategyFactory, - config Config) http.Handler { - - extractFunc := func(u *url.URL) (model.APIIdentifier, *url.URL, *url.URL, apperrors.AppError) { - path := u.EscapedPath() - trimmed := strings.Trim(path, "/") - split := strings.Split(trimmed, "/") - - if len(split) < 3 || split[0] == path { - return model.APIIdentifier{}, nil, nil, apperrors.WrongInput("path must contain Application, Service and Entry name") - } - - apiIdentifier := model.APIIdentifier{ - Application: split[0], - Service: split[1], - Entry: split[2], - } - - targetAPIPath := strings.Join(split[3:], "/") - - gwURL := *u - gwURL.Path = "/" + strings.Join(split[:3], "/") - - targetURL, err := url.Parse(targetAPIPath) - if err != nil { - return model.APIIdentifier{}, nil, nil, apperrors.WrongInput("invalid target path") - } - - return apiIdentifier, targetURL, &gwURL, nil - } - - apiExtractor := compassAPIExtractor{ - serviceDefService: serviceDefService, - } - - return &proxy{ - cache: NewCache(config.ProxyCacheTTL), - proxyTimeout: config.ProxyTimeout, - authorizationStrategyFactory: authorizationStrategyFactory, - csrfTokenStrategyFactory: csrfTokenStrategyFactory, - extractPathFunc: extractFunc, - apiExtractor: apiExtractor, - } -} - -type apiExtractor struct { - serviceDefService metadata.ServiceDefinitionService -} - -func (ae apiExtractor) Get(identifier model.APIIdentifier) (*model.API, apperrors.AppError) { - return ae.serviceDefService.GetAPIByServiceName(identifier.Application, identifier.Service) -} - -type compassAPIExtractor struct { - serviceDefService metadata.ServiceDefinitionService -} - -func (ae compassAPIExtractor) Get(identifier model.APIIdentifier) (*model.API, apperrors.AppError) { - return ae.serviceDefService.GetAPIByEntryName(identifier.Application, identifier.Service, identifier.Entry) -} diff --git a/components/central-application-gateway/internal/proxy/factory_test.go b/components/central-application-gateway/internal/proxy/factory_test.go deleted file mode 100644 index bff90aea4f36..000000000000 --- a/components/central-application-gateway/internal/proxy/factory_test.go +++ /dev/null @@ -1,239 +0,0 @@ -package proxy - -import ( - "net/http" - "net/http/httptest" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" - - "github.com/kyma-project/kyma/components/central-application-gateway/internal/csrf" - "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata" - metadatamocks "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata/mocks" - "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata/model" - metadatamodel "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata/model" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization" - authMock "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/mocks" -) - -type createHandlerFunc func(serviceDefService metadata.ServiceDefinitionService, authorizationStrategyFactory authorization.StrategyFactory, csrfTokenStrategyFactory csrf.TokenStrategyFactory, config Config) http.Handler - -func TestProxyFactory(t *testing.T) { - - type createMockServiceDefServiceFunc func(apiIdentifier model.APIIdentifier, targetURL string, credentials *authorization.Credentials) metadatamocks.ServiceDefinitionService - - type testcase struct { - name string - url string - expectedTargetAPIURL string - createHandlerFunc createHandlerFunc - createMockServiceDefServiceFunc createMockServiceDefServiceFunc - apiIdentifier metadatamodel.APIIdentifier - } - - proxyConfig := Config{ - ProxyTimeout: 10, - Application: "test", - ProxyCacheTTL: 10, - } - - createTestServer := func(t *testing.T, path string) *httptest.Server { - return NewTestServer(func(req *http.Request) { - assert.Equal(t, http.MethodGet, req.Method) - assert.Equal(t, path, req.URL.String()) - }) - } - - createMockServiceDeffService := - func(apiIdentifier metadatamodel.APIIdentifier, targetURL string, credentials *authorization.Credentials) metadatamocks.ServiceDefinitionService { - serviceDefServiceMock := metadatamocks.ServiceDefinitionService{} - serviceDefServiceMock.On("GetAPIByServiceName", apiIdentifier.Application, apiIdentifier.Service).Return(&metadatamodel.API{ - TargetUrl: targetURL, - Credentials: credentials, - EncodeUrl: true, - }, nil).Once() - - return serviceDefServiceMock - } - createMockServiceDeffServiceWithoutEncoding := - func(apiIdentifier metadatamodel.APIIdentifier, targetURL string, credentials *authorization.Credentials) metadatamocks.ServiceDefinitionService { - serviceDefServiceMock := metadatamocks.ServiceDefinitionService{} - serviceDefServiceMock.On("GetAPIByServiceName", apiIdentifier.Application, apiIdentifier.Service).Return(&metadatamodel.API{ - TargetUrl: targetURL, - Credentials: credentials, - EncodeUrl: false, - }, nil).Once() - - return serviceDefServiceMock - } - - createMockServiceDeffServiceForCompass := func(apiIdentifier model.APIIdentifier, targetURL string, credentials *authorization.Credentials) metadatamocks.ServiceDefinitionService { - serviceDefServiceMock := metadatamocks.ServiceDefinitionService{} - serviceDefServiceMock.On("GetAPIByEntryName", apiIdentifier.Application, apiIdentifier.Service, apiIdentifier.Entry).Return(&metadatamodel.API{ - TargetUrl: targetURL, - Credentials: credentials, - }, nil).Once() - - return serviceDefServiceMock - } - - apiIdentifier := metadatamodel.APIIdentifier{ - Application: "app", - Service: "service", - } - - apiIdentifierForCompass := metadatamodel.APIIdentifier{ - Application: "app", - Service: "service", - Entry: "entry", - } - - for _, testCase := range []testcase{ - { - name: "should proxy using application and service name", - url: "/app/service/orders/123", - expectedTargetAPIURL: "/orders/123", - createHandlerFunc: New, - createMockServiceDefServiceFunc: createMockServiceDeffService, - apiIdentifier: apiIdentifier, - }, - { - name: "should proxy using application and service name when accessing root path", - url: "/app/service", - expectedTargetAPIURL: "/", - createHandlerFunc: New, - createMockServiceDefServiceFunc: createMockServiceDeffService, - apiIdentifier: apiIdentifier, - }, - { - name: "should reencode escape sequences", - url: "/app/service/orders/hello('%7Cworld%7C')", - expectedTargetAPIURL: "/orders/hello%28%27%7Cworld%7C%27%29", - createHandlerFunc: New, - createMockServiceDefServiceFunc: createMockServiceDeffService, - apiIdentifier: apiIdentifier, - }, - { - name: "should honour escape sequences", - url: "/app/service/orders/hello('%7Cworld%7C')", - expectedTargetAPIURL: "/orders/hello('%7Cworld%7C')", - createHandlerFunc: New, - createMockServiceDefServiceFunc: createMockServiceDeffServiceWithoutEncoding, - apiIdentifier: apiIdentifier, - }, - { - name: "should proxy using application, service and entry name", - url: "/app/service/entry/orders/123", - expectedTargetAPIURL: "/orders/123", - createHandlerFunc: NewForCompass, - createMockServiceDefServiceFunc: createMockServiceDeffServiceForCompass, - apiIdentifier: apiIdentifierForCompass, - }, - { - name: "should proxy using application, service and entry name when accessing root path", - url: "/app/service/entry", - expectedTargetAPIURL: "/", - createHandlerFunc: NewForCompass, - createMockServiceDefServiceFunc: createMockServiceDeffServiceForCompass, - apiIdentifier: apiIdentifierForCompass, - }, - } { - t.Run(testCase.name, func(t *testing.T) { - // given - ts := createTestServer(t, testCase.expectedTargetAPIURL) - req, err := http.NewRequest(http.MethodGet, testCase.url, nil) - req.URL.RawPath = testCase.url - require.NoError(t, err) - - authStrategyMock := &authMock.Strategy{} - authStrategyMock. - On("AddAuthorization", mock.AnythingOfType("*http.Request"), mock.AnythingOfType("SetClientCertificateFunc"), false). - Return(nil). - Once() - - credentials := &authorization.Credentials{} - authStrategyFactoryMock := &authMock.StrategyFactory{} - authStrategyFactoryMock.On("Create", credentials).Return(authStrategyMock).Once() - - csrfFactoryMock, csrfStrategyMock := mockCSRFStrategy(authStrategyMock, calledOnce, false) - - serviceDefServiceMock := testCase.createMockServiceDefServiceFunc(testCase.apiIdentifier, ts.URL, credentials) - - handler := testCase.createHandlerFunc(&serviceDefServiceMock, authStrategyFactoryMock, csrfFactoryMock, proxyConfig) - rr := httptest.NewRecorder() - - // when - handler.ServeHTTP(rr, req) - - // then - assert.Equal(t, http.StatusOK, rr.Code) - assert.Equal(t, "test", rr.Body.String()) - serviceDefServiceMock.AssertExpectations(t) - authStrategyFactoryMock.AssertExpectations(t) - authStrategyMock.AssertExpectations(t) - csrfFactoryMock.AssertExpectations(t) - csrfStrategyMock.AssertExpectations(t) - }) - } -} - -func TestPathExtractionErrors(t *testing.T) { - proxyConfig := Config{ - ProxyTimeout: 10, - Application: "test", - ProxyCacheTTL: 10, - } - - type testcase struct { - name string - url string - createHandlerFunc createHandlerFunc - } - - testCases := []testcase{ - { - name: "Should return Internal error when failed to extract data from empty path", - url: "", - createHandlerFunc: New, - }, - { - name: "Should return Internal error when failed to extract data from path containing application name only", - url: "/appName", - createHandlerFunc: New, - }, - { - name: "Should return Internal error when failed to extract data from empty path (Compass)", - url: "", - createHandlerFunc: NewForCompass, - }, - { - name: "Should return Internal error when failed to extract data from path containing application name only (Compass)", - url: "/appName", - createHandlerFunc: NewForCompass, - }, - { - name: "Should return Internal error when failed to extract data from path containing application and service name only (Compass)", - url: "/appName/serviceName", - createHandlerFunc: NewForCompass, - }, - } - - for _, testCase := range testCases { - t.Run(testCase.name, func(t *testing.T) { - // given - handler := testCase.createHandlerFunc(nil, nil, nil, proxyConfig) - - req, err := http.NewRequest(http.MethodGet, testCase.url, nil) - require.NoError(t, err) - rr := httptest.NewRecorder() - - // when - handler.ServeHTTP(rr, req) - - // then - assert.Equal(t, http.StatusBadRequest, rr.Code) - }) - } -} diff --git a/components/central-application-gateway/internal/proxy/mocks/APIExtractor.go b/components/central-application-gateway/internal/proxy/mocks/APIExtractor.go deleted file mode 100644 index 61d62299aec6..000000000000 --- a/components/central-application-gateway/internal/proxy/mocks/APIExtractor.go +++ /dev/null @@ -1,55 +0,0 @@ -// Code generated by mockery v2.16.0. DO NOT EDIT. - -package mocks - -import ( - apperrors "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - mock "github.com/stretchr/testify/mock" - - model "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata/model" -) - -// APIExtractor is an autogenerated mock type for the APIExtractor type -type APIExtractor struct { - mock.Mock -} - -// Get provides a mock function with given fields: identifier -func (_m *APIExtractor) Get(identifier model.APIIdentifier) (*model.API, apperrors.AppError) { - ret := _m.Called(identifier) - - var r0 *model.API - if rf, ok := ret.Get(0).(func(model.APIIdentifier) *model.API); ok { - r0 = rf(identifier) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*model.API) - } - } - - var r1 apperrors.AppError - if rf, ok := ret.Get(1).(func(model.APIIdentifier) apperrors.AppError); ok { - r1 = rf(identifier) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(apperrors.AppError) - } - } - - return r0, r1 -} - -type mockConstructorTestingTNewAPIExtractor interface { - mock.TestingT - Cleanup(func()) -} - -// NewAPIExtractor creates a new instance of APIExtractor. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewAPIExtractor(t mockConstructorTestingTNewAPIExtractor) *APIExtractor { - mock := &APIExtractor{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/components/central-application-gateway/internal/proxy/proxy.go b/components/central-application-gateway/internal/proxy/proxy.go deleted file mode 100644 index cec8bc8d4ef7..000000000000 --- a/components/central-application-gateway/internal/proxy/proxy.go +++ /dev/null @@ -1,190 +0,0 @@ -package proxy - -import ( - "bytes" - "context" - "encoding/json" - "io" - "io/ioutil" - "net/http" - "net/url" - "time" - - "github.com/kyma-project/kyma/components/central-application-gateway/internal/csrf" - "github.com/kyma-project/kyma/components/central-application-gateway/internal/httperrors" - "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata/model" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/clientcert" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/httpconsts" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/proxyconfig" -) - -type proxy struct { - cache Cache - proxyTimeout int - authorizationStrategyFactory authorization.StrategyFactory - csrfTokenStrategyFactory csrf.TokenStrategyFactory - extractPathFunc pathExtractorFunc - extractGatewayFunc gatewayURLExtractorFunc - apiExtractor APIExtractor -} - -//go:generate mockery --name=APIExtractor -type APIExtractor interface { - Get(identifier model.APIIdentifier) (*model.API, apperrors.AppError) -} - -// Config stores Proxy config -type Config struct { - ProxyTimeout int - Application string - ProxyCacheTTL int -} - -func (p *proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) { - apiIdentifier, path, gwURL, err := p.extractPath(r.URL) - if err != nil { - handleErrors(w, err) - return - } - - serviceAPI, err := p.apiExtractor.Get(apiIdentifier) - if err != nil { - handleErrors(w, err) - return - } - - r.URL.Path = path.Path - if !serviceAPI.EncodeUrl { - r.URL.RawPath = path.RawPath - } - - cacheEntry, err := p.getOrCreateCacheEntry(apiIdentifier, *serviceAPI) - if err != nil { - handleErrors(w, err) - return - } - - newRequest, cancel := p.setRequestTimeout(r) - defer cancel() - - err = p.addAuthorization(newRequest, cacheEntry, serviceAPI.SkipVerify) - if err != nil { - handleErrors(w, err) - return - } - - cacheEntry.Proxy.ModifyResponse = responseModifier(gwURL, serviceAPI.TargetUrl, urlRewriter) - cacheEntry.Proxy.ServeHTTP(w, newRequest) -} - -func (p *proxy) extractPath(u *url.URL) (model.APIIdentifier, *url.URL, *url.URL, apperrors.AppError) { - apiIdentifier, path, gwURL, err := p.extractPathFunc(u) - if err != nil { - return model.APIIdentifier{}, nil, nil, apperrors.WrongInput("failed to extract API Identifier from path") - } - - return apiIdentifier, path, gwURL, nil -} - -func (p *proxy) getOrCreateCacheEntry(apiIdentifier model.APIIdentifier, serviceAPI model.API) (*CacheEntry, apperrors.AppError) { - cacheObj, found := p.cache.Get(apiIdentifier.Application, apiIdentifier.Service, apiIdentifier.Entry) - - if found { - return cacheObj, nil - } - - return p.createCacheEntry(apiIdentifier, serviceAPI) -} - -func (p *proxy) createCacheEntry(apiIdentifier model.APIIdentifier, serviceAPI model.API) (*CacheEntry, apperrors.AppError) { - clientCertificate := clientcert.NewClientCertificate(nil) - authorizationStrategy := p.newAuthorizationStrategy(serviceAPI.Credentials) - csrfTokenStrategy := p.newCSRFTokenStrategy(authorizationStrategy, serviceAPI.Credentials) - proxy, err := makeProxy(serviceAPI.TargetUrl, serviceAPI.RequestParameters, apiIdentifier.Service, serviceAPI.SkipVerify, authorizationStrategy, csrfTokenStrategy, clientCertificate, p.proxyTimeout) - if err != nil { - return nil, err - } - - return p.cache.Put(apiIdentifier.Application, apiIdentifier.Service, apiIdentifier.Entry, proxy, authorizationStrategy, csrfTokenStrategy, clientCertificate), nil -} - -func (p *proxy) newAuthorizationStrategy(credentials *authorization.Credentials) authorization.Strategy { - return p.authorizationStrategyFactory.Create(credentials) -} - -func (p *proxy) newCSRFTokenStrategy(authorizationStrategy authorization.Strategy, credentials *authorization.Credentials) csrf.TokenStrategy { - csrfTokenEndpointURL := "" - if credentials != nil { - csrfTokenEndpointURL = credentials.CSRFTokenEndpointURL - } - return p.csrfTokenStrategyFactory.Create(authorizationStrategy, csrfTokenEndpointURL) -} - -func (p *proxy) newCSRFTokenStrategyFromCSRFConfig(authorizationStrategy authorization.Strategy, csrfConfig *proxyconfig.CSRFConfig) csrf.TokenStrategy { - csrfTokenEndpointURL := "" - if csrfConfig != nil { - csrfTokenEndpointURL = csrfConfig.TokenURL - } - return p.csrfTokenStrategyFactory.Create(authorizationStrategy, csrfTokenEndpointURL) -} - -func (p *proxy) setRequestTimeout(r *http.Request) (*http.Request, context.CancelFunc) { - ctx, cancel := context.WithTimeout(context.Background(), time.Duration(p.proxyTimeout)*time.Second) - newRequest := r.WithContext(ctx) - - return newRequest, cancel -} - -func (p *proxy) addAuthorization(r *http.Request, cacheEntry *CacheEntry, skipTLSVerify bool) apperrors.AppError { - - err := cacheEntry.AuthorizationStrategy.AddAuthorization(r, skipTLSVerify) - - if err != nil { - return err - } - - return cacheEntry.CSRFTokenStrategy.AddCSRFToken(r, skipTLSVerify) -} - -func copyRequestBody(r *http.Request) (io.ReadCloser, apperrors.AppError) { - if r.Body == nil { - return nil, nil - } - - bodyCopy, secondRequestBody, err := drainBody(r.Body) - if err != nil { - return nil, apperrors.Internal("failed to drain request body, %s", err) - } - r.Body = bodyCopy - - return secondRequestBody, nil -} - -func drainBody(b io.ReadCloser) (r1, r2 io.ReadCloser, err error) { - if b == http.NoBody { - return http.NoBody, http.NoBody, nil - } - var buf bytes.Buffer - if _, err = buf.ReadFrom(b); err != nil { - return nil, b, err - } - if err = b.Close(); err != nil { - return nil, b, err - } - return ioutil.NopCloser(&buf), ioutil.NopCloser(bytes.NewReader(buf.Bytes())), nil -} - -func handleErrors(w http.ResponseWriter, apperr apperrors.AppError) { - code, body := httperrors.AppErrorToResponse(apperr) - respondWithBody(w, code, body) -} - -func respondWithBody(w http.ResponseWriter, code int, body httperrors.ErrorResponse) { - w.Header().Set(httpconsts.HeaderContentType, httpconsts.ContentTypeApplicationJson) - - w.WriteHeader(code) - - json.NewEncoder(w).Encode(body) -} diff --git a/components/central-application-gateway/internal/proxy/proxy_test.go b/components/central-application-gateway/internal/proxy/proxy_test.go deleted file mode 100644 index 93615842ce33..000000000000 --- a/components/central-application-gateway/internal/proxy/proxy_test.go +++ /dev/null @@ -1,574 +0,0 @@ -package proxy - -import ( - "bytes" - "io" - "net/http" - "net/http/httptest" - "net/url" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" - - "github.com/kyma-project/kyma/components/central-application-gateway/internal/csrf" - csrfMock "github.com/kyma-project/kyma/components/central-application-gateway/internal/csrf/mocks" - "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata/model" - metadatamodel "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata/model" - proxyMocks "github.com/kyma-project/kyma/components/central-application-gateway/internal/proxy/mocks" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization" - authMock "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/mocks" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/httpconsts" -) - -func TestProxyRequest(t *testing.T) { - forbiddenHeaders := []string{ - httpconsts.HeaderXForwardedClientCert, - httpconsts.HeaderXForwardedFor, - httpconsts.HeaderXForwardedProto, - httpconsts.HeaderXForwardedHost, - } - type apiExtractor struct { - targetPath string - requestParameters *authorization.RequestParameters - credentials authorization.Credentials - } - type request struct { - url string - header http.Header - } - type expectedProxyRequest struct { - targetUrl string - header http.Header - } - type testcase struct { - name string - request request - apiExtractor apiExtractor - expectedProxyRequest expectedProxyRequest - skipTLSVerify bool - } - tests := []testcase{ - { - name: "Should proxy without escaping the URL path characters when target URL does not contain path", - request: request{ - url: "/somepath/Xyz('123')", - }, - expectedProxyRequest: expectedProxyRequest{ - targetUrl: "/somepath/Xyz('123')", - }, - }, - { - name: "should proxy without escaping the URL path characters when target URL contains path", - request: request{ - url: "/Xyz('123')", - }, - apiExtractor: apiExtractor{ - targetPath: "/somepath", - }, - expectedProxyRequest: expectedProxyRequest{ - targetUrl: "/somepath/Xyz('123')", - }, - }, - { - name: "should proxy without escaping the URL path characters when target URL contains full path", - request: request{ - url: "?$search=XXX", - }, - apiExtractor: apiExtractor{ - targetPath: "/somepath/Xyz('123')", - }, - expectedProxyRequest: expectedProxyRequest{ - targetUrl: "/somepath/Xyz('123')?$search=XXX", - }, - }, - { - name: "should proxy and add additional query parameters", - request: request{ - url: "/orders/123", - }, - apiExtractor: apiExtractor{ - requestParameters: &authorization.RequestParameters{ - QueryParameters: &map[string][]string{ - "param1": {"param-value-1"}, - "param2": {"param-value-2.1", "param-value-2.2"}, - }, - }, - }, - expectedProxyRequest: expectedProxyRequest{ - targetUrl: "/orders/123?param1=param-value-1¶m2=param-value-2.1¶m2=param-value-2.2", - }, - }, - { - name: "should proxy and add additional headers", - request: request{ - url: "/orders/123", - header: map[string][]string{ - "X-Request1": {"request-value-1"}, - "X-Request2": {"request-value-2.1", "request-value-2.2"}, - }, - }, - apiExtractor: apiExtractor{ - requestParameters: &authorization.RequestParameters{ - Headers: &map[string][]string{ - "X-Custom1": {"custom-value-1"}, - "X-Custom2": {"custom-value-2.1", "custom-value-2.2"}, - }, - }, - }, - expectedProxyRequest: expectedProxyRequest{ - targetUrl: "/orders/123", - header: map[string][]string{ - "X-Custom1": {"custom-value-1"}, - "X-Custom2": {"custom-value-2.1", "custom-value-2.2"}, - "X-Request1": {"request-value-1"}, - "X-Request2": {"request-value-2.1", "request-value-2.2"}, - }, - }, - }, - { - name: "should proxy BasicAuth auth calls", - request: request{ - url: "/orders/123", - }, - apiExtractor: apiExtractor{ - credentials: authorization.Credentials{ - BasicAuth: &authorization.BasicAuth{ - Username: "username", - Password: "password", - }, - }, - }, - expectedProxyRequest: expectedProxyRequest{ - targetUrl: "/orders/123", - // authorization header is not set by the mock - }, - }, - { - name: "should proxy OAuth calls", - request: request{ - url: "/orders/123", - }, - apiExtractor: apiExtractor{ - credentials: authorization.Credentials{ - OAuth: &authorization.OAuth{ - ClientID: "clientId", - ClientSecret: "clientSecret", - URL: "www.example.com/token", - }, - }, - }, - expectedProxyRequest: expectedProxyRequest{ - targetUrl: "/orders/123", - // authorization header is not set by the mock - }, - }, - { - name: "should proxy OAuth calls with TLS verification disabled", - request: request{ - url: "/orders/123", - }, - apiExtractor: apiExtractor{ - credentials: authorization.Credentials{ - OAuth: &authorization.OAuth{ - ClientID: "clientId", - ClientSecret: "clientSecret", - URL: "www.example.com/token", - }, - }, - }, - expectedProxyRequest: expectedProxyRequest{ - targetUrl: "/orders/123", - // authorization header is not set by the mock - }, - skipTLSVerify: true, - }, - { - name: "should fail with Bad Gateway error when failed to get OAuth token", - request: request{ - url: "/orders/123", - }, - apiExtractor: apiExtractor{ - credentials: authorization.Credentials{ - OAuth: &authorization.OAuth{ - ClientID: "clientId", - ClientSecret: "clientSecret", - URL: "www.example.com/token", - }, - }, - }, - expectedProxyRequest: expectedProxyRequest{ - targetUrl: "/orders/123", - // authorization header is not set by the mock - }, - }, - } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - // given - ts := NewTestServer(func(req *http.Request) { - expectedUrl, err := url.Parse(tc.expectedProxyRequest.targetUrl) - assert.Nil(t, err) - // compare maps objects, rather than strings built from unordered maps - assert.Equal(t, expectedUrl.Query(), req.URL.Query()) - assert.Equal(t, expectedUrl.RequestURI(), req.URL.RequestURI()) - - for name, values := range tc.expectedProxyRequest.header { - assert.Equal(t, values, req.Header.Values(name)) - } - for _, name := range forbiddenHeaders { - assert.Equal(t, "", req.Header.Get(name)) - } - }) - defer ts.Close() - - req, err := http.NewRequest(http.MethodGet, tc.request.url, nil) - require.NoError(t, err) - for name, values := range tc.request.header { - req.Header[name] = values - } - authStrategyMock := &authMock.Strategy{} - authStrategyMock. - On("AddAuthorization", mock.AnythingOfType("*http.Request"), mock.AnythingOfType("SetClientCertificateFunc"), tc.skipTLSVerify). - Return(nil). - Once() - - credentialsMatcher := createCredentialsMatcher(&tc.apiExtractor.credentials) - authStrategyFactoryMock := &authMock.StrategyFactory{} - authStrategyFactoryMock.On("Create", mock.MatchedBy(credentialsMatcher)).Return(authStrategyMock).Once() - - csrfFactoryMock, csrfStrategyMock := mockCSRFStrategy(authStrategyMock, calledOnce, tc.skipTLSVerify) - - apiExtractorMock := &proxyMocks.APIExtractor{} - apiExtractorMock.On("Get", metadatamodel.APIIdentifier{ - Application: "app", - Service: "service", - Entry: "entry", - }).Return(&metadatamodel.API{ - TargetUrl: ts.URL + tc.apiExtractor.targetPath, - Credentials: &tc.apiExtractor.credentials, - RequestParameters: tc.apiExtractor.requestParameters, - SkipVerify: tc.skipTLSVerify, - }, nil).Once() - - handler := newProxyForTest(apiExtractorMock, authStrategyFactoryMock, csrfFactoryMock, func(u *url.URL) (metadatamodel.APIIdentifier, *url.URL, *url.URL, apperrors.AppError) { - gwURL, err := u.Parse("/") - if err != nil { - return model.APIIdentifier{}, nil, nil, apperrors.WrongInput("Couldn't parse URL") - } - - return metadatamodel.APIIdentifier{ - Application: "app", - Service: "service", - Entry: "entry", - }, u, gwURL, nil - }, - func(url *url.URL) (*url.URL, apperrors.AppError) { - return url, nil - }, - createProxyConfig(10)) - - rr := httptest.NewRecorder() - - // when - handler.ServeHTTP(rr, req) - - // then - assert.Equal(t, http.StatusOK, rr.Code) - assert.Equal(t, "test", rr.Body.String()) - - apiExtractorMock.AssertExpectations(t) - authStrategyFactoryMock.AssertExpectations(t) - authStrategyMock.AssertExpectations(t) - csrfFactoryMock.AssertExpectations(t) - csrfStrategyMock.AssertExpectations(t) - }) - } -} - -func TestProxy(t *testing.T) { - - proxyTimeout := 10 - apiIdentifier := metadatamodel.APIIdentifier{ - Application: "app", - Service: "service", - Entry: "entry", - } - - fakePathExtractor := func(u *url.URL) (metadatamodel.APIIdentifier, *url.URL, *url.URL, apperrors.AppError) { - gwURL, err := u.Parse("/") - if err != nil { - return model.APIIdentifier{}, nil, nil, apperrors.WrongInput("Couldn't parse URL") - } - - apiIdentifier := metadatamodel.APIIdentifier{ - Application: "app", - Service: "service", - Entry: "entry", - } - - return apiIdentifier, u, gwURL, nil - } - - fakeGwExtractor := func(url *url.URL) (*url.URL, apperrors.AppError) { - return url, nil - } - - t.Run("should fail with Bad Gateway error when failed to get OAuth token", func(t *testing.T) { - // given - ts := NewTestServer(func(req *http.Request) { - assert.Equal(t, req.Method, http.MethodGet) - assert.Equal(t, req.RequestURI, "/orders/123") - }) - defer ts.Close() - - req, err := http.NewRequest(http.MethodGet, "/orders/123", nil) - require.NoError(t, err) - - authStrategyMock := &authMock.Strategy{} - authStrategyMock. - On("AddAuthorization", mock.AnythingOfType("*http.Request"), mock.AnythingOfType("SetClientCertificateFunc"), false). - Return(apperrors.UpstreamServerCallFailed("failed")) - - credentialsMatcher := createOAuthCredentialsMatcher("clientId", "clientSecret", "www.example.com/token") - - authStrategyFactoryMock := &authMock.StrategyFactory{} - authStrategyFactoryMock.On("Create", mock.MatchedBy(credentialsMatcher)).Return(authStrategyMock) - csrfFactoryMock, csrfStrategyMock := neverCalledCSRFStrategy(authStrategyMock) - - apiExtractorMock := &proxyMocks.APIExtractor{} - apiExtractorMock.On("Get", apiIdentifier).Return(&metadatamodel.API{ - TargetUrl: ts.URL, - Credentials: &authorization.Credentials{ - OAuth: &authorization.OAuth{ - ClientID: "clientId", - ClientSecret: "clientSecret", - URL: "www.example.com/token", - }, - }, - }, nil) - - handler := newProxyForTest(apiExtractorMock, authStrategyFactoryMock, csrfFactoryMock, fakePathExtractor, fakeGwExtractor, createProxyConfig(proxyTimeout)) - rr := httptest.NewRecorder() - - // when - handler.ServeHTTP(rr, req) - - // then - assert.Equal(t, http.StatusBadGateway, rr.Code) - - apiExtractorMock.AssertExpectations(t) - authStrategyFactoryMock.AssertExpectations(t) - authStrategyMock.AssertExpectations(t) - csrfFactoryMock.AssertExpectations(t) - csrfStrategyMock.AssertExpectations(t) - }) - - testRetryOnAuthFailure := func( - testServerConstructor func(check func(req *http.Request)) *httptest.Server, - requestBody io.Reader, - expectedStatusCode int, - t *testing.T) { - // given - tsf := testServerConstructor(func(req *http.Request) { - assertCookie(t, req, "user-cookie", "user-cookie-value") - assert.Equal(t, req.Method, http.MethodGet) - assert.Equal(t, req.RequestURI, "/orders/123") - }) - defer tsf.Close() - - req, _ := http.NewRequest(http.MethodGet, "/orders/123", requestBody) - req.AddCookie(&http.Cookie{Name: "user-cookie", Value: "user-cookie-value"}) - - apiExtractorMock := &proxyMocks.APIExtractor{} - apiExtractorMock.On("Get", apiIdentifier).Return(&metadatamodel.API{ - TargetUrl: tsf.URL, - Credentials: &authorization.Credentials{}, - }, nil) - - authStrategyMock := &authMock.Strategy{} - authStrategyMock. - On("AddAuthorization", mock.Anything, mock.AnythingOfType("SetClientCertificateFunc"), false). - Return(nil).Twice() - authStrategyMock.On("Invalidate").Return().Once() - - csrfTokenStrategyMock := &csrfMock.TokenStrategy{} - csrfTokenStrategyMock.On("AddCSRFToken", mock.AnythingOfType("*http.Request"), false).Return(nil).Twice() - csrfTokenStrategyMock.On("Invalidate").Return().Once() - - authStrategyFactoryMock := &authMock.StrategyFactory{} - authStrategyFactoryMock.On("Create", mock.Anything).Return(authStrategyMock) - - csrfTokenStrategyFactoryMock := &csrfMock.TokenStrategyFactory{} - csrfTokenStrategyFactoryMock.On("Create", authStrategyMock, "").Return(csrfTokenStrategyMock) - - handler := newProxyForTest(apiExtractorMock, authStrategyFactoryMock, csrfTokenStrategyFactoryMock, fakePathExtractor, fakeGwExtractor, createProxyConfig(proxyTimeout)) - rr := httptest.NewRecorder() - - // when - handler.ServeHTTP(rr, req) - - // then - assert.Equal(t, expectedStatusCode, rr.Code) - assert.Equal(t, "test", rr.Body.String()) - - apiExtractorMock.AssertExpectations(t) - authStrategyFactoryMock.AssertExpectations(t) - authStrategyMock.AssertExpectations(t) - csrfTokenStrategyFactoryMock.AssertExpectations(t) - csrfTokenStrategyMock.AssertExpectations(t) - } - - t.Run("should invalidate proxy and retry when 401 occurred", func(t *testing.T) { - testRetryOnAuthFailure(func(check func(req *http.Request)) *httptest.Server { - return NewTestServerForRetryTest(http.StatusUnauthorized, check) - }, nil, http.StatusOK, t) - }) - - t.Run("should invalidate proxy and retry when 403 occurred due to CRSF Token validation", func(t *testing.T) { - testRetryOnAuthFailure(func(check func(req *http.Request)) *httptest.Server { - return NewTestServerForRetryTest(http.StatusForbidden, check) - }, nil, http.StatusOK, t) - }) - - t.Run("should return 403 status when the call and the retry with body returned 403", func(t *testing.T) { - requestBody := bytes.NewBufferString("some body") - testRetryOnAuthFailure(func(check func(req *http.Request)) *httptest.Server { - return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - r.ParseForm() - check(r) - w.WriteHeader(http.StatusForbidden) - w.Write([]byte("test")) - })) - - }, requestBody, http.StatusForbidden, t) - }) -} - -func assertCookie(t *testing.T, r *http.Request, name, value string) { - cookie, err := r.Cookie(name) - require.NoError(t, err) - - assert.Equal(t, value, cookie.Value) -} - -func NewTestServer(check func(req *http.Request)) *httptest.Server { - return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - r.ParseForm() - check(r) - w.WriteHeader(http.StatusOK) - _, err := w.Write([]byte("test")) - if err != nil { - panic(err) - } - })) -} - -func newProxyForTest( - apiExtractor APIExtractor, - authorizationStrategyFactory authorization.StrategyFactory, - csrfTokenStrategyFactory csrf.TokenStrategyFactory, - pathExtractorFunc pathExtractorFunc, - extractGatewayFunc gatewayURLExtractorFunc, - proxyConfig Config) http.Handler { - - return &proxy{ - cache: NewCache(proxyConfig.ProxyCacheTTL), - proxyTimeout: proxyConfig.ProxyTimeout, - authorizationStrategyFactory: authorizationStrategyFactory, - csrfTokenStrategyFactory: csrfTokenStrategyFactory, - extractPathFunc: pathExtractorFunc, - extractGatewayFunc: extractGatewayFunc, - apiExtractor: apiExtractor, - } -} - -func NewTestServerForRetryTest(status int, check func(req *http.Request)) *httptest.Server { - willFail := true - - return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - r.ParseForm() - check(r) - if willFail { - w.WriteHeader(status) - willFail = false - } else { - w.WriteHeader(http.StatusOK) - } - w.Write([]byte("test")) - })) -} - -func createProxyConfig(proxyTimeout int) Config { - return Config{ - ProxyTimeout: proxyTimeout, - Application: "test", - ProxyCacheTTL: proxyTimeout, - } -} - -type CredentialsMatcherFunc func(*authorization.Credentials) bool - -func createCredentialsMatcher(creds *authorization.Credentials) CredentialsMatcherFunc { - if creds.BasicAuth != nil { - return createBasicCredentialsMatcher(creds.BasicAuth.Username, creds.BasicAuth.Password) - } - if creds.OAuth != nil { - return createOAuthCredentialsMatcher(creds.OAuth.ClientID, creds.OAuth.ClientSecret, creds.OAuth.URL) - } - return createEmptyCredentialsMatcher() -} - -func createEmptyCredentialsMatcher() CredentialsMatcherFunc { - return func(c *authorization.Credentials) bool { - return c != nil && *c == authorization.Credentials{} - } -} - -func createOAuthCredentialsMatcher(clientID, clientSecret, url string) CredentialsMatcherFunc { - return func(c *authorization.Credentials) bool { - return c.OAuth != nil && c.OAuth.ClientID == clientID && - c.OAuth.ClientSecret == clientSecret && - c.OAuth.URL == url - } -} - -func createBasicCredentialsMatcher(username, password string) CredentialsMatcherFunc { - return func(c *authorization.Credentials) bool { - return c.BasicAuth != nil && c.BasicAuth.Username == username && - c.BasicAuth.Password == password - } -} - -func mockCSRFStrategy( - authorizationStrategy authorization.Strategy, - ef ensureCalledFunc, - skipTLSVerify bool) (*csrfMock.TokenStrategyFactory, *csrfMock.TokenStrategy) { - - csrfTokenStrategyMock := &csrfMock.TokenStrategy{} - strategyCall := csrfTokenStrategyMock.On("AddCSRFToken", mock.AnythingOfType("*http.Request"), skipTLSVerify). - Return(nil) - ef(strategyCall) - - csrfTokenStrategyFactoryMock := &csrfMock.TokenStrategyFactory{} - csrfTokenStrategyFactoryMock.On("Create", authorizationStrategy, "").Return(csrfTokenStrategyMock).Once() - - return csrfTokenStrategyFactoryMock, csrfTokenStrategyMock -} - -func neverCalledCSRFStrategy(authorizationStrategy authorization.Strategy) (*csrfMock.TokenStrategyFactory, *csrfMock.TokenStrategy) { - csrfTokenStrategyMock := &csrfMock.TokenStrategy{} - - csrfTokenStrategyFactoryMock := &csrfMock.TokenStrategyFactory{} - csrfTokenStrategyFactoryMock.On("Create", authorizationStrategy, "").Return(csrfTokenStrategyMock).Once() - - return csrfTokenStrategyFactoryMock, csrfTokenStrategyMock -} - -type ensureCalledFunc func(mockCall *mock.Call) - -func calledOnce(mockCall *mock.Call) { - mockCall.Once() -} diff --git a/components/central-application-gateway/internal/proxy/retryableroundtripper.go b/components/central-application-gateway/internal/proxy/retryableroundtripper.go deleted file mode 100644 index 90bed83eb3ef..000000000000 --- a/components/central-application-gateway/internal/proxy/retryableroundtripper.go +++ /dev/null @@ -1,84 +0,0 @@ -package proxy - -import ( - "context" - "io" - "net/http" - "time" - - "github.com/kyma-project/kyma/components/central-application-gateway/internal/csrf" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/clientcert" -) - -type RetryableRoundTripper struct { - roundTripper http.RoundTripper - authorizationStrategy authorization.Strategy - csrfTokenStrategy csrf.TokenStrategy - clientCertificate clientcert.ClientCertificate - timeout int - skipTLSVerify bool -} - -func NewRetryableRoundTripper(roundTripper http.RoundTripper, authorizationStrategy authorization.Strategy, csrfTokenStrategy csrf.TokenStrategy, clientCertificate clientcert.ClientCertificate, timeout int, skipTLSVerify bool) *RetryableRoundTripper { - return &RetryableRoundTripper{ - roundTripper: roundTripper, - authorizationStrategy: authorizationStrategy, - csrfTokenStrategy: csrfTokenStrategy, - clientCertificate: clientCertificate, - timeout: timeout, - skipTLSVerify: skipTLSVerify, - } -} - -func (p *RetryableRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { - // Handle the case when credentials has been changed or OAuth token has expired - secondRequestBody, copyErr := copyRequestBody(req) - if copyErr != nil { - return nil, copyErr - } - resp, err := p.roundTripper.RoundTrip(req) - if err != nil { - return nil, err - } - if !p.shouldRetry(resp) { - return resp, err - } - if req.Context().Err() != nil { - return nil, req.Context().Err() - } - return p.retry(req, secondRequestBody) -} - -func (p *RetryableRoundTripper) shouldRetry(resp *http.Response) bool { - return resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusUnauthorized -} - -func (p *RetryableRoundTripper) retry(req *http.Request, retryBody io.ReadCloser) (*http.Response, error) { - request, cancel := p.prepareRequest(req) - defer cancel() - request.Body = retryBody - if err := p.addAuthorization(request); err != nil { - return nil, err - } - - return p.roundTripper.RoundTrip(request) -} - -func (p *RetryableRoundTripper) prepareRequest(req *http.Request) (*http.Request, context.CancelFunc) { - req.RequestURI = "" - ctx, cancel := context.WithTimeout(context.Background(), time.Duration(p.timeout)*time.Second) - return req.WithContext(ctx), cancel -} - -func (p *RetryableRoundTripper) addAuthorization(r *http.Request) error { - authorizationStrategy := p.authorizationStrategy - authorizationStrategy.Invalidate() - err := authorizationStrategy.AddAuthorization(r, p.clientCertificate.SetCertificate, p.skipTLSVerify) - if err != nil { - return err - } - csrfTokenStrategy := p.csrfTokenStrategy - csrfTokenStrategy.Invalidate() - return csrfTokenStrategy.AddCSRFToken(r, p.skipTLSVerify) -} diff --git a/components/central-application-gateway/internal/proxy/retryableroundtripper_test.go b/components/central-application-gateway/internal/proxy/retryableroundtripper_test.go deleted file mode 100644 index 8cb6bb25d060..000000000000 --- a/components/central-application-gateway/internal/proxy/retryableroundtripper_test.go +++ /dev/null @@ -1,191 +0,0 @@ -package proxy - -import ( - "crypto/tls" - "io/ioutil" - "net/http" - "net/http/httptest" - "strings" - "testing" - - csrfMock "github.com/kyma-project/kyma/components/central-application-gateway/internal/csrf/mocks" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/clientcert" - authMock "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/mocks" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" -) - -func TestRetryableRoundTripper(t *testing.T) { - - defaultAuthStrategyMock := func(_ bool) *authMock.Strategy { - return &authMock.Strategy{} - } - retryAuthStrategyMock := func(skipTLSVerify bool) *authMock.Strategy { - result := &authMock.Strategy{} - result. - On("AddAuthorization", mock.AnythingOfType("*http.Request"), mock.AnythingOfType("SetClientCertificateFunc"), skipTLSVerify). - Return(nil). - Once() - result.On("Invalidate").Return().Once() - return result - } - - defaultCsrfTokenStrategyMock := func(_ bool) *csrfMock.TokenStrategy { - return &csrfMock.TokenStrategy{} - } - retryCsrfTokenStrategyMock := func(skipTLSVerify bool) *csrfMock.TokenStrategy { - result := &csrfMock.TokenStrategy{} - result.On("AddCSRFToken", mock.AnythingOfType("*http.Request"), skipTLSVerify).Return(nil) - result.On("Invalidate").Return().Once() - return result - } - - type serverResponse struct { - statusCode int - body string - } - - tests := []struct { - name string - authStrategyFunc func(bool) *authMock.Strategy - csrfTokenStrategyFunc func(bool) *csrfMock.TokenStrategy - requestBody string - serverResponses []serverResponse - expectedStatusCode int - expectedBody string - expectedClientCert *tls.Certificate - skipTLSVerify bool - }{ - { - name: "Success", - expectedStatusCode: http.StatusOK, - authStrategyFunc: defaultAuthStrategyMock, - csrfTokenStrategyFunc: defaultCsrfTokenStrategyMock, - }, - { - name: "Internal error", - expectedStatusCode: http.StatusInternalServerError, - expectedBody: "internal error", - authStrategyFunc: defaultAuthStrategyMock, - csrfTokenStrategyFunc: defaultCsrfTokenStrategyMock, - serverResponses: []serverResponse{ - { - statusCode: http.StatusInternalServerError, - body: "internal error", - }, - }, - }, - { - name: "Retry on 403 and success", - expectedStatusCode: http.StatusOK, - expectedBody: "success", - authStrategyFunc: retryAuthStrategyMock, - csrfTokenStrategyFunc: retryCsrfTokenStrategyMock, - serverResponses: []serverResponse{ - { - statusCode: http.StatusForbidden, - body: "error", - }, - { - statusCode: http.StatusOK, - body: "success", - }, - }, - skipTLSVerify: true, - }, - { - name: "Retry on 403 and failure", - expectedStatusCode: http.StatusForbidden, - expectedBody: "error 2", - authStrategyFunc: retryAuthStrategyMock, - csrfTokenStrategyFunc: retryCsrfTokenStrategyMock, - serverResponses: []serverResponse{ - { - statusCode: http.StatusForbidden, - body: "error 1", - }, - { - statusCode: http.StatusForbidden, - body: "error 2", - }, - }, - skipTLSVerify: false, - }, - { - name: "Retry on 401 and success", - expectedStatusCode: http.StatusOK, - expectedBody: "success", - authStrategyFunc: retryAuthStrategyMock, - csrfTokenStrategyFunc: retryCsrfTokenStrategyMock, - serverResponses: []serverResponse{ - { - statusCode: http.StatusUnauthorized, - body: "error", - }, - { - statusCode: http.StatusOK, - body: "success", - }, - }, - skipTLSVerify: true, - }, - { - name: "Retry on 401 and failure", - expectedStatusCode: http.StatusInternalServerError, - expectedBody: "error 2", - authStrategyFunc: retryAuthStrategyMock, - csrfTokenStrategyFunc: retryCsrfTokenStrategyMock, - serverResponses: []serverResponse{ - { - statusCode: http.StatusUnauthorized, - body: "error 1", - }, - { - statusCode: http.StatusInternalServerError, - body: "error 2", - }, - }, - skipTLSVerify: false, - }, - } - for _, tc := range tests { - var requestCount int - t.Run(tc.name, func(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if tc.serverResponses == nil || len(tc.serverResponses) <= requestCount { - w.WriteHeader(http.StatusOK) - } else { - serverResponse := tc.serverResponses[requestCount] - w.WriteHeader(serverResponse.statusCode) - w.Write([]byte(serverResponse.body)) - } - requestCount++ - })) - defer ts.Close() - - authStrategyMock := tc.authStrategyFunc(tc.skipTLSVerify) - csrfTokenStrategyMock := tc.csrfTokenStrategyFunc(tc.skipTLSVerify) - clientCertificate := clientcert.NewClientCertificate(nil) - - transport := NewRetryableRoundTripper(http.DefaultTransport, authStrategyMock, csrfTokenStrategyMock, clientCertificate, 10, tc.skipTLSVerify) - httpClient := &http.Client{ - Transport: transport, - } - req, err := http.NewRequest(http.MethodPost, ts.URL, strings.NewReader(tc.requestBody)) - require.NoError(t, err) - - res, err := httpClient.Do(req) - require.NoError(t, err) - - resBody, err := ioutil.ReadAll(res.Body) - _ = res.Body.Close() - require.NoError(t, err) - require.Equal(t, res.StatusCode, tc.expectedStatusCode) - require.Equal(t, string(resBody), tc.expectedBody) - require.Equal(t, clientCertificate.GetCertificate(), tc.expectedClientCert) - - authStrategyMock.AssertExpectations(t) - csrfTokenStrategyMock.AssertExpectations(t) - }) - } -} diff --git a/components/central-application-gateway/internal/proxy/reverseproxy.go b/components/central-application-gateway/internal/proxy/reverseproxy.go deleted file mode 100644 index 4bb966f6dce1..000000000000 --- a/components/central-application-gateway/internal/proxy/reverseproxy.go +++ /dev/null @@ -1,198 +0,0 @@ -package proxy - -import ( - "context" - "errors" - "net/http" - "net/http/httputil" - "net/url" - "strconv" - "strings" - - "go.uber.org/zap" - - "github.com/kyma-project/kyma/components/central-application-gateway/internal/csrf" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/clientcert" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/httpconsts" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/httptools" -) - -func makeProxy( - targetURL string, - requestParameters *authorization.RequestParameters, - serviceName string, - skipTLSVerify bool, - authorizationStrategy authorization.Strategy, - csrfTokenStrategy csrf.TokenStrategy, - clientCertificate clientcert.ClientCertificate, - timeout int, -) (*httputil.ReverseProxy, apperrors.AppError) { - roundTripper := httptools.NewRoundTripper(httptools.WithTLSSkipVerify(skipTLSVerify), httptools.WithGetClientCertificate(clientCertificate.GetClientCertificate)) - retryableRoundTripper := NewRetryableRoundTripper(roundTripper, authorizationStrategy, csrfTokenStrategy, clientCertificate, timeout, skipTLSVerify) - return newProxy(targetURL, requestParameters, serviceName, retryableRoundTripper) -} - -func newProxy(targetURL string, requestParameters *authorization.RequestParameters, serviceName string, transport http.RoundTripper) (*httputil.ReverseProxy, apperrors.AppError) { - target, err := url.Parse(targetURL) - if err != nil { - zap.L().Error("failed to parse target URL", - zap.String("targetURL", targetURL), - zap.Error(err)) - return nil, apperrors.Internal("failed to parse target url '%s': '%s'", targetURL, err.Error()) - } - - targetQuery := target.RawQuery - director := func(req *http.Request) { - zap.L().Info("Proxy call for service", - zap.String("serviceName", serviceName), - zap.String("targetURL", targetURL)) - - req.URL.Scheme = target.Scheme - req.URL.Host = target.Host - req.Host = target.Host - - combinedPath := joinPaths(target.Path, req.URL.Path) - combinedPathEscaped := joinPaths(target.Path, req.URL.RawPath) - req.URL.Path = combinedPath - req.URL.RawPath = combinedPathEscaped - - if targetQuery == "" || req.URL.RawQuery == "" { - req.URL.RawQuery = targetQuery + req.URL.RawQuery - } else { - req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery - } - - if requestParameters != nil { - setCustomQueryParameters(req.URL, requestParameters.QueryParameters) - setCustomHeaders(req.Header, requestParameters.Headers) - } - - zap.L().Info("modified request URL", - zap.String("url", req.URL.String()), - zap.String("schema", req.URL.Scheme), - zap.String("path", req.URL.Path)) - } - - errorHandler := func(rw http.ResponseWriter, req *http.Request, err error) { - zap.L().Warn("Request failed", - zap.Error(err), - zap.Any("requestID", req.Context().Value(httptools.ContextUUID)), - zap.String("method", req.Method), - zap.String("host", req.Host), - zap.String("url", req.URL.RequestURI()), - zap.String("proto", req.Proto), - ) - codeRewriter(rw, err) - } - - return &httputil.ReverseProxy{ - Director: director, - Transport: transport, - ErrorHandler: errorHandler, - }, nil -} - -func joinPaths(a, b string) string { - if b == "" { - return a - } - - aslash := strings.HasSuffix(a, "/") - bslash := strings.HasPrefix(b, "/") - switch { - case aslash && bslash: - return a + b[1:] - case !aslash && !bslash: - return a + "/" + b - } - return a + b -} -func setCustomQueryParameters(reqURL *url.URL, customQueryParams *map[string][]string) { - httptools.SetQueryParameters(reqURL, customQueryParams) -} - -func setCustomHeaders(reqHeaders http.Header, customHeaders *map[string][]string) { - if _, ok := reqHeaders[httpconsts.HeaderUserAgent]; !ok { - // explicitly disable User-Agent so it's not set to default value - reqHeaders.Set(httpconsts.HeaderUserAgent, "") - } - - httptools.SetHeaders(reqHeaders, customHeaders) -} - -func responseModifier( - gatewayURL *url.URL, - targetURL string, - urlRewriter func(gatewayURL, target, loc *url.URL) *url.URL, -) func(*http.Response) error { - return func(resp *http.Response) error { - _ = httptools.LogResponse(zap.L().Sugar(), resp) - - if resp.StatusCode >= 500 && resp.StatusCode < 600 { - resp.Header.Set("Target-System-Status", strconv.Itoa(resp.StatusCode)) - resp.StatusCode = http.StatusBadGateway - } - - if (resp.StatusCode < 300 || resp.StatusCode >= 400) && - resp.StatusCode != http.StatusCreated { - return nil - } - - const locationHeader = "Location" - - locRaw := resp.Header.Get(locationHeader) - - if locRaw == "" { - return nil - } - - loc, err := resp.Request.URL.Parse(locRaw) - if err != nil { - return nil - } - - target, err := url.Parse(targetURL) - if err != nil { - return nil - } - - newURL := urlRewriter(gatewayURL, target, loc) - - if newURL != nil { - resp.Header.Set(locationHeader, newURL.String()) - } - - return nil - } -} - -// urlRewriter modifies redirect URLs for reverse proxy. -// If the URL should be left unmodified - it returns nil. -func urlRewriter(gatewayURL, target, loc *url.URL) *url.URL { - if loc.Scheme != "http" && loc.Scheme != "https" { - return nil - } - - if loc.Hostname() != target.Hostname() || !strings.HasPrefix(loc.Path, target.Path) { - return nil - } - - stripped := strings.TrimPrefix(loc.Path, target.Path) - gatewayURL = gatewayURL.JoinPath(stripped) - gatewayURL.RawQuery = loc.RawQuery - gatewayURL.Fragment = loc.Fragment - - return gatewayURL -} - -func codeRewriter(rw http.ResponseWriter, err error) { - if errors.Is(err, context.DeadlineExceeded) { - zap.L().Warn("HTTP status code rewritten to 504", - zap.Error(err)) - rw.WriteHeader(http.StatusGatewayTimeout) - return - } - rw.WriteHeader(http.StatusBadGateway) -} diff --git a/components/central-application-gateway/internal/proxy/reverseproxy_test.go b/components/central-application-gateway/internal/proxy/reverseproxy_test.go deleted file mode 100644 index 3fe7ad0a9028..000000000000 --- a/components/central-application-gateway/internal/proxy/reverseproxy_test.go +++ /dev/null @@ -1,215 +0,0 @@ -package proxy - -import ( - "net/http" - "net/url" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestURLRewriter(t *testing.T) { - type redirectTest struct { - name string - gwURL string - targetURL string - location string - expected string - empty bool - } - - tests := []redirectTest{ - { - name: "Simple redirect", - gwURL: "http://central-gateway.cluser.local/app/service", - targetURL: "https://httpbin.org/api/v1", - location: "https://httpbin.org/api/v1/some/sub/path", - expected: "http://central-gateway.cluser.local/app/service/some/sub/path", - }, - { - name: "Relative Path", - gwURL: "http://central-gateway.cluser.local/app/service", - targetURL: "https://httpbin.org/api/v1", - location: "/some/sub/path", - empty: true, - }, - { - name: "Changed Host", - gwURL: "http://central-gateway.cluser.local/app/service", - targetURL: "https://httpbin.org/api/v1", - location: "https://otherService.org/api/v1/some/sub/path", - empty: true, - }, - { - name: "Changed Subpath", - gwURL: "http://central-gateway.cluser.local/app/service", - targetURL: "https://httpbin.org/api/v1", - location: "https://httpbin.org/api/v2/some/sub/path", - empty: true, - }, - { - name: "Changed Protocol", - gwURL: "http://central-gateway.cluser.local/app/service", - targetURL: "https://httpbin.org/api/v1", - location: "ftp://httpbin.org/api/v1/some/sub/path", - empty: true, - }, - } - - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - gwURL, err := url.Parse(tc.gwURL) - require.Nil(t, err) - - targetURL, err := url.Parse(tc.targetURL) - require.Nil(t, err) - - location, err := url.Parse(tc.location) - require.Nil(t, err) - - newURL := urlRewriter(gwURL, targetURL, location) - - if tc.empty { - assert.Nil(t, newURL) - } else { - require.NotNil(t, newURL) - - actual := newURL.String() - t.Log("Got", actual) - assert.Equal(t, tc.expected, actual) - } - }) - } -} - -func TestResponseModifier(t *testing.T) { - type testcase struct { - name string - request func() *http.Request - response *http.Response - urlRewriter func(t *testing.T) func(gatewayURL, target, loc *url.URL) *url.URL - validate func(t *testing.T, r *http.Response, called bool) - } - - const locationHeader = "Location" - const target = "https://httpbin.org/api/v1" - const gateway = "http://central-gw.cluster.local" - - tests := []testcase{ - { - name: "Temporary redirect", - request: func() *http.Request { - req, _ := http.NewRequest(http.MethodGet, gateway+"/some/url", nil) - return req - }, - response: &http.Response{ - StatusCode: http.StatusTemporaryRedirect, - Header: http.Header{locationHeader: []string{target + "/some/endpoint"}}, - }, - urlRewriter: func(t *testing.T) func(gatewayURL, target, loc *url.URL) *url.URL { - return func(gatewayURL, trgt, loc *url.URL) *url.URL { - assert.Equal(t, target+"/some/endpoint", loc.String()) - - u, err := url.Parse("https://other.addr/with/path") - require.Nil(t, err) - return u - } - }, - validate: func(t *testing.T, r *http.Response, called bool) { - assert.True(t, called, "url rewrite should have been called") - newLoc := r.Header.Get(locationHeader) - assert.Equal(t, "https://other.addr/with/path", newLoc) - }, - }, - { - name: "Temporary redirect without location", - request: func() *http.Request { - req, _ := http.NewRequest(http.MethodGet, gateway+"/some/url", nil) - return req - }, - response: &http.Response{ - StatusCode: http.StatusTemporaryRedirect, - }, - validate: func(t *testing.T, r *http.Response, called bool) { - assert.False(t, called, "url rewrite shouldn't have been called") - - _, exists := r.Header[locationHeader] - assert.False(t, exists, "location header shouldn't have been added") - }, - }, - { - name: "200 Ok", - request: func() *http.Request { - req, _ := http.NewRequest(http.MethodGet, gateway+"/some/url", nil) - return req - }, - response: &http.Response{ - StatusCode: http.StatusOK, - Header: http.Header{locationHeader: []string{target + "/some/endpoint"}}, - }, - validate: func(t *testing.T, r *http.Response, called bool) { - assert.False(t, called, "url rewrite shouldn't have been called") - newLoc := r.Header.Get(locationHeader) - assert.Equal(t, target+"/some/endpoint", newLoc) - }, - }, - { - name: "201 Created", - request: func() *http.Request { - req, _ := http.NewRequest(http.MethodGet, gateway+"/some/url", nil) - return req - }, - response: &http.Response{ - StatusCode: http.StatusCreated, - Header: http.Header{locationHeader: []string{target + "/some/endpoint"}}, - }, - urlRewriter: func(t *testing.T) func(gatewayURL, target, loc *url.URL) *url.URL { - return func(gatewayURL, trgt, loc *url.URL) *url.URL { - assert.Equal(t, target+"/some/endpoint", loc.String()) - - u, err := url.Parse("https://other.addr/with/path") - require.Nil(t, err) - return u - } - }, - validate: func(t *testing.T, r *http.Response, called bool) { - assert.True(t, called, "url rewrite should have been called") - - newLoc := r.Header.Get(locationHeader) - assert.Equal(t, "https://other.addr/with/path", newLoc) - }, - }, - } - - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - // given - called := false - res := tc.response - res.Request = tc.request() - - rewriter := func(gatewayURL, target, loc *url.URL) *url.URL { - called = true - - if tc.urlRewriter == nil { - return nil - } - - return tc.urlRewriter(t)(gatewayURL, target, loc) - } - - gw, err := url.Parse(gateway) // this could be out of the loop, but here it felt more readable - require.Nil(t, err) - - rm := responseModifier(gw, target, rewriter) - - // when - err = rm(res) - require.Nil(t, err) - - // then - tc.validate(t, res, called) - }) - } -} diff --git a/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1/doc.go b/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1/doc.go deleted file mode 100644 index 461c585da70c..000000000000 --- a/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// +k8s:deepcopy-gen=package,register - -// +groupName=applicationconnector.kyma-project.io -package v1alpha1 diff --git a/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1/methods.go b/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1/methods.go deleted file mode 100644 index 2d5e6dcc4395..000000000000 --- a/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1/methods.go +++ /dev/null @@ -1,54 +0,0 @@ -package v1alpha1 - -import "strings" - -func (app *Application) SetInstallationStatus(status InstallationStatus) { - app.Status.InstallationStatus = status -} - -func (app *Application) SetAccessLabel() { - app.Spec.AccessLabel = app.Name -} - -func (app *Application) SetFinalizer(finalizer string) { - if !app.HasFinalizer(finalizer) { - app.addFinalizer(finalizer) - } -} - -func (app *Application) addFinalizer(finalizer string) { - app.Finalizers = append(app.Finalizers, finalizer) -} - -func (app *Application) HasFinalizer(finalizer string) bool { - return app.finalizerIndex(finalizer) != -1 -} - -func (app *Application) RemoveFinalizer(finalizer string) { - finalizerIndex := app.finalizerIndex(finalizer) - if finalizerIndex == -1 { - return - } - - app.Finalizers = append(app.Finalizers[:finalizerIndex], app.Finalizers[finalizerIndex+1:]...) -} - -func (app *Application) finalizerIndex(finalizer string) int { - for i, e := range app.Finalizers { - if e == finalizer { - return i - } - } - - return -1 -} - -// HasTenant returns true if ApplicationSpec has a non-empty value for Tenant field set -func (appSpec ApplicationSpec) HasTenant() bool { - return strings.TrimSpace(appSpec.Tenant) != "" -} - -// HasGroup returns true if ApplicationSpec has a non-empty value for Group field set -func (appSpec ApplicationSpec) HasGroup() bool { - return strings.TrimSpace(appSpec.Group) != "" -} diff --git a/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1/methods_test.go b/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1/methods_test.go deleted file mode 100644 index a5c15b7bcd61..000000000000 --- a/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1/methods_test.go +++ /dev/null @@ -1,202 +0,0 @@ -package v1alpha1_test - -import ( - "testing" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" - "github.com/stretchr/testify/assert" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func TestApplication_HasFinalizer(t *testing.T) { - testCases := []struct { - finalizers []string - searched string - result bool - }{ - { - finalizers: []string{"finalizer.test", "finalizer.test2", "finalizer.test3"}, - searched: "finalizer.test", - result: true, - }, - { - finalizers: []string{"finalizer.test", "finalizer.test2", "finalizer.test3"}, - searched: "finalizer.not.present", - result: false, - }, - { - finalizers: nil, - searched: "finalizer", - result: false, - }, - } - - t.Run("test has finalizer", func(t *testing.T) { - for _, test := range testCases { - app := v1alpha1.Application{ - ObjectMeta: v1.ObjectMeta{ - Name: "test", - Finalizers: test.finalizers, - }, - } - - assert.Equal(t, test.result, app.HasFinalizer(test.searched)) - } - }) -} - -func TestApplication_RemoveFinalizer(t *testing.T) { - testCases := []struct { - finalizers []string - removed string - result []string - }{ - { - finalizers: []string{"finalizer.test", "finalizer.test2", "finalizer.test3"}, - removed: "finalizer.test", - result: []string{"finalizer.test2", "finalizer.test3"}, - }, - { - finalizers: []string{"finalizer.test", "finalizer.test2", "finalizer.test3"}, - removed: "finalizer.not.present", - result: []string{"finalizer.test", "finalizer.test2", "finalizer.test3"}, - }, - { - finalizers: nil, - removed: "finalizer", - result: nil, - }, - } - - t.Run("test remove finalizer", func(t *testing.T) { - for _, test := range testCases { - app := v1alpha1.Application{ - ObjectMeta: v1.ObjectMeta{ - Name: "test", - Finalizers: test.finalizers, - }, - } - - app.RemoveFinalizer(test.removed) - - assert.Equal(t, test.result, app.Finalizers) - } - }) -} - -func TestApplication_SetFinalizer(t *testing.T) { - testCases := []struct { - finalizers []string - new string - result []string - }{ - { - finalizers: []string{"finalizer.test", "finalizer.test2", "finalizer.test3"}, - new: "finalizer.test4", - result: []string{"finalizer.test", "finalizer.test2", "finalizer.test3", "finalizer.test4"}, - }, - { - finalizers: []string{"finalizer.test", "finalizer.test2", "finalizer.test3"}, - new: "finalizer.test", - result: []string{"finalizer.test", "finalizer.test2", "finalizer.test3"}, - }, - { - finalizers: nil, - new: "finalizer", - result: []string{"finalizer"}, - }, - } - - t.Run("test set finalizer", func(t *testing.T) { - for _, test := range testCases { - app := v1alpha1.Application{ - ObjectMeta: v1.ObjectMeta{ - Name: "test", - Finalizers: test.finalizers, - }, - } - - app.SetFinalizer(test.new) - - assert.Equal(t, test.result, app.Finalizers) - } - }) -} - -func TestApplication_HasTenant(t *testing.T) { - t.Run("HasTenant returns true when tenant is set to a non-empty string", func(t *testing.T) { - app := v1alpha1.Application{ - ObjectMeta: v1.ObjectMeta{ - Name: "test", - }, - Spec: v1alpha1.ApplicationSpec{ - Tenant: "tenant", - }, - } - - assert.True(t, app.Spec.HasTenant()) - }) - - t.Run("HasTenant returns false when tenant is not set", func(t *testing.T) { - app := v1alpha1.Application{ - ObjectMeta: v1.ObjectMeta{ - Name: "test", - }, - Spec: v1alpha1.ApplicationSpec{}, - } - - assert.False(t, app.Spec.HasTenant()) - }) - - t.Run("HasTenant returns false when tenant is set to a empty string", func(t *testing.T) { - app := v1alpha1.Application{ - ObjectMeta: v1.ObjectMeta{ - Name: "", - }, - Spec: v1alpha1.ApplicationSpec{ - Tenant: "", - }, - } - - assert.False(t, app.Spec.HasTenant()) - }) -} - -func TestApplication_HasGroup(t *testing.T) { - t.Run("HasGroup returns true when group is set to a non-empty string", func(t *testing.T) { - app := v1alpha1.Application{ - ObjectMeta: v1.ObjectMeta{ - Name: "test", - }, - Spec: v1alpha1.ApplicationSpec{ - Group: "group", - }, - } - - assert.True(t, app.Spec.HasGroup()) - }) - - t.Run("HasGroup returns false when group is not set", func(t *testing.T) { - app := v1alpha1.Application{ - ObjectMeta: v1.ObjectMeta{ - Name: "test", - }, - Spec: v1alpha1.ApplicationSpec{}, - } - - assert.False(t, app.Spec.HasGroup()) - }) - - t.Run("HasGroup returns false when group is set to a empty string", func(t *testing.T) { - app := v1alpha1.Application{ - ObjectMeta: v1.ObjectMeta{ - Name: "", - }, - Spec: v1alpha1.ApplicationSpec{ - Group: "", - }, - } - - assert.False(t, app.Spec.HasGroup()) - }) -} diff --git a/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1/register.go b/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1/register.go deleted file mode 100644 index ff03a6241fcf..000000000000 --- a/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1/register.go +++ /dev/null @@ -1,39 +0,0 @@ -package v1alpha1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -// SchemeGroupVersion is group version used to register these objects -var SchemeGroupVersion = schema.GroupVersion{Group: "applicationconnector.kyma-project.io", Version: "v1alpha1"} - -// Resource takes an unqualified resource and returns a Group qualified GroupResource -func Resource(resource string) schema.GroupResource { - return SchemeGroupVersion.WithResource(resource).GroupResource() -} - -var ( - // localSchemeBuilder and AddToScheme will stay in k8s.io/kubernetes. - SchemeBuilder runtime.SchemeBuilder - localSchemeBuilder = &SchemeBuilder - AddToScheme = localSchemeBuilder.AddToScheme -) - -func init() { - // We only register manually written functions here. The registration of the - // generated functions takes place in the generated files. The separation - // makes the code compile even when the generated files are missing. - localSchemeBuilder.Register(addKnownTypes) -} - -// Adds the list of known types to api.Scheme. -func addKnownTypes(scheme *runtime.Scheme) error { - scheme.AddKnownTypes(SchemeGroupVersion, - &Application{}, - &ApplicationList{}, - ) - metav1.AddToGroupVersion(scheme, SchemeGroupVersion) - return nil -} diff --git a/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1/types.go b/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1/types.go deleted file mode 100644 index 7ff96c388cd7..000000000000 --- a/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1/types.go +++ /dev/null @@ -1,141 +0,0 @@ -package v1alpha1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -// +genclient -// +genclient:nonNamespaced -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -type Application struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata"` - Spec ApplicationSpec `json:"spec"` - Status ApplicationStatus `json:"status,omitempty"` -} - -func (app Application) ShouldSkipInstallation() bool { - return app.Spec.SkipInstallation -} - -func (app Application) GetApplicationID() string { - if app.Spec.CompassMetadata == nil { - return "" - } - - return app.Spec.CompassMetadata.ApplicationID -} - -type ApplicationStatus struct { - // Represents the status of Application release installation - InstallationStatus InstallationStatus `json:"installationStatus"` -} - -type InstallationStatus struct { - Status string `json:"status"` - Description string `json:"description"` -} - -func (pw *Application) GetObjectKind() schema.ObjectKind { - return &Application{} -} - -// ApplicationSpec defines spec section of the Application custom resource -type ApplicationSpec struct { - Description string `json:"description"` - SkipInstallation bool `json:"skipInstallation,omitempty"` - Services []Service `json:"services"` - Labels map[string]string `json:"labels"` - Tenant string `json:"tenant,omitempty"` - Group string `json:"group,omitempty"` - CompassMetadata *CompassMetadata `json:"compassMetadata,omitempty"` - - // New fields used by V2 version - Tags []string `json:"tags,omitempty"` - DisplayName string `json:"displayName"` - ProviderDisplayName string `json:"providerDisplayName"` - LongDescription string `json:"longDescription"` - - SkipVerify bool `json:"skipVerify"` - EncodeURL bool `json:"encodeUrl"` - - // Deprecated - AccessLabel string `json:"accessLabel,omitempty"` -} - -type CompassMetadata struct { - ApplicationID string `json:"applicationId"` - Authentication Authentication `json:"authentication"` -} - -type Authentication struct { - ClientIds []string `json:"clientIds"` -} - -// Entry defines, what is enabled by activating the service. -type Entry struct { - Type string `json:"type"` - TargetUrl string `json:"targetUrl"` - SpecificationUrl string `json:"specificationUrl,omitempty"` - ApiType string `json:"apiType,omitempty"` - Credentials Credentials `json:"credentials,omitempty"` - RequestParametersSecretName string `json:"requestParametersSecretName,omitempty"` - - // New fields used by V2 version - Name string `json:"name"` - ID string `json:"id"` - - CentralGatewayUrl string `json:"centralGatewayUrl"` - - // Deprecated - AccessLabel string `json:"accessLabel,omitempty"` - // Deprecated - GatewayUrl string `json:"gatewayUrl"` -} - -type CSRFInfo struct { - TokenEndpointURL string `json:"tokenEndpointURL"` -} - -// Credentials defines type of authentication and where the credentials are stored -type Credentials struct { - Type string `json:"type"` - SecretName string `json:"secretName"` - AuthenticationUrl string `json:"authenticationUrl,omitempty"` - CSRFInfo *CSRFInfo `json:"csrfInfo,omitempty"` -} - -// Service represents part of the remote environment, which is mapped 1 to 1 in the service-catalog to: -// - service class in V1 -// - service plans in V2 (since api-packages support) -type Service struct { - ID string `json:"id"` - Identifier string `json:"identifier"` - Name string `json:"name"` - DisplayName string `json:"displayName"` - Description string `json:"description"` - Entries []Entry `json:"entries"` - - // New fields used by V2 version - AuthCreateParameterSchema *string `json:"authCreateParameterSchema,omitempty"` - - // Deprecated - Labels map[string]string `json:"labels,omitempty"` - // Deprecated - LongDescription string `json:"longDescription,omitempty"` - // Deprecated - ProviderDisplayName string `json:"providerDisplayName"` - // Deprecated - Tags []string `json:"tags,omitempty"` -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -type ApplicationList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata"` - - Items []Application `json:"items"` -} diff --git a/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1/zz_generated.deepcopy.go b/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1/zz_generated.deepcopy.go deleted file mode 100644 index b4430d568776..000000000000 --- a/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1/zz_generated.deepcopy.go +++ /dev/null @@ -1,276 +0,0 @@ -//go:build !ignore_autogenerated -// +build !ignore_autogenerated - -// Code generated by deepcopy-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - runtime "k8s.io/apimachinery/pkg/runtime" -) - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Application) DeepCopyInto(out *Application) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - out.Status = in.Status - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Application. -func (in *Application) DeepCopy() *Application { - if in == nil { - return nil - } - out := new(Application) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *Application) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ApplicationList) DeepCopyInto(out *ApplicationList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]Application, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApplicationList. -func (in *ApplicationList) DeepCopy() *ApplicationList { - if in == nil { - return nil - } - out := new(ApplicationList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ApplicationList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ApplicationSpec) DeepCopyInto(out *ApplicationSpec) { - *out = *in - if in.Services != nil { - in, out := &in.Services, &out.Services - *out = make([]Service, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.Labels != nil { - in, out := &in.Labels, &out.Labels - *out = make(map[string]string, len(*in)) - for key, val := range *in { - (*out)[key] = val - } - } - if in.CompassMetadata != nil { - in, out := &in.CompassMetadata, &out.CompassMetadata - *out = new(CompassMetadata) - (*in).DeepCopyInto(*out) - } - if in.Tags != nil { - in, out := &in.Tags, &out.Tags - *out = make([]string, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApplicationSpec. -func (in *ApplicationSpec) DeepCopy() *ApplicationSpec { - if in == nil { - return nil - } - out := new(ApplicationSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ApplicationStatus) DeepCopyInto(out *ApplicationStatus) { - *out = *in - out.InstallationStatus = in.InstallationStatus - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApplicationStatus. -func (in *ApplicationStatus) DeepCopy() *ApplicationStatus { - if in == nil { - return nil - } - out := new(ApplicationStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Authentication) DeepCopyInto(out *Authentication) { - *out = *in - if in.ClientIds != nil { - in, out := &in.ClientIds, &out.ClientIds - *out = make([]string, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Authentication. -func (in *Authentication) DeepCopy() *Authentication { - if in == nil { - return nil - } - out := new(Authentication) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CSRFInfo) DeepCopyInto(out *CSRFInfo) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CSRFInfo. -func (in *CSRFInfo) DeepCopy() *CSRFInfo { - if in == nil { - return nil - } - out := new(CSRFInfo) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CompassMetadata) DeepCopyInto(out *CompassMetadata) { - *out = *in - in.Authentication.DeepCopyInto(&out.Authentication) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CompassMetadata. -func (in *CompassMetadata) DeepCopy() *CompassMetadata { - if in == nil { - return nil - } - out := new(CompassMetadata) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Credentials) DeepCopyInto(out *Credentials) { - *out = *in - if in.CSRFInfo != nil { - in, out := &in.CSRFInfo, &out.CSRFInfo - *out = new(CSRFInfo) - **out = **in - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Credentials. -func (in *Credentials) DeepCopy() *Credentials { - if in == nil { - return nil - } - out := new(Credentials) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Entry) DeepCopyInto(out *Entry) { - *out = *in - in.Credentials.DeepCopyInto(&out.Credentials) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Entry. -func (in *Entry) DeepCopy() *Entry { - if in == nil { - return nil - } - out := new(Entry) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *InstallationStatus) DeepCopyInto(out *InstallationStatus) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new InstallationStatus. -func (in *InstallationStatus) DeepCopy() *InstallationStatus { - if in == nil { - return nil - } - out := new(InstallationStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Service) DeepCopyInto(out *Service) { - *out = *in - if in.Entries != nil { - in, out := &in.Entries, &out.Entries - *out = make([]Entry, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.AuthCreateParameterSchema != nil { - in, out := &in.AuthCreateParameterSchema, &out.AuthCreateParameterSchema - *out = new(string) - **out = **in - } - if in.Labels != nil { - in, out := &in.Labels, &out.Labels - *out = make(map[string]string, len(*in)) - for key, val := range *in { - (*out)[key] = val - } - } - if in.Tags != nil { - in, out := &in.Tags, &out.Tags - *out = make([]string, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Service. -func (in *Service) DeepCopy() *Service { - if in == nil { - return nil - } - out := new(Service) - in.DeepCopyInto(out) - return out -} diff --git a/components/central-application-gateway/pkg/apperrors/apperrors.go b/components/central-application-gateway/pkg/apperrors/apperrors.go deleted file mode 100644 index 45d545d6f34c..000000000000 --- a/components/central-application-gateway/pkg/apperrors/apperrors.go +++ /dev/null @@ -1,53 +0,0 @@ -package apperrors - -import "fmt" - -const ( - CodeInternal = 1 - CodeNotFound = 2 - CodeAlreadyExists = 3 - CodeWrongInput = 4 - CodeUpstreamServerCallFailed = 5 -) - -type AppError interface { - Code() int - Error() string -} - -type appError struct { - code int - message string -} - -func errorf(code int, format string, a ...interface{}) AppError { - return appError{code: code, message: fmt.Sprintf(format, a...)} -} - -func Internal(format string, a ...interface{}) AppError { - return errorf(CodeInternal, format, a...) -} - -func NotFound(format string, a ...interface{}) AppError { - return errorf(CodeNotFound, format, a...) -} - -func AlreadyExists(format string, a ...interface{}) AppError { - return errorf(CodeAlreadyExists, format, a...) -} - -func WrongInput(format string, a ...interface{}) AppError { - return errorf(CodeWrongInput, format, a...) -} - -func UpstreamServerCallFailed(format string, a ...interface{}) AppError { - return errorf(CodeUpstreamServerCallFailed, format, a...) -} - -func (ae appError) Code() int { - return ae.code -} - -func (ae appError) Error() string { - return ae.message -} diff --git a/components/central-application-gateway/pkg/apperrors/apperrors_test.go b/components/central-application-gateway/pkg/apperrors/apperrors_test.go deleted file mode 100644 index 0367732200f6..000000000000 --- a/components/central-application-gateway/pkg/apperrors/apperrors_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package apperrors - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestAppError(t *testing.T) { - - t.Run("should create error with proper code", func(t *testing.T) { - assert.Equal(t, CodeInternal, Internal("error").Code()) - assert.Equal(t, CodeNotFound, NotFound("error").Code()) - assert.Equal(t, CodeAlreadyExists, AlreadyExists("error").Code()) - assert.Equal(t, CodeWrongInput, WrongInput("error").Code()) - assert.Equal(t, CodeUpstreamServerCallFailed, UpstreamServerCallFailed("error").Code()) - }) - - t.Run("should create error with simple message", func(t *testing.T) { - assert.Equal(t, "error", Internal("error").Error()) - assert.Equal(t, "error", NotFound("error").Error()) - assert.Equal(t, "error", AlreadyExists("error").Error()) - assert.Equal(t, "error", WrongInput("error").Error()) - assert.Equal(t, "error", UpstreamServerCallFailed("error").Error()) - }) - - t.Run("should create error with formatted message", func(t *testing.T) { - assert.Equal(t, "code: 1, error: bug", Internal("code: %d, error: %s", 1, "bug").Error()) - assert.Equal(t, "code: 1, error: bug", NotFound("code: %d, error: %s", 1, "bug").Error()) - assert.Equal(t, "code: 1, error: bug", AlreadyExists("code: %d, error: %s", 1, "bug").Error()) - assert.Equal(t, "code: 1, error: bug", WrongInput("code: %d, error: %s", 1, "bug").Error()) - assert.Equal(t, "code: 1, error: bug", UpstreamServerCallFailed("code: %d, error: %s", 1, "bug").Error()) - }) -} diff --git a/components/central-application-gateway/pkg/authorization/basicauthstrategy.go b/components/central-application-gateway/pkg/authorization/basicauthstrategy.go deleted file mode 100644 index cb85e8adc094..000000000000 --- a/components/central-application-gateway/pkg/authorization/basicauthstrategy.go +++ /dev/null @@ -1,29 +0,0 @@ -package authorization - -import ( - "net/http" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/clientcert" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/util" -) - -type basicAuthStrategy struct { - username string - password string -} - -func newBasicAuthStrategy(username, password string) basicAuthStrategy { - return basicAuthStrategy{ - username: username, - password: password, - } -} - -func (b basicAuthStrategy) AddAuthorization(r *http.Request, _ clientcert.SetClientCertificateFunc, _ bool) apperrors.AppError { - util.AddBasicAuthHeader(r, b.username, b.password) - return nil -} - -func (b basicAuthStrategy) Invalidate() { -} diff --git a/components/central-application-gateway/pkg/authorization/basicauthstrategy_test.go b/components/central-application-gateway/pkg/authorization/basicauthstrategy_test.go deleted file mode 100644 index a14872ac0669..000000000000 --- a/components/central-application-gateway/pkg/authorization/basicauthstrategy_test.go +++ /dev/null @@ -1,29 +0,0 @@ -package authorization - -import ( - "net/http" - "testing" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/httpconsts" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestBasicAuthStrategy(t *testing.T) { - - t.Run("should add Authorization header", func(t *testing.T) { - // given - basicAuthStrategy := newBasicAuthStrategy("username", "password") - - request, err := http.NewRequest("GET", "www.example.com", nil) - require.NoError(t, err) - - // when - err = basicAuthStrategy.AddAuthorization(request, nil, false) - - // then - require.NoError(t, err) - authHeader := request.Header.Get(httpconsts.HeaderAuthorization) - assert.Equal(t, "Basic dXNlcm5hbWU6cGFzc3dvcmQ=", authHeader) - }) -} diff --git a/components/central-application-gateway/pkg/authorization/certificategenstrategy.go b/components/central-application-gateway/pkg/authorization/certificategenstrategy.go deleted file mode 100644 index de5cca4fd62b..000000000000 --- a/components/central-application-gateway/pkg/authorization/certificategenstrategy.go +++ /dev/null @@ -1,37 +0,0 @@ -package authorization - -import ( - "crypto/tls" - "net/http" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/clientcert" -) - -type certificateGenStrategy struct { - certificate []byte - privateKey []byte -} - -func newCertificateGenStrategy(certificate, privateKey []byte) certificateGenStrategy { - return certificateGenStrategy{ - certificate: certificate, - privateKey: privateKey, - } -} - -func (b certificateGenStrategy) AddAuthorization(r *http.Request, setter clientcert.SetClientCertificateFunc, _ bool) apperrors.AppError { - cert, err := b.prepareCertificate() - if err != nil { - return apperrors.Internal("Failed to prepare certificate, %s", err.Error()) - } - setter(&cert) - return nil -} - -func (b certificateGenStrategy) Invalidate() { -} - -func (b certificateGenStrategy) prepareCertificate() (tls.Certificate, error) { - return tls.X509KeyPair(b.certificate, b.privateKey) -} diff --git a/components/central-application-gateway/pkg/authorization/certificategenstrategy_test.go b/components/central-application-gateway/pkg/authorization/certificategenstrategy_test.go deleted file mode 100644 index 0a54d0ed60b5..000000000000 --- a/components/central-application-gateway/pkg/authorization/certificategenstrategy_test.go +++ /dev/null @@ -1,86 +0,0 @@ -package authorization - -import ( - "crypto/rsa" - "crypto/tls" - "crypto/x509" - "encoding/pem" - "net/http" - "testing" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/clientcert" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/testconsts" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -var ( - certificate = []byte(testconsts.Certificate) - privateKey = []byte(testconsts.PrivateKey) -) - -func TestCertificateGenStrategy(t *testing.T) { - - t.Run("should add certificates to proxy", func(t *testing.T) { - // given - clientCert := clientcert.NewClientCertificate(nil) - certGenStrategy := newCertificateGenStrategy(certificate, privateKey) - - request, err := http.NewRequest("GET", "www.example.com", nil) - require.NoError(t, err) - - // when - err = certGenStrategy.AddAuthorization(request, func(cert *tls.Certificate) { - clientCert.SetCertificate(cert) - }, false) - require.NoError(t, err) - - // then - assert.Equal(t, &tls.Certificate{ - Certificate: [][]byte{cert()}, - PrivateKey: key(), - }, clientCert.GetCertificate()) - }) - - t.Run("should return error when key is invalid", func(t *testing.T) { - // given - certGenStrategy := newCertificateGenStrategy(certificate, []byte("invalid key")) - - request, err := http.NewRequest("GET", "www.example.com", nil) - require.NoError(t, err) - - // when - err = certGenStrategy.AddAuthorization(request, nil, false) - - // then - require.Error(t, err) - }) - - t.Run("should return error when certificate is invalid", func(t *testing.T) { - // given - - certGenStrategy := newCertificateGenStrategy([]byte("invalid cert"), privateKey) - - request, err := http.NewRequest("GET", "www.example.com", nil) - require.NoError(t, err) - - // when - err = certGenStrategy.AddAuthorization(request, nil, false) - - // then - require.Error(t, err) - }) -} - -func key() *rsa.PrivateKey { - pemBlock, _ := pem.Decode(privateKey) - key, _ := x509.ParsePKCS1PrivateKey(pemBlock.Bytes) - return key -} - -func cert() []byte { - pemBlock, _ := pem.Decode(certificate) - return pemBlock.Bytes -} diff --git a/components/central-application-gateway/pkg/authorization/clientcert/clientcertificate.go b/components/central-application-gateway/pkg/authorization/clientcert/clientcertificate.go deleted file mode 100644 index ca309eb96317..000000000000 --- a/components/central-application-gateway/pkg/authorization/clientcert/clientcertificate.go +++ /dev/null @@ -1,54 +0,0 @@ -package clientcert - -import ( - "crypto/tls" - "sync" -) - -type SetClientCertificateFunc func(cert *tls.Certificate) - -type ClientCertificate interface { - // GetClientCertificate implements the TLSClientConfig.GetClientCertificate function - // which is called when a server requests a certificate from a client. - GetClientCertificate(*tls.CertificateRequestInfo) (*tls.Certificate, error) - - // SetCertificate sets the client certificates. - SetCertificate(certificate *tls.Certificate) - // GetCertificate returns the client certificates. - GetCertificate() *tls.Certificate -} - -func NewClientCertificate(certificate *tls.Certificate) ClientCertificate { - return &clientCertificate{ - certificate: certificate, - } -} - -type clientCertificate struct { - sync.RWMutex - certificate *tls.Certificate -} - -func (c *clientCertificate) GetClientCertificate(_ *tls.CertificateRequestInfo) (*tls.Certificate, error) { - c.RLock() - defer c.RUnlock() - - if c.certificate == nil { - return &tls.Certificate{}, nil - } - return c.certificate, nil -} - -func (c *clientCertificate) GetCertificate() *tls.Certificate { - c.RLock() - defer c.RUnlock() - - return c.certificate -} - -func (c *clientCertificate) SetCertificate(cert *tls.Certificate) { - c.Lock() - defer c.Unlock() - - c.certificate = cert -} diff --git a/components/central-application-gateway/pkg/authorization/externaltokenstrategy.go b/components/central-application-gateway/pkg/authorization/externaltokenstrategy.go deleted file mode 100644 index 2e780e898023..000000000000 --- a/components/central-application-gateway/pkg/authorization/externaltokenstrategy.go +++ /dev/null @@ -1,33 +0,0 @@ -package authorization - -import ( - "net/http" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/clientcert" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/httpconsts" -) - -type externalTokenStrategy struct { - strategy Strategy -} - -func newExternalTokenStrategy(strategy Strategy) Strategy { - return externalTokenStrategy{strategy} -} - -func (e externalTokenStrategy) AddAuthorization(r *http.Request, setter clientcert.SetClientCertificateFunc, skipTLSVerification bool) apperrors.AppError { - externalToken := r.Header.Get(httpconsts.HeaderAccessToken) - if externalToken != "" { - r.Header.Del(httpconsts.HeaderAccessToken) - r.Header.Set(httpconsts.HeaderAuthorization, externalToken) - - return nil - } - - return e.strategy.AddAuthorization(r, setter, skipTLSVerification) -} - -func (o externalTokenStrategy) Invalidate() { - o.strategy.Invalidate() -} diff --git a/components/central-application-gateway/pkg/authorization/externaltokenstrategy_test.go b/components/central-application-gateway/pkg/authorization/externaltokenstrategy_test.go deleted file mode 100644 index ea142c8a1548..000000000000 --- a/components/central-application-gateway/pkg/authorization/externaltokenstrategy_test.go +++ /dev/null @@ -1,79 +0,0 @@ -package authorization - -import ( - "net/http" - "testing" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/oauth/mocks" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/httpconsts" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestExternalAuthStrategy(t *testing.T) { - - t.Run("should use external token", func(t *testing.T) { - // given - oauthClientMock := &mocks.Client{} - - oauthStrategy := newOAuthStrategy(oauthClientMock, "clientId", "clientSecret", "www.example.com/token", nil) - - externalTokenStrategy := newExternalTokenStrategy(&oauthStrategy) - - request, err := http.NewRequest("GET", "www.example.com", nil) - require.NoError(t, err) - - request.Header.Set(httpconsts.HeaderAccessToken, "Bearer external") - - // when - err = externalTokenStrategy.AddAuthorization(request, nil, false) - - // then - require.NoError(t, err) - authHeader := request.Header.Get(httpconsts.HeaderAuthorization) - externalTokenHeader := request.Header.Get(httpconsts.HeaderAccessToken) - - assert.Equal(t, "Bearer external", authHeader) - assert.Equal(t, "", externalTokenHeader) - oauthClientMock.AssertNotCalled(t, "GetToken") - }) - - t.Run("should use provided strategy when external token header is missing", func(t *testing.T) { - // given - oauthClientMock := &mocks.Client{} - oauthClientMock.On("GetToken", "clientId", "clientSecret", "www.example.com/token", (*map[string][]string)(nil), (*map[string][]string)(nil), false).Return("token", nil).Once() - - oauthStrategy := newOAuthStrategy(oauthClientMock, "clientId", "clientSecret", "www.example.com/token", nil) - - externalTokenStrategy := newExternalTokenStrategy(&oauthStrategy) - - request, err := http.NewRequest("GET", "www.example.com", nil) - require.NoError(t, err) - - // when - err = externalTokenStrategy.AddAuthorization(request, nil, false) - - // then - require.NoError(t, err) - authHeader := request.Header.Get(httpconsts.HeaderAuthorization) - - assert.Equal(t, "Bearer token", authHeader) - oauthClientMock.AssertExpectations(t) - }) - - t.Run("should call Invalidate method on the provided strategy", func(t *testing.T) { - // given - oauthClientMock := &mocks.Client{} - oauthClientMock.On("InvalidateTokenCache", "clientId", "clientSecret", "www.example.com/token").Return("token", nil).Once() - - oauthStrategy := newOAuthStrategy(oauthClientMock, "clientId", "clientSecret", "www.example.com/token", nil) - - externalTokenStrategy := newExternalTokenStrategy(&oauthStrategy) - - // when - externalTokenStrategy.Invalidate() - - // then - oauthClientMock.AssertExpectations(t) - }) -} diff --git a/components/central-application-gateway/pkg/authorization/factory.go b/components/central-application-gateway/pkg/authorization/factory.go deleted file mode 100644 index 381b10e90647..000000000000 --- a/components/central-application-gateway/pkg/authorization/factory.go +++ /dev/null @@ -1,72 +0,0 @@ -package authorization - -import ( - "net/http" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/oauth" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/clientcert" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/oauth/tokencache" -) - -//go:generate mockery --name=Strategy -type Strategy interface { - // Adds Authorization header to the request - AddAuthorization(r *http.Request, setter clientcert.SetClientCertificateFunc, skipTLSVerification bool) apperrors.AppError - // Invalidates internal state - Invalidate() -} - -//go:generate mockery --name=StrategyFactory -type StrategyFactory interface { - // Creates strategy for credentials provided - Create(credentials *Credentials) Strategy -} - -//go:generate mockery --name=OAuthClient -type OAuthClient interface { - // GetToken obtains OAuth token - GetToken(clientID string, clientSecret string, authURL string, headers, queryParameters *map[string][]string, skipTLSVerification bool) (string, apperrors.AppError) - GetTokenMTLS(clientID, authURL string, certificate, privateKey []byte, headers, queryParameters *map[string][]string, skipVerify bool) (string, apperrors.AppError) - // InvalidateTokenCache resets internal token cache - InvalidateTokenCache(clientID string, clientSecret string, authURL string) - InvalidateTokenCacheMTLS(clientID, authURL string, certificate, privateKey []byte) -} - -type authorizationStrategyFactory struct { - oauthClient OAuthClient -} - -// Create creates strategy for credentials provided -func (asf authorizationStrategyFactory) Create(c *Credentials) Strategy { - return newExternalTokenStrategy(asf.create(c)) -} - -func (asf authorizationStrategyFactory) create(c *Credentials) Strategy { - if c != nil && c.OAuth != nil { - return newOAuthStrategy(asf.oauthClient, c.OAuth.ClientID, c.OAuth.ClientSecret, c.OAuth.URL, c.OAuth.RequestParameters) - } else if c != nil && c.OAuthWithCert != nil { - oAuthStrategy := newOAuthWithCertStrategy(asf.oauthClient, c.OAuthWithCert.ClientID, c.OAuthWithCert.ClientSecret, c.OAuthWithCert.Certificate, c.OAuthWithCert.PrivateKey, c.OAuthWithCert.URL, c.OAuthWithCert.RequestParameters) - return &oAuthStrategy - } else if c != nil && c.BasicAuth != nil { - return newBasicAuthStrategy(c.BasicAuth.Username, c.BasicAuth.Password) - } else if c != nil && c.CertificateGen != nil { - return newCertificateGenStrategy(c.CertificateGen.Certificate, c.CertificateGen.PrivateKey) - } else { - return newNoAuthStrategy() - } -} - -// FactoryConfiguration holds factory configuration options -type FactoryConfiguration struct { - OAuthClientTimeout int -} - -// NewStrategyFactory creates factory for instantiating Strategy implementations -func NewStrategyFactory(config FactoryConfiguration) StrategyFactory { - cache := tokencache.NewTokenCache() - oauthClient := oauth.NewOauthClient(config.OAuthClientTimeout, cache) - - return authorizationStrategyFactory{oauthClient: oauthClient} -} diff --git a/components/central-application-gateway/pkg/authorization/factory_test.go b/components/central-application-gateway/pkg/authorization/factory_test.go deleted file mode 100644 index 3568e3b9c1bb..000000000000 --- a/components/central-application-gateway/pkg/authorization/factory_test.go +++ /dev/null @@ -1,247 +0,0 @@ -package authorization - -import ( - "crypto/tls" - "net/http" - "testing" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/testconsts" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/clientcert" - - oauthMocks "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/oauth/mocks" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/httpconsts" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestStrategyFactory(t *testing.T) { - t.Run("should create no auth strategy", func(t *testing.T) { - // given - oauthClientMock := &oauthMocks.Client{} - - factory := authorizationStrategyFactory{oauthClient: oauthClientMock} - - // when - strategy := factory.Create(nil) - - // then - require.NotNil(t, strategy) - - // given - request, err := http.NewRequest("GET", "www.example.com", nil) - require.NoError(t, err) - - // when - err = strategy.AddAuthorization(request, nil, false) - - // then - authHeader := request.Header.Get(httpconsts.HeaderAuthorization) - assert.Nil(t, err) - assert.Equal(t, "", authHeader) - - // given - requestWithExternalToken, err := http.NewRequest("GET", "www.example.com", nil) - require.NoError(t, err) - - requestWithExternalToken.Header.Set(httpconsts.HeaderAccessToken, "Bearer external") - - // when - err = strategy.AddAuthorization(requestWithExternalToken, nil, false) - - // then - authHeader = requestWithExternalToken.Header.Get(httpconsts.HeaderAuthorization) - assert.Nil(t, err) - assert.Equal(t, "Bearer external", authHeader) - }) - - t.Run("should create basic auth strategy", func(t *testing.T) { - // given - oauthClientMock := &oauthMocks.Client{} - - factory := authorizationStrategyFactory{oauthClient: oauthClientMock} - credentials := &Credentials{ - BasicAuth: &BasicAuth{ - Username: "username", - Password: "password", - }, - } - - // when - strategy := factory.Create(credentials) - - // then - require.NotNil(t, strategy) - - // given - request, err := http.NewRequest("GET", "www.example.com", nil) - require.NoError(t, err) - - // when - err = strategy.AddAuthorization(request, nil, false) - - // then - authHeader := request.Header.Get(httpconsts.HeaderAuthorization) - assert.Nil(t, err) - assert.Contains(t, authHeader, "Basic ") - - // given - requestWithExternalToken, err := http.NewRequest("GET", "www.example.com", nil) - require.NoError(t, err) - - requestWithExternalToken.Header.Set(httpconsts.HeaderAccessToken, "Bearer external") - - // when - err = strategy.AddAuthorization(requestWithExternalToken, nil, false) - - // then - authHeader = requestWithExternalToken.Header.Get(httpconsts.HeaderAuthorization) - assert.Nil(t, err) - assert.Equal(t, "Bearer external", authHeader) - }) - - t.Run("should create oauth strategy", func(t *testing.T) { - // given - oauthClientMock := &oauthMocks.Client{} - oauthClientMock.On("GetToken", "clientId", "clientSecret", "www.example.com/token", (*map[string][]string)(nil), (*map[string][]string)(nil), false).Return("token", nil) - - factory := authorizationStrategyFactory{oauthClient: oauthClientMock} - credentials := &Credentials{ - OAuth: &OAuth{ - ClientID: "clientId", - ClientSecret: "clientSecret", - URL: "www.example.com/token", - }, - } - - // when - strategy := factory.Create(credentials) - - // then - require.NotNil(t, strategy) - - // given - request, err := http.NewRequest("GET", "www.example.com", nil) - require.NoError(t, err) - - // when - err = strategy.AddAuthorization(request, nil, false) - - // then - authHeader := request.Header.Get(httpconsts.HeaderAuthorization) - assert.Nil(t, err) - assert.Equal(t, authHeader, "Bearer token") - - // given - requestWithExternalToken, err := http.NewRequest("GET", "www.example.com", nil) - require.NoError(t, err) - - requestWithExternalToken.Header.Set(httpconsts.HeaderAccessToken, "Bearer external") - - // when - err = strategy.AddAuthorization(requestWithExternalToken, nil, false) - - // then - authHeader = requestWithExternalToken.Header.Get(httpconsts.HeaderAuthorization) - assert.Nil(t, err) - assert.Equal(t, "Bearer external", authHeader) - }) - - t.Run("should create oauth with cert strategy", func(t *testing.T) { - // given - oauthClientMock := &oauthMocks.Client{} - oauthClientMock.On("GetTokenMTLS", "clientId", "www.example.com/token", []byte(testconsts.Certificate), []byte(testconsts.PrivateKey), (*map[string][]string)(nil), (*map[string][]string)(nil), false).Return("token", nil) - - factory := authorizationStrategyFactory{oauthClient: oauthClientMock} - credentials := &Credentials{ - OAuthWithCert: &OAuthWithCert{ - ClientID: "clientId", - ClientSecret: "clientSecret", - Certificate: certificate, - PrivateKey: privateKey, - URL: "www.example.com/token", - }, - } - - // when - strategy := factory.Create(credentials) - - // then - require.NotNil(t, strategy) - - // given - request, err := http.NewRequest("GET", "www.example.com", nil) - require.NoError(t, err) - - // when - err = strategy.AddAuthorization(request, nil, false) - - // then - authHeader := request.Header.Get(httpconsts.HeaderAuthorization) - assert.Nil(t, err) - assert.Equal(t, authHeader, "Bearer token") - - // given - requestWithExternalToken, err := http.NewRequest("GET", "www.example.com", nil) - require.NoError(t, err) - - requestWithExternalToken.Header.Set(httpconsts.HeaderAccessToken, "Bearer external") - - // when - err = strategy.AddAuthorization(requestWithExternalToken, nil, false) - - // then - authHeader = requestWithExternalToken.Header.Get(httpconsts.HeaderAuthorization) - assert.Nil(t, err) - assert.Equal(t, "Bearer external", authHeader) - }) - - t.Run("should create certificate gen strategy", func(t *testing.T) { - // given - oauthClientMock := &oauthMocks.Client{} - - factory := authorizationStrategyFactory{oauthClient: oauthClientMock} - credentials := &Credentials{ - CertificateGen: &CertificateGen{ - Certificate: certificate, - PrivateKey: privateKey, - }, - } - clientCert := clientcert.NewClientCertificate(nil) - - // when - strategy := factory.Create(credentials) - - // then - require.NotNil(t, strategy) - - // given - request, err := http.NewRequest("GET", "www.example.com", nil) - require.NoError(t, err) - - // when - err = strategy.AddAuthorization(request, func(cert *tls.Certificate) { - clientCert.SetCertificate(cert) - }, false) - - // then - authHeader := request.Header.Get(httpconsts.HeaderAuthorization) - assert.Nil(t, err) - expectedCert, err := tls.X509KeyPair(credentials.CertificateGen.Certificate, credentials.CertificateGen.PrivateKey) - assert.Nil(t, err) - assert.Equal(t, expectedCert, *clientCert.GetCertificate()) - // given - requestWithExternalToken, err := http.NewRequest("GET", "www.example.com", nil) - require.NoError(t, err) - - requestWithExternalToken.Header.Set(httpconsts.HeaderAccessToken, "Bearer external") - - // when - err = strategy.AddAuthorization(requestWithExternalToken, nil, false) - - // then - authHeader = requestWithExternalToken.Header.Get(httpconsts.HeaderAuthorization) - assert.Nil(t, err) - assert.Equal(t, "Bearer external", authHeader) - }) -} diff --git a/components/central-application-gateway/pkg/authorization/mocks/OAuthClient.go b/components/central-application-gateway/pkg/authorization/mocks/OAuthClient.go deleted file mode 100644 index c10c103f3b38..000000000000 --- a/components/central-application-gateway/pkg/authorization/mocks/OAuthClient.go +++ /dev/null @@ -1,85 +0,0 @@ -// Code generated by mockery v2.16.0. DO NOT EDIT. - -package mocks - -import ( - apperrors "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - - mock "github.com/stretchr/testify/mock" -) - -// OAuthClient is an autogenerated mock type for the OAuthClient type -type OAuthClient struct { - mock.Mock -} - -// GetToken provides a mock function with given fields: clientID, clientSecret, authURL, headers, queryParameters, skipTLSVerification -func (_m *OAuthClient) GetToken(clientID string, clientSecret string, authURL string, headers *map[string][]string, queryParameters *map[string][]string, skipTLSVerification bool) (string, apperrors.AppError) { - ret := _m.Called(clientID, clientSecret, authURL, headers, queryParameters, skipTLSVerification) - - var r0 string - if rf, ok := ret.Get(0).(func(string, string, string, *map[string][]string, *map[string][]string, bool) string); ok { - r0 = rf(clientID, clientSecret, authURL, headers, queryParameters, skipTLSVerification) - } else { - r0 = ret.Get(0).(string) - } - - var r1 apperrors.AppError - if rf, ok := ret.Get(1).(func(string, string, string, *map[string][]string, *map[string][]string, bool) apperrors.AppError); ok { - r1 = rf(clientID, clientSecret, authURL, headers, queryParameters, skipTLSVerification) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(apperrors.AppError) - } - } - - return r0, r1 -} - -// GetTokenMTLS provides a mock function with given fields: clientID, authURL, certificate, privateKey, headers, queryParameters, skipVerify -func (_m *OAuthClient) GetTokenMTLS(clientID string, authURL string, certificate []byte, privateKey []byte, headers *map[string][]string, queryParameters *map[string][]string, skipVerify bool) (string, apperrors.AppError) { - ret := _m.Called(clientID, authURL, certificate, privateKey, headers, queryParameters, skipVerify) - - var r0 string - if rf, ok := ret.Get(0).(func(string, string, []byte, []byte, *map[string][]string, *map[string][]string, bool) string); ok { - r0 = rf(clientID, authURL, certificate, privateKey, headers, queryParameters, skipVerify) - } else { - r0 = ret.Get(0).(string) - } - - var r1 apperrors.AppError - if rf, ok := ret.Get(1).(func(string, string, []byte, []byte, *map[string][]string, *map[string][]string, bool) apperrors.AppError); ok { - r1 = rf(clientID, authURL, certificate, privateKey, headers, queryParameters, skipVerify) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(apperrors.AppError) - } - } - - return r0, r1 -} - -// InvalidateTokenCache provides a mock function with given fields: clientID, clientSecret, authURL -func (_m *OAuthClient) InvalidateTokenCache(clientID string, clientSecret string, authURL string) { - _m.Called(clientID, clientSecret, authURL) -} - -// InvalidateTokenCacheMTLS provides a mock function with given fields: clientID, authURL, certificate, privateKey -func (_m *OAuthClient) InvalidateTokenCacheMTLS(clientID string, authURL string, certificate []byte, privateKey []byte) { - _m.Called(clientID, authURL, certificate, privateKey) -} - -type mockConstructorTestingTNewOAuthClient interface { - mock.TestingT - Cleanup(func()) -} - -// NewOAuthClient creates a new instance of OAuthClient. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewOAuthClient(t mockConstructorTestingTNewOAuthClient) *OAuthClient { - mock := &OAuthClient{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/components/central-application-gateway/pkg/authorization/mocks/Strategy.go b/components/central-application-gateway/pkg/authorization/mocks/Strategy.go deleted file mode 100644 index fc2219c8cb95..000000000000 --- a/components/central-application-gateway/pkg/authorization/mocks/Strategy.go +++ /dev/null @@ -1,54 +0,0 @@ -// Code generated by mockery v2.16.0. DO NOT EDIT. - -package mocks - -import ( - apperrors "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - - clientcert "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/clientcert" - - http "net/http" - - mock "github.com/stretchr/testify/mock" -) - -// Strategy is an autogenerated mock type for the Strategy type -type Strategy struct { - mock.Mock -} - -// AddAuthorization provides a mock function with given fields: r, setter, skipTLSVerification -func (_m *Strategy) AddAuthorization(r *http.Request, setter clientcert.SetClientCertificateFunc, skipTLSVerification bool) apperrors.AppError { - ret := _m.Called(r, setter, skipTLSVerification) - - var r0 apperrors.AppError - if rf, ok := ret.Get(0).(func(*http.Request, clientcert.SetClientCertificateFunc, bool) apperrors.AppError); ok { - r0 = rf(r, setter, skipTLSVerification) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(apperrors.AppError) - } - } - - return r0 -} - -// Invalidate provides a mock function with given fields: -func (_m *Strategy) Invalidate() { - _m.Called() -} - -type mockConstructorTestingTNewStrategy interface { - mock.TestingT - Cleanup(func()) -} - -// NewStrategy creates a new instance of Strategy. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewStrategy(t mockConstructorTestingTNewStrategy) *Strategy { - mock := &Strategy{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/components/central-application-gateway/pkg/authorization/mocks/StrategyFactory.go b/components/central-application-gateway/pkg/authorization/mocks/StrategyFactory.go deleted file mode 100644 index aa54933071e4..000000000000 --- a/components/central-application-gateway/pkg/authorization/mocks/StrategyFactory.go +++ /dev/null @@ -1,44 +0,0 @@ -// Code generated by mockery v2.16.0. DO NOT EDIT. - -package mocks - -import ( - authorization "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization" - mock "github.com/stretchr/testify/mock" -) - -// StrategyFactory is an autogenerated mock type for the StrategyFactory type -type StrategyFactory struct { - mock.Mock -} - -// Create provides a mock function with given fields: credentials -func (_m *StrategyFactory) Create(credentials *authorization.Credentials) authorization.Strategy { - ret := _m.Called(credentials) - - var r0 authorization.Strategy - if rf, ok := ret.Get(0).(func(*authorization.Credentials) authorization.Strategy); ok { - r0 = rf(credentials) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(authorization.Strategy) - } - } - - return r0 -} - -type mockConstructorTestingTNewStrategyFactory interface { - mock.TestingT - Cleanup(func()) -} - -// NewStrategyFactory creates a new instance of StrategyFactory. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewStrategyFactory(t mockConstructorTestingTNewStrategyFactory) *StrategyFactory { - mock := &StrategyFactory{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/components/central-application-gateway/pkg/authorization/model.go b/components/central-application-gateway/pkg/authorization/model.go deleted file mode 100644 index 5dda6a34a2e4..000000000000 --- a/components/central-application-gateway/pkg/authorization/model.go +++ /dev/null @@ -1,67 +0,0 @@ -package authorization - -// Credentials contains OAuth or BasicAuth configuration. -type Credentials struct { - // OAuth is OAuth configuration. - OAuth *OAuth - // OAuthWithCert is OAuthWithCert configuration - OAuthWithCert *OAuthWithCert - // BasicAuth is BasicAuth configuration. - BasicAuth *BasicAuth - // CertificateGen is CertificateGen configuration. - CertificateGen *CertificateGen - // CSRFTokenEndpointURL (optional) to fetch CSRF token - // Deprecated: This field is only used for old implementation of fetching credentials from Application and Secrets. It is not used by authorization package. - // It should be removed when it is no longer supported - CSRFTokenEndpointURL string -} - -// BasicAuth contains details of BasicAuth Auth configuration -type BasicAuth struct { - // Username to use for authentication - Username string - // Password to use for authentication - Password string -} - -// OAuth contains details of OAuth configuration -type OAuth struct { - // URL to OAuth token provider. - URL string - // ClientID to use for authorization. - ClientID string - // ClientSecret to use for authorization. - ClientSecret string - // RequestParameters will be used with request send by the Application Gateway. - RequestParameters *RequestParameters -} - -// CertificateGen details of CertificateGen configuration -type CertificateGen struct { - // Certificate generated by Application Registry - Certificate []byte - // PrivateKey generated by Application Registry - PrivateKey []byte -} - -type OAuthWithCert struct { - URL string - ClientID string - ClientSecret string - Certificate []byte - PrivateKey []byte - RequestParameters *RequestParameters -} - -// RequestParameters contains Headers and QueryParameters -type RequestParameters struct { - Headers *map[string][]string `json:"headers,omitempty"` - QueryParameters *map[string][]string `json:"queryParameters,omitempty"` -} - -func (rp *RequestParameters) unpack() (*map[string][]string, *map[string][]string) { - if rp == nil { - return nil, nil - } - return rp.Headers, rp.QueryParameters -} diff --git a/components/central-application-gateway/pkg/authorization/noauthstrategy.go b/components/central-application-gateway/pkg/authorization/noauthstrategy.go deleted file mode 100644 index 783844ba9728..000000000000 --- a/components/central-application-gateway/pkg/authorization/noauthstrategy.go +++ /dev/null @@ -1,24 +0,0 @@ -package authorization - -import ( - "net/http" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/clientcert" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" -) - -func newNoAuthStrategy() noAuthStrategy { - return noAuthStrategy{} -} - -type noAuthStrategy struct { -} - -func (ns noAuthStrategy) AddAuthorization(_ *http.Request, _ clientcert.SetClientCertificateFunc, _ bool) apperrors.AppError { - return nil -} - -func (ns noAuthStrategy) Invalidate() { - -} diff --git a/components/central-application-gateway/pkg/authorization/oauth/mocks/Client.go b/components/central-application-gateway/pkg/authorization/oauth/mocks/Client.go deleted file mode 100644 index 73d7db5a0060..000000000000 --- a/components/central-application-gateway/pkg/authorization/oauth/mocks/Client.go +++ /dev/null @@ -1,84 +0,0 @@ -// Code generated by mockery v2.16.0. DO NOT EDIT. - -package mocks - -import ( - apperrors "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - mock "github.com/stretchr/testify/mock" -) - -// Client is an autogenerated mock type for the Client type -type Client struct { - mock.Mock -} - -// GetToken provides a mock function with given fields: clientID, clientSecret, authURL, headers, queryParameters, skipVerify -func (_m *Client) GetToken(clientID string, clientSecret string, authURL string, headers *map[string][]string, queryParameters *map[string][]string, skipVerify bool) (string, apperrors.AppError) { - ret := _m.Called(clientID, clientSecret, authURL, headers, queryParameters, skipVerify) - - var r0 string - if rf, ok := ret.Get(0).(func(string, string, string, *map[string][]string, *map[string][]string, bool) string); ok { - r0 = rf(clientID, clientSecret, authURL, headers, queryParameters, skipVerify) - } else { - r0 = ret.Get(0).(string) - } - - var r1 apperrors.AppError - if rf, ok := ret.Get(1).(func(string, string, string, *map[string][]string, *map[string][]string, bool) apperrors.AppError); ok { - r1 = rf(clientID, clientSecret, authURL, headers, queryParameters, skipVerify) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(apperrors.AppError) - } - } - - return r0, r1 -} - -// GetTokenMTLS provides a mock function with given fields: clientID, authURL, certificate, privateKey, headers, queryParameters, skipVerify -func (_m *Client) GetTokenMTLS(clientID string, authURL string, certificate []byte, privateKey []byte, headers *map[string][]string, queryParameters *map[string][]string, skipVerify bool) (string, apperrors.AppError) { - ret := _m.Called(clientID, authURL, certificate, privateKey, headers, queryParameters, skipVerify) - - var r0 string - if rf, ok := ret.Get(0).(func(string, string, []byte, []byte, *map[string][]string, *map[string][]string, bool) string); ok { - r0 = rf(clientID, authURL, certificate, privateKey, headers, queryParameters, skipVerify) - } else { - r0 = ret.Get(0).(string) - } - - var r1 apperrors.AppError - if rf, ok := ret.Get(1).(func(string, string, []byte, []byte, *map[string][]string, *map[string][]string, bool) apperrors.AppError); ok { - r1 = rf(clientID, authURL, certificate, privateKey, headers, queryParameters, skipVerify) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(apperrors.AppError) - } - } - - return r0, r1 -} - -// InvalidateTokenCache provides a mock function with given fields: clientID, clientSecret, authURL -func (_m *Client) InvalidateTokenCache(clientID string, clientSecret string, authURL string) { - _m.Called(clientID, clientSecret, authURL) -} - -// InvalidateTokenCacheMTLS provides a mock function with given fields: clientID, authURL, certificate, privateKey -func (_m *Client) InvalidateTokenCacheMTLS(clientID string, authURL string, certificate []byte, privateKey []byte) { - _m.Called(clientID, authURL, certificate, privateKey) -} - -type mockConstructorTestingTNewClient interface { - mock.TestingT - Cleanup(func()) -} - -// NewClient creates a new instance of Client. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewClient(t mockConstructorTestingTNewClient) *Client { - mock := &Client{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/components/central-application-gateway/pkg/authorization/oauth/oauthclient.go b/components/central-application-gateway/pkg/authorization/oauth/oauthclient.go deleted file mode 100644 index 0a3aa0e4215d..000000000000 --- a/components/central-application-gateway/pkg/authorization/oauth/oauthclient.go +++ /dev/null @@ -1,228 +0,0 @@ -package oauth - -import ( - "context" - "crypto/sha256" - "crypto/tls" - "encoding/hex" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "strings" - "time" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/oauth/tokencache" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/util" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/httpconsts" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/httptools" -) - -type oauthResponse struct { - AccessToken string `json:"access_token"` - TokenType string `json:"token_type"` - ExpiresIn int `json:"expires_in"` - Scope string `json:"scope"` -} - -//go:generate mockery --name=Client -type Client interface { - GetToken(clientID, clientSecret, authURL string, headers, queryParameters *map[string][]string, skipVerify bool) (string, apperrors.AppError) - GetTokenMTLS(clientID, authURL string, certificate, privateKey []byte, headers, queryParameters *map[string][]string, skipVerify bool) (string, apperrors.AppError) - InvalidateTokenCache(clientID string, clientSecret string, authURL string) - InvalidateTokenCacheMTLS(clientID, authURL string, certificate, privateKey []byte) -} - -type client struct { - timeoutDuration int - tokenCache tokencache.TokenCache -} - -func NewOauthClient(timeoutDuration int, tokenCache tokencache.TokenCache) Client { - return &client{ - timeoutDuration: timeoutDuration, - tokenCache: tokenCache, - } -} - -func (c *client) GetToken(clientID, clientSecret, authURL string, headers, queryParameters *map[string][]string, skipVerify bool) (string, apperrors.AppError) { - token, found := c.tokenCache.Get(c.makeOAuthTokenCacheKey(clientID, clientSecret, authURL)) - if found { - return token, nil - } - - tokenResponse, err := c.requestToken(clientID, clientSecret, authURL, headers, queryParameters, skipVerify) - if err != nil { - return "", err - } - - c.tokenCache.Add(c.makeOAuthTokenCacheKey(clientID, clientSecret, authURL), tokenResponse.AccessToken, tokenResponse.ExpiresIn) - - return tokenResponse.AccessToken, nil -} - -func (c *client) GetTokenMTLS(clientID, authURL string, certificate, privateKey []byte, headers, queryParameters *map[string][]string, skipVerify bool) (string, apperrors.AppError) { - token, found := c.tokenCache.Get(c.makeMTLSOAuthTokenCacheKey(clientID, authURL, certificate, privateKey)) - if found { - return token, nil - } - - cert, err := tls.X509KeyPair(certificate, privateKey) - if err != nil { - return "", apperrors.Internal("Failed to prepare certificate, %s", err.Error()) - } - - tokenResponse, requestError := c.requestTokenMTLS(clientID, authURL, cert, headers, queryParameters, skipVerify) - if err != nil { - return "", requestError - } - - if tokenResponse == nil { - return "", apperrors.Internal("Failed to fetch token, possible certificate problem") - } - - c.tokenCache.Add(c.makeMTLSOAuthTokenCacheKey(clientID, authURL, certificate, privateKey), tokenResponse.AccessToken, tokenResponse.ExpiresIn) - - return tokenResponse.AccessToken, nil -} - -func (c *client) InvalidateTokenCache(clientID, clientSecret, authURL string) { - c.tokenCache.Remove(c.makeOAuthTokenCacheKey(clientID, clientSecret, authURL)) -} - -func (c *client) InvalidateTokenCacheMTLS(clientID, authURL string, certificate, privateKey []byte) { - c.tokenCache.Remove(c.makeMTLSOAuthTokenCacheKey(clientID, authURL, certificate, privateKey)) -} - -// to avoid case of single clientID and different endpoints for MTLS and standard oauth -func (c *client) makeOAuthTokenCacheKey(clientID, clientSecret, authURL string) string { - return clientID + clientSecret + authURL -} - -func (c *client) makeMTLSOAuthTokenCacheKey(clientID, authURL string, certificate, privateKey []byte) string { - certificateSha := sha256.Sum256(certificate) - keySha := sha256.Sum256(privateKey) - - hashedCertificate := hex.EncodeToString(certificateSha[:]) - hashedKey := hex.EncodeToString(keySha[:]) - return fmt.Sprintf("%v-%v-%v-%v", clientID, hashedCertificate, hashedKey, authURL) -} - -func (c *client) requestToken(clientID, clientSecret, authURL string, headers, queryParameters *map[string][]string, skipVerify bool) (*oauthResponse, apperrors.AppError) { - transport := &http.Transport{ - TLSClientConfig: &tls.Config{InsecureSkipVerify: skipVerify}, - } - client := &http.Client{Transport: transport} - - form := url.Values{} - form.Add("client_id", clientID) - form.Add("client_secret", clientSecret) - form.Add("grant_type", "client_credentials") - - req, err := http.NewRequest(http.MethodPost, authURL, strings.NewReader(form.Encode())) - if err != nil { - return nil, apperrors.Internal("failed to create token request: %s", err.Error()) - } - - util.AddBasicAuthHeader(req, clientID, clientSecret) - req.Header.Add(httpconsts.HeaderContentType, httpconsts.ContentTypeApplicationURLEncoded) - - setCustomQueryParameters(req.URL, queryParameters) - setCustomHeaders(req.Header, headers) - - ctx, cancel := context.WithTimeout(context.Background(), time.Duration(c.timeoutDuration)*time.Second) - defer cancel() - requestWithContext := req.WithContext(ctx) - - response, err := client.Do(requestWithContext) - if err != nil { - return nil, apperrors.UpstreamServerCallFailed("failed to make a request to '%s': %s", authURL, err.Error()) - } - - if response.StatusCode != http.StatusOK { - return nil, apperrors.UpstreamServerCallFailed("incorrect response code '%d' while getting token from %s", response.StatusCode, authURL) - } - - body, err := ioutil.ReadAll(response.Body) - defer response.Body.Close() - if err != nil { - return nil, apperrors.UpstreamServerCallFailed("failed to read token response body from '%s': %s", authURL, err.Error()) - } - - tokenResponse := &oauthResponse{} - - err = json.Unmarshal(body, tokenResponse) - if err != nil { - return nil, apperrors.UpstreamServerCallFailed("failed to unmarshal token response body: %s", err.Error()) - } - - return tokenResponse, nil -} - -func (c *client) requestTokenMTLS(clientID, authURL string, cert tls.Certificate, headers, queryParameters *map[string][]string, skipVerify bool) (*oauthResponse, apperrors.AppError) { - transport := &http.Transport{ - TLSClientConfig: &tls.Config{ - Certificates: []tls.Certificate{cert}, - InsecureSkipVerify: skipVerify, - }, - } - client := &http.Client{Transport: transport} - - form := url.Values{} - form.Add("client_id", clientID) - form.Add("grant_type", "client_credentials") - - req, err := http.NewRequest(http.MethodPost, authURL, strings.NewReader(form.Encode())) - - if err != nil { - return nil, apperrors.Internal("failed to create token request: %s", err.Error()) - } - - req.Header.Add(httpconsts.HeaderContentType, httpconsts.ContentTypeApplicationURLEncoded) - - setCustomQueryParameters(req.URL, queryParameters) - setCustomHeaders(req.Header, headers) - - ctx, cancel := context.WithTimeout(context.Background(), time.Duration(c.timeoutDuration)*time.Second) - defer cancel() - requestWithContext := req.WithContext(ctx) - - response, err := client.Do(requestWithContext) - if err != nil { - return nil, apperrors.UpstreamServerCallFailed("failed to make a request to '%s': %s", authURL, err.Error()) - } - - if response.StatusCode != http.StatusOK { - return nil, apperrors.UpstreamServerCallFailed("incorrect response code '%d' while getting token from %s", response.StatusCode, authURL) - } - - body, err := ioutil.ReadAll(response.Body) - defer response.Body.Close() - if err != nil { - return nil, apperrors.UpstreamServerCallFailed("failed to read token response body from '%s': %s", authURL, err.Error()) - } - - tokenResponse := &oauthResponse{} - - err = json.Unmarshal(body, tokenResponse) - if err != nil { - return nil, apperrors.UpstreamServerCallFailed("failed to unmarshal token response body: %s", err.Error()) - } - - return tokenResponse, nil -} - -func setCustomQueryParameters(reqURL *url.URL, customQueryParams *map[string][]string) { - httptools.SetQueryParameters(reqURL, customQueryParams) -} - -func setCustomHeaders(reqHeaders http.Header, customHeaders *map[string][]string) { - if _, ok := reqHeaders[httpconsts.HeaderUserAgent]; !ok { - // explicitly disable User-Agent so it's not set to default value - reqHeaders.Set(httpconsts.HeaderUserAgent, "") - } - - httptools.SetHeaders(reqHeaders, customHeaders) -} diff --git a/components/central-application-gateway/pkg/authorization/oauth/oauthclient_test.go b/components/central-application-gateway/pkg/authorization/oauth/oauthclient_test.go deleted file mode 100644 index 416ac84505f5..000000000000 --- a/components/central-application-gateway/pkg/authorization/oauth/oauthclient_test.go +++ /dev/null @@ -1,288 +0,0 @@ -package oauth - -import ( - "encoding/base64" - "encoding/json" - "net/http" - "net/http/httptest" - "strings" - "testing" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/httpconsts" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/oauth/tokencache/mocks" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestOauthClient_GetToken(t *testing.T) { - t.Run("should get token from cache if present", func(t *testing.T) { - // given - tokenCache := mocks.TokenCache{} - tokenCache.On("Get", "testIDtestSecret").Return("123456789", true) - - oauthClient := NewOauthClient(10, &tokenCache) - - // when - token, err := oauthClient.GetToken("testID", "testSecret", "", nil, nil, false) - - // then - require.NoError(t, err) - assert.Equal(t, "123456789", token) - tokenCache.AssertExpectations(t) - }) - - t.Run("should fetch token from server when token if not present in cache", func(t *testing.T) { - // given - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - - checkAccessTokenRequest(t, r) - - response := oauthResponse{AccessToken: "123456789", TokenType: "bearer", ExpiresIn: 3600, Scope: "basic"} - - w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(response) - })) - defer ts.Close() - - tokenKey := "testID" + "testSecret" + ts.URL - - tokenCache := mocks.TokenCache{} - tokenCache.On("Get", tokenKey).Return("", false) - tokenCache.On("Add", tokenKey, "123456789", 3600).Return() - - oauthClient := NewOauthClient(10, &tokenCache) - - // when - token, err := oauthClient.GetToken("testID", "testSecret", ts.URL, nil, nil, false) - - // then - require.NoError(t, err) - assert.Equal(t, "123456789", token) - tokenCache.AssertExpectations(t) - }) - - t.Run("should fetch token from insecure server when token if not present in cache", func(t *testing.T) { - // given - ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - - checkAccessTokenRequest(t, r) - - response := oauthResponse{AccessToken: "123456789", TokenType: "bearer", ExpiresIn: 3600, Scope: "basic"} - - w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(response) - })) - - ts.StartTLS() - defer ts.Close() - - tokenKey := "testID" + "testSecret" + ts.URL - - tokenCache := mocks.TokenCache{} - tokenCache.On("Get", tokenKey).Return("", false) - tokenCache.On("Add", tokenKey, "123456789", 3600).Return() - - oauthClient := NewOauthClient(10, &tokenCache) - - // when - token, err := oauthClient.GetToken("testID", "testSecret", ts.URL, nil, nil, true) - - // then - require.NoError(t, err) - assert.Equal(t, "123456789", token) - tokenCache.AssertExpectations(t) - }) - - t.Run("should fetch token using additional headers and query parameters", func(t *testing.T) { - // given - headers := map[string][]string{ - "headerKey": {"headerValue"}, - } - queryParameters := map[string][]string{ - "queryParameterKey": {"queryParameterValue"}, - } - - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - - checkAccessTokenRequest(t, r) - checkAccessTokenRequestAdditionalRequestParameters(t, r) - - response := oauthResponse{AccessToken: "123456789", TokenType: "bearer", ExpiresIn: 3600, Scope: "basic"} - - w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(response) - })) - defer ts.Close() - - tokenKey := "testID" + "testSecret" + ts.URL - - tokenCache := mocks.TokenCache{} - tokenCache.On("Get", tokenKey).Return("", false) - tokenCache.On("Add", tokenKey, "123456789", 3600).Return() - - oauthClient := NewOauthClient(10, &tokenCache) - - // when - token, err := oauthClient.GetToken("testID", "testSecret", ts.URL, &headers, &queryParameters, false) - - // then - require.NoError(t, err) - assert.Equal(t, "123456789", token) - tokenCache.AssertExpectations(t) - }) - - t.Run("should fail when unable to get token", func(t *testing.T) { - // given - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - - w.WriteHeader(http.StatusInternalServerError) - })) - defer ts.Close() - - tokenKey := "testID" + "testSecret" + ts.URL - - tokenCache := mocks.TokenCache{} - tokenCache.On("Get", tokenKey).Return("", false) - - oauthClient := NewOauthClient(10, &tokenCache) - - // when - token, err := oauthClient.GetToken("testID", "testSecret", ts.URL, nil, nil, false) - - // then - require.Error(t, err) - assert.Equal(t, "", token) - tokenCache.AssertExpectations(t) - }) - - t.Run("should fail if payload is empty", func(t *testing.T) { - // given - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - - checkAccessTokenRequest(t, r) - - w.WriteHeader(http.StatusOK) - })) - defer ts.Close() - - tokenKey := "testID" + "testSecret" + ts.URL - - tokenCache := mocks.TokenCache{} - tokenCache.On("Get", tokenKey).Return("", false) - - oauthClient := NewOauthClient(10, &tokenCache) - - // when - token, err := oauthClient.GetToken("testID", "testSecret", ts.URL, nil, nil, false) - - // then - require.Error(t, err) - assert.Equal(t, "", token) - tokenCache.AssertExpectations(t) - }) - - t.Run("should fail if OAuth address is incorrect", func(t *testing.T) { - // given - tokenKey := "testID" + "testSecret" + "http://some_no_existent_address.com/token" - - tokenCache := mocks.TokenCache{} - tokenCache.On("Get", tokenKey).Return("", false) - - oauthClient := NewOauthClient(10, &tokenCache) - - // when - token, err := oauthClient.GetToken("testID", "testSecret", "http://some_no_existent_address.com/token", nil, nil, false) - - // then - require.Error(t, err) - assert.Equal(t, "", token) - tokenCache.AssertExpectations(t) - }) - - t.Run("should fail when calling server protected with self-signed certificate", func(t *testing.T) { - // given - ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - })) - - ts.StartTLS() - defer ts.Close() - - tokenKey := "testID" + "testSecret" + ts.URL - - tokenCache := mocks.TokenCache{} - tokenCache.On("Get", tokenKey).Return("", false) - //tokenCache.On("Add", mock.Anything, mock.Anything, mock.Anything).Times(0) - - oauthClient := NewOauthClient(10, &tokenCache) - - // when - _, err := oauthClient.GetToken("testID", "testSecret", ts.URL, nil, nil, false) - - // then - require.Error(t, err) - tokenCache.AssertExpectations(t) - }) -} - -func TestOauthClient_GetTokenMTLS(t *testing.T) { - var certSHA = "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08" - var keySHA = "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08" - - t.Run("should get token from cache if present", func(t *testing.T) { - // given - tokenCache := mocks.TokenCache{} - tokenCache.On("Get", "testID-"+certSHA+"-"+keySHA+"-testURL").Return("123456789", true) - - oauthClient := NewOauthClient(10, &tokenCache) - - // when - token, err := oauthClient.GetTokenMTLS("testID", "testURL", []byte("test"), []byte("test"), nil, nil, false) - - // then - require.NoError(t, err) - assert.Equal(t, "123456789", token) - tokenCache.AssertExpectations(t) - }) - - t.Run("should fail if Certificate and Private Key is not valid", func(t *testing.T) { - // given - tokenCache := mocks.TokenCache{} - tokenCache.On("Get", "testID-"+certSHA+"-"+keySHA+"-testURL").Return("", false) - - oauthClient := NewOauthClient(10, &tokenCache) - - // when - token, err := oauthClient.GetTokenMTLS("testID", "testURL", []byte("test"), []byte("test"), nil, nil, false) - - // then - assert.Error(t, err, apperrors.Internal("Failed to prepare certificate, %s", err.Error())) - assert.Equal(t, "", token) - tokenCache.AssertExpectations(t) - }) -} - -func checkAccessTokenRequest(t *testing.T, r *http.Request) { - err := r.ParseForm() - require.NoError(t, err) - - assert.Equal(t, "testID", r.PostForm.Get("client_id")) - assert.Equal(t, "testSecret", r.PostForm.Get("client_secret")) - assert.Equal(t, "client_credentials", r.PostForm.Get("grant_type")) - - authHeader := r.Header.Get(httpconsts.HeaderAuthorization) - encodedCredentials := strings.TrimPrefix(string(authHeader), "Basic ") - decoded, err := base64.StdEncoding.DecodeString(encodedCredentials) - require.NoError(t, err) - credentials := strings.Split(string(decoded), ":") - assert.Equal(t, "testID", credentials[0]) - assert.Equal(t, "testSecret", credentials[1]) -} - -func checkAccessTokenRequestAdditionalRequestParameters(t *testing.T, r *http.Request) { - assert.Equal(t, []string{"queryParameterValue"}, r.URL.Query()["queryParameterKey"]) - assert.Equal(t, "headerValue", r.Header.Get("headerKey")) -} diff --git a/components/central-application-gateway/pkg/authorization/oauth/tokencache/mocks/TokenCache.go b/components/central-application-gateway/pkg/authorization/oauth/tokencache/mocks/TokenCache.go deleted file mode 100644 index e305cfd52370..000000000000 --- a/components/central-application-gateway/pkg/authorization/oauth/tokencache/mocks/TokenCache.go +++ /dev/null @@ -1,41 +0,0 @@ -// Code generated by mockery v1.0.0. DO NOT EDIT. - -package mocks - -import mock "github.com/stretchr/testify/mock" - -// TokenCache is an autogenerated mock type for the TokenCache type -type TokenCache struct { - mock.Mock -} - -// Add provides a mock function with given fields: clientID, token, expirationSeconds -func (_m *TokenCache) Add(clientID string, token string, expirationSeconds int) { - _m.Called(clientID, token, expirationSeconds) -} - -// Get provides a mock function with given fields: clientID -func (_m *TokenCache) Get(clientID string) (string, bool) { - ret := _m.Called(clientID) - - var r0 string - if rf, ok := ret.Get(0).(func(string) string); ok { - r0 = rf(clientID) - } else { - r0 = ret.Get(0).(string) - } - - var r1 bool - if rf, ok := ret.Get(1).(func(string) bool); ok { - r1 = rf(clientID) - } else { - r1 = ret.Get(1).(bool) - } - - return r0, r1 -} - -// Remove provides a mock function with given fields: clientID -func (_m *TokenCache) Remove(clientID string) { - _m.Called(clientID) -} diff --git a/components/central-application-gateway/pkg/authorization/oauth/tokencache/tokencache.go b/components/central-application-gateway/pkg/authorization/oauth/tokencache/tokencache.go deleted file mode 100644 index 8aee61a0fe51..000000000000 --- a/components/central-application-gateway/pkg/authorization/oauth/tokencache/tokencache.go +++ /dev/null @@ -1,40 +0,0 @@ -package tokencache - -import ( - "time" - - cache "github.com/patrickmn/go-cache" -) - -type TokenCache interface { - Get(clientID string) (token string, found bool) - Add(clientID, token string, expirationSeconds int) - Remove(clientID string) -} - -type tokenCache struct { - cache *cache.Cache -} - -func NewTokenCache() TokenCache { - return &tokenCache{ - cache: cache.New(cache.NoExpiration, cache.NoExpiration), - } -} - -func (tc *tokenCache) Get(clientId string) (token string, found bool) { - res, found := tc.cache.Get(clientId) - if !found { - return "", false - } - - return res.(string), found -} - -func (tc *tokenCache) Add(clientID, token string, expirationSeconds int) { - tc.cache.Set(clientID, token, time.Duration(expirationSeconds-2)*time.Second) -} - -func (tc *tokenCache) Remove(clientID string) { - tc.cache.Delete(clientID) -} diff --git a/components/central-application-gateway/pkg/authorization/oauth/tokencache/tokencache_test.go b/components/central-application-gateway/pkg/authorization/oauth/tokencache/tokencache_test.go deleted file mode 100644 index 0dc704d4c926..000000000000 --- a/components/central-application-gateway/pkg/authorization/oauth/tokencache/tokencache_test.go +++ /dev/null @@ -1,70 +0,0 @@ -package tokencache - -import ( - "testing" - "time" - - "github.com/stretchr/testify/assert" -) - -const ( - cachedClientID = "cachedClientID" - cachedToken = "cachedToken" -) - -func TestTokenCache(t *testing.T) { - t.Run("should add and retrieve the cachedToken from the cache", func(t *testing.T) { - // given - tokenCache := NewTokenCache() - tokenCache.Add(cachedClientID, cachedToken, 3600) - - // when - token, found := tokenCache.Get(cachedClientID) - - // then - assert.Equal(t, true, found) - assert.Equal(t, cachedToken, token) - - }) - - t.Run("should return false if cachedToken was not found", func(t *testing.T) { - // given - tokenCache := NewTokenCache() - - // when - token, found := tokenCache.Get(cachedClientID) - - // then - assert.Equal(t, false, found) - assert.Equal(t, "", token) - }) - - t.Run("should return false if cachedToken expired", func(t *testing.T) { - // given - tokenCache := NewTokenCache() - tokenCache.Add(cachedClientID, cachedToken, 3) - - time.Sleep(3 * time.Second) - - // when - token, found := tokenCache.Get(cachedClientID) - - // then - assert.Equal(t, false, found) - assert.Equal(t, "", token) - }) - - t.Run("should remove token from the cache", func(t *testing.T) { - // given - tokenCache := NewTokenCache() - tokenCache.Add(cachedClientID, cachedToken, 3600) - tokenCache.Remove(cachedClientID) - - // when - token, found := tokenCache.Get(cachedClientID) - - // then - assert.Equal(t, false, found) - assert.Equal(t, "", token) - }) -} diff --git a/components/central-application-gateway/pkg/authorization/oauthcertstrategy.go b/components/central-application-gateway/pkg/authorization/oauthcertstrategy.go deleted file mode 100644 index e2b641589223..000000000000 --- a/components/central-application-gateway/pkg/authorization/oauthcertstrategy.go +++ /dev/null @@ -1,56 +0,0 @@ -package authorization - -import ( - "fmt" - "net/http" - - "go.uber.org/zap" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/httpconsts" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/clientcert" -) - -type oauthWithCertStrategy struct { - oauthClient OAuthClient - clientId string - clientSecret string - certificate []byte - privateKey []byte - url string - requestParameters *RequestParameters - tokenRequestSkipVerify bool -} - -func newOAuthWithCertStrategy(oauthClient OAuthClient, clientId string, clientSecret string, certificate, privateKey []byte, url string, requestParameters *RequestParameters) oauthWithCertStrategy { - return oauthWithCertStrategy{ - oauthClient: oauthClient, - clientId: clientId, - clientSecret: clientSecret, - certificate: certificate, - privateKey: privateKey, - url: url, - requestParameters: requestParameters, - } -} - -func (o oauthWithCertStrategy) AddAuthorization(r *http.Request, _ clientcert.SetClientCertificateFunc, skipTLSVerification bool) apperrors.AppError { - zap.L().Info("passing skipTLSVerification to GetTokenMTLS", - zap.Bool("skipTLSVerification", skipTLSVerification)) - headers, queryParameters := o.requestParameters.unpack() - token, err := o.oauthClient.GetTokenMTLS(o.clientId, o.url, o.certificate, o.privateKey, headers, queryParameters, skipTLSVerification) - if err != nil { - zap.L().Error("failed to get token", - zap.Error(err)) - return apperrors.Internal("Failed to get token: %s", err.Error()) - } - - r.Header.Set(httpconsts.HeaderAuthorization, fmt.Sprintf("Bearer %s", token)) - - return nil -} - -func (o oauthWithCertStrategy) Invalidate() { - o.oauthClient.InvalidateTokenCacheMTLS(o.clientId, o.url, o.certificate, o.privateKey) -} diff --git a/components/central-application-gateway/pkg/authorization/oauthcertstrategy_test.go b/components/central-application-gateway/pkg/authorization/oauthcertstrategy_test.go deleted file mode 100644 index cb10d3f317d4..000000000000 --- a/components/central-application-gateway/pkg/authorization/oauthcertstrategy_test.go +++ /dev/null @@ -1,73 +0,0 @@ -package authorization - -import ( - "net/http" - "testing" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/testconsts" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - - oauthMocks "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/oauth/mocks" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/httpconsts" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestAuthWithCerStrategy(t *testing.T) { - - t.Run("should add Authorization header", func(t *testing.T) { - // given - oauthClientMock := &oauthMocks.Client{} - - oauthStrategy := newOAuthWithCertStrategy(oauthClientMock, "clientId", "clientSecret", certificate, privateKey, "www.example.com/token", nil) - - oauthClientMock.On("GetTokenMTLS", "clientId", "www.example.com/token", []byte(testconsts.Certificate), []byte(testconsts.PrivateKey), (*map[string][]string)(nil), (*map[string][]string)(nil), true).Return("token", nil) - - request, err := http.NewRequest("GET", "www.example.com", nil) - require.NoError(t, err) - - // when - err = oauthStrategy.AddAuthorization(request, nil, true) - - // then - require.NoError(t, err) - authHeader := request.Header.Get(httpconsts.HeaderAuthorization) - assert.Equal(t, "Bearer token", authHeader) - }) - - t.Run("should invalidate cache", func(t *testing.T) { - // given - oauthClientMock := &oauthMocks.Client{} - oauthClientMock.On("InvalidateTokenCacheMTLS", "clientId", "www.example.com/token", certificate, privateKey).Return("token", nil).Once() - - authWithCertStrategy := newOAuthWithCertStrategy(oauthClientMock, "clientId", "clientSecret", certificate, privateKey, "www.example.com/token", nil) - - // when - authWithCertStrategy.Invalidate() - - // then - oauthClientMock.AssertExpectations(t) - }) - - t.Run("should not add Authorization header when getting token failed", func(t *testing.T) { - // given - oauthClientMock := &oauthMocks.Client{} - - authWithCertStrategy := newOAuthWithCertStrategy(oauthClientMock, "clientId", "clientSecret", certificate, privateKey, "www.example.com/token", nil) - oauthClientMock.On("GetTokenMTLS", "clientId", "www.example.com/token", []byte(testconsts.Certificate), []byte(testconsts.PrivateKey), (*map[string][]string)(nil), (*map[string][]string)(nil), false).Return("", apperrors.Internal("failed")).Once() - - request, err := http.NewRequest("GET", "www.example.com", nil) - require.NoError(t, err) - - // when - err = authWithCertStrategy.AddAuthorization(request, nil, false) - - // then - require.Error(t, err) - authHeader := request.Header.Get(httpconsts.HeaderAuthorization) - assert.Equal(t, "", authHeader) - oauthClientMock.AssertExpectations(t) - }) - -} diff --git a/components/central-application-gateway/pkg/authorization/oauthstrategy.go b/components/central-application-gateway/pkg/authorization/oauthstrategy.go deleted file mode 100644 index 8a198302eab1..000000000000 --- a/components/central-application-gateway/pkg/authorization/oauthstrategy.go +++ /dev/null @@ -1,49 +0,0 @@ -package authorization - -import ( - "fmt" - "net/http" - - "go.uber.org/zap" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/clientcert" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/httpconsts" -) - -type oauthStrategy struct { - oauthClient OAuthClient - clientId string - clientSecret string - url string - requestParameters *RequestParameters - tokenRequestSkipVerify bool -} - -func newOAuthStrategy(oauthClient OAuthClient, clientId, clientSecret, url string, requestParameters *RequestParameters) oauthStrategy { - return oauthStrategy{ - oauthClient: oauthClient, - clientId: clientId, - clientSecret: clientSecret, - url: url, - requestParameters: requestParameters, - } -} - -func (o oauthStrategy) AddAuthorization(r *http.Request, _ clientcert.SetClientCertificateFunc, skipTLSVerification bool) apperrors.AppError { - headers, queryParameters := o.requestParameters.unpack() - token, err := o.oauthClient.GetToken(o.clientId, o.clientSecret, o.url, headers, queryParameters, skipTLSVerification) - if err != nil { - zap.L().Error("failed to get token", - zap.Error(err)) - return err - } - - r.Header.Set(httpconsts.HeaderAuthorization, fmt.Sprintf("Bearer %s", token)) - - return nil -} - -func (o oauthStrategy) Invalidate() { - o.oauthClient.InvalidateTokenCache(o.clientId, o.clientSecret, o.url) -} diff --git a/components/central-application-gateway/pkg/authorization/oauthstrategy_test.go b/components/central-application-gateway/pkg/authorization/oauthstrategy_test.go deleted file mode 100644 index 5bb973c10f05..000000000000 --- a/components/central-application-gateway/pkg/authorization/oauthstrategy_test.go +++ /dev/null @@ -1,69 +0,0 @@ -package authorization - -import ( - "net/http" - "testing" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - oauthMocks "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/oauth/mocks" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/httpconsts" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestAuthStrategy(t *testing.T) { - - t.Run("should add Authorization header", func(t *testing.T) { - // given - oauthClientMock := &oauthMocks.Client{} - oauthClientMock.On("GetToken", "clientId", "clientSecret", "www.example.com/token", (*map[string][]string)(nil), (*map[string][]string)(nil), true).Return("token", nil) - - oauthStrategy := newOAuthStrategy(oauthClientMock, "clientId", "clientSecret", "www.example.com/token", nil) - - request, err := http.NewRequest("GET", "www.example.com", nil) - require.NoError(t, err) - - // when - err = oauthStrategy.AddAuthorization(request, nil, true) - - // then - require.NoError(t, err) - authHeader := request.Header.Get(httpconsts.HeaderAuthorization) - assert.Equal(t, "Bearer token", authHeader) - }) - - t.Run("should invalidate cache", func(t *testing.T) { - // given - oauthClientMock := &oauthMocks.Client{} - oauthClientMock.On("InvalidateTokenCache", "clientId", "clientSecret", "www.example.com/token").Return("token", nil).Once() - - oauthStrategy := newOAuthStrategy(oauthClientMock, "clientId", "clientSecret", "www.example.com/token", nil) - - // when - oauthStrategy.Invalidate() - - // then - oauthClientMock.AssertExpectations(t) - }) - - t.Run("should not add Authorization header when getting token failed", func(t *testing.T) { - // given - oauthClientMock := &oauthMocks.Client{} - oauthClientMock.On("GetToken", "clientId", "clientSecret", "www.example.com/token", (*map[string][]string)(nil), (*map[string][]string)(nil), false).Return("", apperrors.Internal("failed")).Once() - - oauthStrategy := newOAuthStrategy(oauthClientMock, "clientId", "clientSecret", "www.example.com/token", nil) - - request, err := http.NewRequest("GET", "www.example.com", nil) - require.NoError(t, err) - - // when - err = oauthStrategy.AddAuthorization(request, nil, false) - - // then - require.Error(t, err) - authHeader := request.Header.Get(httpconsts.HeaderAuthorization) - assert.Equal(t, "", authHeader) - oauthClientMock.AssertExpectations(t) - }) - -} diff --git a/components/central-application-gateway/pkg/authorization/testconsts/testconsts.go b/components/central-application-gateway/pkg/authorization/testconsts/testconsts.go deleted file mode 100644 index 97d5dfd9932b..000000000000 --- a/components/central-application-gateway/pkg/authorization/testconsts/testconsts.go +++ /dev/null @@ -1,48 +0,0 @@ -package testconsts - -const ( - Certificate = `-----BEGIN CERTIFICATE----- -MIICwDCCAaigAwIBAgIBAjANBgkqhkiG9w0BAQsFADAPMQ0wCwYDVQQDEwR0ZXN0 -MB4XDTE5MDExNzExMDg0M1oXDTIwMDExNzExMDg0M1owDzENMAsGA1UEAxMEdGVz -dDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALG4LTb4U5AfzzZ+5eGv -37yiuBoG7NHl0JWrwv7gGNOUMgN6KzR4SbIhDxEerg0NXF33MaLHsBH7XpXdfu1K -gZzbos+jcMhq9obxByIpWZjVzDqGvFhtJ13GsXHky4Iz01wJkd7Lerbpe06eJfGA -iHgY9XOOl6Ckx0OXyiGwti1ab+Z17W28UuX4rloq15HWzgzWWGLv8dIeG79mKBLX -JjwPpBLQGFDUR29soI0tlcldNlJTDB4I5O04mdBKiJBlNs/k6UU5hPgARFP3vsy6 -xbmECYsiV46RaIvh4pm4tkSvQ2WjaIL5V4oNc00STUPMgM36yxbCcSpOfvbJzwZD -TTUCAwEAAaMnMCUwDgYDVR0PAQH/BAQDAgeAMBMGA1UdJQQMMAoGCCsGAQUFBwMC -MA0GCSqGSIb3DQEBCwUAA4IBAQAXk05jHOpwvBtrKAapzy3zPSIL20KzUwFbE4Ey -FjEB1L5yiJ98DgkeBe2ayJtOI5qADq9ZeZ+Bq2QQZ+f2Y8lwm5TLtc3IAZUzI/sv -4NUj5NaiTeu/6kX165mWUtwZftetUHgJKqyQv1ClRNN6Ayfuv76Qq0DIEfHAvelD -rHWXo6ju4eD8IDRl+xv0wSbID/OUi9n5vBir+CJSIxmwW0jDKo7RZ//7gAm25sue -2oqaDiVVH2bsYbY41SRS/RrJqLYQQCqjNVAxhuGFV1uigz9LxIXpOfD2GrAVHBGJ -WHGZtRZO7LQJ2Yxy4mKYo0ndJOZIPAXzVveu+FY+CxSnWe4y ------END CERTIFICATE-----` - PrivateKey = `-----BEGIN RSA PRIVATE KEY----- -MIIEowIBAAKCAQEAsbgtNvhTkB/PNn7l4a/fvKK4Ggbs0eXQlavC/uAY05QyA3or -NHhJsiEPER6uDQ1cXfcxosewEfteld1+7UqBnNuiz6NwyGr2hvEHIilZmNXMOoa8 -WG0nXcaxceTLgjPTXAmR3st6tul7Tp4l8YCIeBj1c46XoKTHQ5fKIbC2LVpv5nXt -bbxS5fiuWirXkdbODNZYYu/x0h4bv2YoEtcmPA+kEtAYUNRHb2ygjS2VyV02UlMM -Hgjk7TiZ0EqIkGU2z+TpRTmE+ABEU/e+zLrFuYQJiyJXjpFoi+Himbi2RK9DZaNo -gvlXig1zTRJNQ8yAzfrLFsJxKk5+9snPBkNNNQIDAQABAoIBAQCvDGI8ysxEIZDQ -dJ2pdrpB62S6/ic1d8/EHLKsqb7KaCX7FtKHlBPCyJ02l6mIYaihRWI2m8npbFb1 -9n2W7NRN1GjBbJMiVXkN4UrNcz01NSE8ZIoP7zPfQl51eI6baMC+3w43DOWKVN+H -yG5HOfsxkCPz9neTW7qJ8XC/TneiotRD7lc2szXVrmpnGsebKiHL4zIKw2JvDox8 -NU7tiGpab24Yn7M5CRyrZTWtzGADuheiCBi77DW0W87gpQSQJjOAZr7n92F1HnNR -6knBEBlG0ZkGOd5WSIkLw98Wvh4+4wY+yFlXjp7Q4xmJhEnZ/dfSXXsDYLB4peVB -1s2/KQ4BAoGBAOX288zW/imek38Odp0Gqffei+p7pb1B8kJe4s6fK8Vgzf9cRwGM -rVAeYmWM4pj/SAcY9V/60qbBI+gnLStBKMFSgDjOdtq60OK/i80z6+lCxt7LiLRj -hfk0yczWT+7v+uCJYAFa7qLVN+8O+V5tbcx2JkorTh1aowIVEaVr0VSxAoGBAMXX -AVZokkQFStn+TYkbNLeCYKVehxltbVF7aPDOmYxv60g7AHXAhKnCbCpdVpOFWufa -6ug+OR+eEVFy2ODbtaOgH/DnvqltkXITdqcXElV48skADn/K6xOiTDtZQ5NX30ql -YdwZo2EsPpWse2Xx6N2WJr+ry/C5d8g7naQTO3HFAoGAWeYUoPtbGMIZPw5UaEZ2 -o6OoZt43iKkDH9cgK04mOl8BqNZWG9D2399A8BoHa3BApCWppv/S4cWXV+YYzlQG -rqyl2486/38QsdPXvzyQ+PtV6zr+Eibl9OoiCaWuUeYW2ThbA6ycpaNc3mOoMLXu -uoNlrJEJVIheOS4rW9OuXcECgYA7RGLJMQCIUhGPZqhxp23Of8dWIxBT5L04CMFy -SmIjeS/B7rL/k5HqjSz8MAQMo4mNJb7znhhcyWykusQP8KHkh8ap07MBbKqCwyPr -gHTkmBwbbOHrFK4BrsApk180F8HzycGcPy37oVaKXiaFbsf1AdNP3jZ1QgqJOJrM -GVrYhQKBgCNxoVJ+yi1PWWzd+erdSr/rqOwWEKIykDxAOtJUOjAUoH3t8qDzHDPx -Kw3UoadKDOno5X1xjDMGOe/s48bg0o3wsklC/C6QnYnIVCZUR7hvw865T1fQA5kB -eQL/kF0yUbR1b5deQ8Rq7x1UUQV1BcBFwfTaiAutq1sPRTNSHWtP ------END RSA PRIVATE KEY-----` -) diff --git a/components/central-application-gateway/pkg/authorization/util/util.go b/components/central-application-gateway/pkg/authorization/util/util.go deleted file mode 100644 index 1b3a962e4dff..000000000000 --- a/components/central-application-gateway/pkg/authorization/util/util.go +++ /dev/null @@ -1,21 +0,0 @@ -package util - -import ( - "encoding/base64" - "fmt" - "net/http" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/httpconsts" -) - -func AddBasicAuthHeader(request *http.Request, clientId, clientSecret string) { - basicAuthHeader := fmt.Sprintf("Basic %s", encodeBasicAuthCredentials(clientId, clientSecret)) - - request.Header.Set(httpconsts.HeaderAuthorization, basicAuthHeader) -} - -func encodeBasicAuthCredentials(username, password string) string { - auth := username + ":" + password - - return base64.StdEncoding.EncodeToString([]byte(auth)) -} diff --git a/components/central-application-gateway/pkg/client/clientset/versioned/clientset.go b/components/central-application-gateway/pkg/client/clientset/versioned/clientset.go deleted file mode 100644 index dbb4d3eb68ae..000000000000 --- a/components/central-application-gateway/pkg/client/clientset/versioned/clientset.go +++ /dev/null @@ -1,81 +0,0 @@ -// Code generated by client-gen. DO NOT EDIT. - -package versioned - -import ( - "fmt" - - applicationconnectorv1alpha1 "github.com/kyma-project/kyma/components/central-application-gateway/pkg/client/clientset/versioned/typed/applicationconnector/v1alpha1" - discovery "k8s.io/client-go/discovery" - rest "k8s.io/client-go/rest" - flowcontrol "k8s.io/client-go/util/flowcontrol" -) - -type Interface interface { - Discovery() discovery.DiscoveryInterface - ApplicationconnectorV1alpha1() applicationconnectorv1alpha1.ApplicationconnectorV1alpha1Interface -} - -// Clientset contains the clients for groups. Each group has exactly one -// version included in a Clientset. -type Clientset struct { - *discovery.DiscoveryClient - applicationconnectorV1alpha1 *applicationconnectorv1alpha1.ApplicationconnectorV1alpha1Client -} - -// ApplicationconnectorV1alpha1 retrieves the ApplicationconnectorV1alpha1Client -func (c *Clientset) ApplicationconnectorV1alpha1() applicationconnectorv1alpha1.ApplicationconnectorV1alpha1Interface { - return c.applicationconnectorV1alpha1 -} - -// Discovery retrieves the DiscoveryClient -func (c *Clientset) Discovery() discovery.DiscoveryInterface { - if c == nil { - return nil - } - return c.DiscoveryClient -} - -// NewForConfig creates a new Clientset for the given config. -// If config's RateLimiter is not set and QPS and Burst are acceptable, -// NewForConfig will generate a rate-limiter in configShallowCopy. -func NewForConfig(c *rest.Config) (*Clientset, error) { - configShallowCopy := *c - if configShallowCopy.RateLimiter == nil && configShallowCopy.QPS > 0 { - if configShallowCopy.Burst <= 0 { - return nil, fmt.Errorf("burst is required to be greater than 0 when RateLimiter is not set and QPS is set to greater than 0") - } - configShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst) - } - var cs Clientset - var err error - cs.applicationconnectorV1alpha1, err = applicationconnectorv1alpha1.NewForConfig(&configShallowCopy) - if err != nil { - return nil, err - } - - cs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfig(&configShallowCopy) - if err != nil { - return nil, err - } - return &cs, nil -} - -// NewForConfigOrDie creates a new Clientset for the given config and -// panics if there is an error in the config. -func NewForConfigOrDie(c *rest.Config) *Clientset { - var cs Clientset - cs.applicationconnectorV1alpha1 = applicationconnectorv1alpha1.NewForConfigOrDie(c) - - cs.DiscoveryClient = discovery.NewDiscoveryClientForConfigOrDie(c) - return &cs -} - -// New creates a new Clientset for the given RESTClient. -func New(c rest.Interface) *Clientset { - var cs Clientset - cs.applicationconnectorV1alpha1 = applicationconnectorv1alpha1.New(c) - - cs.DiscoveryClient = discovery.NewDiscoveryClient(c) - return &cs -} diff --git a/components/central-application-gateway/pkg/client/clientset/versioned/doc.go b/components/central-application-gateway/pkg/client/clientset/versioned/doc.go deleted file mode 100644 index 0e0c2a8900e2..000000000000 --- a/components/central-application-gateway/pkg/client/clientset/versioned/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// Code generated by client-gen. DO NOT EDIT. - -// This package has the automatically generated clientset. -package versioned diff --git a/components/central-application-gateway/pkg/client/clientset/versioned/fake/clientset_generated.go b/components/central-application-gateway/pkg/client/clientset/versioned/fake/clientset_generated.go deleted file mode 100644 index d1e6ab73a70c..000000000000 --- a/components/central-application-gateway/pkg/client/clientset/versioned/fake/clientset_generated.go +++ /dev/null @@ -1,66 +0,0 @@ -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - clientset "github.com/kyma-project/kyma/components/central-application-gateway/pkg/client/clientset/versioned" - applicationconnectorv1alpha1 "github.com/kyma-project/kyma/components/central-application-gateway/pkg/client/clientset/versioned/typed/applicationconnector/v1alpha1" - fakeapplicationconnectorv1alpha1 "github.com/kyma-project/kyma/components/central-application-gateway/pkg/client/clientset/versioned/typed/applicationconnector/v1alpha1/fake" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/discovery" - fakediscovery "k8s.io/client-go/discovery/fake" - "k8s.io/client-go/testing" -) - -// NewSimpleClientset returns a clientset that will respond with the provided objects. -// It's backed by a very simple object tracker that processes creates, updates and deletions as-is, -// without applying any validations and/or defaults. It shouldn't be considered a replacement -// for a real clientset and is mostly useful in simple unit tests. -func NewSimpleClientset(objects ...runtime.Object) *Clientset { - o := testing.NewObjectTracker(scheme, codecs.UniversalDecoder()) - for _, obj := range objects { - if err := o.Add(obj); err != nil { - panic(err) - } - } - - cs := &Clientset{tracker: o} - cs.discovery = &fakediscovery.FakeDiscovery{Fake: &cs.Fake} - cs.AddReactor("*", "*", testing.ObjectReaction(o)) - cs.AddWatchReactor("*", func(action testing.Action) (handled bool, ret watch.Interface, err error) { - gvr := action.GetResource() - ns := action.GetNamespace() - watch, err := o.Watch(gvr, ns) - if err != nil { - return false, nil, err - } - return true, watch, nil - }) - - return cs -} - -// Clientset implements clientset.Interface. Meant to be embedded into a -// struct to get a default implementation. This makes faking out just the method -// you want to test easier. -type Clientset struct { - testing.Fake - discovery *fakediscovery.FakeDiscovery - tracker testing.ObjectTracker -} - -func (c *Clientset) Discovery() discovery.DiscoveryInterface { - return c.discovery -} - -func (c *Clientset) Tracker() testing.ObjectTracker { - return c.tracker -} - -var _ clientset.Interface = &Clientset{} - -// ApplicationconnectorV1alpha1 retrieves the ApplicationconnectorV1alpha1Client -func (c *Clientset) ApplicationconnectorV1alpha1() applicationconnectorv1alpha1.ApplicationconnectorV1alpha1Interface { - return &fakeapplicationconnectorv1alpha1.FakeApplicationconnectorV1alpha1{Fake: &c.Fake} -} diff --git a/components/central-application-gateway/pkg/client/clientset/versioned/fake/doc.go b/components/central-application-gateway/pkg/client/clientset/versioned/fake/doc.go deleted file mode 100644 index 3630ed1cd17d..000000000000 --- a/components/central-application-gateway/pkg/client/clientset/versioned/fake/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// Code generated by client-gen. DO NOT EDIT. - -// This package has the automatically generated fake clientset. -package fake diff --git a/components/central-application-gateway/pkg/client/clientset/versioned/fake/register.go b/components/central-application-gateway/pkg/client/clientset/versioned/fake/register.go deleted file mode 100644 index ff70226d7efa..000000000000 --- a/components/central-application-gateway/pkg/client/clientset/versioned/fake/register.go +++ /dev/null @@ -1,40 +0,0 @@ -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - applicationconnectorv1alpha1 "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - schema "k8s.io/apimachinery/pkg/runtime/schema" - serializer "k8s.io/apimachinery/pkg/runtime/serializer" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" -) - -var scheme = runtime.NewScheme() -var codecs = serializer.NewCodecFactory(scheme) -var parameterCodec = runtime.NewParameterCodec(scheme) -var localSchemeBuilder = runtime.SchemeBuilder{ - applicationconnectorv1alpha1.AddToScheme, -} - -// AddToScheme adds all types of this clientset into the given scheme. This allows composition -// of clientsets, like in: -// -// import ( -// "k8s.io/client-go/kubernetes" -// clientsetscheme "k8s.io/client-go/kubernetes/scheme" -// aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme" -// ) -// -// kclientset, _ := kubernetes.NewForConfig(c) -// _ = aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme) -// -// After this, RawExtensions in Kubernetes types will serialize kube-aggregator types -// correctly. -var AddToScheme = localSchemeBuilder.AddToScheme - -func init() { - v1.AddToGroupVersion(scheme, schema.GroupVersion{Version: "v1"}) - utilruntime.Must(AddToScheme(scheme)) -} diff --git a/components/central-application-gateway/pkg/client/clientset/versioned/scheme/doc.go b/components/central-application-gateway/pkg/client/clientset/versioned/scheme/doc.go deleted file mode 100644 index 14db57a58f8d..000000000000 --- a/components/central-application-gateway/pkg/client/clientset/versioned/scheme/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// Code generated by client-gen. DO NOT EDIT. - -// This package contains the scheme of the automatically generated clientset. -package scheme diff --git a/components/central-application-gateway/pkg/client/clientset/versioned/scheme/register.go b/components/central-application-gateway/pkg/client/clientset/versioned/scheme/register.go deleted file mode 100644 index 59e157e108c1..000000000000 --- a/components/central-application-gateway/pkg/client/clientset/versioned/scheme/register.go +++ /dev/null @@ -1,40 +0,0 @@ -// Code generated by client-gen. DO NOT EDIT. - -package scheme - -import ( - applicationconnectorv1alpha1 "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - schema "k8s.io/apimachinery/pkg/runtime/schema" - serializer "k8s.io/apimachinery/pkg/runtime/serializer" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" -) - -var Scheme = runtime.NewScheme() -var Codecs = serializer.NewCodecFactory(Scheme) -var ParameterCodec = runtime.NewParameterCodec(Scheme) -var localSchemeBuilder = runtime.SchemeBuilder{ - applicationconnectorv1alpha1.AddToScheme, -} - -// AddToScheme adds all types of this clientset into the given scheme. This allows composition -// of clientsets, like in: -// -// import ( -// "k8s.io/client-go/kubernetes" -// clientsetscheme "k8s.io/client-go/kubernetes/scheme" -// aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme" -// ) -// -// kclientset, _ := kubernetes.NewForConfig(c) -// _ = aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme) -// -// After this, RawExtensions in Kubernetes types will serialize kube-aggregator types -// correctly. -var AddToScheme = localSchemeBuilder.AddToScheme - -func init() { - v1.AddToGroupVersion(Scheme, schema.GroupVersion{Version: "v1"}) - utilruntime.Must(AddToScheme(Scheme)) -} diff --git a/components/central-application-gateway/pkg/client/clientset/versioned/typed/applicationconnector/v1alpha1/application.go b/components/central-application-gateway/pkg/client/clientset/versioned/typed/applicationconnector/v1alpha1/application.go deleted file mode 100644 index 5ead07fbc1a9..000000000000 --- a/components/central-application-gateway/pkg/client/clientset/versioned/typed/applicationconnector/v1alpha1/application.go +++ /dev/null @@ -1,168 +0,0 @@ -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - "context" - "time" - - v1alpha1 "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" - scheme "github.com/kyma-project/kyma/components/central-application-gateway/pkg/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" -) - -// ApplicationsGetter has a method to return a ApplicationInterface. -// A group's client should implement this interface. -type ApplicationsGetter interface { - Applications() ApplicationInterface -} - -// ApplicationInterface has methods to work with Application resources. -type ApplicationInterface interface { - Create(ctx context.Context, application *v1alpha1.Application, opts v1.CreateOptions) (*v1alpha1.Application, error) - Update(ctx context.Context, application *v1alpha1.Application, opts v1.UpdateOptions) (*v1alpha1.Application, error) - UpdateStatus(ctx context.Context, application *v1alpha1.Application, opts v1.UpdateOptions) (*v1alpha1.Application, error) - Delete(ctx context.Context, name string, opts v1.DeleteOptions) error - DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.Application, error) - List(ctx context.Context, opts v1.ListOptions) (*v1alpha1.ApplicationList, error) - Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.Application, err error) - ApplicationExpansion -} - -// applications implements ApplicationInterface -type applications struct { - client rest.Interface -} - -// newApplications returns a Applications -func newApplications(c *ApplicationconnectorV1alpha1Client) *applications { - return &applications{ - client: c.RESTClient(), - } -} - -// Get takes name of the application, and returns the corresponding application object, and an error if there is any. -func (c *applications) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.Application, err error) { - result = &v1alpha1.Application{} - err = c.client.Get(). - Resource("applications"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(ctx). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of Applications that match those selectors. -func (c *applications) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.ApplicationList, err error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - result = &v1alpha1.ApplicationList{} - err = c.client.Get(). - Resource("applications"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Do(ctx). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested applications. -func (c *applications) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - opts.Watch = true - return c.client.Get(). - Resource("applications"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Watch(ctx) -} - -// Create takes the representation of a application and creates it. Returns the server's representation of the application, and an error, if there is any. -func (c *applications) Create(ctx context.Context, application *v1alpha1.Application, opts v1.CreateOptions) (result *v1alpha1.Application, err error) { - result = &v1alpha1.Application{} - err = c.client.Post(). - Resource("applications"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(application). - Do(ctx). - Into(result) - return -} - -// Update takes the representation of a application and updates it. Returns the server's representation of the application, and an error, if there is any. -func (c *applications) Update(ctx context.Context, application *v1alpha1.Application, opts v1.UpdateOptions) (result *v1alpha1.Application, err error) { - result = &v1alpha1.Application{} - err = c.client.Put(). - Resource("applications"). - Name(application.Name). - VersionedParams(&opts, scheme.ParameterCodec). - Body(application). - Do(ctx). - Into(result) - return -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). -func (c *applications) UpdateStatus(ctx context.Context, application *v1alpha1.Application, opts v1.UpdateOptions) (result *v1alpha1.Application, err error) { - result = &v1alpha1.Application{} - err = c.client.Put(). - Resource("applications"). - Name(application.Name). - SubResource("status"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(application). - Do(ctx). - Into(result) - return -} - -// Delete takes name of the application and deletes it. Returns an error if one occurs. -func (c *applications) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - return c.client.Delete(). - Resource("applications"). - Name(name). - Body(&opts). - Do(ctx). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *applications) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - var timeout time.Duration - if listOpts.TimeoutSeconds != nil { - timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second - } - return c.client.Delete(). - Resource("applications"). - VersionedParams(&listOpts, scheme.ParameterCodec). - Timeout(timeout). - Body(&opts). - Do(ctx). - Error() -} - -// Patch applies the patch and returns the patched application. -func (c *applications) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.Application, err error) { - result = &v1alpha1.Application{} - err = c.client.Patch(pt). - Resource("applications"). - Name(name). - SubResource(subresources...). - VersionedParams(&opts, scheme.ParameterCodec). - Body(data). - Do(ctx). - Into(result) - return -} diff --git a/components/central-application-gateway/pkg/client/clientset/versioned/typed/applicationconnector/v1alpha1/applicationconnector_client.go b/components/central-application-gateway/pkg/client/clientset/versioned/typed/applicationconnector/v1alpha1/applicationconnector_client.go deleted file mode 100644 index 2136ed64c19c..000000000000 --- a/components/central-application-gateway/pkg/client/clientset/versioned/typed/applicationconnector/v1alpha1/applicationconnector_client.go +++ /dev/null @@ -1,73 +0,0 @@ -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/client/clientset/versioned/scheme" - rest "k8s.io/client-go/rest" -) - -type ApplicationconnectorV1alpha1Interface interface { - RESTClient() rest.Interface - ApplicationsGetter -} - -// ApplicationconnectorV1alpha1Client is used to interact with features provided by the applicationconnector.kyma-project.io group. -type ApplicationconnectorV1alpha1Client struct { - restClient rest.Interface -} - -func (c *ApplicationconnectorV1alpha1Client) Applications() ApplicationInterface { - return newApplications(c) -} - -// NewForConfig creates a new ApplicationconnectorV1alpha1Client for the given config. -func NewForConfig(c *rest.Config) (*ApplicationconnectorV1alpha1Client, error) { - config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } - client, err := rest.RESTClientFor(&config) - if err != nil { - return nil, err - } - return &ApplicationconnectorV1alpha1Client{client}, nil -} - -// NewForConfigOrDie creates a new ApplicationconnectorV1alpha1Client for the given config and -// panics if there is an error in the config. -func NewForConfigOrDie(c *rest.Config) *ApplicationconnectorV1alpha1Client { - client, err := NewForConfig(c) - if err != nil { - panic(err) - } - return client -} - -// New creates a new ApplicationconnectorV1alpha1Client for the given RESTClient. -func New(c rest.Interface) *ApplicationconnectorV1alpha1Client { - return &ApplicationconnectorV1alpha1Client{c} -} - -func setConfigDefaults(config *rest.Config) error { - gv := v1alpha1.SchemeGroupVersion - config.GroupVersion = &gv - config.APIPath = "/apis" - config.NegotiatedSerializer = scheme.Codecs.WithoutConversion() - - if config.UserAgent == "" { - config.UserAgent = rest.DefaultKubernetesUserAgent() - } - - return nil -} - -// RESTClient returns a RESTClient that is used to communicate -// with API server by this client implementation. -func (c *ApplicationconnectorV1alpha1Client) RESTClient() rest.Interface { - if c == nil { - return nil - } - return c.restClient -} diff --git a/components/central-application-gateway/pkg/client/clientset/versioned/typed/applicationconnector/v1alpha1/doc.go b/components/central-application-gateway/pkg/client/clientset/versioned/typed/applicationconnector/v1alpha1/doc.go deleted file mode 100644 index 93a7ca4e0e2b..000000000000 --- a/components/central-application-gateway/pkg/client/clientset/versioned/typed/applicationconnector/v1alpha1/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// Code generated by client-gen. DO NOT EDIT. - -// This package has the automatically generated typed clients. -package v1alpha1 diff --git a/components/central-application-gateway/pkg/client/clientset/versioned/typed/applicationconnector/v1alpha1/fake/doc.go b/components/central-application-gateway/pkg/client/clientset/versioned/typed/applicationconnector/v1alpha1/fake/doc.go deleted file mode 100644 index 2b5ba4c8e442..000000000000 --- a/components/central-application-gateway/pkg/client/clientset/versioned/typed/applicationconnector/v1alpha1/fake/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// Code generated by client-gen. DO NOT EDIT. - -// Package fake has the automatically generated clients. -package fake diff --git a/components/central-application-gateway/pkg/client/clientset/versioned/typed/applicationconnector/v1alpha1/fake/fake_application.go b/components/central-application-gateway/pkg/client/clientset/versioned/typed/applicationconnector/v1alpha1/fake/fake_application.go deleted file mode 100644 index 7ae54af40ac3..000000000000 --- a/components/central-application-gateway/pkg/client/clientset/versioned/typed/applicationconnector/v1alpha1/fake/fake_application.go +++ /dev/null @@ -1,117 +0,0 @@ -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - "context" - - v1alpha1 "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - schema "k8s.io/apimachinery/pkg/runtime/schema" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" -) - -// FakeApplications implements ApplicationInterface -type FakeApplications struct { - Fake *FakeApplicationconnectorV1alpha1 -} - -var applicationsResource = schema.GroupVersionResource{Group: "applicationconnector.kyma-project.io", Version: "v1alpha1", Resource: "applications"} - -var applicationsKind = schema.GroupVersionKind{Group: "applicationconnector.kyma-project.io", Version: "v1alpha1", Kind: "Application"} - -// Get takes name of the application, and returns the corresponding application object, and an error if there is any. -func (c *FakeApplications) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.Application, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootGetAction(applicationsResource, name), &v1alpha1.Application{}) - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Application), err -} - -// List takes label and field selectors, and returns the list of Applications that match those selectors. -func (c *FakeApplications) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.ApplicationList, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootListAction(applicationsResource, applicationsKind, opts), &v1alpha1.ApplicationList{}) - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1alpha1.ApplicationList{ListMeta: obj.(*v1alpha1.ApplicationList).ListMeta} - for _, item := range obj.(*v1alpha1.ApplicationList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested applications. -func (c *FakeApplications) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewRootWatchAction(applicationsResource, opts)) -} - -// Create takes the representation of a application and creates it. Returns the server's representation of the application, and an error, if there is any. -func (c *FakeApplications) Create(ctx context.Context, application *v1alpha1.Application, opts v1.CreateOptions) (result *v1alpha1.Application, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootCreateAction(applicationsResource, application), &v1alpha1.Application{}) - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Application), err -} - -// Update takes the representation of a application and updates it. Returns the server's representation of the application, and an error, if there is any. -func (c *FakeApplications) Update(ctx context.Context, application *v1alpha1.Application, opts v1.UpdateOptions) (result *v1alpha1.Application, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootUpdateAction(applicationsResource, application), &v1alpha1.Application{}) - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Application), err -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). -func (c *FakeApplications) UpdateStatus(ctx context.Context, application *v1alpha1.Application, opts v1.UpdateOptions) (*v1alpha1.Application, error) { - obj, err := c.Fake. - Invokes(testing.NewRootUpdateSubresourceAction(applicationsResource, "status", application), &v1alpha1.Application{}) - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Application), err -} - -// Delete takes name of the application and deletes it. Returns an error if one occurs. -func (c *FakeApplications) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewRootDeleteAction(applicationsResource, name), &v1alpha1.Application{}) - return err -} - -// DeleteCollection deletes a collection of objects. -func (c *FakeApplications) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - action := testing.NewRootDeleteCollectionAction(applicationsResource, listOpts) - - _, err := c.Fake.Invokes(action, &v1alpha1.ApplicationList{}) - return err -} - -// Patch applies the patch and returns the patched application. -func (c *FakeApplications) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.Application, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootPatchSubresourceAction(applicationsResource, name, pt, data, subresources...), &v1alpha1.Application{}) - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Application), err -} diff --git a/components/central-application-gateway/pkg/client/clientset/versioned/typed/applicationconnector/v1alpha1/fake/fake_applicationconnector_client.go b/components/central-application-gateway/pkg/client/clientset/versioned/typed/applicationconnector/v1alpha1/fake/fake_applicationconnector_client.go deleted file mode 100644 index 9ccba0681d55..000000000000 --- a/components/central-application-gateway/pkg/client/clientset/versioned/typed/applicationconnector/v1alpha1/fake/fake_applicationconnector_client.go +++ /dev/null @@ -1,24 +0,0 @@ -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha1 "github.com/kyma-project/kyma/components/central-application-gateway/pkg/client/clientset/versioned/typed/applicationconnector/v1alpha1" - rest "k8s.io/client-go/rest" - testing "k8s.io/client-go/testing" -) - -type FakeApplicationconnectorV1alpha1 struct { - *testing.Fake -} - -func (c *FakeApplicationconnectorV1alpha1) Applications() v1alpha1.ApplicationInterface { - return &FakeApplications{c} -} - -// RESTClient returns a RESTClient that is used to communicate -// with API server by this client implementation. -func (c *FakeApplicationconnectorV1alpha1) RESTClient() rest.Interface { - var ret *rest.RESTClient - return ret -} diff --git a/components/central-application-gateway/pkg/client/clientset/versioned/typed/applicationconnector/v1alpha1/generated_expansion.go b/components/central-application-gateway/pkg/client/clientset/versioned/typed/applicationconnector/v1alpha1/generated_expansion.go deleted file mode 100644 index e050c4b6f5a9..000000000000 --- a/components/central-application-gateway/pkg/client/clientset/versioned/typed/applicationconnector/v1alpha1/generated_expansion.go +++ /dev/null @@ -1,5 +0,0 @@ -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -type ApplicationExpansion interface{} diff --git a/components/central-application-gateway/pkg/client/informers/externalversions/applicationconnector/interface.go b/components/central-application-gateway/pkg/client/informers/externalversions/applicationconnector/interface.go deleted file mode 100644 index cda413687324..000000000000 --- a/components/central-application-gateway/pkg/client/informers/externalversions/applicationconnector/interface.go +++ /dev/null @@ -1,30 +0,0 @@ -// Code generated by informer-gen. DO NOT EDIT. - -package applicationconnector - -import ( - v1alpha1 "github.com/kyma-project/kyma/components/central-application-gateway/pkg/client/informers/externalversions/applicationconnector/v1alpha1" - internalinterfaces "github.com/kyma-project/kyma/components/central-application-gateway/pkg/client/informers/externalversions/internalinterfaces" -) - -// Interface provides access to each of this group's versions. -type Interface interface { - // V1alpha1 provides access to shared informers for resources in V1alpha1. - V1alpha1() v1alpha1.Interface -} - -type group struct { - factory internalinterfaces.SharedInformerFactory - namespace string - tweakListOptions internalinterfaces.TweakListOptionsFunc -} - -// New returns a new Interface. -func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { - return &group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} -} - -// V1alpha1 returns a new v1alpha1.Interface. -func (g *group) V1alpha1() v1alpha1.Interface { - return v1alpha1.New(g.factory, g.namespace, g.tweakListOptions) -} diff --git a/components/central-application-gateway/pkg/client/informers/externalversions/applicationconnector/v1alpha1/application.go b/components/central-application-gateway/pkg/client/informers/externalversions/applicationconnector/v1alpha1/application.go deleted file mode 100644 index 8d973b80466e..000000000000 --- a/components/central-application-gateway/pkg/client/informers/externalversions/applicationconnector/v1alpha1/application.go +++ /dev/null @@ -1,73 +0,0 @@ -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - "context" - time "time" - - applicationconnectorv1alpha1 "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" - versioned "github.com/kyma-project/kyma/components/central-application-gateway/pkg/client/clientset/versioned" - internalinterfaces "github.com/kyma-project/kyma/components/central-application-gateway/pkg/client/informers/externalversions/internalinterfaces" - v1alpha1 "github.com/kyma-project/kyma/components/central-application-gateway/pkg/client/listers/applicationconnector/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// ApplicationInformer provides access to a shared informer and lister for -// Applications. -type ApplicationInformer interface { - Informer() cache.SharedIndexInformer - Lister() v1alpha1.ApplicationLister -} - -type applicationInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc -} - -// NewApplicationInformer constructs a new informer for Application type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewApplicationInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredApplicationInformer(client, resyncPeriod, indexers, nil) -} - -// NewFilteredApplicationInformer constructs a new informer for Application type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredApplicationInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - &cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.ApplicationconnectorV1alpha1().Applications().List(context.TODO(), options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.ApplicationconnectorV1alpha1().Applications().Watch(context.TODO(), options) - }, - }, - &applicationconnectorv1alpha1.Application{}, - resyncPeriod, - indexers, - ) -} - -func (f *applicationInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredApplicationInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *applicationInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&applicationconnectorv1alpha1.Application{}, f.defaultInformer) -} - -func (f *applicationInformer) Lister() v1alpha1.ApplicationLister { - return v1alpha1.NewApplicationLister(f.Informer().GetIndexer()) -} diff --git a/components/central-application-gateway/pkg/client/informers/externalversions/applicationconnector/v1alpha1/interface.go b/components/central-application-gateway/pkg/client/informers/externalversions/applicationconnector/v1alpha1/interface.go deleted file mode 100644 index dad45b41dcf6..000000000000 --- a/components/central-application-gateway/pkg/client/informers/externalversions/applicationconnector/v1alpha1/interface.go +++ /dev/null @@ -1,29 +0,0 @@ -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - internalinterfaces "github.com/kyma-project/kyma/components/central-application-gateway/pkg/client/informers/externalversions/internalinterfaces" -) - -// Interface provides access to all the informers in this group version. -type Interface interface { - // Applications returns a ApplicationInformer. - Applications() ApplicationInformer -} - -type version struct { - factory internalinterfaces.SharedInformerFactory - namespace string - tweakListOptions internalinterfaces.TweakListOptionsFunc -} - -// New returns a new Interface. -func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { - return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} -} - -// Applications returns a ApplicationInformer. -func (v *version) Applications() ApplicationInformer { - return &applicationInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} -} diff --git a/components/central-application-gateway/pkg/client/informers/externalversions/factory.go b/components/central-application-gateway/pkg/client/informers/externalversions/factory.go deleted file mode 100644 index 9ed689498d1c..000000000000 --- a/components/central-application-gateway/pkg/client/informers/externalversions/factory.go +++ /dev/null @@ -1,164 +0,0 @@ -// Code generated by informer-gen. DO NOT EDIT. - -package externalversions - -import ( - reflect "reflect" - sync "sync" - time "time" - - versioned "github.com/kyma-project/kyma/components/central-application-gateway/pkg/client/clientset/versioned" - applicationconnector "github.com/kyma-project/kyma/components/central-application-gateway/pkg/client/informers/externalversions/applicationconnector" - internalinterfaces "github.com/kyma-project/kyma/components/central-application-gateway/pkg/client/informers/externalversions/internalinterfaces" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - schema "k8s.io/apimachinery/pkg/runtime/schema" - cache "k8s.io/client-go/tools/cache" -) - -// SharedInformerOption defines the functional option type for SharedInformerFactory. -type SharedInformerOption func(*sharedInformerFactory) *sharedInformerFactory - -type sharedInformerFactory struct { - client versioned.Interface - namespace string - tweakListOptions internalinterfaces.TweakListOptionsFunc - lock sync.Mutex - defaultResync time.Duration - customResync map[reflect.Type]time.Duration - - informers map[reflect.Type]cache.SharedIndexInformer - // startedInformers is used for tracking which informers have been started. - // This allows Start() to be called multiple times safely. - startedInformers map[reflect.Type]bool -} - -// WithCustomResyncConfig sets a custom resync period for the specified informer types. -func WithCustomResyncConfig(resyncConfig map[v1.Object]time.Duration) SharedInformerOption { - return func(factory *sharedInformerFactory) *sharedInformerFactory { - for k, v := range resyncConfig { - factory.customResync[reflect.TypeOf(k)] = v - } - return factory - } -} - -// WithTweakListOptions sets a custom filter on all listers of the configured SharedInformerFactory. -func WithTweakListOptions(tweakListOptions internalinterfaces.TweakListOptionsFunc) SharedInformerOption { - return func(factory *sharedInformerFactory) *sharedInformerFactory { - factory.tweakListOptions = tweakListOptions - return factory - } -} - -// WithNamespace limits the SharedInformerFactory to the specified namespace. -func WithNamespace(namespace string) SharedInformerOption { - return func(factory *sharedInformerFactory) *sharedInformerFactory { - factory.namespace = namespace - return factory - } -} - -// NewSharedInformerFactory constructs a new instance of sharedInformerFactory for all namespaces. -func NewSharedInformerFactory(client versioned.Interface, defaultResync time.Duration) SharedInformerFactory { - return NewSharedInformerFactoryWithOptions(client, defaultResync) -} - -// NewFilteredSharedInformerFactory constructs a new instance of sharedInformerFactory. -// Listers obtained via this SharedInformerFactory will be subject to the same filters -// as specified here. -// Deprecated: Please use NewSharedInformerFactoryWithOptions instead -func NewFilteredSharedInformerFactory(client versioned.Interface, defaultResync time.Duration, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) SharedInformerFactory { - return NewSharedInformerFactoryWithOptions(client, defaultResync, WithNamespace(namespace), WithTweakListOptions(tweakListOptions)) -} - -// NewSharedInformerFactoryWithOptions constructs a new instance of a SharedInformerFactory with additional options. -func NewSharedInformerFactoryWithOptions(client versioned.Interface, defaultResync time.Duration, options ...SharedInformerOption) SharedInformerFactory { - factory := &sharedInformerFactory{ - client: client, - namespace: v1.NamespaceAll, - defaultResync: defaultResync, - informers: make(map[reflect.Type]cache.SharedIndexInformer), - startedInformers: make(map[reflect.Type]bool), - customResync: make(map[reflect.Type]time.Duration), - } - - // Apply all options - for _, opt := range options { - factory = opt(factory) - } - - return factory -} - -// Start initializes all requested informers. -func (f *sharedInformerFactory) Start(stopCh <-chan struct{}) { - f.lock.Lock() - defer f.lock.Unlock() - - for informerType, informer := range f.informers { - if !f.startedInformers[informerType] { - go informer.Run(stopCh) - f.startedInformers[informerType] = true - } - } -} - -// WaitForCacheSync waits for all started informers' cache were synced. -func (f *sharedInformerFactory) WaitForCacheSync(stopCh <-chan struct{}) map[reflect.Type]bool { - informers := func() map[reflect.Type]cache.SharedIndexInformer { - f.lock.Lock() - defer f.lock.Unlock() - - informers := map[reflect.Type]cache.SharedIndexInformer{} - for informerType, informer := range f.informers { - if f.startedInformers[informerType] { - informers[informerType] = informer - } - } - return informers - }() - - res := map[reflect.Type]bool{} - for informType, informer := range informers { - res[informType] = cache.WaitForCacheSync(stopCh, informer.HasSynced) - } - return res -} - -// InternalInformerFor returns the SharedIndexInformer for obj using an internal -// client. -func (f *sharedInformerFactory) InformerFor(obj runtime.Object, newFunc internalinterfaces.NewInformerFunc) cache.SharedIndexInformer { - f.lock.Lock() - defer f.lock.Unlock() - - informerType := reflect.TypeOf(obj) - informer, exists := f.informers[informerType] - if exists { - return informer - } - - resyncPeriod, exists := f.customResync[informerType] - if !exists { - resyncPeriod = f.defaultResync - } - - informer = newFunc(f.client, resyncPeriod) - f.informers[informerType] = informer - - return informer -} - -// SharedInformerFactory provides shared informers for resources in all known -// API group versions. -type SharedInformerFactory interface { - internalinterfaces.SharedInformerFactory - ForResource(resource schema.GroupVersionResource) (GenericInformer, error) - WaitForCacheSync(stopCh <-chan struct{}) map[reflect.Type]bool - - Applicationconnector() applicationconnector.Interface -} - -func (f *sharedInformerFactory) Applicationconnector() applicationconnector.Interface { - return applicationconnector.New(f, f.namespace, f.tweakListOptions) -} diff --git a/components/central-application-gateway/pkg/client/informers/externalversions/generic.go b/components/central-application-gateway/pkg/client/informers/externalversions/generic.go deleted file mode 100644 index 1f055862eeae..000000000000 --- a/components/central-application-gateway/pkg/client/informers/externalversions/generic.go +++ /dev/null @@ -1,46 +0,0 @@ -// Code generated by informer-gen. DO NOT EDIT. - -package externalversions - -import ( - "fmt" - - v1alpha1 "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" - schema "k8s.io/apimachinery/pkg/runtime/schema" - cache "k8s.io/client-go/tools/cache" -) - -// GenericInformer is type of SharedIndexInformer which will locate and delegate to other -// sharedInformers based on type -type GenericInformer interface { - Informer() cache.SharedIndexInformer - Lister() cache.GenericLister -} - -type genericInformer struct { - informer cache.SharedIndexInformer - resource schema.GroupResource -} - -// Informer returns the SharedIndexInformer. -func (f *genericInformer) Informer() cache.SharedIndexInformer { - return f.informer -} - -// Lister returns the GenericLister. -func (f *genericInformer) Lister() cache.GenericLister { - return cache.NewGenericLister(f.Informer().GetIndexer(), f.resource) -} - -// ForResource gives generic access to a shared informer of the matching type -// TODO extend this to unknown resources with a client pool -func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) { - switch resource { - // Group=applicationconnector.kyma-project.io, Version=v1alpha1 - case v1alpha1.SchemeGroupVersion.WithResource("applications"): - return &genericInformer{resource: resource.GroupResource(), informer: f.Applicationconnector().V1alpha1().Applications().Informer()}, nil - - } - - return nil, fmt.Errorf("no informer found for %v", resource) -} diff --git a/components/central-application-gateway/pkg/client/informers/externalversions/internalinterfaces/factory_interfaces.go b/components/central-application-gateway/pkg/client/informers/externalversions/internalinterfaces/factory_interfaces.go deleted file mode 100644 index 47d4012b2fc3..000000000000 --- a/components/central-application-gateway/pkg/client/informers/externalversions/internalinterfaces/factory_interfaces.go +++ /dev/null @@ -1,24 +0,0 @@ -// Code generated by informer-gen. DO NOT EDIT. - -package internalinterfaces - -import ( - time "time" - - versioned "github.com/kyma-project/kyma/components/central-application-gateway/pkg/client/clientset/versioned" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - cache "k8s.io/client-go/tools/cache" -) - -// NewInformerFunc takes versioned.Interface and time.Duration to return a SharedIndexInformer. -type NewInformerFunc func(versioned.Interface, time.Duration) cache.SharedIndexInformer - -// SharedInformerFactory a small interface to allow for adding an informer without an import cycle -type SharedInformerFactory interface { - Start(stopCh <-chan struct{}) - InformerFor(obj runtime.Object, newFunc NewInformerFunc) cache.SharedIndexInformer -} - -// TweakListOptionsFunc is a function that transforms a v1.ListOptions. -type TweakListOptionsFunc func(*v1.ListOptions) diff --git a/components/central-application-gateway/pkg/client/listers/applicationconnector/v1alpha1/application.go b/components/central-application-gateway/pkg/client/listers/applicationconnector/v1alpha1/application.go deleted file mode 100644 index b5726d77329c..000000000000 --- a/components/central-application-gateway/pkg/client/listers/applicationconnector/v1alpha1/application.go +++ /dev/null @@ -1,49 +0,0 @@ -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" -) - -// ApplicationLister helps list Applications. -type ApplicationLister interface { - // List lists all Applications in the indexer. - List(selector labels.Selector) (ret []*v1alpha1.Application, err error) - // Get retrieves the Application from the index for a given name. - Get(name string) (*v1alpha1.Application, error) - ApplicationListerExpansion -} - -// applicationLister implements the ApplicationLister interface. -type applicationLister struct { - indexer cache.Indexer -} - -// NewApplicationLister returns a new ApplicationLister. -func NewApplicationLister(indexer cache.Indexer) ApplicationLister { - return &applicationLister{indexer: indexer} -} - -// List lists all Applications in the indexer. -func (s *applicationLister) List(selector labels.Selector) (ret []*v1alpha1.Application, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.Application)) - }) - return ret, err -} - -// Get retrieves the Application from the index for a given name. -func (s *applicationLister) Get(name string) (*v1alpha1.Application, error) { - obj, exists, err := s.indexer.GetByKey(name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("application"), name) - } - return obj.(*v1alpha1.Application), nil -} diff --git a/components/central-application-gateway/pkg/client/listers/applicationconnector/v1alpha1/expansion_generated.go b/components/central-application-gateway/pkg/client/listers/applicationconnector/v1alpha1/expansion_generated.go deleted file mode 100644 index be538447bd83..000000000000 --- a/components/central-application-gateway/pkg/client/listers/applicationconnector/v1alpha1/expansion_generated.go +++ /dev/null @@ -1,7 +0,0 @@ -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha1 - -// ApplicationListerExpansion allows custom methods to be added to -// ApplicationLister. -type ApplicationListerExpansion interface{} diff --git a/components/central-application-gateway/pkg/httpconsts/httpconsts.go b/components/central-application-gateway/pkg/httpconsts/httpconsts.go deleted file mode 100644 index 18c423b79684..000000000000 --- a/components/central-application-gateway/pkg/httpconsts/httpconsts.go +++ /dev/null @@ -1,24 +0,0 @@ -package httpconsts - -const ( - HeaderContentType = "Content-Type" - HeaderAuthorization = "Authorization" - HeaderAccessToken = "Access-Token" - HeaderCSRFToken = "X-csrf-token" - HeaderUserAgent = "User-Agent" - HeaderXForwardedProto = "X-Forwarded-Proto" - HeaderXForwardedFor = "X-Forwarded-For" - HeaderXForwardedHost = "X-Forwarded-Host" - HeaderXForwardedClientCert = "X-Forwarded-Client-Cert" - HeaderCSRFTokenVal = "fetch" - HeaderAccept = "Accept" - HeaderAcceptVal = "*/*" - HeaderCacheControl = "cache-control" - HeaderCacheControlVal = "no-cache" - HeaderCookie = "Cookie" -) - -const ( - ContentTypeApplicationJson = "application/json;charset=UTF-8" - ContentTypeApplicationURLEncoded = "application/x-www-form-urlencoded" -) diff --git a/components/central-application-gateway/pkg/httptools/headers.go b/components/central-application-gateway/pkg/httptools/headers.go deleted file mode 100644 index 97e934edccc9..000000000000 --- a/components/central-application-gateway/pkg/httptools/headers.go +++ /dev/null @@ -1,32 +0,0 @@ -package httptools - -import ( - "net/http" - - "go.uber.org/zap" -) - -// SetHeaders modifies request headers setting additional entries from customHeaders -func SetHeaders(reqHeaders http.Header, customHeaders *map[string][]string) { - if customHeaders == nil { - return - } - - for header, values := range *customHeaders { - if _, ok := reqHeaders[header]; ok { - // if header is already specified we do not interfere with it - continue - } - - reqHeaders[header] = values - } -} - -// RemoveHeader modifies request headers removing headerToRemove entry -func RemoveHeader(reqHeaders http.Header, headerToRemove string) { - if _, ok := reqHeaders[headerToRemove]; ok { - zap.L().Debug("Removing header", - zap.String("header", headerToRemove)) - reqHeaders.Del(headerToRemove) - } -} diff --git a/components/central-application-gateway/pkg/httptools/http.go b/components/central-application-gateway/pkg/httptools/http.go deleted file mode 100644 index ec9407bd7c94..000000000000 --- a/components/central-application-gateway/pkg/httptools/http.go +++ /dev/null @@ -1,21 +0,0 @@ -package httptools - -import ( - "io" - "net/http" -) - -type HttpClientProvider func() HttpClient -type HttpRequestProvider func(method, url string, body io.Reader) (*http.Request, error) - -type HttpClient interface { - Do(req *http.Request) (*http.Response, error) -} - -func DefaultHttpClientProvider() HttpClient { - return http.DefaultClient -} - -func DefaultHttpRequestProvider(method, url string, body io.Reader) (*http.Request, error) { - return http.NewRequest(method, url, body) -} diff --git a/components/central-application-gateway/pkg/httptools/logging.go b/components/central-application-gateway/pkg/httptools/logging.go deleted file mode 100644 index 355ae2c225c1..000000000000 --- a/components/central-application-gateway/pkg/httptools/logging.go +++ /dev/null @@ -1,78 +0,0 @@ -package httptools - -import ( - "net/http" - "time" - - "go.uber.org/zap" -) - -type ContextKey string - -const ContextUUID ContextKey = "context-uuid" - -func LogResponse(log *zap.SugaredLogger, res *http.Response) error { - req := res.Request - log.WithOptions( - zap.AddCallerSkip(1), - ). - With( - "method", req.Method, - "host", req.Host, - "url", req.URL.RequestURI(), - "proto", req.Proto, - "code", res.StatusCode, - "contentLength", res.ContentLength, - "kind", "response", - ).Debugf("%s %s %s %s", req.Method, req.Host, req.URL.RequestURI(), req.Proto) - - return nil -} - -func LogRequest(log *zap.SugaredLogger, r *http.Request) { - log.WithOptions( - zap.AddCallerSkip(1), - ).With( - "method", r.Method, - "host", r.Host, - "url", r.URL.RequestURI(), - "proto", r.Proto, - "kind", "request", - ).Debugf("%s %s %s %s", r.Method, r.Host, r.URL.RequestURI(), r.Proto) -} - -func RequestLogger(label string, h http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - - lw := newLoggingResponseWriter(w) - - h.ServeHTTP(lw, r) - - responseCode := lw.status - duration := time.Since(lw.start).Nanoseconds() / int64(time.Millisecond) - - log := zap.L().Sugar(). - With( - "label", label, - "duration", duration, - "code", responseCode, - ) - - LogRequest(log, r) - }) -} - -type loggingResponseWriter struct { - http.ResponseWriter - status int - start time.Time -} - -func newLoggingResponseWriter(w http.ResponseWriter) *loggingResponseWriter { - return &loggingResponseWriter{ResponseWriter: w, start: time.Now()} -} - -func (w *loggingResponseWriter) WriteHeader(statusCode int) { - w.ResponseWriter.WriteHeader(statusCode) - w.status = statusCode -} diff --git a/components/central-application-gateway/pkg/httptools/queryparameters.go b/components/central-application-gateway/pkg/httptools/queryparameters.go deleted file mode 100644 index 900078ece29c..000000000000 --- a/components/central-application-gateway/pkg/httptools/queryparameters.go +++ /dev/null @@ -1,21 +0,0 @@ -package httptools - -import "net/url" - -func SetQueryParameters(url *url.URL, queryParameters *map[string][]string) { - if queryParameters == nil { - return - } - - reqQueryValues := url.Query() - - for customQueryParam, values := range *queryParameters { - if _, ok := reqQueryValues[customQueryParam]; ok { - continue - } - - reqQueryValues[customQueryParam] = values - } - - url.RawQuery = reqQueryValues.Encode() -} diff --git a/components/central-application-gateway/pkg/httptools/roundtripper.go b/components/central-application-gateway/pkg/httptools/roundtripper.go deleted file mode 100644 index fdc7e4eb8409..000000000000 --- a/components/central-application-gateway/pkg/httptools/roundtripper.go +++ /dev/null @@ -1,68 +0,0 @@ -package httptools - -import ( - "crypto/tls" - "net" - "net/http" - "time" -) - -type RoundTripper struct { - transport *http.Transport -} - -type RoundTripperOption func(*RoundTripper) - -func WithTLSConfig(config *tls.Config) RoundTripperOption { - return func(rt *RoundTripper) { - rt.transport.TLSClientConfig = config - } -} - -func WithTLSSkipVerify(skipVerify bool) RoundTripperOption { - return func(rt *RoundTripper) { - if rt.transport.TLSClientConfig == nil { - rt.transport.TLSClientConfig = &tls.Config{} - } - rt.transport.TLSClientConfig.InsecureSkipVerify = skipVerify - } -} - -func WithGetClientCertificate(f func(*tls.CertificateRequestInfo) (*tls.Certificate, error)) RoundTripperOption { - return func(rt *RoundTripper) { - if rt.transport.TLSClientConfig == nil { - rt.transport.TLSClientConfig = &tls.Config{} - } - rt.transport.TLSClientConfig.GetClientCertificate = f - } -} - -func NewRoundTripper(options ...RoundTripperOption) *RoundTripper { - rt := &RoundTripper{ - transport: newDefaultTransport(), - } - for _, option := range options { - option(rt) - } - return rt -} - -func (p *RoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { - return p.transport.RoundTrip(req) -} - -func newDefaultTransport() *http.Transport { - // http.DefaultTransport - return &http.Transport{ - Proxy: http.ProxyFromEnvironment, - DialContext: (&net.Dialer{ - Timeout: 30 * time.Second, - KeepAlive: 30 * time.Second, - }).DialContext, - ForceAttemptHTTP2: true, - MaxIdleConns: 100, - IdleConnTimeout: 90 * time.Second, - TLSHandshakeTimeout: 10 * time.Second, - ExpectContinueTimeout: 1 * time.Second, - } -} diff --git a/components/central-application-gateway/pkg/httptools/roundtripper_test.go b/components/central-application-gateway/pkg/httptools/roundtripper_test.go deleted file mode 100644 index 89a2bf7881a0..000000000000 --- a/components/central-application-gateway/pkg/httptools/roundtripper_test.go +++ /dev/null @@ -1,255 +0,0 @@ -package httptools - -import ( - "crypto/rand" - "crypto/rsa" - "crypto/tls" - "crypto/x509" - "crypto/x509/pkix" - "io/ioutil" - "math/big" - mathrand "math/rand" - "net" - "net/http" - "net/http/httptest" - "testing" - "time" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/clientcert" - - "github.com/stretchr/testify/require" -) - -func TestRoundTripper(t *testing.T) { - tests := []struct { - name string - transport http.RoundTripper - startTLS bool - requestError bool - }{ - { - name: "Default round tripper", - transport: NewRoundTripper(), - }, - { - name: "TLSSkipVerify false", - transport: NewRoundTripper(WithTLSSkipVerify(false)), - }, - { - name: "TLSSkipVerify true", - transport: NewRoundTripper(WithTLSSkipVerify(true)), - }, - { - name: "TLSSkipVerify false with TLS", - transport: NewRoundTripper(WithTLSSkipVerify(false)), - startTLS: true, - requestError: true, - }, - { - name: "TLSSkipVerify true with TLS\"", - transport: NewRoundTripper(WithTLSSkipVerify(true)), - startTLS: true, - }, - { - name: "Empty GetClientCertificate response", - transport: NewRoundTripper(WithGetClientCertificate(func(info *tls.CertificateRequestInfo) (*tls.Certificate, error) { - return nil, nil - })), - }, - { - name: "Empty GetClientCertificate response with TLS", - transport: NewRoundTripper(WithTLSSkipVerify(true), WithGetClientCertificate(func(info *tls.CertificateRequestInfo) (*tls.Certificate, error) { - return nil, nil - })), - startTLS: true, - }, - } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - // given - ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - })) - defer ts.Close() - - if tc.startTLS { - ts.StartTLS() - } else { - ts.Start() - } - - httpClient := &http.Client{ - Transport: tc.transport, - } - req, err := http.NewRequest(http.MethodGet, ts.URL, nil) - require.NoError(t, err) - - res, err := httpClient.Do(req) - if tc.requestError { - require.NotNil(t, err) - return - } - require.NoError(t, err) - - _, err = ioutil.ReadAll(res.Body) - _ = res.Body.Close() - require.NoError(t, err) - require.Equal(t, res.StatusCode, http.StatusOK) - - }) - } -} - -func TestRoundTripperMTLS(t *testing.T) { - caTLSCert, caX509Cert, err := newCA() - require.NoError(t, err) - - serverCert, err := newCert(caTLSCert) - require.NoError(t, err) - - clientCert, err := newCert(caTLSCert) - require.NoError(t, err) - - certpool := x509.NewCertPool() - certpool.AddCert(caX509Cert) - - ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - })) - ts.TLS = &tls.Config{ - Certificates: []tls.Certificate{*serverCert}, - ClientAuth: tls.RequireAndVerifyClientCert, - ClientCAs: certpool, - } - ts.StartTLS() - defer ts.Close() - - transport := NewRoundTripper( - WithTLSConfig(&tls.Config{RootCAs: certpool}), - WithGetClientCertificate(clientcert.NewClientCertificate(clientCert).GetClientCertificate)) - - httpClient := &http.Client{ - Transport: transport, - } - - req, err := http.NewRequest(http.MethodGet, ts.URL, nil) - require.NoError(t, err) - - res, err := httpClient.Do(req) - require.NoError(t, err) - - _ = res.Body.Close() - require.Equal(t, res.StatusCode, http.StatusOK) -} - -func TestRoundTripperMTLSMissingCert_RequireAndVerifyClientCert(t *testing.T) { - _, err := roundTripperMTLSMissingCert(t, tls.RequireAndVerifyClientCert) - require.NotNil(t, err, "Should have tls: client didn't provide a certificate error") -} - -func TestRoundTripperMTLSMissingCert_RequestClientCert(t *testing.T) { - res, err := roundTripperMTLSMissingCert(t, tls.RequestClientCert) - require.NoError(t, err) - - _ = res.Body.Close() - require.Equal(t, res.StatusCode, http.StatusOK) -} - -func roundTripperMTLSMissingCert(t *testing.T, clientAuth tls.ClientAuthType) (*http.Response, error) { - caTLSCert, caX509Cert, err := newCA() - require.NoError(t, err) - - serverCert, err := newCert(caTLSCert) - require.NoError(t, err) - - certpool := x509.NewCertPool() - certpool.AddCert(caX509Cert) - - ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - })) - ts.TLS = &tls.Config{ - Certificates: []tls.Certificate{*serverCert}, - ClientAuth: clientAuth, - ClientCAs: certpool, - } - ts.StartTLS() - defer ts.Close() - - transport := NewRoundTripper( - WithTLSConfig(&tls.Config{RootCAs: certpool}), - WithGetClientCertificate(clientcert.NewClientCertificate(nil).GetClientCertificate)) - - httpClient := &http.Client{ - Transport: transport, - } - - req, err := http.NewRequest(http.MethodGet, ts.URL, nil) - require.NoError(t, err) - - return httpClient.Do(req) -} - -func newCert(caCert *tls.Certificate) (*tls.Certificate, error) { - certificate := &x509.Certificate{ - SerialNumber: big.NewInt(mathrand.Int63()), - Subject: pkix.Name{ - CommonName: "localhost", - }, - NotBefore: time.Now(), - NotAfter: time.Now().AddDate(10, 0, 0), - SubjectKeyId: []byte{1, 2, 3, 4, 6}, - ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}, - KeyUsage: x509.KeyUsageDigitalSignature, - DNSNames: []string{"localhost"}, - IPAddresses: []net.IP{net.IP([]byte{127, 0, 0, 1})}, - } - priv, err := rsa.GenerateKey(rand.Reader, 2048) - if err != nil { - return nil, err - } - ca, err := x509.ParseCertificate(caCert.Certificate[0]) - if err != nil { - return nil, err - } - cert_b, err := x509.CreateCertificate(rand.Reader, certificate, ca, &priv.PublicKey, caCert.PrivateKey) - if err != nil { - return nil, err - } - return &tls.Certificate{ - Certificate: [][]byte{cert_b}, - PrivateKey: priv, - }, nil - -} -func newCA() (*tls.Certificate, *x509.Certificate, error) { - certificate := &x509.Certificate{ - SerialNumber: big.NewInt(20210616), - Subject: pkix.Name{ - CommonName: "ca-cert", - }, - NotBefore: time.Now(), - NotAfter: time.Now().AddDate(10, 0, 0), - IsCA: true, - ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}, - KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, - BasicConstraintsValid: true, - } - - caPriv, err := rsa.GenerateKey(rand.Reader, 2048) - if err != nil { - return nil, nil, err - } - cert_b, err := x509.CreateCertificate(rand.Reader, certificate, certificate, &caPriv.PublicKey, caPriv) - if err != nil { - return nil, nil, err - } - x509Cert, err := x509.ParseCertificate(cert_b) - if err != nil { - return nil, nil, err - } - return &tls.Certificate{ - Certificate: [][]byte{cert_b}, - PrivateKey: caPriv, - }, x509Cert, nil -} diff --git a/components/central-application-gateway/pkg/normalization/normalization.go b/components/central-application-gateway/pkg/normalization/normalization.go deleted file mode 100644 index cea7eda35663..000000000000 --- a/components/central-application-gateway/pkg/normalization/normalization.go +++ /dev/null @@ -1,50 +0,0 @@ -package normalization - -import ( - "crypto/sha1" - "encoding/hex" - "fmt" - "regexp" - "strings" - "unicode" -) - -var nonAlphaNumeric = regexp.MustCompile("[^A-Za-z0-9]+") - -// NormalizeServiceNameWithId creates the OSB Service Name for given Application Service. -// The OSB Service Name is used in the Service Catalog as the clusterServiceClassExternalName, so it need to be normalized. -// -// Normalization rules: -// - MUST only contain lowercase characters, numbers and hyphens (no spaces). -// - MUST be unique across all service objects returned in this response. MUST be a non-empty string. -func NormalizeServiceNameWithId(displayName, id string) string { - - normalizedName := NormalizeName(displayName) - - // add suffix - // generate 5 characters suffix from the id - sha := sha1.New() - sha.Write([]byte(id)) - suffix := hex.EncodeToString(sha.Sum(nil))[:5] - normalizedName = fmt.Sprintf("%s-%s", normalizedName, suffix) - // remove dash prefix if exists - // - can happen, if the name was empty before adding suffix empty or had dash prefix - normalizedName = strings.TrimPrefix(normalizedName, "-") - - return normalizedName -} - -func NormalizeName(displayName string) string { - - // remove all characters, which is not alpha numeric - normalizedName := nonAlphaNumeric.ReplaceAllString(displayName, "-") - // to lower - normalizedName = strings.Map(unicode.ToLower, normalizedName) - // trim dashes if exists - normalizedName = strings.TrimSuffix(normalizedName, "-") - if len(normalizedName) > 57 { - normalizedName = normalizedName[:57] - } - - return strings.TrimPrefix(normalizedName, "-") -} diff --git a/components/central-application-gateway/pkg/normalization/normalization_test.go b/components/central-application-gateway/pkg/normalization/normalization_test.go deleted file mode 100644 index 3340a3cba489..000000000000 --- a/components/central-application-gateway/pkg/normalization/normalization_test.go +++ /dev/null @@ -1,56 +0,0 @@ -package normalization - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestNormalizeServiceName(t *testing.T) { - - tests := []struct { - name string - displayName string - id string - expected string - expectedWithId string - }{ - { - name: "should replace upper case with lower case", - displayName: "DisplayName", - id: "id", - expected: "displayname", - expectedWithId: "displayname-87ea5", - }, - { - name: "should replace non alpha numeric characters with --", - displayName: "display_!@#$%^&*()name", - id: "id", - expected: "display-name", - expectedWithId: "display-name-87ea5", - }, - { - name: "should remove leading dashes", - displayName: "-----displayname", - id: "id", - expected: "displayname", - expectedWithId: "displayname-87ea5", - }, - { - name: "should trim if name too long", - displayName: "VeryVeryVeryVeryVeryVeryVEryVeryVeryVeryVeryVeryVeryVeryLongDescription", - id: "id", - expected: "veryveryveryveryveryveryveryveryveryveryveryveryveryveryl", - expectedWithId: "veryveryveryveryveryveryveryveryveryveryveryveryveryveryl-87ea5", - }, - } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - normalised := NormalizeName(tc.displayName) - assert.Equal(t, tc.expected, normalised) - - normalisedWithId := NormalizeServiceNameWithId(tc.displayName, tc.id) - assert.Equal(t, tc.expectedWithId, normalisedWithId) - }) - } -} diff --git a/components/central-application-gateway/pkg/proxyconfig/destination_config.go b/components/central-application-gateway/pkg/proxyconfig/destination_config.go deleted file mode 100644 index 1c72ce49ca33..000000000000 --- a/components/central-application-gateway/pkg/proxyconfig/destination_config.go +++ /dev/null @@ -1,96 +0,0 @@ -package proxyconfig - -import ( - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization" -) - -//go:generate mockery --name=TargetConfigProvider - -// TargetConfigProvider allows to fetch ProxyDestinationConfig for specific service -type TargetConfigProvider interface { - GetDestinationConfig(secretName, apiName string) (ProxyDestinationConfig, apperrors.AppError) -} - -// AuthType determines the secret structure -type AuthType string - -const ( - Undefined AuthType = "" - NoAuth AuthType = "noauth" - Oauth AuthType = "oauth" - Basic AuthType = "basicauth" - Certificate AuthType = "certificate" -) - -// ProxyDestinationConfig is Proxy configuration for specific target -type ProxyDestinationConfig struct { - TargetURL string `json:"targetUrl"` - Configuration Configuration `json:"configuration"` -} - -type Configuration struct { - RequestParameters *authorization.RequestParameters `json:"requestParameters,omitempty"` - CSRFConfig *CSRFConfig `json:"csrfConfig,omitempty"` - Credentials Credentials `json:"credentials,omitempty"` -} - -type CSRFConfig struct { - TokenURL string `json:"tokenUrl"` -} - -type Credentials interface { - ToCredentials() *authorization.Credentials -} - -type NoAuthConfig struct{} - -func (oc NoAuthConfig) ToCredentials() *authorization.Credentials { - return nil -} - -type OauthConfig struct { - ClientId string `json:"clientId"` - ClientSecret string `json:"clientSecret"` - TokenURL string `json:"tokenUrl"` - RequestParameters authorization.RequestParameters `json:"requestParameters,omitempty"` -} - -func (oc OauthConfig) ToCredentials() *authorization.Credentials { - return &authorization.Credentials{ - OAuth: &authorization.OAuth{ - URL: oc.TokenURL, - ClientID: oc.ClientId, - ClientSecret: oc.ClientSecret, - RequestParameters: &oc.RequestParameters, - }, - } -} - -type BasicAuthConfig struct { - Username string `json:"username"` - Password string `json:"password"` -} - -func (bc BasicAuthConfig) ToCredentials() *authorization.Credentials { - return &authorization.Credentials{ - BasicAuth: &authorization.BasicAuth{ - Username: bc.Username, - Password: bc.Password, - }, - } -} - -type CertificateConfig struct { - Certificate []byte `json:"certificate"` - PrivateKey []byte `json:"privateKey"` -} - -func (cc CertificateConfig) ToCredentials() *authorization.Credentials { - return &authorization.Credentials{ - CertificateGen: &authorization.CertificateGen{ - PrivateKey: cc.PrivateKey, - Certificate: cc.Certificate, - }, - } -} diff --git a/components/central-application-gateway/pkg/proxyconfig/mocks/TargetConfigProvider.go b/components/central-application-gateway/pkg/proxyconfig/mocks/TargetConfigProvider.go deleted file mode 100644 index 49290b05a408..000000000000 --- a/components/central-application-gateway/pkg/proxyconfig/mocks/TargetConfigProvider.go +++ /dev/null @@ -1,53 +0,0 @@ -// Code generated by mockery v2.16.0. DO NOT EDIT. - -package mocks - -import ( - apperrors "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors" - mock "github.com/stretchr/testify/mock" - - proxyconfig "github.com/kyma-project/kyma/components/central-application-gateway/pkg/proxyconfig" -) - -// TargetConfigProvider is an autogenerated mock type for the TargetConfigProvider type -type TargetConfigProvider struct { - mock.Mock -} - -// GetDestinationConfig provides a mock function with given fields: secretName, apiName -func (_m *TargetConfigProvider) GetDestinationConfig(secretName string, apiName string) (proxyconfig.ProxyDestinationConfig, apperrors.AppError) { - ret := _m.Called(secretName, apiName) - - var r0 proxyconfig.ProxyDestinationConfig - if rf, ok := ret.Get(0).(func(string, string) proxyconfig.ProxyDestinationConfig); ok { - r0 = rf(secretName, apiName) - } else { - r0 = ret.Get(0).(proxyconfig.ProxyDestinationConfig) - } - - var r1 apperrors.AppError - if rf, ok := ret.Get(1).(func(string, string) apperrors.AppError); ok { - r1 = rf(secretName, apiName) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(apperrors.AppError) - } - } - - return r0, r1 -} - -type mockConstructorTestingTNewTargetConfigProvider interface { - mock.TestingT - Cleanup(func()) -} - -// NewTargetConfigProvider creates a new instance of TargetConfigProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewTargetConfigProvider(t mockConstructorTestingTNewTargetConfigProvider) *TargetConfigProvider { - mock := &TargetConfigProvider{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/components/central-application-gateway/scripts/delete-all.sh b/components/central-application-gateway/scripts/delete-all.sh deleted file mode 100755 index b694d7f12aea..000000000000 --- a/components/central-application-gateway/scripts/delete-all.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/usr/bin/env bash - -HOST=51.144.236.138:8081 - -curl http://$HOST/v1/metadata/services | jq ".[].id" -r > IDs.txt - -while read p; do - echo "$p => $(curl -sIX DELETE http://$HOST/v1/metadata/services/$p | head -n 1)" - echo -done { - let body = []; - request.on('data', (chunk) => { - body.push(chunk); - }).on('end', () => { - body = Buffer.concat(body).toString(); - - console.log(`==== ${request.method} ${request.url}`); - console.log('> Headers'); - console.log(request.headers); - - console.log('> Body'); - console.log(body); - response.writeHead(200, {"Content-Type": "application/json"}); - response.end(JSON.stringify({ - "token_type": "Bearer", - "access_token": "122-b012b9bd-0073-4415-0b2b-f06c36cc4031", - "expires_in": 3600, - "scope": "" - })); - }); -}).listen(8084); diff --git a/components/central-application-gateway/scripts/log-request.js b/components/central-application-gateway/scripts/log-request.js deleted file mode 100644 index 9a2d26439f5a..000000000000 --- a/components/central-application-gateway/scripts/log-request.js +++ /dev/null @@ -1,19 +0,0 @@ -const http = require('http'); -const server = http.createServer(); - -server.on('request', (request, response) => { - let body = []; - request.on('data', (chunk) => { - body.push(chunk); - }).on('end', () => { - body = Buffer.concat(body).toString(); - - console.log(`==== ${request.method} ${request.url}`); - console.log('> Headers'); - console.log(request.headers); - - console.log('> Body'); - console.log(body); - response.end(); - }); -}).listen(8083); diff --git a/components/compass-runtime-agent/.gitignore b/components/compass-runtime-agent/.gitignore deleted file mode 100644 index c8b1fdddc9d7..000000000000 --- a/components/compass-runtime-agent/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -/config -licenses -/compass-runtime-agent diff --git a/components/compass-runtime-agent/Dockerfile b/components/compass-runtime-agent/Dockerfile deleted file mode 100644 index a0ce3d1fef2b..000000000000 --- a/components/compass-runtime-agent/Dockerfile +++ /dev/null @@ -1,28 +0,0 @@ -FROM golang:1.22.2-alpine3.18 as builder - - -ARG DOCK_PKG_DIR=/compass-runtime-agent -WORKDIR $DOCK_PKG_DIR - -COPY . $DOCK_PKG_DIR - -RUN echo "nobody:x:65534:5534:nobody:/:" > /etc_passwd - -RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o compass-runtime-agent ./cmd - - -FROM eu.gcr.io/kyma-project/external/alpine:3.17.3 as certs -RUN apk add -U --no-cache ca-certificates - -FROM scratch -LABEL source=git@github.com:kyma-project/kyma.git - -WORKDIR /app - -COPY --from=certs /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ -COPY --from=builder $DOCK_PKG_DIR/compass-runtime-agent . - -COPY --from=builder /etc_passwd /etc/passwd -USER nobody - -CMD ["/app/compass-runtime-agent"] diff --git a/components/compass-runtime-agent/Makefile b/components/compass-runtime-agent/Makefile deleted file mode 100755 index 7b663e0c7c32..000000000000 --- a/components/compass-runtime-agent/Makefile +++ /dev/null @@ -1,41 +0,0 @@ -APP_NAME = compass-runtime-agent -APP_PATH = components/$(APP_NAME) -SCRIPTS_DIR = $(realpath $(shell pwd)/../..)/common/makefiles - -override ENTRYPOINT = cmd/ - -include $(SCRIPTS_DIR)/generic-make-go.mk - -VERIFY_IGNORE := /vendor\|/mocks - -resolve-local: - GO111MODULE=on go mod vendor -v - -release: - $(MAKE) gomod-release-local - -.PHONY: path-to-referenced-charts -path-to-referenced-charts: - @echo "resources/compass-runtime-agent" - -.PHONY: test -test: envtest ## Run tests. - if [ -d "$(ARTIFACTS)" ]; then \ - KUBEBUILDER_ASSETS="$(shell $(ENVTEST) use $(ENVTEST_K8S_VERSION) --bin-dir $(LOCALBIN) -p path)" go test ./... -v -coverprofile $(ARTIFACTS)/filtered.cov; \ - else \ - KUBEBUILDER_ASSETS="$(shell $(ENVTEST) use $(ENVTEST_K8S_VERSION) --bin-dir $(LOCALBIN) -p path)" go test ./... -v; \ - fi - - -ENVTEST_K8S_VERSION = 1.26.0 - -LOCALBIN ?= $(shell pwd)/bin -$(LOCALBIN): - mkdir -p $(LOCALBIN) - -ENVTEST ?= $(LOCALBIN)/setup-envtest - -.PHONY: envtest -envtest: $(ENVTEST) ## Download envtest-setup locally if necessary. -$(ENVTEST): $(LOCALBIN) - test -s $(LOCALBIN)/setup-envtest || GOBIN=$(LOCALBIN) go install sigs.k8s.io/controller-runtime/tools/setup-envtest@latest diff --git a/components/compass-runtime-agent/README.md b/components/compass-runtime-agent/README.md deleted file mode 100644 index 564aaeec94c2..000000000000 --- a/components/compass-runtime-agent/README.md +++ /dev/null @@ -1,63 +0,0 @@ -# Runtime Agent - -## Overview - -This is the repository for Runtime Agent. - -The main responsibilities of Runtime Agent are: -- Establishing a trusted connection between the Runtime and Compass -- Renewing the trusted connection between the Runtime and Compass -- Configuring the Runtime - -## Prerequisites - -Runtime Agent requires Go 1.8 or higher. - -## Unit Testing - -To execute unit tests for controller functionality, Runtime Agent requires an additional `etcd` binary to be installed on your local machine at this location: `/usr/local/kubebuilder/bin`. - -See [this link](https://book.kubebuilder.io/reference/envtest.html) for installation instructions. - -## Usage - -To start Runtime Agent, run this command: - -```bash -./compass-runtime-agent -``` - -## Parameters and Environment Variables - -Runtime Agent uses these environment variables: -- **APP_AGENT_CONFIGURATION_SECRET** specifies the namespace and the Name of the Secret containing the Runtime Agent Configuration. -- **APP_CONTROLLER_SYNC_PERIOD** specifies the time period between resynchronizing existing resources. -- **APP_MINIMAL_COMPASS_SYNC_TIME** specifies the minimal time between synchronizing the configuration. -- **APP_CERT_VALIDITY_RENEWAL_THRESHOLD** specifies when the certificate must be renewed based on the remaining validity time of the current certificate. -- **APP_CLUSTER_CERTIFICATES_SECRET** specifies the namespace and the Name of the Secret in which to store the client certificate and the key. -- **APP_CA_CERTIFICATES_SECRET** specifies the namespace and the Name of the Secret in which to store the CA certificate. -- **APP_SKIP_COMPASS_TLS_VERIFY** specifies whether to communicate with Connector and Director with disabled TLS verification. -- **APP_SKIP_APPS_TLS_VERIFY** specifies whether to set up Applications synchronized from Compass to communicate with external systems with disabled TLS verification. -- **APP_GATEWAY_PORT** specifies the Application Gateway port. -- **APP_QUERY_LOGGING** specifies whether to log GraphQL queries. -- **APP_RUNTIME_EVENTS_URL** specifies the Events URL of the cluster that Runtime Agent runs on. -- **APP_RUNTIME_CONSOLE_URL** specifies the Console URL of the cluster that Runtime Agent runs on. -- **APP_HEALTH_PORT** specifies the health check port. -- **APP_CA_CERT_SECRET_TO_MIGRATE** specifies the namespace and the name of the Secret which stores the CA certificate to be renamed. Requires the `{NAMESPACE}/{SECRET_NAME}` format. -- **APP_CA_CERT_SECRET_KEYS_TO_MIGRATE** specifies the list of keys to be copied when migrating the old Secret specified in **APP_CA_CERT_SECRET_TO_MIGRATE** to the new one specified in **APP_CA_CERTIFICATES_SECRET**. Requires the JSON table format. - -## Renaming Secrets - -To rename the Secret containing the CA cert, you must specify these environment variables: -- **APP_CA_CERTIFICATES_SECRET** -- **APP_CA_CERT_SECRET_TO_MIGRATE** -- **APP_CA_CERT_SECRET_KEYS_TO_MIGRATE** - -## Generating Custom Resource Client - -Because Go Modules do not support code generation, you must run the code generator inside a Docker container. -To generate a custom resource client and deep copy Functions, run this command from the component directory: - -```bash -./hack/code-gen-in-docker.sh -``` diff --git a/components/compass-runtime-agent/cmd/init.go b/components/compass-runtime-agent/cmd/init.go deleted file mode 100644 index a3dae2b76150..000000000000 --- a/components/compass-runtime-agent/cmd/init.go +++ /dev/null @@ -1,90 +0,0 @@ -package main - -import ( - "time" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/k8sconsts" - appsecrets "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/secrets" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/secrets/strategy" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/secrets" - - appclient "github.com/kyma-project/kyma/components/central-application-gateway/pkg/client/clientset/versioned" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/apperrors" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/applications" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/metrics" - "github.com/pkg/errors" - "k8s.io/client-go/dynamic" - "k8s.io/client-go/kubernetes" - restclient "k8s.io/client-go/rest" - clientset "k8s.io/metrics/pkg/client/clientset/versioned" -) - -type k8sResourceClientSets struct { - core *kubernetes.Clientset - application *appclient.Clientset - dynamic dynamic.Interface -} - -func k8sResourceClients(k8sConfig *restclient.Config) (*k8sResourceClientSets, error) { - coreClientset, err := kubernetes.NewForConfig(k8sConfig) - if err != nil { - return nil, errors.Wrap(err, "Failed to create k8s core client") - } - - applicationClientset, err := appclient.NewForConfig(k8sConfig) - if err != nil { - return nil, apperrors.Internal("Failed to create k8s application client, %s", err) - } - - dynamicClient, err := dynamic.NewForConfig(k8sConfig) - if err != nil { - return nil, apperrors.Internal("Failed to create dynamic client, %s", err) - } - - return &k8sResourceClientSets{ - core: coreClientset, - application: applicationClientset, - dynamic: dynamicClient, - }, nil -} - -func createKymaService(k8sResourceClients *k8sResourceClientSets, integrationNamespace string, centralGatewayServiceUrl string, appTLSSkipVerify bool) (kyma.Service, error) { - nameResolver := k8sconsts.NewNameResolver() - secretsManagerConstructor := func(namespace string) secrets.Manager { - return k8sResourceClients.core.CoreV1().Secrets(namespace) - } - repository := appsecrets.NewRepository(secretsManagerConstructor(integrationNamespace)) - - applicationManager := newApplicationManager(k8sResourceClients.application) - - converter := applications.NewConverter(nameResolver, centralGatewayServiceUrl, appTLSSkipVerify) - credentialsService := appsecrets.NewCredentialsService(repository, strategy.NewSecretsStrategyFactory(), nameResolver) - requestParametersService := appsecrets.NewRequestParametersService(repository, nameResolver) - - return kyma.NewService(applicationManager, converter, credentialsService, requestParametersService), nil -} - -func newApplicationManager(appClientset *appclient.Clientset) applications.Repository { - appInterface := appClientset.ApplicationconnectorV1alpha1().Applications() - return applications.NewRepository(appInterface) -} - -func newMetricsLogger(loggingTimeInterval time.Duration) (metrics.Logger, error) { - config, err := restclient.InClusterConfig() - if err != nil { - return nil, errors.Wrap(err, "failed to get cluster config") - } - - resourcesClientset, err := kubernetes.NewForConfig(config) - if err != nil { - return nil, errors.Wrap(err, "failed to create resources clientset for config") - } - - metricsClientset, err := clientset.NewForConfig(config) - if err != nil { - return nil, errors.Wrap(err, "failed to create metrics clientset for config") - } - - return metrics.NewMetricsLogger(resourcesClientset, metricsClientset, loggingTimeInterval), nil -} diff --git a/components/compass-runtime-agent/cmd/main.go b/components/compass-runtime-agent/cmd/main.go deleted file mode 100755 index af1ba2668037..000000000000 --- a/components/compass-runtime-agent/cmd/main.go +++ /dev/null @@ -1,137 +0,0 @@ -package main - -import ( - "context" - "github.com/google/uuid" - "github.com/kyma-incubator/compass/components/director/pkg/correlation" - "github.com/kyma-incubator/compass/components/director/pkg/str" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/certificates" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/compass" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/compass/cache" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/compassconnection" - confProvider "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/config" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/graphql" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/healthz" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/secrets" - apis "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/apis/compass/v1alpha1" - - "github.com/pkg/errors" - log "github.com/sirupsen/logrus" - "github.com/vrischmann/envconfig" - _ "k8s.io/client-go/plugin/pkg/client/auth/gcp" - "sigs.k8s.io/controller-runtime/pkg/client/config" - "sigs.k8s.io/controller-runtime/pkg/manager" - "sigs.k8s.io/controller-runtime/pkg/manager/signals" -) - -func main() { - log.Infoln("Starting Runtime Agent") - - var options Config - err := envconfig.InitWithPrefix(&options, "APP") - exitOnError(err, "Failed to process environment variables") - - log.Infof("Env config: %s", options.String()) - - // Get a config to talk to the apiserver - log.Info("Setting up client for manager") - cfg, err := config.GetConfig() - exitOnError(err, "Failed to set up client config") - - k8sResourceClientSets, err := k8sResourceClients(cfg) - exitOnError(err, "Failed to initialize K8s resource clients") - - secretsManagerConstructor := func(namespace string) secrets.Manager { - return k8sResourceClientSets.core.CoreV1().Secrets(namespace) - } - - caCertSecret := parseNamespacedName(options.CaCertificatesSecret) - - secretsRepository := secrets.NewRepository(secretsManagerConstructor) - - clusterCertSecret := parseNamespacedName(options.ClusterCertificatesSecret) - agentConfigSecret := parseNamespacedName(options.AgentConfigurationSecret) - - log.Info("Setting up manager") - mgr, err := manager.New(cfg, manager.Options{SyncPeriod: &options.ControllerSyncPeriod}) - exitOnError(err, "Failed to set up overall controller manager") - - // Setup Scheme for all resources - log.Info("Setting up scheme") - err = apis.AddToScheme(mgr.GetScheme()) - exitOnError(err, "Failed to add APIs to scheme") - - log.Info("Registering Components.") - - certManager := certificates.NewCredentialsManager(clusterCertSecret, caCertSecret, secretsRepository) - - syncService, err := createSynchronisationService(k8sResourceClientSets, options) - exitOnError(err, "Failed to create synchronization service") - - connectionDataCache := cache.NewConnectionDataCache() - - configProvider := confProvider.NewConfigProvider(agentConfigSecret, secretsRepository) - clientsProvider := compass.NewClientsProvider(graphql.New, options.SkipCompassTLSVerify, options.QueryLogging) - connectionDataCache.AddSubscriber(clientsProvider.UpdateConnectionData) - - log.Infoln("Setting up Controller") - controllerDependencies := compassconnection.DependencyConfig{ - K8sConfig: cfg, - ControllerManager: mgr, - ClientsProvider: clientsProvider, - CredentialsManager: certManager, - SynchronizationService: syncService, - ConfigProvider: configProvider, - ConnectionDataCache: connectionDataCache, - RuntimeURLsConfig: options.Runtime, - CertValidityRenewalThreshold: options.CertValidityRenewalThreshold, - MinimalCompassSyncTime: options.MinimalCompassSyncTime, - } - - compassConnectionSupervisor, err := controllerDependencies.InitializeController() - exitOnError(err, "Failed to initialize Controller") - - correlationID := uuid.New().String() - ctx := correlation.SaveCorrelationIDHeaderToContext(context.Background(), str.Ptr(correlation.RequestIDHeaderKey), str.Ptr(correlationID)) - - log.Infoln("Initializing Compass Connection CR") - _, err = compassConnectionSupervisor.InitializeCompassConnection(ctx) - exitOnError(err, "Failed to initialize Compass Connection CR") - - log.Infoln("Initializing metrics logger") - metricsLogger, err := newMetricsLogger(options.MetricsLoggingTimeInterval) - exitOnError(err, "Failed to create metrics logger") - err = mgr.Add(metricsLogger) - exitOnError(err, "Failed to add metrics logger to manager") - - go func() { - log.Info("Starting Healthcheck Server") - healthz.StartHealthCheckServer(log.StandardLogger(), options.HealthPort) - }() - - log.Info("Starting the Cmd.") - err = mgr.Start(signals.SetupSignalHandler()) - exitOnError(err, "Failed to run the manager") -} - -func createSynchronisationService(k8sResourceClients *k8sResourceClientSets, options Config) (kyma.Service, error) { - - var syncService kyma.Service - var err error - - syncService, err = createKymaService(k8sResourceClients, options.IntegrationNamespace, options.CentralGatewayServiceUrl, options.SkipAppsTLSVerify) - - if err != nil { - return nil, err - } - - return syncService, nil -} - -func exitOnError(err error, context string) { - if err != nil { - log.Fatal(errors.Wrap(err, context)) - } -} diff --git a/components/compass-runtime-agent/cmd/options.go b/components/compass-runtime-agent/cmd/options.go deleted file mode 100644 index 7cb914cbbea9..000000000000 --- a/components/compass-runtime-agent/cmd/options.go +++ /dev/null @@ -1,85 +0,0 @@ -package main - -import ( - "fmt" - "strings" - "time" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/compass/director" - - "k8s.io/apimachinery/pkg/types" -) - -const ( - defaultNamespace = "default" -) - -type Config struct { - AgentConfigurationSecret string `envconfig:"default=kyma-system/compass-agent-configuration"` - ControllerSyncPeriod time.Duration `envconfig:"default=20s"` - MinimalCompassSyncTime time.Duration `envconfig:"default=10s"` - CertValidityRenewalThreshold float64 `envconfig:"default=0.3"` - ClusterCertificatesSecret string `envconfig:"default=kyma-system/cluster-client-certificates"` - CaCertificatesSecret string `envconfig:"default=istio-system/ca-certificates"` - SkipCompassTLSVerify bool `envconfig:"default=false"` - GatewayPort int `envconfig:"default=8080"` - SkipAppsTLSVerify bool `envconfig:"default=false"` - CentralGatewayServiceUrl string `envconfig:"default=http://central-application-gateway.kyma-system.svc.cluster.local:8082"` - QueryLogging bool `envconfig:"default=false"` - MetricsLoggingTimeInterval time.Duration `envconfig:"default=30m"` - HealthPort string `envconfig:"default=8090"` - IntegrationNamespace string `envconfig:"default=kyma-system"` - Runtime director.RuntimeURLsConfig -} - -func (o *Config) String() string { - return fmt.Sprintf("AgentConfigurationSecret=%s, "+ - "ControllerSyncPeriod=%s, MinimalCompassSyncTime=%s, "+ - "CertValidityRenewalThreshold=%f, ClusterCertificatesSecret=%s, CaCertificatesSecret=%s, "+ - "SkipCompassTLSVerify=%v, GatewayPort=%d,"+ - "SkipAppTLSVerify=%v, "+ - "QueryLogging=%v, MetricsLoggingTimeInterval=%s, "+ - "RuntimeEventsURL=%s, RuntimeConsoleURL=%s, "+ - "HealthPort=%s, IntegrationNamespace=%s, CentralGatewayServiceUrl=%v", - o.AgentConfigurationSecret, - o.ControllerSyncPeriod.String(), o.MinimalCompassSyncTime.String(), - o.CertValidityRenewalThreshold, o.ClusterCertificatesSecret, o.CaCertificatesSecret, - o.SkipCompassTLSVerify, o.GatewayPort, - o.SkipAppsTLSVerify, - o.QueryLogging, o.MetricsLoggingTimeInterval, - o.Runtime.EventsURL, o.Runtime.ConsoleURL, - o.HealthPort, o.IntegrationNamespace, o.CentralGatewayServiceUrl, - ) -} - -func parseNamespacedName(value string) types.NamespacedName { - parts := strings.Split(value, string(types.Separator)) - - if singleValueProvided(parts) { - return types.NamespacedName{ - Name: parts[0], - Namespace: defaultNamespace, - } - } - - namespace := get(parts, 0) - if namespace == "" { - namespace = defaultNamespace - } - - return types.NamespacedName{ - Namespace: namespace, - Name: get(parts, 1), - } -} - -func singleValueProvided(split []string) bool { - return len(split) == 1 || get(split, 1) == "" -} - -func get(array []string, index int) string { - if len(array) > index { - return array[index] - } - return "" -} diff --git a/components/compass-runtime-agent/cmd/options_test.go b/components/compass-runtime-agent/cmd/options_test.go deleted file mode 100644 index 382ed9d9fbd9..000000000000 --- a/components/compass-runtime-agent/cmd/options_test.go +++ /dev/null @@ -1,55 +0,0 @@ -package main - -import ( - "fmt" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestParseNamespacedName(t *testing.T) { - testCases := []struct { - value string - namespace string - name string - }{ - { - value: "kyma-system/ca-secret", - namespace: "kyma-system", - name: "ca-secret", - }, - { - value: "ca-secret", - namespace: defaultNamespace, - name: "ca-secret", - }, - { - value: "/ca-secret", - namespace: defaultNamespace, - name: "ca-secret", - }, - { - value: "ca-secret/", - namespace: defaultNamespace, - name: "ca-secret", - }, - { - value: "/", - namespace: defaultNamespace, - name: "", - }, - { - value: "", - namespace: defaultNamespace, - name: "", - }, - } - - for _, test := range testCases { - t.Run(fmt.Sprintf("should parse \"%s\" namespaced name", test.value), func(t *testing.T) { - namespaceName := parseNamespacedName(test.value) - assert.Equal(t, test.namespace, namespaceName.Namespace) - assert.Equal(t, test.name, namespaceName.Name) - }) - } -} diff --git a/components/compass-runtime-agent/go.mod b/components/compass-runtime-agent/go.mod deleted file mode 100644 index 6afa653c474a..000000000000 --- a/components/compass-runtime-agent/go.mod +++ /dev/null @@ -1,101 +0,0 @@ -module github.com/kyma-project/kyma/components/compass-runtime-agent - -go 1.21 - -require ( - github.com/google/uuid v1.6.0 - github.com/gorilla/mux v1.8.1 - github.com/kofalt/go-memoize v0.0.0-20200917044458-9b55a8d73e1c - github.com/kyma-incubator/compass/components/connector v0.0.0-20220104122431-99ed924ea212 - github.com/kyma-incubator/compass/components/director v0.0.0-20220126084901-92232f5eced0 - github.com/kyma-project/kyma/components/central-application-gateway v0.0.0-20230201152417-102edd243eab - github.com/machinebox/graphql v0.2.3-0.20181106130121-3a9253180225 - github.com/pkg/errors v0.9.1 - github.com/sirupsen/logrus v1.9.3 - github.com/stretchr/testify v1.9.0 - github.com/vrischmann/envconfig v1.3.0 - k8s.io/api v0.26.7 - k8s.io/apimachinery v0.27.4 - k8s.io/client-go v0.26.7 - k8s.io/metrics v0.26.7 - sigs.k8s.io/controller-runtime v0.14.6 -) - -require ( - github.com/99designs/gqlgen v0.11.3 // indirect - github.com/agnivade/levenshtein v1.1.0 // indirect - github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d // indirect - github.com/beorn7/perks v1.0.1 // indirect - github.com/cespare/xxhash/v2 v2.1.2 // indirect - github.com/davecgh/go-spew v1.1.1 // indirect - github.com/emicklei/go-restful/v3 v3.9.0 // indirect - github.com/evanphx/json-patch v4.12.0+incompatible // indirect - github.com/evanphx/json-patch/v5 v5.6.0 // indirect - github.com/fsnotify/fsnotify v1.6.0 // indirect - github.com/go-logr/logr v1.2.3 // indirect - github.com/go-openapi/jsonpointer v0.19.6 // indirect - github.com/go-openapi/jsonreference v0.20.1 // indirect - github.com/go-openapi/swag v0.22.3 // indirect - github.com/go-ozzo/ozzo-validation/v4 v4.3.0 // indirect - github.com/gogo/protobuf v1.3.2 // indirect - github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect - github.com/golang/protobuf v1.5.3 // indirect - github.com/google/gnostic v0.5.7-v3refs // indirect - github.com/google/go-cmp v0.5.9 // indirect - github.com/google/gofuzz v1.2.0 // indirect - github.com/hashicorp/errwrap v1.1.0 // indirect - github.com/hashicorp/go-multierror v1.1.1 // indirect - github.com/imdario/mergo v0.3.12 // 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/matttproud/golang_protobuf_extensions v1.0.2 // 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/onrik/logrus v0.9.0 // indirect - github.com/patrickmn/go-cache v2.1.0+incompatible // indirect - github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/prometheus/client_golang v1.14.0 // indirect - github.com/prometheus/client_model v0.3.0 // indirect - github.com/prometheus/common v0.37.0 // indirect - github.com/prometheus/procfs v0.8.0 // indirect - github.com/rogpeppe/go-internal v1.10.0 // indirect - github.com/spf13/pflag v1.0.5 // indirect - github.com/stretchr/objx v0.5.2 // indirect - github.com/vektah/gqlparser/v2 v2.1.0 // indirect - github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect - github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect - github.com/xeipuuv/gojsonschema v1.2.0 // indirect - golang.org/x/net v0.19.0 // indirect - golang.org/x/oauth2 v0.0.0-20220223155221-ee480838109b // indirect - golang.org/x/sync v0.1.0 // indirect - golang.org/x/sys v0.15.0 // indirect - golang.org/x/term v0.15.0 // indirect - golang.org/x/text v0.14.0 // indirect - golang.org/x/time v0.3.0 // indirect - gomodules.xyz/jsonpatch/v2 v2.2.0 // indirect - google.golang.org/appengine v1.6.7 // indirect - google.golang.org/protobuf v1.28.1 // 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/apiextensions-apiserver v0.26.1 // indirect - k8s.io/component-base v0.26.1 // indirect - k8s.io/klog/v2 v2.90.1 // indirect - k8s.io/kube-openapi v0.0.0-20230501164219-8b0f38b5fd1f // indirect - k8s.io/utils v0.0.0-20230209194617-a36077c30491 // indirect - sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect - sigs.k8s.io/structured-merge-diff/v4 v4.2.3 // indirect - sigs.k8s.io/yaml v1.3.0 // indirect -) - -replace ( - github.com/containerd/containerd => github.com/containerd/containerd v1.4.11 - github.com/docker/distribution => github.com/docker/distribution v0.0.0-20191216044856-a8371794149d - github.com/docker/docker => github.com/docker/docker v20.10.8+incompatible - golang.org/x/crypto => golang.org/x/crypto v0.16.0 - golang.org/x/net => golang.org/x/net v0.19.0 - golang.org/x/sys => golang.org/x/sys v0.15.0 - golang.org/x/text => golang.org/x/text v0.14.0 -) diff --git a/components/compass-runtime-agent/go.sum b/components/compass-runtime-agent/go.sum deleted file mode 100644 index 7547544d433d..000000000000 --- a/components/compass-runtime-agent/go.sum +++ /dev/null @@ -1,649 +0,0 @@ -cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= -cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU= -cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= -cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc= -cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0= -cloud.google.com/go v0.50.0/go.mod h1:r9sluTvynVuxRIOHXQEHMFffphuXHOMZMycpNR5e6To= -cloud.google.com/go v0.52.0/go.mod h1:pXajvRH/6o3+F9jDHZWQ5PbGhn+o8w9qiu/CffaVdO4= -cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6M= -cloud.google.com/go v0.54.0/go.mod h1:1rq2OEkV3YMf6n/9ZvGWI3GWw0VoqH/1x2nd8Is/bPc= -cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKVk= -cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs= -cloud.google.com/go v0.62.0/go.mod h1:jmCYTdRCQuc1PHIIJ/maLInMho30T/Y0M4hTdTShOYc= -cloud.google.com/go v0.65.0/go.mod h1:O5N8zS7uWy9vkA9vayVHs65eM1ubvY4h553ofrNHObY= -cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= -cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE= -cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc= -cloud.google.com/go/bigquery v1.5.0/go.mod h1:snEHRnqQbz117VIFhE8bmtwIDY80NLUZUMb4Nv6dBIg= -cloud.google.com/go/bigquery v1.7.0/go.mod h1://okPTzCYNXSlb24MZs83e2Do+h+VXtc4gLoIoXIAPc= -cloud.google.com/go/bigquery v1.8.0/go.mod h1:J5hqkt3O0uAFnINi6JXValWIb1v0goeZM77hZzJN/fQ= -cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= -cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk= -cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= -cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw= -cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA= -cloud.google.com/go/pubsub v1.3.1/go.mod h1:i+ucay31+CNRpDW4Lu78I4xXG+O1r/MAHgjpRVR+TSU= -cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= -cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos= -cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk= -cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= -cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= -dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= -github.com/99designs/gqlgen v0.11.3 h1:oFSxl1DFS9X///uHV3y6CEfpcXWrDUxVblR4Xib2bs4= -github.com/99designs/gqlgen v0.11.3/go.mod h1:RgX5GRRdDWNkh4pBrdzNpNPFVsdoUFY2+adM6nb1N+4= -github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= -github.com/agnivade/levenshtein v1.0.1/go.mod h1:CURSv5d9Uaml+FovSIICkLbAUZ9S4RqaHDIsdSBg7lM= -github.com/agnivade/levenshtein v1.0.3/go.mod h1:4SFRZbbXWLF4MU1T9Qg0pGgH3Pjs+t6ie5efyrwRJXs= -github.com/agnivade/levenshtein v1.1.0 h1:n6qGwyHG61v3ABce1rPVZklEYRT8NFpCMrpZdBUbYGM= -github.com/agnivade/levenshtein v1.1.0/go.mod h1:veldBMzWxcCG2ZvUTKD2kJNRdCk5hVbJomOvKkmgYbo= -github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= -github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= -github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= -github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= -github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= -github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883 h1:bvNMNQO63//z+xNgfBlViaCIJKLlCJ6/fmUseuG0wVQ= -github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8= -github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0 h1:jfIu9sQUG6Ig+0+Ap1h4unLjW6YQJpKZVmUzxsD4E/Q= -github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0/go.mod h1:t2tdKJDJF9BV14lnkjHmOQgcvEKgtqs5a1N3LNdJhGE= -github.com/asaskevich/govalidator v0.0.0-20200108200545-475eaeb16496/go.mod h1:oGkLhpf+kjZl6xBf758TQhh5XrAeiJv/7FRz/2spLIg= -github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d h1:Byv0BzEl3/e6D5CLfI0j/7hiIEtvGVFPCZ7Ei2oq8iQ= -github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= -github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= -github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= -github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= -github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= -github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= -github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE= -github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= -github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= -github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= -github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= -github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= -github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= -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/dgryski/trifles v0.0.0-20190318185328-a8d75aae118c/go.mod h1:if7Fbed8SFyPtHLHbg49SI7NAdJiC5WIA09pe59rfAA= -github.com/dgryski/trifles v0.0.0-20200323201526-dd97f9abfb48 h1:fRzb/w+pyskVMQ+UbP35JkH8yB7MYb4q/qhBarqZE6g= -github.com/dgryski/trifles v0.0.0-20200323201526-dd97f9abfb48/go.mod h1:if7Fbed8SFyPtHLHbg49SI7NAdJiC5WIA09pe59rfAA= -github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815/go.mod h1:WwZ+bS3ebgob9U8Nd0kOddGdZWjyMGR8Wziv+TBNwSE= -github.com/emicklei/go-restful/v3 v3.9.0 h1:XwGDlfxEnQZzuopoqxwSEllNcCOM9DhhFyhFIIGKwxE= -github.com/emicklei/go-restful/v3 v3.9.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= -github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= -github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= -github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= -github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/evanphx/json-patch v0.5.2/go.mod h1:ZWS5hhDbVDyob71nXKNL0+PWn6ToqBHMikGIFbs31qQ= -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/evanphx/json-patch/v5 v5.6.0 h1:b91NhWfaz02IuVxO9faSllyAtNXHMPkC5J8sJCLunww= -github.com/evanphx/json-patch/v5 v5.6.0/go.mod h1:G79N1coSVB93tBe7j6PhzjmR3/2VvlbKOFpnXhI9Bw4= -github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= -github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= -github.com/go-chi/chi v3.3.2+incompatible/go.mod h1:eB3wogJHnLi3x/kFX2A+IbTBlXxmMeXJVKy9tTv1XzQ= -github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= -github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= -github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= -github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= -github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= -github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY= -github.com/go-kit/log v0.2.0/go.mod h1:NwTd00d/i8cPZ3xOwwiv2PO5MOcx78fFErGNcVmBjv0= -github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= -github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= -github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= -github.com/go-logfmt/logfmt v0.5.1/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs= -github.com/go-logr/logr v1.2.0/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.2.3 h1:2DntVwHkVopvECVRSlL5PSo9eG+cAkDCuckLubN+rq0= -github.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/zapr v1.2.3 h1:a9vnzlIBPQBBkeaR9IuMUfmVOrQlkoC4YfPoFkX3T7A= -github.com/go-logr/zapr v1.2.3/go.mod h1:eIauM6P8qSvTw5o2ez6UEAfGjQKrxQTl5EoK+Qa2oG4= -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.1 h1:FBLnyygC4/IZZr893oiomc9XaghoveYTrLC1F86HID8= -github.com/go-openapi/jsonreference v0.20.1/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-ozzo/ozzo-validation/v4 v4.3.0 h1:byhDUpfEwjsVQb1vBunvIjh2BHQ9ead57VkAEY4V+Es= -github.com/go-ozzo/ozzo-validation/v4 v4.3.0/go.mod h1:2NKgrcHl3z6cJs+3Oo940FPRiTzuqKbvfrL2RxCj6Ew= -github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= -github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0 h1:p104kn46Q8WdvHunIJ9dAyjPVtrBPhSr3KT2yUst43I= -github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= -github.com/gogo/protobuf v1.0.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= -github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= -github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= -github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= -github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= -github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE= -github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= -github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= -github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= -github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= -github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= -github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= -github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= -github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= -github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= -github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= -github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= -github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= -github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= -github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= -github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= -github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= -github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= -github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= -github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= -github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= -github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= -github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= -github.com/google/gnostic v0.5.7-v3refs h1:FhTMOKj2VhjpouxvWJAV1TL304uMlb9zcDqkl6cEI54= -github.com/google/gnostic v0.5.7-v3refs/go.mod h1:73MKFl6jIHelAJNaBGFzt3SPtZULs9dYrGFt8OiIsHQ= -github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= -github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= -github.com/google/go-cmp v0.5.9/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/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= -github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= -github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= -github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= -github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -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/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= -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/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= -github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= -github.com/gorilla/context v0.0.0-20160226214623-1ea25387ff6f/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= -github.com/gorilla/mux v1.6.1/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= -github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= -github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= -github.com/gorilla/websocket v1.2.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= -github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= -github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= -github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= -github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= -github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= -github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= -github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= -github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= -github.com/imdario/mergo v0.3.12 h1:b6R2BslTbIEToALKP7LxUvijTsNI9TAe80pLWN2g/HU= -github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= -github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= -github.com/jmoiron/sqlx v1.3.4 h1:wv+0IJZfL5z0uZoUjlpKgHkgaFSYD+r9CfrXjEXsO7w= -github.com/jmoiron/sqlx v1.3.4/go.mod h1:2BljVx/86SuTyjE+aPYlHCTNvZrnJXghYGpNiXLBMCQ= -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/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= -github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= -github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= -github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= -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/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= -github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= -github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= -github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= -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/kofalt/go-memoize v0.0.0-20200917044458-9b55a8d73e1c h1:iQm590VHHIeY1j9OFi2qBPgIeDqxz+PmHdDK/fUcN7s= -github.com/kofalt/go-memoize v0.0.0-20200917044458-9b55a8d73e1c/go.mod h1:IvB2BCBCdgZFN9ZSgInoUlL1sAu0Xbvqfd7D+qqzTeo= -github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= -github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= -github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= -github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= -github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= -github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= -github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= -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/kyma-incubator/compass/components/connector v0.0.0-20220104122431-99ed924ea212 h1:UO1j1+3Tc+Pge3qzF92ycWuysHMHAtC/7Fjol2qcrm0= -github.com/kyma-incubator/compass/components/connector v0.0.0-20220104122431-99ed924ea212/go.mod h1:NHpaOE/9XuX0XIEi7ButaDyWejakMXRo/mh4JhjDoxY= -github.com/kyma-incubator/compass/components/director v0.0.0-20220126084901-92232f5eced0 h1:5pDxnqY8TK59Zp+9PqsC8uEG6ZeeURJKHxUo19ez+jY= -github.com/kyma-incubator/compass/components/director v0.0.0-20220126084901-92232f5eced0/go.mod h1:62mrVWDkGdPxAqj+X97FKiA/e8jYSZ/MARgzoThk9AU= -github.com/kyma-project/kyma/components/central-application-gateway v0.0.0-20230201152417-102edd243eab h1:Q6kUp8GI7W9sIl3xXYaa+hLvet8a5pOpqZ/BDQ9Y7js= -github.com/kyma-project/kyma/components/central-application-gateway v0.0.0-20230201152417-102edd243eab/go.mod h1:NL5E+cv7oyD8xJtDywLrHnkublvqifMBt5HFdw94adc= -github.com/lib/pq v1.10.4 h1:SO9z7FRPzA03QhHKJrH5BXA6HU1rS4V2nIVrrNC1iYk= -github.com/lib/pq v1.10.4/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= -github.com/logrusorgru/aurora v0.0.0-20200102142835-e9ef32dff381/go.mod h1:7rIyQOR62GCctdiQpZ/zOJlFyk6y+94wXzv6RNZgaR4= -github.com/machinebox/graphql v0.2.3-0.20181106130121-3a9253180225 h1:guHWmqIKr4G+gQ4uYU5vcZjsUhhklRA2uOcGVfcfqis= -github.com/machinebox/graphql v0.2.3-0.20181106130121-3a9253180225/go.mod h1:F+kbVMHuwrQ5tYgU9JXlnskM8nOaFxCAEolaQybkjWA= -github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= -github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= -github.com/matryer/is v1.4.0 h1:sosSmIWwkYITGrxZ25ULNDeKiMNzFSr4V/eqBQP0PeE= -github.com/matryer/is v1.4.0/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU= -github.com/matryer/moq v0.0.0-20200106131100-75d0ddfc0007/go.mod h1:9ELz6aaclSIGnZBoaSLZ3NAl1VTufbOrXBPvtcy6WiQ= -github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= -github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= -github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= -github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= -github.com/matttproud/golang_protobuf_extensions v1.0.2 h1:hAHbPm5IJGijwng3PWk09JkG9WeqChjprR5s9bBZ+OM= -github.com/matttproud/golang_protobuf_extensions v1.0.2/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4= -github.com/mitchellh/mapstructure v0.0.0-20180203102830-a4e142e9c047/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= -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 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= -github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= -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/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= -github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= -github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= -github.com/onrik/logrus v0.9.0 h1:oT7VstCUxWBoX7fswYK61fi9bzRBSpROq5CR2b7wxQo= -github.com/onrik/logrus v0.9.0/go.mod h1:qfe9NeZVAJfIxviw3cYkZo3kvBtLoPRJriAO8zl7qTk= -github.com/onsi/ginkgo/v2 v2.9.1 h1:zie5Ly042PD3bsCvsSOPvRnFwyo3rKe64TJlD6nu0mk= -github.com/onsi/ginkgo/v2 v2.9.1/go.mod h1:FEcmzVcCHl+4o9bQZVab+4dC9+j+91t2FHSzmGAPfuo= -github.com/onsi/gomega v1.27.4 h1:Z2AnStgsdSayCMDiCU42qIz+HLqEPcgiOCXjAU/w+8E= -github.com/onsi/gomega v1.27.4/go.mod h1:riYq/GJKh8hhoM01HN6Vmuy93AarCXCBGpvFDK3q3fQ= -github.com/opentracing/basictracer-go v1.0.0/go.mod h1:QfBfYuafItcjQuMwinw9GhYKwFXS9KnPs5lxoYwgW74= -github.com/opentracing/opentracing-go v1.0.2/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= -github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc= -github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ= -github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -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/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= -github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= -github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= -github.com/prometheus/client_golang v1.11.0/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqroYurpAkEiz0P2BEV0= -github.com/prometheus/client_golang v1.12.1/go.mod h1:3Z9XVyYiZYEO+YQWt3RD2R3jrbd179Rt297l4aS6nDY= -github.com/prometheus/client_golang v1.14.0 h1:nJdhIvne2eSX/XRAFV9PcvFFRbrjbcTUj0VP62TMhnw= -github.com/prometheus/client_golang v1.14.0/go.mod h1:8vpkKitgIVNcqrRBWh1C4TIUQgYNtG/XQE4E/Zae36Y= -github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= -github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/client_model v0.3.0 h1:UBgGFHqYdG/TPFD1B1ogZywDqEkwp3fBMvqdiQ7Xew4= -github.com/prometheus/client_model v0.3.0/go.mod h1:LDGWKZIo7rky3hgvBe+caln+Dr3dPggB5dvjtD7w9+w= -github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= -github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= -github.com/prometheus/common v0.26.0/go.mod h1:M7rCNAaPfAosfx8veZJCuw84e35h3Cfd9VFqTh1DIvc= -github.com/prometheus/common v0.32.1/go.mod h1:vu+V0TpY+O6vW9J44gczi3Ap/oXXR10b+M/gUGO4Hls= -github.com/prometheus/common v0.37.0 h1:ccBbHCgIiT9uSoFY0vX8H3zsNR5eLt17/RQLUvn8pXE= -github.com/prometheus/common v0.37.0/go.mod h1:phzohg0JFMnBEFGxTDbfu3QyL5GI8gTQJFhYO5B3mfA= -github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= -github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= -github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= -github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= -github.com/prometheus/procfs v0.7.3/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= -github.com/prometheus/procfs v0.8.0 h1:ODq8ZFEaYeCaZOJlZZdJA2AbQR98dSHSM1KW/You5mo= -github.com/prometheus/procfs v0.8.0/go.mod h1:z7EfXMXOkbkqb9IINtpCn86r/to3BnA0uaxHdg830/4= -github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= -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/rs/cors v1.6.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= -github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0= -github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= -github.com/shurcooL/httpfs v0.0.0-20171119174359-809beceb2371/go.mod h1:ZY1cvUeJuFPAdZ/B6v7RHavJWZn2YPVFQ1OSXhCGOkg= -github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= -github.com/shurcooL/vfsgen v0.0.0-20180121065927-ffb13db8def0/go.mod h1:TrYk7fJVaAttu97ZZKrO9UbRa8izdowaMIZcxYMbVaw= -github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= -github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= -github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= -github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= -github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= -github.com/smartystreets/assertions v1.2.0 h1:42S6lae5dvLc7BrLu/0ugRtcFVjoJNMC/N3yZFZkDFs= -github.com/smartystreets/assertions v1.2.0/go.mod h1:tcbTF8ujkAEcZ8TElKY+i30BzYlVhC/LOxJk7iOWnoo= -github.com/smartystreets/gunit v1.4.2 h1:tyWYZffdPhQPfK5VsMQXfauwnJkqg7Tv5DLuQVYxq3Q= -github.com/smartystreets/gunit v1.4.2/go.mod h1:ZjM1ozSIMJlAz/ay4SG8PeKF00ckUp+zMHZXV9/bvak= -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/stoewer/go-strcase v1.2.0/go.mod h1:IBiWB2sKIp3wVVQ3Y035++gc+knqhUQag1KpM8ahLw8= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.1.1/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/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= -github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= -github.com/stretchr/testify v1.2.1/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= -github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -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.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= -github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= -github.com/tidwall/gjson v1.12.1 h1:ikuZsLdhr8Ws0IdROXUS1Gi4v9Z4pGqpX/CvJkxvfpo= -github.com/tidwall/gjson v1.12.1/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= -github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= -github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= -github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs= -github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= -github.com/tidwall/sjson v1.2.4 h1:cuiLzLnaMeBhRmEv00Lpk3tkYrcxpmbU81tAY4Dw0tc= -github.com/tidwall/sjson v1.2.4/go.mod h1:098SZ494YoMWPmMO6ct4dcFnqxwj9r/gF0Etp19pSNM= -github.com/urfave/cli/v2 v2.1.1/go.mod h1:SE9GqnLQmjVa0iPEY0f1w3ygNIYcIJ0OKPMoW2caLfQ= -github.com/vektah/dataloaden v0.2.1-0.20190515034641-a19b9a6e7c9e/go.mod h1:/HUdMve7rvxZma+2ZELQeNh88+003LL7Pf/CZ089j8U= -github.com/vektah/gqlparser/v2 v2.0.1/go.mod h1:SyUiHgLATUR8BiYURfTirrTcGpcE+4XkV2se04Px1Ms= -github.com/vektah/gqlparser/v2 v2.1.0 h1:uiKJ+T5HMGGQM2kRKQ8Pxw8+Zq9qhhZhz/lieYvCMns= -github.com/vektah/gqlparser/v2 v2.1.0/go.mod h1:SyUiHgLATUR8BiYURfTirrTcGpcE+4XkV2se04Px1Ms= -github.com/vrischmann/envconfig v1.3.0 h1:4XIvQTXznxmWMnjouj0ST5lFo/WAYf5Exgl3x82crEk= -github.com/vrischmann/envconfig v1.3.0/go.mod h1:bbvxFYJdRSpXrhS63mBFtKJzkDiNkyArOLXtY6q0kuI= -github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= -github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo= -github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= -github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= -github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= -github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= -github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= -github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= -go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= -go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= -go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= -go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= -go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= -go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw= -go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= -go.uber.org/goleak v1.2.0 h1:xqgm/S+aQvhWFTtR0XK3Jvg7z8kGV8P4X14IzwN3Eqk= -go.uber.org/goleak v1.2.0/go.mod h1:XJYK+MuIchqpmGmUSAzotztawfKvYLUIgg7guXrwVUo= -go.uber.org/multierr v1.6.0 h1:y6IPFStTAIT5Ytl7/XYmHvzXQ7S3g/IeZW9hyZ5thw4= -go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= -go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60= -go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg= -golang.org/x/crypto v0.16.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4= -golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= -golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek= -golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY= -golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= -golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= -golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= -golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= -golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= -golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= -golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= -golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= -golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= -golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= -golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= -golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= -golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= -golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= -golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= -golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= -golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= -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/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/net v0.19.0 h1:zTwKpTd2XuCqf8huc7Fo2iSy+4RHPd10s4KzeTnVr1c= -golang.org/x/net v0.19.0/go.mod h1:CfAk/cbD4CthTvqiEl8NpboMuiuOYsAr/7NOjZJtv1U= -golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20220223155221-ee480838109b h1:clP8eMhB30EHdc0bd2Twtq6kgU7yl5ub2cQLSdrv1Dg= -golang.org/x/oauth2 v0.0.0-20220223155221-ee480838109b/go.mod h1:DAh4E804XQdzx2j+YRIaUnCqCV2RuMz24cGBJ5QYIrc= -golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -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-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o= -golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc= -golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/term v0.15.0 h1:y/Oo/a/q3IXu26lQgl04j/gjuBDOBlx7X6Om1j2CPW4= -golang.org/x/term v0.15.0/go.mod h1:BDl952bC7+uMoWR75FIrCDx79TPU9oHkTZ9yRbYOrX0= -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.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -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-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190125232054-d66bd3c5d5a6/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= -golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190515012406-7d7faa4812bd/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200114235610-7ae403b6b589/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200204074204-1cc6d1ef6c74/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200224181240-023911ca70b2/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200304193943-95d2e580d8eb/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= -golang.org/x/tools v0.0.0-20200312045724-11d5b4c81c7d/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= -golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= -golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/tools v0.7.0 h1:W4OVu8VVOaIO0yzWMNdepAulS7YfoS3Zabrm8DOXXU4= -golang.org/x/tools v0.7.0/go.mod h1:4pg6aUX35JBAogB10C9AtvVL+qowtN4pT3CGSQex14s= -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= -gomodules.xyz/jsonpatch/v2 v2.2.0 h1:4pT439QV83L+G9FkcCriY6EkpcK6r6bK+A5FBUMI7qY= -gomodules.xyz/jsonpatch/v2 v2.2.0/go.mod h1:WXp+iVDkoLQqPudfQ9GBlwB2eZ5DKOnjQZCYdOS8GPY= -google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= -google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= -google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= -google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= -google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= -google.golang.org/api v0.14.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= -google.golang.org/api v0.15.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= -google.golang.org/api v0.17.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.18.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.19.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.20.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.22.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.24.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= -google.golang.org/api v0.28.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= -google.golang.org/api v0.29.0/go.mod h1:Lcubydp8VUV7KeIHD9z2Bys/sm/vGKnG1UHuDBSrHWM= -google.golang.org/api v0.30.0/go.mod h1:QGmEvQ87FHZNiUVJkT14jQNYJ4ZJjdRF23ZXz5138Fc= -google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= -google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= -google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -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/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= -google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= -google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= -google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= -google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20191115194625-c23dd37a84c9/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20191216164720-4f79533eabd1/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20191230161307-f3c370f40bfb/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20200115191322-ca5a22157cba/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20200204135345-fa8e72b47b90/go.mod h1:GmwEX6Z4W5gMy59cAlVYjN9JhxgbQH6Gn+gFDQe2lzA= -google.golang.org/genproto v0.0.0-20200212174721-66ed5ce911ce/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200224152610-e50cd9704f63/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200228133532-8c2c7df3a383/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200305110556-506484158171/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200312145019-da6875a35672/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200331122359-1ee6d9798940/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200430143042-b979b6f78d84/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200511104702-f5ebc3bea380/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200515170657-fc4c6c6a6587/go.mod h1:YsZOwe1myG/8QRHRsmBRE1LrgQY60beZKjly0O1fX9U= -google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= -google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7FcilCzHH/e9qn6dsT145K34l5v+OpcnNgKAAA= -google.golang.org/genproto v0.0.0-20200729003335-053ba62fc06f/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20201019141844-1ed22bb0c154/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= -google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= -google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= -google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= -google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= -google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= -google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= -google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= -google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= -google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= -google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= -google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= -google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= -google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= -google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= -google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= -google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= -google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.28.1 h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w= -google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= -gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/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/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= -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.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.3.0/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.0-20200615113413-eeeca48fe776/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= -honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= -honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= -honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= -k8s.io/api v0.26.7 h1:Lf4iEBEJb5OFNmawtBfSZV/UNi9riSJ0t1qdhyZqI40= -k8s.io/api v0.26.7/go.mod h1:Vk9bMadzA49UHPmHB//lX7VRCQSXGoVwfLd3Sc1SSXI= -k8s.io/apiextensions-apiserver v0.26.1 h1:cB8h1SRk6e/+i3NOrQgSFij1B2S0Y0wDoNl66bn8RMI= -k8s.io/apiextensions-apiserver v0.26.1/go.mod h1:AptjOSXDGuE0JICx/Em15PaoO7buLwTs0dGleIHixSM= -k8s.io/apimachinery v0.27.4 h1:CdxflD4AF61yewuid0fLl6bM4a3q04jWel0IlP+aYjs= -k8s.io/apimachinery v0.27.4/go.mod h1:XNfZ6xklnMCOGGFNqXG7bUrQCoR04dh/E7FprV6pb+E= -k8s.io/client-go v0.26.7 h1:hyU9aKHlwVOykgyxzGYkrDSLCc4+mimZVyUJjPyUn1E= -k8s.io/client-go v0.26.7/go.mod h1:okYjy0jtq6sdeztALDvCh24tg4opOQS1XNvsJlERDAo= -k8s.io/component-base v0.26.1 h1:4ahudpeQXHZL5kko+iDHqLj/FSGAEUnSVO0EBbgDd+4= -k8s.io/component-base v0.26.1/go.mod h1:VHrLR0b58oC035w6YQiBSbtsf0ThuSwXP+p5dD/kAWU= -k8s.io/klog/v2 v2.90.1 h1:m4bYOKall2MmOiRaR1J+We67Do7vm9KiQVlT96lnHUw= -k8s.io/klog/v2 v2.90.1/go.mod h1:y1WjHnz7Dj687irZUWR/WLkLc5N1YHtjLdmgWjndZn0= -k8s.io/kube-openapi v0.0.0-20230501164219-8b0f38b5fd1f h1:2kWPakN3i/k81b0gvD5C5FJ2kxm1WrQFanWchyKuqGg= -k8s.io/kube-openapi v0.0.0-20230501164219-8b0f38b5fd1f/go.mod h1:byini6yhqGC14c3ebc/QwanvYwhuMWF6yz2F8uwW8eg= -k8s.io/metrics v0.26.7 h1:GziC+HlH1Gpbh4xrI5Vfz8QxBmy5nXzzRiul2HS5Ioc= -k8s.io/metrics v0.26.7/go.mod h1:k1LCQu9vAS1HRZ2BGAosFHy2qSGZEUYn6bqHVMiFNK0= -k8s.io/utils v0.0.0-20230209194617-a36077c30491 h1:r0BAOLElQnnFhE/ApUsg3iHdVYYPBjNSSOMowRZxxsY= -k8s.io/utils v0.0.0-20230209194617-a36077c30491/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= -rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= -rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= -rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= -sigs.k8s.io/controller-runtime v0.14.6 h1:oxstGVvXGNnMvY7TAESYk+lzr6S3V5VFxQ6d92KcwQA= -sigs.k8s.io/controller-runtime v0.14.6/go.mod h1:WqIdsAY6JBsjfc/CqO0CORmNtoCtE4S6qbPc9s68h+0= -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.2.3 h1:PRbqxJClWWYMNV1dhaG4NsibJbArud9kFxnAMREiWFE= -sigs.k8s.io/structured-merge-diff/v4 v4.2.3/go.mod h1:qjx8mGObPmV2aSZepjQjbmb2ihdVs8cGKBraizNC69E= -sigs.k8s.io/yaml v1.3.0 h1:a2VclLzOGrwOHDiV8EfBGhvjHvP46CtW5j6POvhYGGo= -sigs.k8s.io/yaml v1.3.0/go.mod h1:GeOyir5tyXNByN85N/dRIT9es5UQNerPYEKK56eTBm8= -sourcegraph.com/sourcegraph/appdash v0.0.0-20180110180208-2cc67fd64755/go.mod h1:hI742Nqp5OhwiqlzhgfbWU4mW4yO10fP+LoT9WOswdU= -sourcegraph.com/sourcegraph/appdash-data v0.0.0-20151005221446-73f23eafcf67/go.mod h1:L5q+DGLGOQFpo1snNEkLOJT2d1YTW66rWNzatr3He1k= diff --git a/components/compass-runtime-agent/hack/Dockerfile b/components/compass-runtime-agent/hack/Dockerfile deleted file mode 100644 index d42dfe7d0fe4..000000000000 --- a/components/compass-runtime-agent/hack/Dockerfile +++ /dev/null @@ -1,26 +0,0 @@ -FROM golang:1.14 - -ENV GO111MODULE=off - -WORKDIR /go/src/k8s.io - -RUN git clone https://github.com/kubernetes/code-generator.git -# Versions needs to be compatible with Kuberentes client used -# hadolint ignore=DL3003 -RUN cd code-generator && git fetch && git checkout release-1.21 - -RUN go get k8s.io/apimachinery; exit 0 - -ARG repo="${GOPATH}/src/${PROJECT_MODULE}" - -RUN mkdir -p $repo - -WORKDIR $GOPATH/src/k8s.io/code-generator - -ENV GO111MODULE=on - -RUN go mod vendor - -ENV GO111MODULE=off - -VOLUME $repo \ No newline at end of file diff --git a/components/compass-runtime-agent/hack/boilerplate.go.txt b/components/compass-runtime-agent/hack/boilerplate.go.txt deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/components/compass-runtime-agent/hack/code-gen-in-docker.sh b/components/compass-runtime-agent/hack/code-gen-in-docker.sh deleted file mode 100755 index 122a2a8bc8c4..000000000000 --- a/components/compass-runtime-agent/hack/code-gen-in-docker.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/bin/bash -e - -CURRENT_DIR=$(pwd) -GEN_DIR=$(dirname $0) -REPO_DIR="$CURRENT_DIR/$GEN_DIR/.." -echo $REPO_DIR - -PROJECT_MODULE="github.com/kyma-project/kyma/components/compass-runtime-agent" -IMAGE_NAME="kubernetes-codegen:latest" - -CUSTOM_RESOURCE_GROUP_DIR="compass" -CUSTOM_RESOURCE_VERSION="v1alpha1" - -echo "Building codegen Docker image..." -docker build -f "${GEN_DIR}/Dockerfile" \ - -t "${IMAGE_NAME}" \ - "${REPO_DIR}" - -PROJECT_IN_GOPATH="/go/src/${PROJECT_MODULE}" - -copy_cmd="cp -r ${PROJECT_IN_GOPATH}/vendor ." - -cmd="./generate-groups.sh "deepcopy,client,informer,lister" \ - "$PROJECT_MODULE/pkg/client" \ - "$PROJECT_MODULE/pkg/apis" \ - $CUSTOM_RESOURCE_GROUP_DIR:$CUSTOM_RESOURCE_VERSION \ - --go-header-file ${PROJECT_IN_GOPATH}/hack/boilerplate.go.txt" - -echo "Generating client codes..." -docker run -it --rm \ - -v "${REPO_DIR}:${PROJECT_IN_GOPATH}" \ - -e PROJECT_MODULE=${PROJECT_MODULE} \ - "${IMAGE_NAME}" $cmd - diff --git a/components/compass-runtime-agent/internal/apperrors/apperrors.go b/components/compass-runtime-agent/internal/apperrors/apperrors.go deleted file mode 100644 index b27953c6990e..000000000000 --- a/components/compass-runtime-agent/internal/apperrors/apperrors.go +++ /dev/null @@ -1,66 +0,0 @@ -package apperrors - -import "fmt" - -const ( - CodeInternal = 1 - CodeNotFound = 2 - CodeAlreadyExists = 3 - CodeWrongInput = 4 - CodeUpstreamServerCallFailed = 5 -) - -type AppError interface { - Append(string, ...interface{}) AppError - Code() int - Error() string -} - -type appError struct { - code int - message string -} - -func errorf(code int, format string, a ...interface{}) AppError { - return appError{code: code, message: fmt.Sprintf(format, a...)} -} - -func Internal(format string, a ...interface{}) AppError { - return errorf(CodeInternal, format, a...) -} - -func NotFound(format string, a ...interface{}) AppError { - return errorf(CodeNotFound, format, a...) -} - -func AlreadyExists(format string, a ...interface{}) AppError { - return errorf(CodeAlreadyExists, format, a...) -} - -func WrongInput(format string, a ...interface{}) AppError { - return errorf(CodeWrongInput, format, a...) -} - -func UpstreamServerCallFailed(format string, a ...interface{}) AppError { - return errorf(CodeUpstreamServerCallFailed, format, a...) -} - -func (ae appError) Append(additionalFormat string, a ...interface{}) AppError { - format := additionalFormat + ", " + ae.message - return errorf(ae.code, format, a...) -} - -func (ae appError) Code() int { - return ae.code -} - -func (ae appError) Error() string { - return ae.message -} -func AppendError(wrapped AppError, new AppError) AppError { - if wrapped == nil { - return new - } - - return wrapped.Append("", new) -} diff --git a/components/compass-runtime-agent/internal/apperrors/apperrors_test.go b/components/compass-runtime-agent/internal/apperrors/apperrors_test.go deleted file mode 100644 index 674782f1f423..000000000000 --- a/components/compass-runtime-agent/internal/apperrors/apperrors_test.go +++ /dev/null @@ -1,80 +0,0 @@ -package apperrors - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestAppError(t *testing.T) { - - t.Run("should create error with proper code", func(t *testing.T) { - assert.Equal(t, CodeInternal, Internal("error").Code()) - assert.Equal(t, CodeNotFound, NotFound("error").Code()) - assert.Equal(t, CodeAlreadyExists, AlreadyExists("error").Code()) - assert.Equal(t, CodeWrongInput, WrongInput("error").Code()) - assert.Equal(t, CodeUpstreamServerCallFailed, UpstreamServerCallFailed("error").Code()) - }) - - t.Run("should create error with simple message", func(t *testing.T) { - assert.Equal(t, "error", Internal("error").Error()) - assert.Equal(t, "error", NotFound("error").Error()) - assert.Equal(t, "error", AlreadyExists("error").Error()) - assert.Equal(t, "error", WrongInput("error").Error()) - assert.Equal(t, "error", UpstreamServerCallFailed("error").Error()) - }) - - t.Run("should create error with formatted message", func(t *testing.T) { - assert.Equal(t, "code: 1, error: bug", Internal("code: %d, error: %s", 1, "bug").Error()) - assert.Equal(t, "code: 1, error: bug", NotFound("code: %d, error: %s", 1, "bug").Error()) - assert.Equal(t, "code: 1, error: bug", AlreadyExists("code: %d, error: %s", 1, "bug").Error()) - assert.Equal(t, "code: 1, error: bug", WrongInput("code: %d, error: %s", 1, "bug").Error()) - assert.Equal(t, "code: 1, error: bug", UpstreamServerCallFailed("code: %d, error: %s", 1, "bug").Error()) - }) - - t.Run("should append apperrors without changing error code", func(t *testing.T) { - //given - createdInternalErr := Internal("Some Internal apperror, %s", "Some pkg err") - createdNotFoundErr := NotFound("Some NotFound apperror, %s", "Some pkg err") - createdAlreadyExistsErr := AlreadyExists("Some AlreadyExists apperror, %s", "Some pkg err") - createdWrongInputErr := WrongInput("Some WrongInput apperror, %s", "Some pkg err") - createdUpstreamServerCallFailedErr := UpstreamServerCallFailed("Some UpstreamServerCallFailed apperror, %s", "Some pkg err") - - //when - appendedInternalErr := createdInternalErr.Append("Some additional message") - appendedNotFoundErr := createdNotFoundErr.Append("Some additional message") - appendedAlreadyExistsErr := createdAlreadyExistsErr.Append("Some additional message") - appendedWrongInputErr := createdWrongInputErr.Append("Some additional message") - appendedUpstreamServerCallFailedErr := createdUpstreamServerCallFailedErr.Append("Some additional message") - - //then - assert.Equal(t, CodeInternal, appendedInternalErr.Code()) - assert.Equal(t, CodeNotFound, appendedNotFoundErr.Code()) - assert.Equal(t, CodeAlreadyExists, appendedAlreadyExistsErr.Code()) - assert.Equal(t, CodeWrongInput, appendedWrongInputErr.Code()) - assert.Equal(t, CodeUpstreamServerCallFailed, appendedUpstreamServerCallFailedErr.Code()) - }) - - t.Run("should append apperrors and chain messages correctly", func(t *testing.T) { - //given - createdInternalErr := Internal("Some Internal apperror, %s", "Some pkg err") - createdNotFoundErr := NotFound("Some NotFound apperror, %s", "Some pkg err") - createdAlreadyExistsErr := AlreadyExists("Some AlreadyExists apperror, %s", "Some pkg err") - createdWrongInputErr := WrongInput("Some WrongInput apperror, %s", "Some pkg err") - createdUpstreamServerCallFailedErr := UpstreamServerCallFailed("Some UpstreamServerCallFailed apperror, %s", "Some pkg err") - - //when - appendedInternalErr := createdInternalErr.Append("Some additional message: %s", "error") - appendedNotFoundErr := createdNotFoundErr.Append("Some additional message: %s", "error") - appendedAlreadyExistsErr := createdAlreadyExistsErr.Append("Some additional message: %s", "error") - appendedWrongInputErr := createdWrongInputErr.Append("Some additional message: %s", "error") - appendedUpstreamServerCallFailedErr := createdUpstreamServerCallFailedErr.Append("Some additional message: %s", "error") - - //then - assert.Equal(t, "Some additional message: error, Some Internal apperror, Some pkg err", appendedInternalErr.Error()) - assert.Equal(t, "Some additional message: error, Some NotFound apperror, Some pkg err", appendedNotFoundErr.Error()) - assert.Equal(t, "Some additional message: error, Some AlreadyExists apperror, Some pkg err", appendedAlreadyExistsErr.Error()) - assert.Equal(t, "Some additional message: error, Some WrongInput apperror, Some pkg err", appendedWrongInputErr.Error()) - assert.Equal(t, "Some additional message: error, Some UpstreamServerCallFailed apperror, Some pkg err", appendedUpstreamServerCallFailedErr.Error()) - }) -} diff --git a/components/compass-runtime-agent/internal/certificates/csrprovider.go b/components/compass-runtime-agent/internal/certificates/csrprovider.go deleted file mode 100644 index bba964ab8669..000000000000 --- a/components/compass-runtime-agent/internal/certificates/csrprovider.go +++ /dev/null @@ -1,60 +0,0 @@ -package certificates - -import ( - "crypto/rand" - "crypto/rsa" - "crypto/x509" - "crypto/x509/pkix" - "encoding/base64" - "encoding/pem" - - "github.com/pkg/errors" -) - -const ( - rsaKeySize = 4096 -) - -//go:generate mockery --name=CSRProvider -type CSRProvider interface { - CreateCSR(subject pkix.Name) (string, *rsa.PrivateKey, error) -} - -type csrProvider struct { -} - -func NewCSRProvider() CSRProvider { - return &csrProvider{} -} - -// CreateCSR generates private key and returns it along with base 64 encoded CSR -func (cp *csrProvider) CreateCSR(subject pkix.Name) (string, *rsa.PrivateKey, error) { - clusterPrivateKey, err := rsa.GenerateKey(rand.Reader, rsaKeySize) - if err != nil { - return "", nil, err - } - - csr, err := createCSR(subject, clusterPrivateKey) - if err != nil { - return "", nil, err - } - - return base64.StdEncoding.EncodeToString(csr), clusterPrivateKey, nil -} - -func createCSR(subject pkix.Name, key *rsa.PrivateKey) ([]byte, error) { - csrTemplate := x509.CertificateRequest{ - Subject: subject, - } - - csr, err := x509.CreateCertificateRequest(rand.Reader, &csrTemplate, key) - if err != nil { - return nil, errors.Wrap(err, "Failed to create cluster CSR") - } - - pemEncodedCSR := pem.EncodeToMemory(&pem.Block{ - Type: "CERTIFICATE REQUEST", Bytes: csr, - }) - - return pemEncodedCSR, nil -} diff --git a/components/compass-runtime-agent/internal/certificates/csrprovider_test.go b/components/compass-runtime-agent/internal/certificates/csrprovider_test.go deleted file mode 100644 index 27ae81324c6b..000000000000 --- a/components/compass-runtime-agent/internal/certificates/csrprovider_test.go +++ /dev/null @@ -1,65 +0,0 @@ -package certificates - -import ( - "crypto/x509" - "crypto/x509/pkix" - "encoding/base64" - "encoding/pem" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestCsrProvider_CreateCSR(t *testing.T) { - - subject := pkix.Name{ - OrganizationalUnit: []string{"OrgUnit"}, - Organization: []string{"Organization"}, - Locality: []string{"Waldorf"}, - Province: []string{"Waldorf"}, - Country: []string{"DE"}, - CommonName: "test-app", - } - - t.Run("should create CSR with new key", func(t *testing.T) { - // given - csrProvider := NewCSRProvider() - - // when - csr, key, err := csrProvider.CreateCSR(subject) - - // then - require.NoError(t, err) - require.NotEmpty(t, csr) - require.NotEmpty(t, key) - - receivedCSR := decodeCSR(t, csr) - - require.NotNil(t, receivedCSR) - assertSubject(t, receivedCSR) - }) - -} - -func assertSubject(t *testing.T, csr *x509.CertificateRequest) { - assert.Equal(t, "test-app", csr.Subject.CommonName) - assert.Equal(t, "OrgUnit", csr.Subject.OrganizationalUnit[0]) - assert.Equal(t, "Organization", csr.Subject.Organization[0]) - assert.Equal(t, "Waldorf", csr.Subject.Locality[0]) - assert.Equal(t, "Waldorf", csr.Subject.Province[0]) - assert.Equal(t, "DE", csr.Subject.Country[0]) -} - -func decodeCSR(t *testing.T, encodedCSR string) *x509.CertificateRequest { - csrBytes, err := base64.StdEncoding.DecodeString(encodedCSR) - require.NoError(t, err) - - pemCSR, _ := pem.Decode(csrBytes) - require.NotNil(t, pemCSR) - - receivedCSR, err := x509.ParseCertificateRequest(pemCSR.Bytes) - require.NoError(t, err) - - return receivedCSR -} diff --git a/components/compass-runtime-agent/internal/certificates/main_test.go b/components/compass-runtime-agent/internal/certificates/main_test.go deleted file mode 100644 index 00fc3c1bf7b6..000000000000 --- a/components/compass-runtime-agent/internal/certificates/main_test.go +++ /dev/null @@ -1,33 +0,0 @@ -package certificates - -import ( - "fmt" - "os" - "testing" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/testutil" -) - -var ( - crtChain []byte - clientCRT []byte - caCRT []byte - clientKey []byte -) - -func TestMain(m *testing.M) { - certsData, err := testutil.LoadCertsTestData("../testutil/testdata") - if err != nil { - fmt.Println(err.Error()) - os.Exit(1) - } - - crtChain = certsData.CertificateChain - clientCRT = certsData.ClientCertificate - caCRT = certsData.CACertificate - clientKey = certsData.ClientKey - - exitCode := m.Run() - - os.Exit(exitCode) -} diff --git a/components/compass-runtime-agent/internal/certificates/manager.go b/components/compass-runtime-agent/internal/certificates/manager.go deleted file mode 100644 index 9c70ff23518c..000000000000 --- a/components/compass-runtime-agent/internal/certificates/manager.go +++ /dev/null @@ -1,132 +0,0 @@ -package certificates - -import ( - "crypto/x509" - "encoding/pem" - "fmt" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/secrets" - "github.com/pkg/errors" - "k8s.io/apimachinery/pkg/types" -) - -const ( - clusterCertificateSecretKey = "crt" - clusterKeySecretKey = "key" - certificateChainSecretKey = "crtChain" - - caCertificateSecretKey = "cacert" -) - -//go:generate mockery --name=Manager -type Manager interface { - GetClientCredentials() (ClientCredentials, error) - PreserveCredentials(Credentials) error - CredentialsExist() (bool, error) -} - -func NewCredentialsManager(clusterCertificateSecretName, caCertSecretName types.NamespacedName, secretsRepository secrets.Repository) *credentialsManager { - return &credentialsManager{ - caCertSecretName: caCertSecretName, - clusterCertificatesSecretName: clusterCertificateSecretName, - secretsRepository: secretsRepository, - } -} - -type credentialsManager struct { - caCertSecretName types.NamespacedName - clusterCertificatesSecretName types.NamespacedName - secretsRepository secrets.Repository -} - -func (cm *credentialsManager) GetClientCredentials() (ClientCredentials, error) { - secretData, err := cm.secretsRepository.Get(cm.clusterCertificatesSecretName) - if err != nil { - return ClientCredentials{}, errors.Wrap(err, fmt.Sprintf("Failed to read %s secret with certificates", cm.clusterCertificatesSecretName)) - } - - pemCredentials := PemEncodedCredentials{ - ClientKey: secretData[clusterKeySecretKey], - CertificateChain: secretData[certificateChainSecretKey], - ClientCertificate: secretData[clusterCertificateSecretKey], - } - - return pemCredentials.AsClientCredentials() -} - -func (cm *credentialsManager) CredentialsExist() (bool, error) { - return cm.secretsRepository.Exists(cm.caCertSecretName) -} - -func (cm *credentialsManager) PreserveCredentials(credentials Credentials) error { - pemCredentials := credentials.AsPemEncoded() - - err := cm.saveClusterCertificateAndKey(pemCredentials.ClientKey, pemCredentials.ClientCertificate, pemCredentials.CertificateChain) - if err != nil { - return err - } - - return cm.saveCACertificate(pemCredentials.CACertificates) -} - -func (cm *credentialsManager) saveClusterCertificateAndKey(clientKey, clientCert, certificateChain []byte) error { - clusterSecretData := map[string][]byte{ - clusterCertificateSecretKey: clientCert, - clusterKeySecretKey: clientKey, - certificateChainSecretKey: certificateChain, - } - - err := cm.secretsRepository.UpsertWithMerge(cm.clusterCertificatesSecretName, clusterSecretData) - if err != nil { - return errors.Wrap(err, "Failed to preserve client certificate and key in secret") - } - - return nil -} - -func (cm *credentialsManager) saveCACertificate(caCertificate []byte) error { - caSecretData := map[string][]byte{ - caCertificateSecretKey: caCertificate, - } - - err := cm.secretsRepository.UpsertWithMerge(cm.caCertSecretName, caSecretData) - if err != nil { - return errors.Wrap(err, "Failed to preserve CA certificate in secret") - } - - return nil -} - -func decodeCertificate(certificate []byte) (*x509.Certificate, error) { - certs, err := decodeCertificates(certificate) - if err != nil { - return nil, err - } - - return certs[0], nil -} - -func decodeCertificates(certificate []byte) ([]*x509.Certificate, error) { - if certificate == nil { - return nil, errors.New("Certificate data is empty") - } - - var certificates []*x509.Certificate - - for block, rest := pem.Decode(certificate); block != nil && rest != nil; { - cert, err := x509.ParseCertificate(block.Bytes) - if err != nil { - return nil, errors.Wrap(err, "Failed to decode one of the pem blocks") - } - - certificates = append(certificates, cert) - - block, rest = pem.Decode(rest) - } - - if len(certificates) == 0 { - return nil, errors.New("No certificates found in the pem block") - } - - return certificates, nil -} diff --git a/components/compass-runtime-agent/internal/certificates/manager_test.go b/components/compass-runtime-agent/internal/certificates/manager_test.go deleted file mode 100644 index fae05a95d0e0..000000000000 --- a/components/compass-runtime-agent/internal/certificates/manager_test.go +++ /dev/null @@ -1,269 +0,0 @@ -package certificates - -import ( - "testing" - - "github.com/stretchr/testify/assert" - - "github.com/pkg/errors" - - "k8s.io/apimachinery/pkg/types" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/secrets/mocks" - "github.com/stretchr/testify/require" -) - -const ( - clusterCertSecretName = "cluster-certificate" - clusterCertSecretNamespace = "kyma-system" - caCertSecretName = "ca-cert" - caCertSecretNamespace = "istio-system" -) - -var ( - clusterCertSecretNamespaceName = types.NamespacedName{ - Name: clusterCertSecretName, - Namespace: clusterCertSecretNamespace, - } - caCertSecretNamespaceName = types.NamespacedName{ - Name: caCertSecretName, - Namespace: caCertSecretNamespace, - } -) - -func TestCredentialsExist(t *testing.T) { - t.Run("should return false if credentials does not exist", func(t *testing.T) { - // given - expectedErr := errors.New("oh, no") - - secretsRepository := &mocks.Repository{} - secretsRepository.On("Exists", caCertSecretNamespaceName).Return(false, expectedErr) - - // when - credentialsManager := NewCredentialsManager(clusterCertSecretNamespaceName, caCertSecretNamespaceName, secretsRepository) - - // then - exists, err := credentialsManager.CredentialsExist() - assert.Equal(t, expectedErr, err) - assert.Equal(t, false, exists) - }) - - t.Run("should return true if credentials exist", func(t *testing.T) { - // given - secretsRepository := &mocks.Repository{} - secretsRepository.On("Exists", caCertSecretNamespaceName).Return(true, nil) - - // when - credentialsManager := NewCredentialsManager(clusterCertSecretNamespaceName, caCertSecretNamespaceName, secretsRepository) - - // then - exists, err := credentialsManager.CredentialsExist() - assert.Equal(t, nil, err) - assert.Equal(t, true, exists) - }) -} - -func TestCertificatePreserver_PreserveCertificates(t *testing.T) { - - pemCredentials := PemEncodedCredentials{ - ClientKey: clientKey, - CertificateChain: crtChain, - ClientCertificate: clientCRT, - CACertificates: caCRT, - } - - credentials, err := pemCredentials.AsCredentials() - require.NoError(t, err) - - t.Run("should preserve certificates", func(t *testing.T) { - // given - clusterSecretData := map[string][]byte{ - clusterCertificateSecretKey: clientCRT, - clusterKeySecretKey: clientKey, - certificateChainSecretKey: crtChain, - } - caSecretData := map[string][]byte{caCertificateSecretKey: caCRT} - - secretsRepository := &mocks.Repository{} - secretsRepository.On("UpsertWithMerge", clusterCertSecretNamespaceName, clusterSecretData).Return(nil) - secretsRepository.On("UpsertWithMerge", caCertSecretNamespaceName, caSecretData).Return(nil) - - credentialsManager := NewCredentialsManager(clusterCertSecretNamespaceName, caCertSecretNamespaceName, secretsRepository) - - // when - err := credentialsManager.PreserveCredentials(credentials) - - // then - require.NoError(t, err) - secretsRepository.AssertExpectations(t) - }) - - t.Run("should return error when failed to save cluster secret", func(t *testing.T) { - // given - clusterSecretData := map[string][]byte{ - clusterCertificateSecretKey: clientCRT, - clusterKeySecretKey: clientKey, - certificateChainSecretKey: crtChain, - } - - secretsRepository := &mocks.Repository{} - secretsRepository.On("UpsertWithMerge", clusterCertSecretNamespaceName, clusterSecretData).Return(errors.New("error")) - - credentialsManager := NewCredentialsManager(clusterCertSecretNamespaceName, caCertSecretNamespaceName, secretsRepository) - - // when - err := credentialsManager.PreserveCredentials(credentials) - - // then - require.Error(t, err) - secretsRepository.AssertExpectations(t) - }) - - t.Run("should return error when failed to save ca secret", func(t *testing.T) { - // given - clusterSecretData := map[string][]byte{ - clusterCertificateSecretKey: clientCRT, - clusterKeySecretKey: clientKey, - certificateChainSecretKey: crtChain, - } - caSecretData := map[string][]byte{caCertificateSecretKey: caCRT} - - secretsRepository := &mocks.Repository{} - secretsRepository.On("UpsertWithMerge", clusterCertSecretNamespaceName, clusterSecretData).Return(nil) - secretsRepository.On("UpsertWithMerge", caCertSecretNamespaceName, caSecretData).Return(errors.New("error")) - - credentialsManager := NewCredentialsManager(clusterCertSecretNamespaceName, caCertSecretNamespaceName, secretsRepository) - - // when - err := credentialsManager.PreserveCredentials(credentials) - - // then - require.Error(t, err) - secretsRepository.AssertExpectations(t) - }) -} - -func TestCertificateProvider_GetClientCredentials(t *testing.T) { - - pemCredentials := PemEncodedCredentials{ - ClientKey: clientKey, - CertificateChain: crtChain, - ClientCertificate: clientCRT, - CACertificates: caCRT, - } - - t.Run("should get client credentials", func(t *testing.T) { - // given - expectedCreds, err := pemCredentials.AsClientCredentials() - require.NoError(t, err) - - secretData := map[string][]byte{ - clusterCertificateSecretKey: clientCRT, - clusterKeySecretKey: clientKey, - certificateChainSecretKey: crtChain, - } - - secretsRepository := &mocks.Repository{} - secretsRepository.On("Get", clusterCertSecretNamespaceName).Return(secretData, nil) - - credentialsManager := NewCredentialsManager(clusterCertSecretNamespaceName, caCertSecretNamespaceName, secretsRepository) - - // when - clientCreds, err := credentialsManager.GetClientCredentials() - - // then - require.NoError(t, err) - require.NotNil(t, clientCreds) - assert.Equal(t, expectedCreds, clientCreds) - }) - - t.Run("should return error when failed to read secret", func(t *testing.T) { - // given - secretsRepository := &mocks.Repository{} - secretsRepository.On("Get", clusterCertSecretNamespaceName).Return(nil, errors.New("error")) - - credentialsManager := NewCredentialsManager(clusterCertSecretNamespaceName, caCertSecretNamespaceName, secretsRepository) - - // when - _, err := credentialsManager.GetClientCredentials() - - // then - require.Error(t, err) - }) - - t.Run("should return error when no data in secret", func(t *testing.T) { - // given - secretData := map[string][]byte{} - - secretsRepository := &mocks.Repository{} - secretsRepository.On("Get", clusterCertSecretNamespaceName).Return(secretData, nil) - - credentialsManager := NewCredentialsManager(clusterCertSecretNamespaceName, caCertSecretNamespaceName, secretsRepository) - - // when - _, err := credentialsManager.GetClientCredentials() - - // then - require.Error(t, err) - }) - - t.Run("should return error when failed to decode cert", func(t *testing.T) { - // given - secretData := map[string][]byte{ - clusterCertificateSecretKey: []byte("invalid pem"), - clusterKeySecretKey: clientKey, - certificateChainSecretKey: crtChain, - } - - secretsRepository := &mocks.Repository{} - secretsRepository.On("Get", clusterCertSecretNamespaceName).Return(secretData, nil) - - credentialsManager := NewCredentialsManager(clusterCertSecretNamespaceName, caCertSecretNamespaceName, secretsRepository) - - // when - _, err := credentialsManager.GetClientCredentials() - - // then - require.Error(t, err) - }) - - t.Run("should return error when failed to decode certificate chain", func(t *testing.T) { - // given - secretData := map[string][]byte{ - clusterCertificateSecretKey: clientCRT, - clusterKeySecretKey: clientKey, - certificateChainSecretKey: []byte("invalid pem"), - } - - secretsRepository := &mocks.Repository{} - secretsRepository.On("Get", clusterCertSecretNamespaceName).Return(secretData, nil) - - credentialsManager := NewCredentialsManager(clusterCertSecretNamespaceName, caCertSecretNamespaceName, secretsRepository) - - // when - _, err := credentialsManager.GetClientCredentials() - - // then - require.Error(t, err) - }) - - t.Run("should return error when failed to decode client key", func(t *testing.T) { - // given - secretData := map[string][]byte{ - clusterCertificateSecretKey: clientCRT, - clusterKeySecretKey: []byte("invalid pem"), - certificateChainSecretKey: crtChain, - } - - secretsRepository := &mocks.Repository{} - secretsRepository.On("Get", clusterCertSecretNamespaceName).Return(secretData, nil) - - credentialsManager := NewCredentialsManager(clusterCertSecretNamespaceName, caCertSecretNamespaceName, secretsRepository) - - // when - _, err := credentialsManager.GetClientCredentials() - - // then - require.Error(t, err) - }) -} diff --git a/components/compass-runtime-agent/internal/certificates/mocks/CSRProvider.go b/components/compass-runtime-agent/internal/certificates/mocks/CSRProvider.go deleted file mode 100644 index 8239b0a278dd..000000000000 --- a/components/compass-runtime-agent/internal/certificates/mocks/CSRProvider.go +++ /dev/null @@ -1,46 +0,0 @@ -// Code generated by mockery v2.10.0. DO NOT EDIT. - -package mocks - -import ( - pkix "crypto/x509/pkix" - - mock "github.com/stretchr/testify/mock" - - rsa "crypto/rsa" -) - -// CSRProvider is an autogenerated mock type for the CSRProvider type -type CSRProvider struct { - mock.Mock -} - -// CreateCSR provides a mock function with given fields: subject -func (_m *CSRProvider) CreateCSR(subject pkix.Name) (string, *rsa.PrivateKey, error) { - ret := _m.Called(subject) - - var r0 string - if rf, ok := ret.Get(0).(func(pkix.Name) string); ok { - r0 = rf(subject) - } else { - r0 = ret.Get(0).(string) - } - - var r1 *rsa.PrivateKey - if rf, ok := ret.Get(1).(func(pkix.Name) *rsa.PrivateKey); ok { - r1 = rf(subject) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(*rsa.PrivateKey) - } - } - - var r2 error - if rf, ok := ret.Get(2).(func(pkix.Name) error); ok { - r2 = rf(subject) - } else { - r2 = ret.Error(2) - } - - return r0, r1, r2 -} diff --git a/components/compass-runtime-agent/internal/certificates/mocks/Manager.go b/components/compass-runtime-agent/internal/certificates/mocks/Manager.go deleted file mode 100644 index aba26f7da34d..000000000000 --- a/components/compass-runtime-agent/internal/certificates/mocks/Manager.go +++ /dev/null @@ -1,69 +0,0 @@ -// Code generated by mockery v2.10.0. DO NOT EDIT. - -package mocks - -import ( - certificates "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/certificates" - mock "github.com/stretchr/testify/mock" -) - -// Manager is an autogenerated mock type for the Manager type -type Manager struct { - mock.Mock -} - -// CredentialsExist provides a mock function with given fields: -func (_m *Manager) CredentialsExist() (bool, error) { - ret := _m.Called() - - var r0 bool - if rf, ok := ret.Get(0).(func() bool); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(bool) - } - - var r1 error - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetClientCredentials provides a mock function with given fields: -func (_m *Manager) GetClientCredentials() (certificates.ClientCredentials, error) { - ret := _m.Called() - - var r0 certificates.ClientCredentials - if rf, ok := ret.Get(0).(func() certificates.ClientCredentials); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(certificates.ClientCredentials) - } - - var r1 error - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// PreserveCredentials provides a mock function with given fields: _a0 -func (_m *Manager) PreserveCredentials(_a0 certificates.Credentials) error { - ret := _m.Called(_a0) - - var r0 error - if rf, ok := ret.Get(0).(func(certificates.Credentials) error); ok { - r0 = rf(_a0) - } else { - r0 = ret.Error(0) - } - - return r0 -} diff --git a/components/compass-runtime-agent/internal/certificates/model.go b/components/compass-runtime-agent/internal/certificates/model.go deleted file mode 100644 index 77eed3e414fa..000000000000 --- a/components/compass-runtime-agent/internal/certificates/model.go +++ /dev/null @@ -1,151 +0,0 @@ -package certificates - -import ( - "crypto/rsa" - "crypto/tls" - "crypto/x509" - "encoding/base64" - "encoding/pem" - - gqlschema "github.com/kyma-incubator/compass/components/connector/pkg/graphql/externalschema" - "github.com/pkg/errors" -) - -type Credentials struct { - ClientCredentials - CACertificates []*x509.Certificate -} - -type ClientCredentials struct { - ClientKey *rsa.PrivateKey - CertificateChain []*x509.Certificate - ClientCertificate *x509.Certificate -} - -func NewCredentials(key *rsa.PrivateKey, certificateResponse gqlschema.CertificationResult) (Credentials, error) { - pemCertChain, err := base64.StdEncoding.DecodeString(certificateResponse.CertificateChain) - if err != nil { - return Credentials{}, errors.Wrap(err, "Failed to decode base 64 certificate chain") - } - certificateChain, err := decodeCertificates(pemCertChain) - if err != nil { - return Credentials{}, errors.Wrap(err, "Failed to decode certificate chain") - } - pemClientCert, err := base64.StdEncoding.DecodeString(certificateResponse.ClientCertificate) - if err != nil { - return Credentials{}, errors.Wrap(err, "Failed to decode base 64 client certificate") - } - clientCert, err := decodeCertificate(pemClientCert) - if err != nil { - return Credentials{}, errors.Wrap(err, "Failed to decode client certificate") - } - pemCACert, err := base64.StdEncoding.DecodeString(certificateResponse.CaCertificate) - if err != nil { - return Credentials{}, errors.Wrap(err, "Failed to decode base 64 CA certificate") - } - caCerts, err := decodeCertificates(pemCACert) - if err != nil { - return Credentials{}, errors.Wrap(err, "Failed to decode CA certificate") - } - - return Credentials{ - ClientCredentials: ClientCredentials{ - ClientKey: key, - CertificateChain: certificateChain, - ClientCertificate: clientCert, - }, - CACertificates: caCerts, - }, nil -} - -func ParsePrivateKey(clusterKey []byte) (*rsa.PrivateKey, error) { - if clusterKey == nil { - return nil, errors.New("Private key data is empty") - } - - block, _ := pem.Decode(clusterKey) - if block == nil { - return nil, errors.New("Failed to decode client key pem") - } - - return x509.ParsePKCS1PrivateKey(block.Bytes) -} - -type PemEncodedCredentials struct { - ClientKey []byte - CertificateChain []byte - ClientCertificate []byte - CACertificates []byte -} - -func (c ClientCredentials) AsTLSCertificate() tls.Certificate { - var rawCerts [][]byte - - for _, cert := range c.CertificateChain { - rawCerts = append(rawCerts, cert.Raw) - } - - return tls.Certificate{ - PrivateKey: c.ClientKey, - Certificate: rawCerts, - } -} - -func (c Credentials) AsPemEncoded() PemEncodedCredentials { - return PemEncodedCredentials{ - ClientKey: pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(c.ClientKey)}), - CertificateChain: toPem(c.CertificateChain...), - ClientCertificate: toPem(c.ClientCertificate), - CACertificates: toPem(c.CACertificates...), - } -} - -func toPem(certificates ...*x509.Certificate) []byte { - certChainPem := make([]byte, 0) - for _, cert := range certificates { - certBytes := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw}) - certChainPem = append(certChainPem, certBytes...) - } - - return certChainPem -} - -func (c PemEncodedCredentials) AsClientCredentials() (ClientCredentials, error) { - certificateChain, err := decodeCertificates(c.CertificateChain) - if err != nil { - return ClientCredentials{}, errors.Wrap(err, "Failed to decode certificate chain") - } - - clientCertificate, err := decodeCertificate(c.ClientCertificate) - if err != nil { - return ClientCredentials{}, errors.Wrap(err, "Failed to decode client certificate") - } - - clientKey, err := ParsePrivateKey(c.ClientKey) - if err != nil { - return ClientCredentials{}, errors.Wrap(err, "Failed to decode client key") - } - - return ClientCredentials{ - ClientKey: clientKey, - CertificateChain: certificateChain, - ClientCertificate: clientCertificate, - }, nil -} - -func (c PemEncodedCredentials) AsCredentials() (Credentials, error) { - clientCredentials, err := c.AsClientCredentials() - if err != nil { - return Credentials{}, err - } - - caCerts, err := decodeCertificates(c.CACertificates) - if err != nil { - return Credentials{}, errors.Wrap(err, "Failed to decode CA certificate") - } - - return Credentials{ - ClientCredentials: clientCredentials, - CACertificates: caCerts, - }, nil -} diff --git a/components/compass-runtime-agent/internal/certificates/model_test.go b/components/compass-runtime-agent/internal/certificates/model_test.go deleted file mode 100644 index 60ab13037abd..000000000000 --- a/components/compass-runtime-agent/internal/certificates/model_test.go +++ /dev/null @@ -1,79 +0,0 @@ -package certificates - -import ( - "crypto/rsa" - "crypto/x509" - "encoding/base64" - "testing" - - gqlschema "github.com/kyma-incubator/compass/components/connector/pkg/graphql/externalschema" - - "github.com/stretchr/testify/assert" - - "github.com/stretchr/testify/require" -) - -func TestClientCredentials_AsTLSCertificate(t *testing.T) { - // given - pemCredentials := PemEncodedCredentials{ - ClientKey: clientKey, - CertificateChain: crtChain, - ClientCertificate: clientCRT, - CACertificates: caCRT, - } - - credentials, err := pemCredentials.AsCredentials() - require.NoError(t, err) - - // when - tlsCert := credentials.AsTLSCertificate() - - // then - require.NotNil(t, tlsCert) - require.NotEmpty(t, tlsCert.PrivateKey) - require.NotEmpty(t, tlsCert.Certificate) - - privKey, ok := tlsCert.PrivateKey.(*rsa.PrivateKey) - assert.True(t, ok) - assert.Equal(t, credentials.ClientKey, privKey) - - certs := make([]*x509.Certificate, 0, len(tlsCert.Certificate)) - for _, bytes := range tlsCert.Certificate { - cert, err := x509.ParseCertificate(bytes) - require.NoError(t, err) - - certs = append(certs, cert) - } - - require.Equal(t, 2, len(certs)) - assert.NotEmpty(t, certs[0]) - assert.NotEmpty(t, certs[1]) - assert.Equal(t, credentials.CertificateChain, certs) -} - -func TestNewCredentials(t *testing.T) { - // given - expectedCredentials, err := PemEncodedCredentials{ - ClientKey: clientKey, - ClientCertificate: clientCRT, - CertificateChain: crtChain, - CACertificates: caCRT, - }.AsCredentials() - require.NoError(t, err) - - certificateResponse := gqlschema.CertificationResult{ - CertificateChain: base64.StdEncoding.EncodeToString(crtChain), - CaCertificate: base64.StdEncoding.EncodeToString(caCRT), - ClientCertificate: base64.StdEncoding.EncodeToString(clientCRT), - } - - key, err := ParsePrivateKey(clientKey) - require.NoError(t, err) - - // when - credentials, err := NewCredentials(key, certificateResponse) - require.NoError(t, err) - - // then - assert.Equal(t, expectedCredentials, credentials) -} diff --git a/components/compass-runtime-agent/internal/compass/cache/connection_data_cache.go b/components/compass-runtime-agent/internal/compass/cache/connection_data_cache.go deleted file mode 100644 index 382f4a11fa63..000000000000 --- a/components/compass-runtime-agent/internal/compass/cache/connection_data_cache.go +++ /dev/null @@ -1,58 +0,0 @@ -package cache - -import ( - "crypto/tls" - - "github.com/sirupsen/logrus" -) - -type ConnectionData struct { - Certificate tls.Certificate - DirectorURL string - ConnectorURL string -} - -type ConnectionDataCache interface { - AddSubscriber(s ConnectionDataSubscriber) - UpdateConnectionData(cert tls.Certificate, directorURL, connectorURL string) - UpdateURLs(directorURL, connectorURL string) -} - -type connectionDataCache struct { - connectionData ConnectionData - subscribers []ConnectionDataSubscriber -} - -type ConnectionDataSubscriber func(data ConnectionData) error - -func NewConnectionDataCache() *connectionDataCache { - return &connectionDataCache{} -} - -func (c *connectionDataCache) AddSubscriber(s ConnectionDataSubscriber) { - c.subscribers = append(c.subscribers, s) -} - -func (c *connectionDataCache) UpdateConnectionData(cert tls.Certificate, directorURL, connectorURL string) { - c.connectionData.Certificate = cert - c.connectionData.DirectorURL = directorURL - c.connectionData.ConnectorURL = connectorURL - - c.notifySubscribers() -} - -func (c *connectionDataCache) UpdateURLs(directorURL, connectorURL string) { - c.connectionData.DirectorURL = directorURL - c.connectionData.ConnectorURL = connectorURL - - c.notifySubscribers() -} - -func (c *connectionDataCache) notifySubscribers() { - for _, s := range c.subscribers { - err := s(c.connectionData) - if err != nil { - logrus.Errorf("error notifying about connection data change: %s", err.Error()) - } - } -} diff --git a/components/compass-runtime-agent/internal/compass/cache/connection_data_cache_test.go b/components/compass-runtime-agent/internal/compass/cache/connection_data_cache_test.go deleted file mode 100644 index e56b7574adb5..000000000000 --- a/components/compass-runtime-agent/internal/compass/cache/connection_data_cache_test.go +++ /dev/null @@ -1,42 +0,0 @@ -package cache - -import ( - "crypto/tls" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestConnectionDataCache(t *testing.T) { - - connectorURL := "https://connector.kyma" - directorURL := "https://director.kyma" - cert := tls.Certificate{} - - assertionsSubscriber := func(data ConnectionData) error { - assert.Equal(t, cert, data.Certificate) - assert.Equal(t, directorURL, data.DirectorURL) - assert.Equal(t, connectorURL, data.ConnectorURL) - return nil - } - - t.Run("should notify on UpdateConnectionData", func(t *testing.T) { - // given - cache := NewConnectionDataCache() - cache.AddSubscriber(assertionsSubscriber) - - // when - cache.UpdateConnectionData(cert, directorURL, connectorURL) - }) - - t.Run("should notify on UpdateURLs", func(t *testing.T) { - // given - cache := NewConnectionDataCache() - cache.UpdateConnectionData(cert, "", "") - - cache.AddSubscriber(assertionsSubscriber) - - // when - cache.UpdateURLs(directorURL, connectorURL) - }) -} diff --git a/components/compass-runtime-agent/internal/compass/clients_provider.go b/components/compass-runtime-agent/internal/compass/clients_provider.go deleted file mode 100644 index 2d3aea2ca19b..000000000000 --- a/components/compass-runtime-agent/internal/compass/clients_provider.go +++ /dev/null @@ -1,105 +0,0 @@ -package compass - -import ( - "crypto/tls" - "fmt" - "net/http" - "time" - - cmp_http "github.com/kyma-incubator/compass/components/director/pkg/http" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/compass/cache" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/compass/connector" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/compass/director" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/config" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/graphql" - "github.com/pkg/errors" -) - -//go:generate mockery --name=ClientsProvider -type ClientsProvider interface { - GetDirectorClient(runtimeConfig config.RuntimeConfig) (director.DirectorClient, error) - GetConnectorTokensClient(url string) (connector.Client, error) - GetConnectorCertSecuredClient() (connector.Client, error) -} - -func NewClientsProvider(gqlClientConstr graphql.ClientConstructor, skipCompassTLSVerification, enableLogging bool) *clientsProvider { - transport := http.DefaultTransport.(*http.Transport).Clone() - transport.TLSClientConfig.InsecureSkipVerify = skipCompassTLSVerification - corrIdTransport := cmp_http.NewCorrelationIDTransport(transport) - - return &clientsProvider{ - gqlClientConstructor: gqlClientConstr, - skipCompassTLSVerification: skipCompassTLSVerification, - enableLogging: enableLogging, - - httpClient: &http.Client{ - Timeout: 30 * time.Second, - Transport: corrIdTransport, - }, - } -} - -type clientsProvider struct { - gqlClientConstructor graphql.ClientConstructor - skipCompassTLSVerification bool - enableLogging bool - httpClient *http.Client - - // lazy init after establishing connection - mtlsHTTPClient *http.Client - connectorSecuredURL string - directorURL string -} - -func (cp *clientsProvider) UpdateConnectionData(data cache.ConnectionData) error { - var transport *http.Transport - if cp.mtlsHTTPClient == nil { - cp.mtlsHTTPClient = &http.Client{Timeout: 30 * time.Second} - } - transport = http.DefaultTransport.(*http.Transport).Clone() - - transport.TLSClientConfig.InsecureSkipVerify = cp.skipCompassTLSVerification - transport.TLSClientConfig.Certificates = []tls.Certificate{data.Certificate} - - cp.mtlsHTTPClient.Transport = cmp_http.NewCorrelationIDTransport(transport) - cp.directorURL = data.DirectorURL - cp.connectorSecuredURL = data.ConnectorURL - - return nil -} - -func (cp *clientsProvider) GetDirectorClient(runtimeConfig config.RuntimeConfig) (director.DirectorClient, error) { - if cp.mtlsHTTPClient == nil { - return nil, fmt.Errorf("failed to get Director client: mTLS HTTP client not initialized") - } - - gqlClient, err := cp.gqlClientConstructor(cp.mtlsHTTPClient, cp.directorURL, cp.enableLogging) - if err != nil { - return nil, errors.Wrap(err, "Failed to create GraphQL client") - } - - return director.NewConfigurationClient(gqlClient, runtimeConfig), nil -} - -func (cp *clientsProvider) GetConnectorTokensClient(url string) (connector.Client, error) { - gqlClient, err := cp.gqlClientConstructor(cp.httpClient, url, cp.enableLogging) - if err != nil { - return nil, errors.Wrap(err, "Failed to create GraphQL client") - } - - return connector.NewConnectorClient(gqlClient), nil -} - -func (cp *clientsProvider) GetConnectorCertSecuredClient() (connector.Client, error) { - if cp.mtlsHTTPClient == nil { - return nil, fmt.Errorf("failed to get secured Connector client: mTLS HTTP client not initialized") - } - - gqlClient, err := cp.gqlClientConstructor(cp.mtlsHTTPClient, cp.connectorSecuredURL, cp.enableLogging) - if err != nil { - return nil, errors.Wrap(err, "Failed to create GraphQL client") - } - - return connector.NewConnectorClient(gqlClient), nil -} diff --git a/components/compass-runtime-agent/internal/compass/clients_provider_test.go b/components/compass-runtime-agent/internal/compass/clients_provider_test.go deleted file mode 100644 index b5132fd45f8f..000000000000 --- a/components/compass-runtime-agent/internal/compass/clients_provider_test.go +++ /dev/null @@ -1,161 +0,0 @@ -package compass - -import ( - "errors" - "net/http" - "testing" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/compass/cache" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/config" - - "github.com/stretchr/testify/require" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/graphql/mocks" - "github.com/stretchr/testify/assert" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/graphql" -) - -func newMockGQLConstructor( - t *testing.T, - returnedError error, - expectedEndpoint string, - expectedLogging bool) graphql.ClientConstructor { - return func(httpClient *http.Client, graphqlEndpoint string, enableLogging bool) (graphql.Client, error) { - assert.Equal(t, expectedEndpoint, graphqlEndpoint) - assert.Equal(t, expectedLogging, enableLogging) - - return &mocks.Client{}, returnedError - } -} - -func TestClientsProvider_GetCompassConfigClient(t *testing.T) { - - runtimeConfig := config.RuntimeConfig{ - RuntimeId: "runtimeId", - Tenant: "tenant", - } - - url := "http://api.io" - enableLogging := true - skipCompassTLSVerify := true - - t.Run("should create new Compass Config Client", func(t *testing.T) { - // given - constructor := newMockGQLConstructor(t, nil, url, enableLogging) - - provider := NewClientsProvider(constructor, skipCompassTLSVerify, enableLogging) - _ = provider.UpdateConnectionData(cache.ConnectionData{DirectorURL: url}) - - // when - configClient, err := provider.GetDirectorClient(runtimeConfig) - - // then - require.NoError(t, err) - assert.NotNil(t, configClient) - }) - - t.Run("should return error when failed to create GraphQL client", func(t *testing.T) { - // given - constructor := newMockGQLConstructor(t, errors.New("error"), url, enableLogging) - - provider := NewClientsProvider(constructor, skipCompassTLSVerify, enableLogging) - _ = provider.UpdateConnectionData(cache.ConnectionData{DirectorURL: url}) - - // when - _, err := provider.GetDirectorClient(runtimeConfig) - - // then - require.Error(t, err) - }) - -} - -func TestClientsProvider_GetConnectorTokenSecuredClient(t *testing.T) { - - url := "http://api.io" - enableLogging := true - insecureFetch := true - - t.Run("should create new Connector token-secured Client", func(t *testing.T) { - // given - constructor := newMockGQLConstructor(t, nil, url, enableLogging) - - provider := NewClientsProvider(constructor, insecureFetch, enableLogging) - - // when - configClient, err := provider.GetConnectorTokensClient(url) - - // then - require.NoError(t, err) - assert.NotNil(t, configClient) - }) - - t.Run("should return error when failed to create GraphQL client", func(t *testing.T) { - // given - constructor := newMockGQLConstructor(t, errors.New("error"), url, enableLogging) - - provider := NewClientsProvider(constructor, insecureFetch, enableLogging) - - // when - _, err := provider.GetConnectorTokensClient(url) - - // then - require.Error(t, err) - }) -} - -func TestClientsProvider_GetConnectorCertSecuredClient(t *testing.T) { - - url := "http://api.io" - enableLogging := true - insecureFetch := true - - t.Run("should create new Connector cert-secured Client", func(t *testing.T) { - // given - constructor := newMockGQLConstructor(t, nil, url, enableLogging) - - provider := NewClientsProvider(constructor, insecureFetch, enableLogging) - _ = provider.UpdateConnectionData(cache.ConnectionData{ConnectorURL: url}) - - // when - configClient, err := provider.GetConnectorCertSecuredClient() - - // then - require.NoError(t, err) - assert.NotNil(t, configClient) - }) - - t.Run("should return error when failed to create GraphQL client", func(t *testing.T) { - // given - constructor := newMockGQLConstructor(t, errors.New("error"), url, enableLogging) - - provider := NewClientsProvider(constructor, insecureFetch, enableLogging) - _ = provider.UpdateConnectionData(cache.ConnectionData{ConnectorURL: url}) - - // when - _, err := provider.GetConnectorCertSecuredClient() - - // then - require.Error(t, err) - }) -} - -func TestClientsProvider_UpdateConnectionData(t *testing.T) { - url := "http://api.io" - enableLogging := true - insecureFetch := true - - t.Run("should update connection data twice", func(t *testing.T) { - constructor := newMockGQLConstructor(t, nil, url, enableLogging) - - provider := NewClientsProvider(constructor, insecureFetch, enableLogging) - - err := provider.UpdateConnectionData(cache.ConnectionData{ConnectorURL: url}) - require.NoError(t, err) - - err = provider.UpdateConnectionData(cache.ConnectionData{ConnectorURL: url}) - require.NoError(t, err) - }) -} diff --git a/components/compass-runtime-agent/internal/compass/connector/client.go b/components/compass-runtime-agent/internal/compass/connector/client.go deleted file mode 100644 index 73de51138a1a..000000000000 --- a/components/compass-runtime-agent/internal/compass/connector/client.go +++ /dev/null @@ -1,77 +0,0 @@ -package connector - -import ( - "context" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/graphql" - - schema "github.com/kyma-incubator/compass/components/connector/pkg/graphql/externalschema" - gcli "github.com/machinebox/graphql" - "github.com/pkg/errors" -) - -//go:generate mockery --name=Client -type Client interface { - Configuration(ctx context.Context, headers map[string]string) (schema.Configuration, error) - SignCSR(ctx context.Context, csr string, headers map[string]string) (schema.CertificationResult, error) -} - -type connectorClient struct { - graphQlClient graphql.Client - queryProvider queryProvider -} - -func NewConnectorClient(graphQlClient graphql.Client) Client { - return &connectorClient{ - graphQlClient: graphQlClient, - queryProvider: queryProvider{}, - } -} - -func (c connectorClient) Configuration(ctx context.Context, headers map[string]string) (schema.Configuration, error) { - query := c.queryProvider.configuration() - req := gcli.NewRequest(query) - - applyHeaders(req, headers) - - var response ConfigurationResponse - - err := c.graphQlClient.Do(ctx, req, &response) - if err != nil { - return schema.Configuration{}, errors.Wrap(err, "Failed to get configuration") - } - return response.Result, nil -} - -func (c connectorClient) SignCSR(ctx context.Context, csr string, headers map[string]string) (schema.CertificationResult, error) { - query := c.queryProvider.signCSR(csr) - req := gcli.NewRequest(query) - - applyHeaders(req, headers) - - var response CertificationResponse - - err := c.graphQlClient.Do(ctx, req, &response) - if err != nil { - return schema.CertificationResult{}, errors.Wrap(err, "Failed to generate certificate") - } - return response.Result, nil -} - -func applyHeaders(req *gcli.Request, headers map[string]string) { - for h, val := range headers { - req.Header.Set(h, val) - } -} - -type ConfigurationResponse struct { - Result schema.Configuration `json:"result"` -} - -type CertificationResponse struct { - Result schema.CertificationResult `json:"result"` -} - -type RevokeResult struct { - Result bool `json:"result"` -} diff --git a/components/compass-runtime-agent/internal/compass/connector/client_test.go b/components/compass-runtime-agent/internal/compass/connector/client_test.go deleted file mode 100644 index 80647396b259..000000000000 --- a/components/compass-runtime-agent/internal/compass/connector/client_test.go +++ /dev/null @@ -1,162 +0,0 @@ -package connector - -import ( - "context" - "testing" - - gqlschema "github.com/kyma-incubator/compass/components/connector/pkg/graphql/externalschema" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/graphql/mocks" - gql "github.com/machinebox/graphql" - "github.com/pkg/errors" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" -) - -const ( - TokenHeader = "Connector-Token" - - expectedConfigurationQuery = `query { - result: configuration() { - token { token } - certificateSigningRequestInfo { subject keyAlgorithm } - managementPlaneInfo { - directorURL - certificateSecuredConnectorURL - } - } -}` - - expectedSigningQuery = `mutation { - result: signCertificateSigningRequest(csr: "encodedCSR") { - certificateChain - caCertificate - clientCertificate - } -}` - - encodedCSR = "encodedCSR" - - token = "token" -) - -var ( - connectorTokenHeaders map[string]string = map[string]string{TokenHeader: token} -) - -func TestCertificateSecuredClient_Configuration(t *testing.T) { - expectedRequest := gql.NewRequest(expectedConfigurationQuery) - expectedRequest.Header.Set(TokenHeader, token) - - setExpectedConfigFunc := func(config gqlschema.Configuration) func(args mock.Arguments) { - return func(args mock.Arguments) { - response, ok := args[2].(*ConfigurationResponse) - require.True(t, ok) - assert.Empty(t, response) - response.Result = config - } - } - - t.Run("should fetch configuration", func(t *testing.T) { - // given - expectedResponse := gqlschema.Configuration{ - Token: &gqlschema.Token{Token: "new-token"}, - CertificateSigningRequestInfo: &gqlschema.CertificateSigningRequestInfo{ - Subject: "CN=app", - KeyAlgorithm: "rsa2048", - }, - ManagementPlaneInfo: &gqlschema.ManagementPlaneInfo{}, - } - - client := &mocks.Client{} - client. - On("Do", context.Background(), expectedRequest, &ConfigurationResponse{}). - Return(nil). - Run(setExpectedConfigFunc(expectedResponse)). - Once() - - certSecuredClient := NewConnectorClient(client) - - // when - configResponse, err := certSecuredClient.Configuration(context.Background(), connectorTokenHeaders) - - // then - require.NoError(t, err) - assert.Equal(t, expectedResponse, configResponse) - }) - - t.Run("should return error when failed to fetch config", func(t *testing.T) { - // given - client := &mocks.Client{} - client. - On("Do", context.Background(), expectedRequest, &ConfigurationResponse{}). - Return(errors.New("error")) - - certSecuredClient := NewConnectorClient(client) - - // when - configResponse, err := certSecuredClient.Configuration(context.Background(), connectorTokenHeaders) - - // then - require.Error(t, err) - assert.Contains(t, err.Error(), "Failed to get configuration") - assert.Empty(t, configResponse) - }) -} - -func TestCertificateSecuredClient_SignCSR(t *testing.T) { - expectedRequest := gql.NewRequest(expectedSigningQuery) - expectedRequest.Header.Set(TokenHeader, token) - - setExpectedCertFunc := func(cert gqlschema.CertificationResult) func(args mock.Arguments) { - return func(args mock.Arguments) { - response, ok := args[2].(*CertificationResponse) - require.True(t, ok) - assert.Empty(t, response) - response.Result = cert - } - } - - t.Run("should sign csr", func(t *testing.T) { - // given - expectedResponse := gqlschema.CertificationResult{ - ClientCertificate: "clientCert", - CertificateChain: "certChain", - CaCertificate: "caCert", - } - - client := &mocks.Client{} - client. - On("Do", context.Background(), expectedRequest, &CertificationResponse{}). - Return(nil). - Run(setExpectedCertFunc(expectedResponse)). - Once() - - certSecuredClient := NewConnectorClient(client) - - // when - configResponse, err := certSecuredClient.SignCSR(context.Background(), encodedCSR, connectorTokenHeaders) - - // then - require.NoError(t, err) - assert.Equal(t, expectedResponse, configResponse) - }) - - t.Run("should return error when failed to sign CSR", func(t *testing.T) { - // given - client := &mocks.Client{} - client. - On("Do", context.Background(), expectedRequest, &CertificationResponse{}). - Return(errors.New("error")) - - certSecuredClient := NewConnectorClient(client) - - // when - configResponse, err := certSecuredClient.SignCSR(context.Background(), encodedCSR, connectorTokenHeaders) - - // then - require.Error(t, err) - assert.Contains(t, err.Error(), "Failed to generate certificate") - assert.Empty(t, configResponse) - }) -} diff --git a/components/compass-runtime-agent/internal/compass/connector/mocks/Client.go b/components/compass-runtime-agent/internal/compass/connector/mocks/Client.go deleted file mode 100644 index 8a103baf7082..000000000000 --- a/components/compass-runtime-agent/internal/compass/connector/mocks/Client.go +++ /dev/null @@ -1,57 +0,0 @@ -// Code generated by mockery v2.10.0. DO NOT EDIT. - -package mocks - -import ( - context "context" - - externalschema "github.com/kyma-incubator/compass/components/connector/pkg/graphql/externalschema" - mock "github.com/stretchr/testify/mock" -) - -// Client is an autogenerated mock type for the Client type -type Client struct { - mock.Mock -} - -// Configuration provides a mock function with given fields: ctx, headers -func (_m *Client) Configuration(ctx context.Context, headers map[string]string) (externalschema.Configuration, error) { - ret := _m.Called(ctx, headers) - - var r0 externalschema.Configuration - if rf, ok := ret.Get(0).(func(context.Context, map[string]string) externalschema.Configuration); ok { - r0 = rf(ctx, headers) - } else { - r0 = ret.Get(0).(externalschema.Configuration) - } - - var r1 error - if rf, ok := ret.Get(1).(func(context.Context, map[string]string) error); ok { - r1 = rf(ctx, headers) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// SignCSR provides a mock function with given fields: ctx, csr, headers -func (_m *Client) SignCSR(ctx context.Context, csr string, headers map[string]string) (externalschema.CertificationResult, error) { - ret := _m.Called(ctx, csr, headers) - - var r0 externalschema.CertificationResult - if rf, ok := ret.Get(0).(func(context.Context, string, map[string]string) externalschema.CertificationResult); ok { - r0 = rf(ctx, csr, headers) - } else { - r0 = ret.Get(0).(externalschema.CertificationResult) - } - - var r1 error - if rf, ok := ret.Get(1).(func(context.Context, string, map[string]string) error); ok { - r1 = rf(ctx, csr, headers) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} diff --git a/components/compass-runtime-agent/internal/compass/connector/query.go b/components/compass-runtime-agent/internal/compass/connector/query.go deleted file mode 100644 index 4e1c8413b123..000000000000 --- a/components/compass-runtime-agent/internal/compass/connector/query.go +++ /dev/null @@ -1,36 +0,0 @@ -package connector - -import "fmt" - -type queryProvider struct{} - -func (qp queryProvider) configuration() string { - return fmt.Sprintf(`query { - result: configuration() { - %s - } -}`, configurationResult()) -} - -func (qp queryProvider) signCSR(csr string) string { - return fmt.Sprintf(`mutation { - result: signCertificateSigningRequest(csr: "%s") { - %s - } -}`, csr, certificationResult()) -} - -func configurationResult() string { - return `token { token } - certificateSigningRequestInfo { subject keyAlgorithm } - managementPlaneInfo { - directorURL - certificateSecuredConnectorURL - }` -} - -func certificationResult() string { - return `certificateChain - caCertificate - clientCertificate` -} diff --git a/components/compass-runtime-agent/internal/compass/director/client.go b/components/compass-runtime-agent/internal/compass/director/client.go deleted file mode 100644 index 9508b3e94b92..000000000000 --- a/components/compass-runtime-agent/internal/compass/director/client.go +++ /dev/null @@ -1,112 +0,0 @@ -package director - -import ( - "context" - - "github.com/kyma-incubator/compass/components/director/pkg/graphql" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/config" - gql "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/graphql" - kymamodel "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/model" - gcli "github.com/machinebox/graphql" - "github.com/pkg/errors" -) - -const ( - TenantHeader = "Tenant" - - eventsURLLabelKey = "runtime_eventServiceUrl" - consoleURLLabelKey = "runtime_consoleUrl" -) - -type RuntimeURLsConfig struct { - EventsURL string `envconfig:"default=https://gateway.kyma.local"` - ConsoleURL string `envconfig:"default=https://console.kyma.local"` -} - -//go:generate mockery --name=DirectorClient -type DirectorClient interface { - FetchConfiguration(ctx context.Context) ([]kymamodel.Application, graphql.Labels, error) - SetURLsLabels(ctx context.Context, urlsCfg RuntimeURLsConfig, actualLabels graphql.Labels) (graphql.Labels, error) -} - -func NewConfigurationClient(gqlClient gql.Client, runtimeConfig config.RuntimeConfig) DirectorClient { - return &directorClient{ - gqlClient: gqlClient, - queryProvider: queryProvider{}, - runtimeConfig: runtimeConfig, - } -} - -type directorClient struct { - gqlClient gql.Client - queryProvider queryProvider - runtimeConfig config.RuntimeConfig -} - -func (cc *directorClient) FetchConfiguration(ctx context.Context) ([]kymamodel.Application, graphql.Labels, error) { - response := ApplicationsAndLabelsForRuntimeResponse{} - - appsAndLabelsForRuntimeQuery := cc.queryProvider.applicationsAndLabelsForRuntimeQuery(cc.runtimeConfig.RuntimeId) - req := gcli.NewRequest(appsAndLabelsForRuntimeQuery) - req.Header.Set(TenantHeader, cc.runtimeConfig.Tenant) - - err := cc.gqlClient.Do(ctx, req, &response) - if err != nil { - return nil, nil, errors.Wrap(err, "Failed to fetch Applications and Labels") - } - - // Nil check is necessary due to GraphQL client not checking response code - if response.Runtime == nil || response.ApplicationsPage == nil { - return nil, nil, errors.Errorf("Failed fetch Applications or Labels for Runtime from Director: received nil response.") - } - - // TODO: After implementation of paging modify the fetching logic - - applications := make([]kymamodel.Application, len(response.ApplicationsPage.Data)) - for i, app := range response.ApplicationsPage.Data { - applications[i] = app.ToApplication() - } - - return applications, response.Runtime.Labels, nil -} - -func (cc *directorClient) SetURLsLabels(ctx context.Context, urlsCfg RuntimeURLsConfig, currentLabels graphql.Labels) (graphql.Labels, error) { - targetLabels := map[string]string{ - eventsURLLabelKey: urlsCfg.EventsURL, - consoleURLLabelKey: urlsCfg.ConsoleURL, - } - - updatedLabels := make(map[string]interface{}) - for key, value := range targetLabels { - if val, ok := currentLabels[key]; !ok || val != value { - l, err := cc.setURLLabel(ctx, key, value) - if err != nil { - return nil, errors.WithMessagef(err, "Failed to set %s Runtime label to value %s", key, val) - } - - updatedLabels[l.Key] = l.Value - } - } - - return updatedLabels, nil -} - -func (cc *directorClient) setURLLabel(ctx context.Context, key, value string) (*graphql.Label, error) { - response := SetRuntimeLabelResponse{} - - setLabelQuery := cc.queryProvider.setRuntimeLabelMutation(cc.runtimeConfig.RuntimeId, key, value) - req := gcli.NewRequest(setLabelQuery) - req.Header.Set(TenantHeader, cc.runtimeConfig.Tenant) - - err := cc.gqlClient.Do(ctx, req, &response) - if err != nil { - return nil, errors.WithMessagef(err, "Failed to set %s Runtime label to value %s", key, value) - } - - // Nil check is necessary due to GraphQL client not checking response code - if response.Result == nil { - return nil, errors.Errorf("Failed to set %s Runtime label to value %s. Received nil response.", key, value) - } - - return response.Result, nil -} diff --git a/components/compass-runtime-agent/internal/compass/director/client_test.go b/components/compass-runtime-agent/internal/compass/director/client_test.go deleted file mode 100644 index 695eb826b88c..000000000000 --- a/components/compass-runtime-agent/internal/compass/director/client_test.go +++ /dev/null @@ -1,463 +0,0 @@ -package director - -import ( - "context" - "testing" - - "github.com/kyma-incubator/compass/components/director/pkg/graphql" - gcli "github.com/machinebox/graphql" - "github.com/pkg/errors" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/config" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/graphql/mocks" - kymamodel "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/model" -) - -const ( - tenant = "tenant" - runtimeId = "runtimeId" - - expectedAppsAndLabelsForRuntimeQuery = `query { - runtime(id: "runtimeId") { - labels - } - applicationsForRuntime(runtimeID: "runtimeId") { - data { - id - name - providerName - description - labels - auths {id} - bundles {data { - id - name - description - instanceAuthRequestInputSchema - apiDefinitions {data { - id - name - description - targetURL - group - version {value - deprecated - deprecatedSince - forRemoval} - } - pageInfo {startCursor - endCursor - hasNextPage} - totalCount - } - eventDefinitions {data { - - id - name - description - group - version {value - deprecated - deprecatedSince - forRemoval} - - } - pageInfo {startCursor - endCursor - hasNextPage} - totalCount - } - defaultInstanceAuth { - credential { - ... on BasicCredentialData { - username - password - } - ... on OAuthCredentialData { - clientId - clientSecret - url - } - } - additionalHeaders - additionalQueryParams - requestAuth { - csrf { - tokenEndpointURL - } - } - } - - } - pageInfo {startCursor - endCursor - hasNextPage} - totalCount - } - - } - pageInfo {startCursor - endCursor - hasNextPage} - totalCount - - } - }` - - expectedSetEventsURLLabelQuery = `mutation { - setRuntimeLabel(runtimeID: "runtimeId", key: "runtime_eventServiceUrl", value: "https://gateway.kyma.local") { - key - value - } - }` - expectedSetConsoleURLLabelQuery = `mutation { - setRuntimeLabel(runtimeID: "runtimeId", key: "runtime_consoleUrl", value: "https://console.kyma.local") { - key - value - } - }` -) - -var runtimeConfig = config.RuntimeConfig{ - RuntimeId: runtimeId, - Tenant: tenant, -} - -func TestConfigClient_FetchConfiguration(t *testing.T) { - expectedRequest := gcli.NewRequest(expectedAppsAndLabelsForRuntimeQuery) - expectedRequest.Header.Set(TenantHeader, tenant) - - setExpectedFetchConfigFunc := func(appsResponse *ApplicationPage, runtimeResponse *Runtime) func(args mock.Arguments) { - return func(args mock.Arguments) { - response, ok := args[2].(*ApplicationsAndLabelsForRuntimeResponse) - require.True(t, ok) - assert.Empty(t, response.ApplicationsPage) - assert.Empty(t, response.Runtime) - response.ApplicationsPage = appsResponse - response.Runtime = runtimeResponse - } - } - - t.Run("should fetch configuration", func(t *testing.T) { - // given - expectedResponseApplications := &ApplicationPage{ - Data: []*Application{ - { - ID: "abcd-efgh", - Name: "App1", - }, - { - ID: "ijkl-mnop", - Name: "App2", - }, - { - ID: "asda-oqiu", - Name: "App3", - Auths: []*graphql.AppSystemAuth{{ID: "asd"}}, - }, - }, - PageInfo: &graphql.PageInfo{}, - TotalCount: 3, - } - - expectedResponseRuntime := &Runtime{ - Labels: graphql.Labels{ - eventsURLLabelKey: "eventsURL", - consoleURLLabelKey: "consoleURL", - }, - } - - expectedApps := []kymamodel.Application{ - { - Name: "App1", - ID: "abcd-efgh", - SystemAuthsIDs: make([]string, 0), - }, - { - ID: "ijkl-mnop", - Name: "App2", - SystemAuthsIDs: make([]string, 0), - }, - { - ID: "asda-oqiu", - Name: "App3", - SystemAuthsIDs: []string{"asd"}, - }, - } - - expectedLabels := graphql.Labels{ - eventsURLLabelKey: "eventsURL", - consoleURLLabelKey: "consoleURL", - } - - client := &mocks.Client{} - client. - On("Do", context.Background(), expectedRequest, &ApplicationsAndLabelsForRuntimeResponse{}). - Return(nil). - Run(setExpectedFetchConfigFunc(expectedResponseApplications, expectedResponseRuntime)). - Once() - - configClient := NewConfigurationClient(client, runtimeConfig) - - // when - applicationsResponse, labelsResponse, err := configClient.FetchConfiguration(context.Background()) - - // then - require.NoError(t, err) - assert.Equal(t, expectedApps, applicationsResponse) - assert.Equal(t, expectedLabels, labelsResponse) - }) - - t.Run("should return empty array if no Apps for Runtime", func(t *testing.T) { - // given - expectedResponseApps := &ApplicationPage{ - Data: nil, - PageInfo: &graphql.PageInfo{}, - TotalCount: 0, - } - - expectedResponseRuntime := &Runtime{ - Labels: nil, - } - - client := &mocks.Client{} - client. - On("Do", context.Background(), expectedRequest, &ApplicationsAndLabelsForRuntimeResponse{}). - Return(nil). - Run(setExpectedFetchConfigFunc(expectedResponseApps, expectedResponseRuntime)). - Once() - - configClient := NewConfigurationClient(client, runtimeConfig) - - // when - applicationsResponse, _, err := configClient.FetchConfiguration(context.Background()) - - // then - require.NoError(t, err) - assert.Empty(t, applicationsResponse) - }) - - t.Run("should return empty array if no Labels for Runtime", func(t *testing.T) { - // given - expectedResponseRuntime := &Runtime{ - Labels: nil, - } - - expectedResponseApps := &ApplicationPage{ - Data: nil, - PageInfo: &graphql.PageInfo{}, - TotalCount: 0, - } - - client := &mocks.Client{} - client. - On("Do", context.Background(), expectedRequest, &ApplicationsAndLabelsForRuntimeResponse{}). - Return(nil). - Run(setExpectedFetchConfigFunc(expectedResponseApps, expectedResponseRuntime)). - Once() - - configClient := NewConfigurationClient(client, runtimeConfig) - - // when - _, labelsResponse, err := configClient.FetchConfiguration(context.Background()) - - // then - require.NoError(t, err) - assert.Empty(t, labelsResponse) - }) - - t.Run("should return error when result is nil", func(t *testing.T) { - // given - client := &mocks.Client{} - client. - On("Do", context.Background(), expectedRequest, &ApplicationsAndLabelsForRuntimeResponse{}). - Return(nil). - Run(setExpectedFetchConfigFunc(nil, nil)). - Once() - - configClient := NewConfigurationClient(client, runtimeConfig) - - // when - applicationsResponse, labelsResponse, err := configClient.FetchConfiguration(context.Background()) - - // then - require.Error(t, err) - assert.Contains(t, err.Error(), "nil response") - assert.Empty(t, labelsResponse) - assert.Empty(t, applicationsResponse) - }) - - t.Run("should return error when failed to fetch Applications and Labels for Runtime", func(t *testing.T) { - // given - client := &mocks.Client{} - client. - On("Do", context.Background(), expectedRequest, &ApplicationsAndLabelsForRuntimeResponse{}). - Return(errors.New("error")). - Once() - - configClient := NewConfigurationClient(client, runtimeConfig) - - // when - applicationsResponse, labelsResponse, err := configClient.FetchConfiguration(context.Background()) - - // then - require.Error(t, err) - assert.Contains(t, err.Error(), "Failed to fetch Applications and Labels") - assert.Nil(t, applicationsResponse) - assert.Nil(t, labelsResponse) - }) -} - -func TestConfigClient_SetURLsLabels(t *testing.T) { - runtimeURLsConfig := RuntimeURLsConfig{ - EventsURL: "https://gateway.kyma.local", - ConsoleURL: "https://console.kyma.local", - } - - expectedSetEventsURLRequest := gcli.NewRequest(expectedSetEventsURLLabelQuery) - expectedSetEventsURLRequest.Header.Set(TenantHeader, tenant) - expectedSetConsoleURLRequest := gcli.NewRequest(expectedSetConsoleURLLabelQuery) - expectedSetConsoleURLRequest.Header.Set(TenantHeader, tenant) - - setExpectedRuntimeLabelFunc := func(expectedResponses *graphql.Label) func(args mock.Arguments) { - return func(args mock.Arguments) { - response, ok := args[2].(*SetRuntimeLabelResponse) - require.True(t, ok) - assert.Empty(t, response.Result) - response.Result = expectedResponses - } - } - - eventsURLLabel := &graphql.Label{ - Key: eventsURLLabelKey, - Value: runtimeURLsConfig.EventsURL, - } - - consoleURLLabel := &graphql.Label{ - Key: consoleURLLabelKey, - Value: runtimeURLsConfig.ConsoleURL, - } - - t.Run("should set URLs as labels if no labels are set", func(t *testing.T) { - currentLabels := graphql.Labels{} - - client := &mocks.Client{} - client. - On("Do", context.Background(), expectedSetEventsURLRequest, &SetRuntimeLabelResponse{}). - Return(nil). - Run(setExpectedRuntimeLabelFunc(eventsURLLabel)). - Once() - client. - On("Do", context.Background(), expectedSetConsoleURLRequest, &SetRuntimeLabelResponse{}). - Return(nil). - Run(setExpectedRuntimeLabelFunc(consoleURLLabel)). - Once() - - configClient := NewConfigurationClient(client, runtimeConfig) - - // when - updatedLabels, err := configClient.SetURLsLabels(context.Background(), runtimeURLsConfig, currentLabels) - - // then - require.NoError(t, err) - assert.Equal(t, 2, len(updatedLabels)) - assert.Equal(t, runtimeURLsConfig.EventsURL, updatedLabels[eventsURLLabelKey]) - assert.Equal(t, runtimeURLsConfig.ConsoleURL, updatedLabels[consoleURLLabelKey]) - }) - - t.Run("should not set URLs as labels if there are already set and they're the same", func(t *testing.T) { - currentLabels := graphql.Labels{} - currentLabels[eventsURLLabelKey] = runtimeURLsConfig.EventsURL - currentLabels[consoleURLLabelKey] = runtimeURLsConfig.ConsoleURL - - configClient := NewConfigurationClient(&mocks.Client{}, runtimeConfig) - - // when - updatedLabels, err := configClient.SetURLsLabels(context.Background(), runtimeURLsConfig, currentLabels) - - // then - require.NoError(t, err) - assert.Equal(t, 0, len(updatedLabels)) - }) - - t.Run("should override URLs if there are already set but are different", func(t *testing.T) { - currentLabels := graphql.Labels{} - currentLabels[eventsURLLabelKey] = runtimeURLsConfig.EventsURL + " something different" - currentLabels[consoleURLLabelKey] = runtimeURLsConfig.ConsoleURL + " something different" - - client := &mocks.Client{} - client. - On("Do", context.Background(), expectedSetEventsURLRequest, &SetRuntimeLabelResponse{}). - Return(nil). - Run(setExpectedRuntimeLabelFunc(eventsURLLabel)). - Once() - client. - On("Do", context.Background(), expectedSetConsoleURLRequest, &SetRuntimeLabelResponse{}). - Return(nil). - Run(setExpectedRuntimeLabelFunc(consoleURLLabel)). - Once() - - configClient := NewConfigurationClient(client, runtimeConfig) - - // when - updatedLabels, err := configClient.SetURLsLabels(context.Background(), runtimeURLsConfig, currentLabels) - - // then - require.NoError(t, err) - assert.Equal(t, 2, len(updatedLabels)) - assert.Equal(t, runtimeURLsConfig.EventsURL, updatedLabels[eventsURLLabelKey]) - assert.Equal(t, runtimeURLsConfig.ConsoleURL, updatedLabels[consoleURLLabelKey]) - }) - - t.Run("should set only missing URLs as labels", func(t *testing.T) { - currentLabels := graphql.Labels{} - currentLabels[eventsURLLabelKey] = runtimeURLsConfig.EventsURL - - client := &mocks.Client{} - client. - On("Do", context.Background(), expectedSetConsoleURLRequest, &SetRuntimeLabelResponse{}). - Return(nil). - Run(setExpectedRuntimeLabelFunc(consoleURLLabel)). - Once() - - configClient := NewConfigurationClient(client, runtimeConfig) - - // when - updatedLabels, err := configClient.SetURLsLabels(context.Background(), runtimeURLsConfig, currentLabels) - - // then - require.NoError(t, err) - assert.Equal(t, 1, len(updatedLabels)) - assert.Equal(t, runtimeURLsConfig.ConsoleURL, updatedLabels[consoleURLLabelKey]) - }) - - t.Run("should return error if setting label returned nil response", func(t *testing.T) { - currentLabels := graphql.Labels{} - - client := &mocks.Client{} - client. - On("Do", context.Background(), expectedSetEventsURLRequest, &SetRuntimeLabelResponse{}). - Return(nil). - Run(setExpectedRuntimeLabelFunc(eventsURLLabel)). - Once() - - client. - On("Do", context.Background(), expectedSetConsoleURLRequest, &SetRuntimeLabelResponse{}). - Return(nil). - Run(setExpectedRuntimeLabelFunc(nil)). - Once() - - configClient := NewConfigurationClient(client, runtimeConfig) - - // when - updatedLabels, err := configClient.SetURLsLabels(context.Background(), runtimeURLsConfig, currentLabels) - - // then - require.Error(t, err) - assert.Contains(t, err.Error(), "nil response") - assert.Nil(t, updatedLabels) - }) -} diff --git a/components/compass-runtime-agent/internal/compass/director/converter.go b/components/compass-runtime-agent/internal/compass/director/converter.go deleted file mode 100644 index 8d102874713e..000000000000 --- a/components/compass-runtime-agent/internal/compass/director/converter.go +++ /dev/null @@ -1,193 +0,0 @@ -package director - -import ( - "github.com/kyma-incubator/compass/components/director/pkg/graphql" - - kymamodel "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/model" -) - -func (app Application) ToApplication() kymamodel.Application { - var bundles []kymamodel.APIBundle - if app.Bundles != nil { - bundles = convertAPIBundles(app.Bundles.Data) - } - - description := "" - if app.Description != nil { - description = *app.Description - } - - providerName := "" - if app.ProviderName != nil { - providerName = *app.ProviderName - } - - return kymamodel.Application{ - ID: app.ID, - Name: app.Name, - ProviderDisplayName: providerName, - Description: description, - Labels: app.Labels, - SystemAuthsIDs: extractSystemAuthIDs(app.Auths), - ApiBundles: bundles, - } -} - -func convertAPIBundles(apiBundles []*graphql.BundleExt) []kymamodel.APIBundle { - bundles := make([]kymamodel.APIBundle, len(apiBundles)) - - for i, apiBundle := range apiBundles { - bundles[i] = convertAPIBundle(apiBundle) - } - - return bundles -} - -func convertAPIBundle(apiBundle *graphql.BundleExt) kymamodel.APIBundle { - apis := convertAPIsExt(apiBundle.APIDefinitions.Data) - eventAPIs := convertEventAPIsExt(apiBundle.EventDefinitions.Data) - defaultInstanceAuth := convertAuth(apiBundle.DefaultInstanceAuth) - - var authRequestInputSchema *string - if apiBundle.InstanceAuthRequestInputSchema != nil { - s := string(*apiBundle.InstanceAuthRequestInputSchema) - authRequestInputSchema = &s - } - return kymamodel.APIBundle{ - ID: apiBundle.ID, - Name: apiBundle.Name, - Description: apiBundle.Description, - InstanceAuthRequestInputSchema: authRequestInputSchema, - APIDefinitions: apis, - EventDefinitions: eventAPIs, - DefaultInstanceAuth: defaultInstanceAuth, - } -} - -func convertAPIsExt(compassAPIs []*graphql.APIDefinitionExt) []kymamodel.APIDefinition { - apis := make([]kymamodel.APIDefinition, len(compassAPIs)) - - for i, cAPI := range compassAPIs { - apis[i] = convertAPIExt(cAPI) - } - - return apis -} - -func convertEventAPIsExt(compassEventAPIs []*graphql.EventAPIDefinitionExt) []kymamodel.EventAPIDefinition { - eventAPIs := make([]kymamodel.EventAPIDefinition, len(compassEventAPIs)) - - for i, cAPI := range compassEventAPIs { - eventAPIs[i] = convertEventAPIExt(cAPI) - } - - return eventAPIs -} - -func extractSystemAuthIDs(auths []*graphql.AppSystemAuth) []string { - ids := make([]string, 0, len(auths)) - - for _, auth := range auths { - ids = append(ids, auth.ID) - } - - return ids -} - -func convertAPIExt(compassAPI *graphql.APIDefinitionExt) kymamodel.APIDefinition { - description := "" - if compassAPI.Description != nil { - description = *compassAPI.Description - } - - api := kymamodel.APIDefinition{ - ID: compassAPI.ID, - Name: compassAPI.Name, - Description: description, - TargetUrl: compassAPI.TargetURL, - } - - return api -} - -func convertEventAPIExt(compassEventAPI *graphql.EventAPIDefinitionExt) kymamodel.EventAPIDefinition { - description := "" - if compassEventAPI.Description != nil { - description = *compassEventAPI.Description - } - - eventAPI := kymamodel.EventAPIDefinition{ - ID: compassEventAPI.ID, - Name: compassEventAPI.Name, - Description: description, - } - - return eventAPI -} - -func convertAuth(compassAuth *graphql.Auth) *kymamodel.Auth { - if compassAuth == nil { - return nil - } - return &kymamodel.Auth{ - Credentials: convertCredentials(compassAuth), - RequestParameters: convertRequestParameters(compassAuth), - } -} - -func convertCredentials(compassAuth *graphql.Auth) *kymamodel.Credentials { - if compassAuth == nil { - return nil - } - switch compassAuth.Credential.(type) { - case *graphql.OAuthCredentialData: - v := compassAuth.Credential.(*graphql.OAuthCredentialData) - if v != nil { - return &kymamodel.Credentials{ - Oauth: &kymamodel.Oauth{ - URL: v.URL, - ClientID: v.ClientID, - ClientSecret: v.ClientSecret, - }, - CSRFInfo: convertCSRFInfo(compassAuth), - } - } - case *graphql.BasicCredentialData: - v := compassAuth.Credential.(*graphql.BasicCredentialData) - if v != nil { - return &kymamodel.Credentials{ - Basic: &kymamodel.Basic{ - Username: v.Username, - Password: v.Password, - }, - CSRFInfo: convertCSRFInfo(compassAuth), - } - } - } - return nil -} - -func convertRequestParameters(compassAuth *graphql.Auth) *kymamodel.RequestParameters { - if compassAuth.AdditionalHeaders != nil || compassAuth.AdditionalQueryParams != nil { - result := &kymamodel.RequestParameters{} - if compassAuth.AdditionalHeaders != nil { - v := map[string][]string(compassAuth.AdditionalHeaders) - result.Headers = &v - } - if compassAuth.AdditionalQueryParams != nil { - v := map[string][]string(compassAuth.AdditionalQueryParams) - result.QueryParameters = &v - } - return result - } - return nil -} - -func convertCSRFInfo(compassAuth *graphql.Auth) *kymamodel.CSRFInfo { - if compassAuth.RequestAuth != nil && compassAuth.RequestAuth.Csrf != nil { - return &kymamodel.CSRFInfo{ - TokenEndpointURL: compassAuth.RequestAuth.Csrf.TokenEndpointURL, - } - } - return nil -} diff --git a/components/compass-runtime-agent/internal/compass/director/converter_test.go b/components/compass-runtime-agent/internal/compass/director/converter_test.go deleted file mode 100644 index 41b3af3e3f1b..000000000000 --- a/components/compass-runtime-agent/internal/compass/director/converter_test.go +++ /dev/null @@ -1,456 +0,0 @@ -package director - -import ( - "testing" - - "github.com/kyma-incubator/compass/components/director/pkg/graphql" - "github.com/stretchr/testify/assert" - - kymaModel "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/model" -) - -const ( - baseAPIId = "apiId" - baseAPIName = "awesome api name" - baseAPIDesc = "so awesome this api description" - baseAPIURL = "https://api.url.com" - - baseBundleID = "bundleID" - baseBundleName = "bundleName" - baseBundleDesc = "bundleDesc" - baseBundleInputSchema = "input schema" -) - -// TODO: add test cases for request parameters when they will be supported - -func TestApplication_ToApplication(t *testing.T) { - appId := "abcd" - appName := "my awesome app" - providerName := "provider" - appDesc := "app is so awesome" - appLabels := map[string]interface{}{ - "appSlice": []string{appName, "app"}, - "app": "test", - } - - for _, testCase := range []struct { - description string - compassApp Application - expectedApp kymaModel.Application - }{ - { - description: "not fail if Application is empty", - expectedApp: kymaModel.Application{ - SystemAuthsIDs: make([]string, 0), - }, - }, - { - description: "convert Compass App with auths to internal model", - compassApp: Application{ - ID: appId, - Name: appName, - ProviderName: &providerName, - Description: &appDesc, - Labels: appLabels, - Auths: []*graphql.AppSystemAuth{ - {ID: "1", Auth: &graphql.Auth{Credential: graphql.BasicCredentialData{Password: "password", Username: "user"}}}, - {ID: "2", Auth: &graphql.Auth{Credential: graphql.OAuthCredentialData{ClientSecret: "secret", ClientID: "id"}}}, - }, - }, - expectedApp: kymaModel.Application{ - ID: appId, - Name: appName, - ProviderDisplayName: providerName, - Description: appDesc, - Labels: appLabels, - SystemAuthsIDs: []string{"1", "2"}, - }, - }, - { - description: "convert Compass App using API Bundles to internal model", - compassApp: Application{ - ID: appId, - Name: appName, - ProviderName: &providerName, - Description: &appDesc, - Labels: appLabels, - Bundles: &graphql.BundlePageExt{ - Data: []*graphql.BundleExt{ - fixCompassBundleExt("1"), - fixCompassBundleExt("2"), - fixCompassBundleExt("3"), - }, - }, - }, - expectedApp: kymaModel.Application{ - ID: appId, - Name: appName, - ProviderDisplayName: providerName, - Description: appDesc, - Labels: appLabels, - SystemAuthsIDs: make([]string, 0), - ApiBundles: []kymaModel.APIBundle{ - fixInternalAPIBundle("1"), - fixInternalAPIBundle("2"), - fixInternalAPIBundle("3"), - }, - }, - }, - { - description: "convert Compass App using API Bundles to internal model with default instance auth", - compassApp: Application{ - ID: appId, - Name: appName, - ProviderName: &providerName, - Description: &appDesc, - Labels: appLabels, - Bundles: &graphql.BundlePageExt{ - Data: []*graphql.BundleExt{ - fixCompassBundleWithDefaultInstanceAuth("1", nil), - fixCompassBundleWithDefaultInstanceAuth("2", &graphql.Auth{ - Credential: &graphql.BasicCredentialData{ - Username: "my-user", - Password: "my-password", - }, - AdditionalHeaders: graphql.HTTPHeaders{"h1": {"v1"}}, - AdditionalQueryParams: graphql.QueryParams{"q1": {"p1"}}, - }), - fixCompassBundleWithDefaultInstanceAuth("3", &graphql.Auth{ - Credential: &graphql.OAuthCredentialData{ - ClientID: "my-client-id", - ClientSecret: "my-client-secret", - URL: "https://test-oauth.com", - }, - AdditionalHeaders: graphql.HTTPHeaders{"h1": {"v1"}}, - AdditionalQueryParams: graphql.QueryParams{"q1": {"p1"}}, - }), - fixCompassBundleWithDefaultInstanceAuth("4", &graphql.Auth{ - Credential: &graphql.BasicCredentialData{ - Username: "my-user2", - Password: "my-password2", - }, - RequestAuth: &graphql.CredentialRequestAuth{ - Csrf: &graphql.CSRFTokenCredentialRequestAuth{ - TokenEndpointURL: "https://csrf.basic.example.com", - }, - }, - }), - fixCompassBundleWithDefaultInstanceAuth("5", &graphql.Auth{ - Credential: &graphql.OAuthCredentialData{ - ClientID: "my-client-id2", - ClientSecret: "my-client-secret2", - URL: "https://test2-oauth.com", - }, - RequestAuth: &graphql.CredentialRequestAuth{ - Csrf: &graphql.CSRFTokenCredentialRequestAuth{ - TokenEndpointURL: "https://csrf.oauth.example.com", - }, - }, - }), - }, - }, - }, - expectedApp: kymaModel.Application{ - ID: appId, - Name: appName, - ProviderDisplayName: providerName, - Description: appDesc, - Labels: appLabels, - SystemAuthsIDs: make([]string, 0), - ApiBundles: []kymaModel.APIBundle{ - fixInternalAPIBundleWithInstanceAuth("1", nil), - fixInternalAPIBundleWithInstanceAuth("2", &kymaModel.Auth{ - Credentials: &kymaModel.Credentials{ - Basic: &kymaModel.Basic{ - Username: "my-user", - Password: "my-password", - }, - }, - RequestParameters: &kymaModel.RequestParameters{ - Headers: &map[string][]string{ - "h1": {"v1"}, - }, - QueryParameters: &map[string][]string{ - "q1": {"p1"}, - }, - }, - }), - fixInternalAPIBundleWithInstanceAuth("3", &kymaModel.Auth{ - Credentials: &kymaModel.Credentials{ - Oauth: &kymaModel.Oauth{ - ClientID: "my-client-id", - ClientSecret: "my-client-secret", - URL: "https://test-oauth.com", - }, - }, - RequestParameters: &kymaModel.RequestParameters{ - Headers: &map[string][]string{ - "h1": {"v1"}, - }, - QueryParameters: &map[string][]string{ - "q1": {"p1"}, - }, - }, - }), - fixInternalAPIBundleWithInstanceAuth("4", &kymaModel.Auth{ - Credentials: &kymaModel.Credentials{ - Basic: &kymaModel.Basic{ - Username: "my-user2", - Password: "my-password2", - }, - CSRFInfo: &kymaModel.CSRFInfo{ - TokenEndpointURL: "https://csrf.basic.example.com", - }, - }, - }), - fixInternalAPIBundleWithInstanceAuth("5", &kymaModel.Auth{ - Credentials: &kymaModel.Credentials{ - Oauth: &kymaModel.Oauth{ - ClientID: "my-client-id2", - ClientSecret: "my-client-secret2", - URL: "https://test2-oauth.com", - }, - CSRFInfo: &kymaModel.CSRFInfo{ - TokenEndpointURL: "https://csrf.oauth.example.com", - }, - }, - }), - }, - }, - }, - { - description: "convert Compass App using API Bundles with instance auths to internal model", - compassApp: Application{ - ID: appId, - Name: appName, - ProviderName: &providerName, - Description: &appDesc, - Labels: appLabels, - Bundles: &graphql.BundlePageExt{ - Data: []*graphql.BundleExt{ - fixCompassBundleExt("1"), - fixCompassBundleExt("2"), - fixCompassBundleExt("3"), - }, - }, - }, - expectedApp: kymaModel.Application{ - ID: appId, - Name: appName, - ProviderDisplayName: providerName, - Description: appDesc, - Labels: appLabels, - SystemAuthsIDs: make([]string, 0), - ApiBundles: []kymaModel.APIBundle{ - fixInternalAPIBundle("1"), - fixInternalAPIBundle("2"), - fixInternalAPIBundle("3"), - }, - }, - }, - { - description: "convert Compass App with empty Bundle pages", - compassApp: Application{ - ID: appId, - Name: appName, - Description: &appDesc, - ProviderName: &providerName, - Labels: appLabels, - }, - expectedApp: kymaModel.Application{ - ID: appId, - Name: appName, - Description: appDesc, - ProviderDisplayName: providerName, - Labels: appLabels, - SystemAuthsIDs: make([]string, 0), - }, - }, - { - description: "convert Compass App with bundles", - compassApp: Application{ - ID: appId, - Name: appName, - Description: &appDesc, - ProviderName: &providerName, - Bundles: &graphql.BundlePageExt{ - Data: []*graphql.BundleExt{ - fixCompassBundleExt("1"), - fixCompassBundleExt("2"), - fixCompassBundleExt("3"), - }, - }, - }, - expectedApp: kymaModel.Application{ - ID: appId, - Name: appName, - Description: appDesc, - ProviderDisplayName: providerName, - ApiBundles: []kymaModel.APIBundle{ - fixInternalAPIBundle("1"), - fixInternalAPIBundle("2"), - fixInternalAPIBundle("3"), - }, - SystemAuthsIDs: make([]string, 0), - }, - }, - } { - t.Run(testCase.description, func(t *testing.T) { - // when - internalApp := testCase.compassApp.ToApplication() - - // then - assert.Equal(t, testCase.expectedApp, internalApp) - }) - } -} - -func fixInternalAPIBundle(suffix string) kymaModel.APIBundle { - return kymaModel.APIBundle{ - ID: baseBundleID + suffix, - Name: baseBundleName + suffix, - Description: stringPtr(baseBundleDesc + suffix), - InstanceAuthRequestInputSchema: stringPtr(baseBundleInputSchema + suffix), - APIDefinitions: []kymaModel.APIDefinition{ - fixInternalAPIDefinition("1", nil), - fixInternalAPIDefinition("2", nil), - fixInternalAPIDefinition("3", nil), - fixInternalAPIDefinition("4", nil), - }, - EventDefinitions: []kymaModel.EventAPIDefinition{ - fixInternalEventAPIDefinition("1"), - fixInternalEventAPIDefinition("2"), - }, - } -} - -func fixInternalAPIDefinition(suffix string, credentials *kymaModel.Credentials) kymaModel.APIDefinition { - return kymaModel.APIDefinition{ - ID: baseAPIId + suffix, - Name: baseAPIName + suffix, - Description: baseAPIDesc + suffix, - TargetUrl: baseAPIURL + suffix, - Credentials: credentials, - } -} - -func fixInternalEventAPIDefinition(suffix string) kymaModel.EventAPIDefinition { - return kymaModel.EventAPIDefinition{ - ID: baseAPIId + suffix, - Name: baseAPIName + suffix, - Description: baseAPIDesc + suffix, - } -} - -func fixCompassBundleWithDefaultInstanceAuth(suffix string, defaultInstanceAuth *graphql.Auth) *graphql.BundleExt { - return &graphql.BundleExt{ - Bundle: fixCompassBundle(suffix, defaultInstanceAuth), - APIDefinitions: fixAPIDefinitionPageExt(), - EventDefinitions: fixEventAPIDefinitionPageExt(), - } -} - -func fixInternalAPIBundleWithInstanceAuth(suffix string, defaultInstanceAuth *kymaModel.Auth) kymaModel.APIBundle { - return kymaModel.APIBundle{ - ID: baseBundleID + suffix, - Name: baseBundleName + suffix, - Description: stringPtr(baseBundleDesc + suffix), - InstanceAuthRequestInputSchema: stringPtr(baseBundleInputSchema + suffix), - APIDefinitions: []kymaModel.APIDefinition{ - fixInternalAPIDefinition("1", nil), - fixInternalAPIDefinition("2", nil), - fixInternalAPIDefinition("3", nil), - fixInternalAPIDefinition("4", nil), - }, - EventDefinitions: []kymaModel.EventAPIDefinition{ - fixInternalEventAPIDefinition("1"), - fixInternalEventAPIDefinition("2"), - }, - DefaultInstanceAuth: defaultInstanceAuth, - } -} - -func fixCompassBundleExt(suffix string) *graphql.BundleExt { - return &graphql.BundleExt{ - Bundle: fixCompassBundle(suffix, nil), - APIDefinitions: fixAPIDefinitionPageExt(), - EventDefinitions: fixEventAPIDefinitionPageExt(), - } -} - -func fixCompassBundle(suffix string, defaultInstanceAuth *graphql.Auth) graphql.Bundle { - return graphql.Bundle{ - BaseEntity: &graphql.BaseEntity{ - ID: baseBundleID + suffix, - }, - Name: baseBundleName + suffix, - Description: stringPtr(baseBundleDesc + suffix), - InstanceAuthRequestInputSchema: (*graphql.JSONSchema)(stringPtr(baseBundleInputSchema + suffix)), - DefaultInstanceAuth: defaultInstanceAuth, - } -} - -func fixAPIDefinitionPageExt() graphql.APIDefinitionPageExt { - return graphql.APIDefinitionPageExt{ - Data: []*graphql.APIDefinitionExt{ - fixCompassAPIDefinitionExt("1"), - fixCompassAPIDefinitionExt("2"), - fixCompassAPIDefinitionExt("3"), - fixCompassAPIDefinitionExt("4"), - }, - } -} - -func fixCompassAPIDefinitionExt(suffix string) *graphql.APIDefinitionExt { - apiDefinition := fixCompassAPIDefinition(suffix) - - return &graphql.APIDefinitionExt{ - APIDefinition: *apiDefinition, - } -} - -func fixEventAPIDefinitionPageExt() graphql.EventAPIDefinitionPageExt { - return graphql.EventAPIDefinitionPageExt{ - Data: []*graphql.EventAPIDefinitionExt{ - fixEventAPIDefinitionExt("1"), - fixEventAPIDefinitionExt("2"), - }, - } -} - -func fixEventAPIDefinitionExt(suffix string) *graphql.EventAPIDefinitionExt { - eventDefinition := fixCompassEventAPIDefinition(suffix) - - return &graphql.EventAPIDefinitionExt{ - EventDefinition: *eventDefinition, - } -} - -func fixCompassAPIDefinition(suffix string) *graphql.APIDefinition { - desc := baseAPIDesc + suffix - - return &graphql.APIDefinition{ - BaseEntity: &graphql.BaseEntity{ - ID: baseAPIId + suffix, - }, - Name: baseAPIName + suffix, - Description: &desc, - TargetURL: baseAPIURL + suffix, - } -} - -func fixCompassEventAPIDefinition(suffix string) *graphql.EventDefinition { - desc := baseAPIDesc + suffix - - return &graphql.EventDefinition{ - BaseEntity: &graphql.BaseEntity{ - ID: baseAPIId + suffix, - }, - Name: baseAPIName + suffix, - Description: &desc, - } -} - -func stringPtr(str string) *string { - return &str -} diff --git a/components/compass-runtime-agent/internal/compass/director/mocks/DirectorClient.go b/components/compass-runtime-agent/internal/compass/director/mocks/DirectorClient.go deleted file mode 100644 index 24bcba828bed..000000000000 --- a/components/compass-runtime-agent/internal/compass/director/mocks/DirectorClient.go +++ /dev/null @@ -1,74 +0,0 @@ -// Code generated by mockery v2.10.0. DO NOT EDIT. - -package mocks - -import ( - context "context" - - graphql "github.com/kyma-incubator/compass/components/director/pkg/graphql" - director "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/compass/director" - - mock "github.com/stretchr/testify/mock" - - model "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/model" -) - -// DirectorClient is an autogenerated mock type for the DirectorClient type -type DirectorClient struct { - mock.Mock -} - -// FetchConfiguration provides a mock function with given fields: ctx -func (_m *DirectorClient) FetchConfiguration(ctx context.Context) ([]model.Application, graphql.Labels, error) { - ret := _m.Called(ctx) - - var r0 []model.Application - if rf, ok := ret.Get(0).(func(context.Context) []model.Application); ok { - r0 = rf(ctx) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]model.Application) - } - } - - var r1 graphql.Labels - if rf, ok := ret.Get(1).(func(context.Context) graphql.Labels); ok { - r1 = rf(ctx) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(graphql.Labels) - } - } - - var r2 error - if rf, ok := ret.Get(2).(func(context.Context) error); ok { - r2 = rf(ctx) - } else { - r2 = ret.Error(2) - } - - return r0, r1, r2 -} - -// SetURLsLabels provides a mock function with given fields: ctx, urlsCfg, actualLabels -func (_m *DirectorClient) SetURLsLabels(ctx context.Context, urlsCfg director.RuntimeURLsConfig, actualLabels graphql.Labels) (graphql.Labels, error) { - ret := _m.Called(ctx, urlsCfg, actualLabels) - - var r0 graphql.Labels - if rf, ok := ret.Get(0).(func(context.Context, director.RuntimeURLsConfig, graphql.Labels) graphql.Labels); ok { - r0 = rf(ctx, urlsCfg, actualLabels) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(graphql.Labels) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(context.Context, director.RuntimeURLsConfig, graphql.Labels) error); ok { - r1 = rf(ctx, urlsCfg, actualLabels) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} diff --git a/components/compass-runtime-agent/internal/compass/director/model.go b/components/compass-runtime-agent/internal/compass/director/model.go deleted file mode 100644 index 334d97a88db2..000000000000 --- a/components/compass-runtime-agent/internal/compass/director/model.go +++ /dev/null @@ -1,34 +0,0 @@ -package director - -import ( - "github.com/kyma-incubator/compass/components/director/pkg/graphql" -) - -type ApplicationsAndLabelsForRuntimeResponse struct { - Runtime *Runtime `json:"runtime"` - ApplicationsPage *ApplicationPage `json:"applicationsForRuntime"` -} - -type SetRuntimeLabelResponse struct { - Result *graphql.Label `json:"setRuntimeLabel"` -} - -type ApplicationPage struct { - Data []*Application `json:"data"` - PageInfo *graphql.PageInfo `json:"pageInfo"` - TotalCount int `json:"totalCount"` -} - -type Application struct { - ID string `json:"id"` - Name string `json:"name"` - ProviderName *string `json:"providerName"` - Description *string `json:"description"` - Labels map[string]interface{} `json:"labels"` - Auths []*graphql.AppSystemAuth `json:"auths"` - Bundles *graphql.BundlePageExt `json:"bundles"` -} - -type Runtime struct { - Labels map[string]interface{} `json:"labels"` -} diff --git a/components/compass-runtime-agent/internal/compass/director/query.go b/components/compass-runtime-agent/internal/compass/director/query.go deleted file mode 100644 index 7b7153e8bf7b..000000000000 --- a/components/compass-runtime-agent/internal/compass/director/query.go +++ /dev/null @@ -1,147 +0,0 @@ -package director - -import "fmt" - -type queryProvider struct{} - -func (qp queryProvider) applicationsAndLabelsForRuntimeQuery(runtimeID string) string { - return fmt.Sprintf(`query { - runtime(id: "%s") { - %s - } - applicationsForRuntime(runtimeID: "%s") { - %s - } - }`, runtimeID, labels(), runtimeID, applicationsQueryData()) -} - -func (qp queryProvider) setRuntimeLabelMutation(runtimeId, key, value string) string { - return fmt.Sprintf(`mutation { - setRuntimeLabel(runtimeID: "%s", key: "%s", value: "%s") { - %s - } - }`, runtimeId, key, value, labelData()) -} - -func labels() string { - return `labels` -} - -func applicationsQueryData() string { - return pageData(applicationData()) -} - -func labelData() string { - return `key - value` -} - -func pageData(item string) string { - return fmt.Sprintf(`data { - %s - } - pageInfo {%s} - totalCount - `, item, pageInfoData()) -} - -func pageInfoData() string { - return `startCursor - endCursor - hasNextPage` -} - -func applicationData() string { - return fmt.Sprintf(`id - name - providerName - description - labels - auths {%s} - bundles {%s} - `, systemAuthData(), pageData(bundlesData())) -} - -func systemAuthData() string { - return "id" -} - -func bundlesData() string { - return fmt.Sprintf(`id - name - description - instanceAuthRequestInputSchema - apiDefinitions {%s} - eventDefinitions {%s} - defaultInstanceAuth {%s} - `, pageData(bundleApiDefinitions()), pageData(eventAPIData()), authData()) -} - -func bundleApiDefinitions() string { - return fmt.Sprintf(` id - name - description - targetURL - group - version {%s}`, versionData()) -} - -func versionData() string { - return `value - deprecated - deprecatedSince - forRemoval` -} - -func eventAPIData() string { - return fmt.Sprintf(` - id - name - description - group - version {%s} - `, versionData()) -} - -func authData() string { - return fmt.Sprintf(` - credential {%s} - additionalHeaders - additionalQueryParams - requestAuth {%s} - `, credentialData(), requestAuthData()) -} - -func credentialData() string { - return fmt.Sprintf(` - ... on BasicCredentialData {%s} - ... on OAuthCredentialData {%s} - `, basicCredentialData(), oauthCredentialData()) -} - -func basicCredentialData() string { - return ` - username - password - ` -} - -func oauthCredentialData() string { - return ` - clientId - clientSecret - url - ` -} - -func requestAuthData() string { - return fmt.Sprintf(` - csrf {%s} - `, csrfData()) -} - -func csrfData() string { - return ` - tokenEndpointURL - ` -} diff --git a/components/compass-runtime-agent/internal/compass/mocks/ClientsProvider.go b/components/compass-runtime-agent/internal/compass/mocks/ClientsProvider.go deleted file mode 100644 index 8b98d6ed4e88..000000000000 --- a/components/compass-runtime-agent/internal/compass/mocks/ClientsProvider.go +++ /dev/null @@ -1,86 +0,0 @@ -// Code generated by mockery v2.10.0. DO NOT EDIT. - -package mocks - -import ( - connector "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/compass/connector" - config "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/config" - - director "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/compass/director" - - mock "github.com/stretchr/testify/mock" -) - -// ClientsProvider is an autogenerated mock type for the ClientsProvider type -type ClientsProvider struct { - mock.Mock -} - -// GetConnectorCertSecuredClient provides a mock function with given fields: -func (_m *ClientsProvider) GetConnectorCertSecuredClient() (connector.Client, error) { - ret := _m.Called() - - var r0 connector.Client - if rf, ok := ret.Get(0).(func() connector.Client); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(connector.Client) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetConnectorTokensClient provides a mock function with given fields: url -func (_m *ClientsProvider) GetConnectorTokensClient(url string) (connector.Client, error) { - ret := _m.Called(url) - - var r0 connector.Client - if rf, ok := ret.Get(0).(func(string) connector.Client); ok { - r0 = rf(url) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(connector.Client) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(url) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetDirectorClient provides a mock function with given fields: runtimeConfig -func (_m *ClientsProvider) GetDirectorClient(runtimeConfig config.RuntimeConfig) (director.DirectorClient, error) { - ret := _m.Called(runtimeConfig) - - var r0 director.DirectorClient - if rf, ok := ret.Get(0).(func(config.RuntimeConfig) director.DirectorClient); ok { - r0 = rf(runtimeConfig) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(director.DirectorClient) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(config.RuntimeConfig) error); ok { - r1 = rf(runtimeConfig) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} diff --git a/components/compass-runtime-agent/internal/compassconnection/connector.go b/components/compass-runtime-agent/internal/compassconnection/connector.go deleted file mode 100644 index 4b45c0b48f29..000000000000 --- a/components/compass-runtime-agent/internal/compassconnection/connector.go +++ /dev/null @@ -1,197 +0,0 @@ -package compassconnection - -import ( - "context" - "crypto/x509/pkix" - "strings" - - "github.com/kyma-incubator/compass/components/director/pkg/correlation" - - gqlschema "github.com/kyma-incubator/compass/components/connector/pkg/graphql/externalschema" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/certificates" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/compass" - "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/apis/compass/v1alpha1" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" -) - -type EstablishedConnection struct { - Credentials certificates.Credentials - ManagementInfo v1alpha1.ManagementInfo -} - -const ( - ConnectorTokenHeader = "Connector-Token" -) - -//go:generate mockery --name=Connector -type Connector interface { - EstablishConnection(ctx context.Context, connectorURL, token string) (EstablishedConnection, error) - MaintainConnection(ctx context.Context, renewCert bool, credentialsExist bool) (*certificates.Credentials, v1alpha1.ManagementInfo, error) -} - -func NewCompassConnector( - csrProvider certificates.CSRProvider, - clientsProvider compass.ClientsProvider, -) Connector { - return &compassConnector{ - csrProvider: csrProvider, - clientsProvider: clientsProvider, - } -} - -type compassConnector struct { - csrProvider certificates.CSRProvider - clientsProvider compass.ClientsProvider -} - -func (cc *compassConnector) EstablishConnection(ctx context.Context, connectorURL, token string) (EstablishedConnection, error) { - connection, err := cc.establishConnection(ctx, connectorURL, token) - requestID := correlation.HeadersFromContext(ctx)[correlation.RequestIDHeaderKey] - return connection, errors.Wrapf(err, "x-request-id: %s failed", requestID) -} - -func (cc *compassConnector) establishConnection(ctx context.Context, connectorURL, token string) (EstablishedConnection, error) { - requestID := correlation.HeadersFromContext(ctx)[correlation.RequestIDHeaderKey] - logger := logrus.WithFields(logrus.Fields{"x-request-id": requestID}) - - if connectorURL == "" { - return EstablishedConnection{}, errors.New("Failed to establish connection. Connector URL is empty") - } - - tokenSecuredConnectorClient, err := cc.clientsProvider.GetConnectorTokensClient(connectorURL) - if err != nil { - return EstablishedConnection{}, errors.Wrap(err, "Failed to prepare Connector Token-secured client") - } - - logger.Infof("Fetching configuration") - configuration, err := tokenSecuredConnectorClient.Configuration(ctx, connectorTokenHeader(token)) - if err != nil { - return EstablishedConnection{}, errors.Wrap(err, "Failed to fetch configuration") - } - - subject := parseSubject(configuration.CertificateSigningRequestInfo.Subject) - csr, key, err := cc.csrProvider.CreateCSR(subject) - if err != nil { - return EstablishedConnection{}, errors.Wrap(err, "Failed to generate CSR") - } - - logger.Infof("Signing CSR") - certResponse, err := tokenSecuredConnectorClient.SignCSR(ctx, csr, connectorTokenHeader(configuration.Token.Token)) - if err != nil { - return EstablishedConnection{}, errors.Wrap(err, "Failed to sign CSR") - } - - credentials, err := certificates.NewCredentials(key, certResponse) - if err != nil { - return EstablishedConnection{}, errors.Wrap(err, "Failed to parse certification response to credentials") - } - - return EstablishedConnection{ - Credentials: credentials, - ManagementInfo: toManagementInfo(configuration.ManagementPlaneInfo), - }, nil -} - -func (cc *compassConnector) MaintainConnection(ctx context.Context, renewCert bool, credentialsExist bool) (*certificates.Credentials, v1alpha1.ManagementInfo, error) { - certSecuredClient, err := cc.clientsProvider.GetConnectorCertSecuredClient() - if err != nil { - return nil, v1alpha1.ManagementInfo{}, errors.Wrap(err, "Failed to prepare Certificate-secured Connector client while checking connection") - } - - configuration, err := certSecuredClient.Configuration(ctx, nil) - if err != nil { - return nil, v1alpha1.ManagementInfo{}, errors.Wrap(err, "Failed to query Connection Configuration while checking connection") - } - - // Due to bug in Graphql client the response may not result in error but be empty - if err := validateConfigInfo(configuration.ManagementPlaneInfo); err != nil { - return nil, v1alpha1.ManagementInfo{}, err - } - - if !renewCert && credentialsExist { - return nil, toManagementInfo(configuration.ManagementPlaneInfo), nil - } - - subject := parseSubject(configuration.CertificateSigningRequestInfo.Subject) - csr, key, err := cc.csrProvider.CreateCSR(subject) - if err != nil { - return nil, v1alpha1.ManagementInfo{}, errors.Wrap(err, "Failed to create CSR while renewing connection") - } - - certResponse, err := certSecuredClient.SignCSR(ctx, csr, nil) - if err != nil { - return nil, v1alpha1.ManagementInfo{}, errors.Wrap(err, "Failed to sign CSR while renewing connection") - } - - renewedCredentials, err := certificates.NewCredentials(key, certResponse) - if err != nil { - return nil, v1alpha1.ManagementInfo{}, errors.Wrap(err, "Failed to parse certification response to credentials while renewing connection") - } - - return &renewedCredentials, toManagementInfo(configuration.ManagementPlaneInfo), nil -} - -func validateConfigInfo(configInfo *gqlschema.ManagementPlaneInfo) error { - if configInfo == nil { - return errors.New("Management info is empty") - } - - if configInfo.CertificateSecuredConnectorURL == nil || configInfo.DirectorURL == nil { - return errors.New("Connector URL or Director URL is empty") - } - - return nil -} - -func toManagementInfo(configInfo *gqlschema.ManagementPlaneInfo) v1alpha1.ManagementInfo { - if configInfo == nil { - return v1alpha1.ManagementInfo{} - } - - var directorURL = "" - if configInfo.DirectorURL != nil { - directorURL = *configInfo.DirectorURL - } - var certSecuredConnectorURL = "" - if configInfo.CertificateSecuredConnectorURL != nil { - certSecuredConnectorURL = *configInfo.CertificateSecuredConnectorURL - } - - return v1alpha1.ManagementInfo{ - DirectorURL: directorURL, - ConnectorURL: certSecuredConnectorURL, - } -} - -func connectorTokenHeader(token string) map[string]string { - return map[string]string{ - ConnectorTokenHeader: token, - } -} - -func parseSubject(plainSubject string) pkix.Name { - subjectInfo := extractSubject(plainSubject) - - return pkix.Name{ - CommonName: subjectInfo["CN"], - Country: []string{subjectInfo["C"]}, - Organization: []string{subjectInfo["O"]}, - OrganizationalUnit: []string{subjectInfo["OU"]}, - Locality: []string{subjectInfo["L"]}, - Province: []string{subjectInfo["ST"]}, - } -} - -func extractSubject(plainSubject string) map[string]string { - result := map[string]string{} - - segments := strings.Split(plainSubject, ",") - - for _, segment := range segments { - parts := strings.Split(segment, "=") - result[parts[0]] = parts[1] - } - - return result -} diff --git a/components/compass-runtime-agent/internal/compassconnection/controller.go b/components/compass-runtime-agent/internal/compassconnection/controller.go deleted file mode 100644 index e476e28a010d..000000000000 --- a/components/compass-runtime-agent/internal/compassconnection/controller.go +++ /dev/null @@ -1,204 +0,0 @@ -package compassconnection - -import ( - "context" - "time" - - "github.com/google/uuid" - "github.com/kyma-incubator/compass/components/director/pkg/correlation" - "github.com/kyma-incubator/compass/components/director/pkg/str" - "github.com/sirupsen/logrus" - "k8s.io/apimachinery/pkg/api/errors" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/controller" - "sigs.k8s.io/controller-runtime/pkg/handler" - "sigs.k8s.io/controller-runtime/pkg/manager" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - "sigs.k8s.io/controller-runtime/pkg/source" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/config" - "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/apis/compass/v1alpha1" -) - -const ( - controllerName = "compass-connection-controller" -) - -type Client interface { - Get(ctx context.Context, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error - Update(ctx context.Context, obj client.Object, opts ...client.UpdateOption) error - Delete(ctx context.Context, obj client.Object, opts ...client.DeleteOption) error -} - -// Reconciler reconciles a CompassConnection object -type Reconciler struct { - client Client - supervisor Supervisor - - minimalConfigSyncTime time.Duration - - log *logrus.Entry - runtimeID string - configProvider config.Provider -} - -func InitCompassConnectionController( - mgr manager.Manager, - supervisior Supervisor, - minimalConfigSyncTime time.Duration, - configProvider config.Provider) error { - - reconciler := newReconciler(mgr.GetClient(), supervisior, minimalConfigSyncTime, configProvider) - - return startController(mgr, reconciler) -} - -func startController(mgr manager.Manager, reconciler reconcile.Reconciler) error { - c, err := controller.New(controllerName, mgr, controller.Options{Reconciler: reconciler}) - if err != nil { - return err - } - - return c.Watch(&source.Kind{Type: &v1alpha1.CompassConnection{}}, &handler.EnqueueRequestForObject{}) -} - -func newReconciler(client Client, supervisior Supervisor, minimalConfigSyncTime time.Duration, configProvider config.Provider) reconcile.Reconciler { - return &Reconciler{ - client: client, - supervisor: supervisior, - minimalConfigSyncTime: minimalConfigSyncTime, - log: logrus.WithField("Controller", "CompassConnection"), - configProvider: configProvider, - } -} - -func (r *Reconciler) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) { - - if r.runtimeID == "" { - runtimeConfig, err := r.configProvider.GetRuntimeConfig() - if err == nil { - r.runtimeID = runtimeConfig.RuntimeId - } - } - - correlationID := r.runtimeID + "_" + uuid.New().String() - logFields := logrus.Fields{ - "CompassConnection": request.Name, - correlation.RequestIDHeaderKey: correlationID, - } - log := r.log.WithFields(logFields) - ctx = correlation.SaveCorrelationIDHeaderToContext(ctx, str.Ptr(correlation.RequestIDHeaderKey), str.Ptr(correlationID)) - - connection, err := r.getConnection(ctx, log, request) - if err != nil { - return reconcile.Result{}, err - } - - if connection == nil { - _, err := r.initConnection(ctx, log) - return reconcile.Result{}, err - } - - // Make sure the minimal time passed since last Compass Connection synchronization. - // This allows to rate limit Compass calls - if skipConnectionSync(connection, log, r.minimalConfigSyncTime) { - return reconcile.Result{}, nil - } - - if connection.Failed() { - _, err := r.initConnection(ctx, log) - return reconcile.Result{}, err - } - - if err := r.ensureCertificateIsValid(ctx, connection, log); err != nil { - return reconcile.Result{}, err - } - - log.Info("Trying to connect to Compass and apply Runtime configuration...") - - // Make sure the minimal time passed since last Application synchronization. - // This allows to rate limit Compass calls - if skipApplicationSync(connection, log, r.minimalConfigSyncTime) { - return reconcile.Result{}, nil - } - - return reconcile.Result{}, r.synchronizeApplications(ctx, connection, log) -} - -func (r *Reconciler) getConnection(ctx context.Context, log *logrus.Entry, request reconcile.Request) (*v1alpha1.CompassConnection, error) { - instance := &v1alpha1.CompassConnection{} - err := r.client.Get(ctx, request.NamespacedName, instance) - if err != nil { - if errors.IsNotFound(err) { - log.Info("Compass Connection deleted") - return nil, nil - } - - log.Info("Failed to read Compass Connection.") - return nil, err - } - - return instance, nil -} - -func (r *Reconciler) initConnection(ctx context.Context, log *logrus.Entry) (*v1alpha1.CompassConnection, error) { - log.Info("Trying to initialize new connection...") - - instance, err := r.supervisor.InitializeCompassConnection(ctx) - if err != nil { - log.Errorf("Failed to initialize Compass Connection: %s", err.Error()) - return nil, err - } - - log.Infof("Attempt to initialize Compass Connection ended with status: %s", instance.Status) - return instance, nil -} - -func (r *Reconciler) synchronizeApplications(ctx context.Context, connection *v1alpha1.CompassConnection, log *logrus.Entry) error { - synchronized, err := r.supervisor.SynchronizeWithCompass(ctx, connection) - if err != nil { - log.Errorf("Failed to synchronize with Compass: %s", err.Error()) - return err - } - - log.Infof("Synchronization finished. Compass Connection status: %s", synchronized.Status) - return nil -} - -func (r *Reconciler) ensureCertificateIsValid(ctx context.Context, connection *v1alpha1.CompassConnection, log *logrus.Entry) error { - log.Infof("Attempting to maintain connection with Compass...") - err := r.supervisor.MaintainCompassConnection(ctx, connection) - - if err != nil { - log.Errorf("Failed to maintain connection with Compass: %s", err.Error()) - return err - } - - return nil -} - -func skipConnectionSync(connection *v1alpha1.CompassConnection, log *logrus.Entry, minimalConfigSyncTime time.Duration) bool { - if connection.Spec.ResyncNow || connection.Status.ConnectionStatus == nil { - return false - } - timeSinceLastConnAttempt := time.Now().Unix() - connection.Status.ConnectionStatus.LastSync.Unix() - - if timeSinceLastConnAttempt < int64(minimalConfigSyncTime.Seconds()) { - log.Infof("Skipping connection initialization/maintenance. Minimal resync time not passed. Last attempt: %v", connection.Status.ConnectionStatus.LastSync) - return true - } - return false -} - -func skipApplicationSync(connection *v1alpha1.CompassConnection, log *logrus.Entry, minimalConfigSyncTime time.Duration) bool { - if connection.Spec.ResyncNow || connection.Status.SynchronizationStatus == nil { - return false - } - timeSinceLastSyncAttempt := time.Now().Unix() - connection.Status.SynchronizationStatus.LastAttempt.Unix() - - if timeSinceLastSyncAttempt < int64(minimalConfigSyncTime.Seconds()) { - log.Infof("Skipping application synchronization. Minimal resync time not passed. Last attempt: %v", connection.Status.SynchronizationStatus.LastAttempt) - return true - } - return false -} diff --git a/components/compass-runtime-agent/internal/compassconnection/init.go b/components/compass-runtime-agent/internal/compassconnection/init.go deleted file mode 100644 index 333a17d041cd..000000000000 --- a/components/compass-runtime-agent/internal/compassconnection/init.go +++ /dev/null @@ -1,64 +0,0 @@ -package compassconnection - -import ( - "time" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/compass/cache" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/compass/director" - - "github.com/pkg/errors" - - "sigs.k8s.io/controller-runtime/pkg/manager" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/certificates" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/compass" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/config" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma" - "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/client/clientset/versioned/typed/compass/v1alpha1" - - "k8s.io/client-go/rest" -) - -type DependencyConfig struct { - K8sConfig *rest.Config - ControllerManager manager.Manager - - ClientsProvider compass.ClientsProvider - CredentialsManager certificates.Manager - SynchronizationService kyma.Service - ConfigProvider config.Provider - ConnectionDataCache cache.ConnectionDataCache - - RuntimeURLsConfig director.RuntimeURLsConfig - CertValidityRenewalThreshold float64 - MinimalCompassSyncTime time.Duration -} - -func (config DependencyConfig) InitializeController() (Supervisor, error) { - compassConnectionCRClient, err := v1alpha1.NewForConfig(config.K8sConfig) - if err != nil { - return nil, errors.Wrap(err, "Unable to setup Compass Connection CR client") - } - - csrProvider := certificates.NewCSRProvider() - compassConnector := NewCompassConnector(csrProvider, config.ClientsProvider) - - connectionSupervisor := NewSupervisor( - compassConnector, - compassConnectionCRClient.CompassConnections(), - config.CredentialsManager, - config.ClientsProvider, - config.SynchronizationService, - config.ConfigProvider, - config.CertValidityRenewalThreshold, - config.MinimalCompassSyncTime, - config.RuntimeURLsConfig, - config.ConnectionDataCache) - - if err := InitCompassConnectionController(config.ControllerManager, connectionSupervisor, config.MinimalCompassSyncTime, config.ConfigProvider); err != nil { - return nil, errors.Wrap(err, "Unable to register controllers to the manager") - } - - return connectionSupervisor, nil -} diff --git a/components/compass-runtime-agent/internal/compassconnection/mocks/CRManager.go b/components/compass-runtime-agent/internal/compassconnection/mocks/CRManager.go deleted file mode 100644 index 05fe7ddfe1e1..000000000000 --- a/components/compass-runtime-agent/internal/compassconnection/mocks/CRManager.go +++ /dev/null @@ -1,100 +0,0 @@ -// Code generated by mockery v2.10.0. DO NOT EDIT. - -package mocks - -import ( - context "context" - - mock "github.com/stretchr/testify/mock" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - v1alpha1 "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/apis/compass/v1alpha1" -) - -// CRManager is an autogenerated mock type for the CRManager type -type CRManager struct { - mock.Mock -} - -// Create provides a mock function with given fields: ctx, cc, options -func (_m *CRManager) Create(ctx context.Context, cc *v1alpha1.CompassConnection, options v1.CreateOptions) (*v1alpha1.CompassConnection, error) { - ret := _m.Called(ctx, cc, options) - - var r0 *v1alpha1.CompassConnection - if rf, ok := ret.Get(0).(func(context.Context, *v1alpha1.CompassConnection, v1.CreateOptions) *v1alpha1.CompassConnection); ok { - r0 = rf(ctx, cc, options) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*v1alpha1.CompassConnection) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(context.Context, *v1alpha1.CompassConnection, v1.CreateOptions) error); ok { - r1 = rf(ctx, cc, options) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// Delete provides a mock function with given fields: ctx, name, options -func (_m *CRManager) Delete(ctx context.Context, name string, options v1.DeleteOptions) error { - ret := _m.Called(ctx, name, options) - - var r0 error - if rf, ok := ret.Get(0).(func(context.Context, string, v1.DeleteOptions) error); ok { - r0 = rf(ctx, name, options) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// Get provides a mock function with given fields: ctx, name, options -func (_m *CRManager) Get(ctx context.Context, name string, options v1.GetOptions) (*v1alpha1.CompassConnection, error) { - ret := _m.Called(ctx, name, options) - - var r0 *v1alpha1.CompassConnection - if rf, ok := ret.Get(0).(func(context.Context, string, v1.GetOptions) *v1alpha1.CompassConnection); ok { - r0 = rf(ctx, name, options) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*v1alpha1.CompassConnection) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(context.Context, string, v1.GetOptions) error); ok { - r1 = rf(ctx, name, options) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// Update provides a mock function with given fields: ctx, cc, options -func (_m *CRManager) Update(ctx context.Context, cc *v1alpha1.CompassConnection, options v1.UpdateOptions) (*v1alpha1.CompassConnection, error) { - ret := _m.Called(ctx, cc, options) - - var r0 *v1alpha1.CompassConnection - if rf, ok := ret.Get(0).(func(context.Context, *v1alpha1.CompassConnection, v1.UpdateOptions) *v1alpha1.CompassConnection); ok { - r0 = rf(ctx, cc, options) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*v1alpha1.CompassConnection) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(context.Context, *v1alpha1.CompassConnection, v1.UpdateOptions) error); ok { - r1 = rf(ctx, cc, options) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} diff --git a/components/compass-runtime-agent/internal/compassconnection/mocks/Connector.go b/components/compass-runtime-agent/internal/compassconnection/mocks/Connector.go deleted file mode 100644 index 7693352b9b44..000000000000 --- a/components/compass-runtime-agent/internal/compassconnection/mocks/Connector.go +++ /dev/null @@ -1,70 +0,0 @@ -// Code generated by mockery v2.10.0. DO NOT EDIT. - -package mocks - -import ( - certificates "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/certificates" - compassconnection "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/compassconnection" - - context "context" - - mock "github.com/stretchr/testify/mock" - - v1alpha1 "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/apis/compass/v1alpha1" -) - -// Connector is an autogenerated mock type for the Connector type -type Connector struct { - mock.Mock -} - -// EstablishConnection provides a mock function with given fields: ctx, connectorURL, token -func (_m *Connector) EstablishConnection(ctx context.Context, connectorURL string, token string) (compassconnection.EstablishedConnection, error) { - ret := _m.Called(ctx, connectorURL, token) - - var r0 compassconnection.EstablishedConnection - if rf, ok := ret.Get(0).(func(context.Context, string, string) compassconnection.EstablishedConnection); ok { - r0 = rf(ctx, connectorURL, token) - } else { - r0 = ret.Get(0).(compassconnection.EstablishedConnection) - } - - var r1 error - if rf, ok := ret.Get(1).(func(context.Context, string, string) error); ok { - r1 = rf(ctx, connectorURL, token) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// MaintainConnection provides a mock function with given fields: ctx, renewCert, credentialsExist -func (_m *Connector) MaintainConnection(ctx context.Context, renewCert bool, credentialsExist bool) (*certificates.Credentials, v1alpha1.ManagementInfo, error) { - ret := _m.Called(ctx, renewCert, credentialsExist) - - var r0 *certificates.Credentials - if rf, ok := ret.Get(0).(func(context.Context, bool, bool) *certificates.Credentials); ok { - r0 = rf(ctx, renewCert, credentialsExist) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*certificates.Credentials) - } - } - - var r1 v1alpha1.ManagementInfo - if rf, ok := ret.Get(1).(func(context.Context, bool, bool) v1alpha1.ManagementInfo); ok { - r1 = rf(ctx, renewCert, credentialsExist) - } else { - r1 = ret.Get(1).(v1alpha1.ManagementInfo) - } - - var r2 error - if rf, ok := ret.Get(2).(func(context.Context, bool, bool) error); ok { - r2 = rf(ctx, renewCert, credentialsExist) - } else { - r2 = ret.Error(2) - } - - return r0, r1, r2 -} diff --git a/components/compass-runtime-agent/internal/compassconnection/mocks/Supervisor.go b/components/compass-runtime-agent/internal/compassconnection/mocks/Supervisor.go deleted file mode 100644 index 388e8afd36dd..000000000000 --- a/components/compass-runtime-agent/internal/compassconnection/mocks/Supervisor.go +++ /dev/null @@ -1,75 +0,0 @@ -// Code generated by mockery v2.10.0. DO NOT EDIT. - -package mocks - -import ( - context "context" - - v1alpha1 "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/apis/compass/v1alpha1" - mock "github.com/stretchr/testify/mock" -) - -// Supervisor is an autogenerated mock type for the Supervisor type -type Supervisor struct { - mock.Mock -} - -// InitializeCompassConnection provides a mock function with given fields: ctx -func (_m *Supervisor) InitializeCompassConnection(ctx context.Context) (*v1alpha1.CompassConnection, error) { - ret := _m.Called(ctx) - - var r0 *v1alpha1.CompassConnection - if rf, ok := ret.Get(0).(func(context.Context) *v1alpha1.CompassConnection); ok { - r0 = rf(ctx) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*v1alpha1.CompassConnection) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(context.Context) error); ok { - r1 = rf(ctx) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// MaintainCompassConnection provides a mock function with given fields: ctx, connection -func (_m *Supervisor) MaintainCompassConnection(ctx context.Context, connection *v1alpha1.CompassConnection) error { - ret := _m.Called(ctx, connection) - - var r0 error - if rf, ok := ret.Get(0).(func(context.Context, *v1alpha1.CompassConnection) error); ok { - r0 = rf(ctx, connection) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// SynchronizeWithCompass provides a mock function with given fields: ctx, connection -func (_m *Supervisor) SynchronizeWithCompass(ctx context.Context, connection *v1alpha1.CompassConnection) (*v1alpha1.CompassConnection, error) { - ret := _m.Called(ctx, connection) - - var r0 *v1alpha1.CompassConnection - if rf, ok := ret.Get(0).(func(context.Context, *v1alpha1.CompassConnection) *v1alpha1.CompassConnection); ok { - r0 = rf(ctx, connection) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*v1alpha1.CompassConnection) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(context.Context, *v1alpha1.CompassConnection) error); ok { - r1 = rf(ctx, connection) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} diff --git a/components/compass-runtime-agent/internal/compassconnection/package_main_test.go b/components/compass-runtime-agent/internal/compassconnection/package_main_test.go deleted file mode 100644 index 46bea7b05490..000000000000 --- a/components/compass-runtime-agent/internal/compassconnection/package_main_test.go +++ /dev/null @@ -1,124 +0,0 @@ -package compassconnection - -import ( - "crypto/rsa" - "encoding/base64" - "os" - "path/filepath" - "testing" - - gqlschema "github.com/kyma-incubator/compass/components/connector/pkg/graphql/externalschema" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/certificates" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/testutil" - compassCRClientset "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/client/clientset/versioned/typed/compass/v1alpha1" - - "github.com/sirupsen/logrus" - - "github.com/pkg/errors" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/apis/compass/v1alpha1" - - "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/rest" - "sigs.k8s.io/controller-runtime/pkg/envtest" -) - -var cfg *rest.Config -var testEnv *envtest.Environment - -var compassConnectionCRClient compassCRClientset.CompassConnectionInterface - -var ( - crtChain []byte - clientCRT []byte - caCRT []byte - clientKey *rsa.PrivateKey - credentials certificates.Credentials -) - -var ( - connectorCertResponse gqlschema.CertificationResult -) - -func TestMain(m *testing.M) { - os.Exit(runTests(m)) -} - -func runTests(m *testing.M) int { - err := setupEnv() - if err != nil { - logrus.Errorf("Failed to setup test environment: %s", err.Error()) - os.Exit(1) - } - defer func() { - err := testEnv.Stop() - if err != nil { - logrus.Errorf("error while deleting Compass Connection: %s", err.Error()) - } - }() - - compassClientset, err := compassCRClientset.NewForConfig(cfg) - if err != nil { - logrus.Errorf("Failed to setup CompassConnection clientset: %s", err.Error()) - os.Exit(1) - } - - compassConnectionCRClient = compassClientset.CompassConnections() - - err = setupCredentials() - if err != nil { - logrus.Errorf("Failed to setup credentials: %s", err.Error()) - os.Exit(1) - } - - return m.Run() -} - -func setupEnv() error { - testEnv = &envtest.Environment{ - CRDDirectoryPaths: []string{filepath.Join("testdata")}, - } - - var err error - cfg, err = testEnv.Start() - if err != nil { - return errors.Wrap(err, "Failed to start test environment") - } - - err = v1alpha1.AddToScheme(scheme.Scheme) - if err != nil { - return errors.Wrap(err, "Failed to add to schema") - } - - return nil -} - -func setupCredentials() error { - certsData, err := testutil.LoadCertsTestData("../testutil/testdata") - if err != nil { - return errors.Wrap(err, "Failed to load certs test data") - } - - crtChain = certsData.CertificateChain - clientCRT = certsData.ClientCertificate - caCRT = certsData.CACertificate - clientKey, err = certificates.ParsePrivateKey(certsData.ClientKey) - if err != nil { - return errors.Wrap(err, "Failed to parse private key") - } - - connectorCertResponse = gqlschema.CertificationResult{ - CertificateChain: base64.StdEncoding.EncodeToString(crtChain), - CaCertificate: base64.StdEncoding.EncodeToString(caCRT), - ClientCertificate: base64.StdEncoding.EncodeToString(clientCRT), - } - - credentials, err = certificates.NewCredentials(clientKey, connectorCertResponse) - if err != nil { - return errors.Wrap(err, "Failed to create credentials") - } - - return nil -} diff --git a/components/compass-runtime-agent/internal/compassconnection/package_test.go b/components/compass-runtime-agent/internal/compassconnection/package_test.go deleted file mode 100644 index 2829d39d519f..000000000000 --- a/components/compass-runtime-agent/internal/compassconnection/package_test.go +++ /dev/null @@ -1,714 +0,0 @@ -package compassconnection - -import ( - "context" - "errors" - "sync" - "testing" - "time" - - "github.com/kyma-incubator/compass/components/director/pkg/str" - - "github.com/kyma-incubator/compass/components/director/pkg/correlation" - - k8serrors "k8s.io/apimachinery/pkg/api/errors" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/compass/cache" - - "github.com/kyma-incubator/compass/components/director/pkg/graphql" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/compass/director" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/apperrors" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/certificates" - - "github.com/stretchr/testify/assert" - - certsMocks "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/certificates/mocks" - directorMocks "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/compass/director/mocks" - compassMocks "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/compass/mocks" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/config" - configMocks "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/config/mocks" - kymaMocks "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/mocks" - kymaModel "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/model" - - "github.com/stretchr/testify/mock" - - gqlschema "github.com/kyma-incubator/compass/components/connector/pkg/graphql/externalschema" - - connectorMocks "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/compass/connector/mocks" - - "sigs.k8s.io/controller-runtime/pkg/manager" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/apis/compass/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - "github.com/stretchr/testify/require" -) - -const ( - compassConnectionName = "compass-connection" - token = "token" - runtimeId = "abcd-efgh-ijkl" - - syncPeriod = 2 * time.Second - minimalConfigSyncTime = 4 * time.Second - - checkInterval = 2 * time.Second - testTimeout = 20 * time.Second -) - -var ( - connectorTokenHeaders = map[string]string{ - ConnectorTokenHeader: token, - } - connectorTokenHeadersFunc = mock.MatchedBy(func(input map[string]string) bool { - for k, v := range connectorTokenHeaders { - if input[k] != v { - return false - } - } - return true - }) - nilHeaders map[string]string - - connectorURL = "https://connector.com" - directorURL = "https://director.com" - certSecuredConnectorURL = "https://cert-connector.com" - - connectorConfigurationResponse = gqlschema.Configuration{ - Token: &gqlschema.Token{Token: token}, - CertificateSigningRequestInfo: &gqlschema.CertificateSigningRequestInfo{ - Subject: "O=Org,OU=OrgUnit,L=locality,ST=province,C=DE,CN=test", - KeyAlgorithm: "rsa2048", - }, - ManagementPlaneInfo: &gqlschema.ManagementPlaneInfo{ - DirectorURL: &directorURL, - CertificateSecuredConnectorURL: &certSecuredConnectorURL, - }, - } - - connectionConfig = config.ConnectionConfig{ - Token: token, - ConnectorURL: connectorURL, - } - - runtimeConfig = config.RuntimeConfig{RuntimeId: runtimeId} - - runtimeURLsConfig = director.RuntimeURLsConfig{ - EventsURL: "https://gateway.kyma.local", - ConsoleURL: "https://console.kyma.local", - } - - runtimeLabels = graphql.Labels{ - "events": runtimeURLsConfig.EventsURL, - "console": runtimeURLsConfig.ConsoleURL, - } - - kymaModelApps = []kymaModel.Application{{Name: "App-1", ID: "abcd-efgh"}} - testCtx = correlation.SaveCorrelationIDHeaderToContext(context.Background(), str.Ptr(correlation.RequestIDHeaderKey), str.Ptr("test-correlation-id-123")) - - operationResults = []kyma.Result{{ApplicationName: "App-1", ApplicationID: "abcd-efgh", Operation: kyma.Create}} - requestIDCtxMatcher = mock.MatchedBy(func(ctx context.Context) bool { - if val := ctx.Value(correlation.HeadersContextKey); val != nil { - if h, ok := val.(correlation.Headers); ok { - _, res := h[correlation.RequestIDHeaderKey] - return res - } - } - return false - }) -) - -func TestCompassConnectionController(t *testing.T) { - - syncPeriodTime := syncPeriod - ctrlManager, err := manager.New(cfg, manager.Options{SyncPeriod: &syncPeriodTime}) - require.NoError(t, err) - - // Credentials manager - credentialsManagerMock := &certsMocks.Manager{} - credentialsManagerMock.On("PreserveCredentials", mock.AnythingOfType("certificates.Credentials")).Run(func(args mock.Arguments) { - credentials, ok := args[0].(certificates.Credentials) - assert.True(t, ok) - assert.NotEmpty(t, credentials) - }).Return(nil) - credentialsManagerMock.On("CredentialsExist").Return(true, nil) - - // Config provider - configProviderMock := configProviderMock() - // Connector clients - tokensConnectorClientMock := connectorTokensClientMock(requestIDCtxMatcher) - certsConnectorClientMock := connectorCertClientMock(requestIDCtxMatcher) - // Director config client - configurationClientMock := &directorMocks.DirectorClient{} - configurationClientMock.On("FetchConfiguration", requestIDCtxMatcher).Return(kymaModelApps, graphql.Labels{}, nil) - configurationClientMock.On("SetURLsLabels", requestIDCtxMatcher, runtimeURLsConfig, graphql.Labels{}).Return(runtimeLabels, nil) - // Clients provider - clientsProviderMock := clientsProviderMock(configurationClientMock, tokensConnectorClientMock, certsConnectorClientMock) - // Sync service - synchronizationServiceMock := &kymaMocks.Service{} - synchronizationServiceMock.On("Apply", kymaModelApps).Return(operationResults, nil) - - connectionDataCache := cache.NewConnectionDataCache() - connectionDataCache.AddSubscriber(func(data cache.ConnectionData) error { - assert.NotEmpty(t, data.Certificate) - assert.Equal(t, certSecuredConnectorURL, data.ConnectorURL) - assert.Equal(t, directorURL, data.DirectorURL) - return nil - }) - - var baseDependencies = DependencyConfig{ - K8sConfig: cfg, - ControllerManager: ctrlManager, - - ClientsProvider: clientsProviderMock, - CredentialsManager: credentialsManagerMock, - SynchronizationService: synchronizationServiceMock, - ConfigProvider: configProviderMock, - CertValidityRenewalThreshold: 0.3, - MinimalCompassSyncTime: minimalConfigSyncTime, - ConnectionDataCache: connectionDataCache, - - RuntimeURLsConfig: runtimeURLsConfig, - } - - supervisor, err := baseDependencies.InitializeController() - require.NoError(t, err) - - defer func() { - err := compassConnectionCRClient.Delete(context.Background(), compassConnectionName, v1.DeleteOptions{}) - if err != nil { - t.Logf("error while deleting Compass Connection: %s", err.Error()) - } - }() - cancelFunc, _ := StartTestManager(t, ctrlManager) - defer cancelFunc() - - connection, err := supervisor.InitializeCompassConnection(testCtx) - require.NoError(t, err) - assert.NotEmpty(t, connection) - - t.Run("Compass Connection should be synchronized after few seconds", func(t *testing.T) { - // when - waitForResynchronization() - - // then - assertCompassConnectionState(t, v1alpha1.Synchronized) - assertConnectionStatusSet(t) - assertManagementInfoSetInCR(t) - - mock.AssertExpectationsForObjects(t, - tokensConnectorClientMock, - configurationClientMock, - synchronizationServiceMock, - clientsProviderMock, - configProviderMock, - credentialsManagerMock) - certsConnectorClientMock.AssertCalled(t, "Configuration", requestIDCtxMatcher, nilHeaders) - certsConnectorClientMock.AssertNotCalled(t, "SignCSR", requestIDCtxMatcher, mock.AnythingOfType("string"), nilHeaders) - }) - - t.Run("Compass Connection should be reinitialized if deleted", func(t *testing.T) { - // given - err := compassConnectionCRClient.Delete(context.Background(), compassConnectionName, v1.DeleteOptions{}) - require.NoError(t, err) - - // then - err = waitFor(checkInterval, testTimeout, func() bool { - return isConnectionInState(v1alpha1.Synchronized) - }) - require.NoError(t, err) - assertConnectionStatusSet(t) - assertManagementInfoSetInCR(t) - - mock.AssertExpectationsForObjects(t, - tokensConnectorClientMock, - configurationClientMock, - synchronizationServiceMock, - clientsProviderMock, - configProviderMock, - credentialsManagerMock) - certsConnectorClientMock.AssertCalled(t, "Configuration", requestIDCtxMatcher, nilHeaders) - certsConnectorClientMock.AssertNotCalled(t, "SignCSR", requestIDCtxMatcher, mock.AnythingOfType("string"), nilHeaders) - }) - - t.Run("Should not reinitialized connection if connection is in Synchronized state", func(t *testing.T) { - // when - credentialsManagerMock.On("GetClientCredentials").Return(credentials.ClientCredentials, nil) - - connection, err := supervisor.InitializeCompassConnection(context.Background()) - - // then - require.NoError(t, err) - assert.Equal(t, v1alpha1.Synchronized, connection.Status.State) - }) - - t.Run("Should renew certificate if RefreshCredentialsNow set to true", func(t *testing.T) { - // given - connectedConnection, err := compassConnectionCRClient.Get(context.Background(), compassConnectionName, v1.GetOptions{}) - require.NoError(t, err) - - connectedConnection.Spec.RefreshCredentialsNow = true - - // when - _, err = compassConnectionCRClient.Update(context.Background(), connectedConnection, v1.UpdateOptions{}) - require.NoError(t, err) - - err = waitFor(checkInterval, testTimeout, func() bool { - fakeT := &testing.T{} - called := certsConnectorClientMock.AssertCalled(fakeT, "SignCSR", requestIDCtxMatcher, mock.AnythingOfType("string"), nilHeaders) - return called - }) - - // then - require.NoError(t, err) - require.NoError(t, waitForResourceUpdate(v1alpha1.Synchronized)) - - assertCertificateRenewed(t) - assertManagementInfoSetInCR(t) - certsConnectorClientMock.AssertCalled(t, "SignCSR", requestIDCtxMatcher, mock.AnythingOfType("string"), nilHeaders) - }) - - t.Run("Compass Connection should be in MetadataUpdateFailed state if failed to set labels on Runtime", func(t *testing.T) { - // given - clearMockCalls(&configurationClientMock.Mock) - configurationClientMock.On("FetchConfiguration", requestIDCtxMatcher).Return(kymaModelApps, graphql.Labels{}, nil) - configurationClientMock.On("SetURLsLabels", requestIDCtxMatcher, runtimeURLsConfig, graphql.Labels{}).Return(nil, apperrors.Internal("error")) - - // when - err = waitFor(checkInterval, testTimeout, func() bool { - return mockFunctionCalled(&configurationClientMock.Mock, "SetURLsLabels", requestIDCtxMatcher, runtimeURLsConfig, graphql.Labels{}) - }) - - // then - require.NoError(t, err) - require.NoError(t, waitForResourceUpdate(v1alpha1.MetadataUpdateFailed)) - assertManagementInfoSetInCR(t) - - clearMockCalls(&configurationClientMock.Mock) - // restore previous director mock configuration to not interfere with other tests - configurationClientMock.On("FetchConfiguration", requestIDCtxMatcher).Return(kymaModelApps, graphql.Labels{}, nil) - configurationClientMock.On("SetURLsLabels", requestIDCtxMatcher, runtimeURLsConfig, graphql.Labels{}).Return(runtimeLabels, nil) - }) - - t.Run("Compass Connection should be in ResourceApplicationFailed state if failed to apply resources", func(t *testing.T) { - // given - clearMockCalls(&synchronizationServiceMock.Mock) - synchronizationServiceMock.On("Apply", kymaModelApps).Return(nil, apperrors.Internal("error")) - - // when - err = waitFor(checkInterval, testTimeout, func() bool { - return mockFunctionCalled(&synchronizationServiceMock.Mock, "Apply", kymaModelApps) - }) - - // then - require.NoError(t, err) - require.NoError(t, waitForResourceUpdate(v1alpha1.ResourceApplicationFailed)) - assertManagementInfoSetInCR(t) - assertSynchronizationStatusError(t) - - // restore previous sync service mock configuration to not interfere with other tests - clearMockCalls(&synchronizationServiceMock.Mock) - synchronizationServiceMock.On("Apply", kymaModelApps).Return(operationResults, nil) - }) - - t.Run("Compass Connection should be in SynchronizationFailed state if failed to fetch configuration from Director", func(t *testing.T) { - // given - clearMockCalls(&configurationClientMock.Mock) - configurationClientMock.On("FetchConfiguration", requestIDCtxMatcher).Return(nil, nil, errors.New("error")) - - // when - err = waitFor(checkInterval, testTimeout, func() bool { - return mockFunctionCalled(&configurationClientMock.Mock, "FetchConfiguration", requestIDCtxMatcher) - }) - - // then - require.NoError(t, err) - require.NoError(t, waitForResourceUpdate(v1alpha1.SynchronizationFailed)) - assertManagementInfoSetInCR(t) - assertSynchronizationStatusError(t) - - // restore previous director mock configuration to not interfere with other tests - clearMockCalls(&configurationClientMock.Mock) - configurationClientMock.On("FetchConfiguration", requestIDCtxMatcher).Return(kymaModelApps, graphql.Labels{}, nil) - configurationClientMock.On("SetURLsLabels", requestIDCtxMatcher, runtimeURLsConfig, graphql.Labels{}).Return(runtimeLabels, nil) - }) - - t.Run("Compass Connection should be in SynchronizationFailed state if failed create Director config client", func(t *testing.T) { - // given - assertRecreateSynchronizedConnection(t) - require.Equal(t, true, isConnectionInState(v1alpha1.Synchronized)) - clientsProviderMock.ExpectedCalls = nil - clientsProviderMock.Calls = nil - clientsProviderMock.On("GetConnectorTokensClient", connectorURL).Return(tokensConnectorClientMock, nil) - clientsProviderMock.On("GetConnectorCertSecuredClient").Return(certsConnectorClientMock, nil) - clientsProviderMock.On("GetDirectorClient", runtimeConfig).Return(nil, errors.New("error")) - - // when - err = waitFor(checkInterval, testTimeout, func() bool { - return mockFunctionCalled(&clientsProviderMock.Mock, "GetDirectorClient", runtimeConfig) - }) - - // then - require.NoError(t, err) - require.NoError(t, waitForResourceUpdate(v1alpha1.SynchronizationFailed)) - assertManagementInfoSetInCR(t) - assertSynchronizationStatusError(t) - }) - - t.Run("Compass Connection should be in SynchronizationFailed state if failed to read runtime configuration", func(t *testing.T) { - // given - configProviderMock.ExpectedCalls = nil - configProviderMock.Calls = nil - configProviderMock.On("GetConnectionConfig").Return(connectionConfig, nil) - configProviderMock.On("GetRuntimeConfig").Return(runtimeConfig, errors.New("error")) - - // when - err = waitFor(checkInterval, testTimeout, func() bool { - return mockFunctionCalled(&configProviderMock.Mock, "GetRuntimeConfig") - }) - - // then - require.NoError(t, err) - require.NoError(t, waitForResourceUpdate(v1alpha1.SynchronizationFailed)) - assertManagementInfoSetInCR(t) - assertSynchronizationStatusError(t) - }) - - t.Run("Compass Connection should be in ConnectionMaintenanceFailed if Management Info is empty and no error", func(t *testing.T) { - // given - certsConnectorClientMock.ExpectedCalls = nil - certsConnectorClientMock.On("Configuration", requestIDCtxMatcher, nilHeaders).Return(gqlschema.Configuration{ManagementPlaneInfo: nil}, nil) - - // when - err = waitFor(checkInterval, testTimeout, func() bool { - return mockFunctionCalled(&certsConnectorClientMock.Mock, "Configuration", requestIDCtxMatcher, nilHeaders) - }) - - // then - require.NoError(t, err) - require.NoError(t, waitForResourceUpdate(v1alpha1.ConnectionMaintenanceFailed)) - assertManagementInfoSetInCR(t) - assertConnectionStatusSet(t) - }) - - t.Run("Compass Connection should be in ConnectionMaintenanceFailed if failed to access Connector Configuration query", func(t *testing.T) { - // given - certsConnectorClientMock.ExpectedCalls = nil - certsConnectorClientMock.On("Configuration", requestIDCtxMatcher, nilHeaders).Return(gqlschema.Configuration{}, errors.New("error")) - - // when - err = waitFor(checkInterval, testTimeout, func() bool { - return mockFunctionCalled(&certsConnectorClientMock.Mock, "Configuration", requestIDCtxMatcher, nilHeaders) - }) - - // then - require.NoError(t, err) - require.NoError(t, waitForResourceUpdate(v1alpha1.ConnectionMaintenanceFailed)) - assertConnectionStatusSet(t) - }) - - t.Run("Compass Connection should be in ConnectionMaintenanceFailed state if failed create Cert secured client", func(t *testing.T) { - // given - clientsProviderMock.ExpectedCalls = nil - clientsProviderMock.On("GetConnectorCertSecuredClient").Return(nil, errors.New("error")) - - // when - err = waitFor(checkInterval, testTimeout, func() bool { - return mockFunctionCalled(&clientsProviderMock.Mock, "GetConnectorCertSecuredClient") - }) - - // then - require.NoError(t, err) - require.NoError(t, waitForResourceUpdate(v1alpha1.ConnectionMaintenanceFailed)) - assertConnectionStatusSet(t) - }) -} - -func TestFailedToInitializeConnection(t *testing.T) { - - syncPeriodTime := syncPeriod - ctrlManager, err := manager.New(cfg, manager.Options{SyncPeriod: &syncPeriodTime}) - require.NoError(t, err) - - // Connector token client - connectorTokenClientMock := connectorTokensClientMock(requestIDCtxMatcher) - // Config provider - configProviderMock := configProviderMock() - // Clients provider - clientsProviderMock := clientsProviderMock(nil, connectorTokenClientMock, nil) - - // Credentials manager - credentialsManagerMock := &certsMocks.Manager{} - - var baseDependencies = DependencyConfig{ - K8sConfig: cfg, - ControllerManager: ctrlManager, - - ClientsProvider: clientsProviderMock, - CredentialsManager: credentialsManagerMock, - SynchronizationService: nil, - ConfigProvider: configProviderMock, - CertValidityRenewalThreshold: 0.3, - MinimalCompassSyncTime: minimalConfigSyncTime, - } - - supervisor, err := baseDependencies.InitializeController() - require.NoError(t, err) - - defer func() { - err := compassConnectionCRClient.Delete(context.Background(), compassConnectionName, v1.DeleteOptions{}) - if err != nil { - t.Logf("error while deleting Compass Connection: %s", err.Error()) - } - }() - cancelFunc, _ := StartTestManager(t, ctrlManager) - defer cancelFunc() - - initConnectionIfNotExist := func() { - _, err := compassConnectionCRClient.Get(context.Background(), compassConnectionName, v1.GetOptions{}) - if err != nil { - if !k8serrors.IsNotFound(err) { - t.Fatalf("Failed to initialize Connection: %s", err.Error()) - } - - connection, err := supervisor.InitializeCompassConnection(testCtx) - require.NoError(t, err) - assert.NotEmpty(t, connection) - } - } - - for _, test := range []struct { - description string - setupFunc func() - waitFunction func() bool - }{ - { - description: "failed to preserve credentials", - setupFunc: func() { - credentialsManagerMock.Calls = nil - credentialsManagerMock.On("PreserveCredentials", mock.AnythingOfType("certificates.Credentials")).Return(errors.New("error")) - }, - waitFunction: func() bool { - return mockFunctionCalled(&credentialsManagerMock.Mock, "PreserveCredentials", mock.AnythingOfType("certificates.Credentials")) - }, - }, - { - description: "failed to sign CSR", - setupFunc: func() { - clearMockCalls(&connectorTokenClientMock.Mock) - connectorTokenClientMock.On("Configuration", requestIDCtxMatcher, connectorTokenHeadersFunc).Return(connectorConfigurationResponse, nil) - connectorTokenClientMock.On("SignCSR", requestIDCtxMatcher, mock.AnythingOfType("string"), connectorTokenHeadersFunc).Return(gqlschema.CertificationResult{}, errors.New("error")) - }, - waitFunction: func() bool { - return mockFunctionCalled(&connectorTokenClientMock.Mock, "SignCSR", mock.AnythingOfType("string"), connectorTokenHeaders) - }, - }, - { - description: "failed to fetch Configuration", - setupFunc: func() { - clearMockCalls(&connectorTokenClientMock.Mock) - connectorTokenClientMock.On("Configuration", requestIDCtxMatcher, connectorTokenHeadersFunc).Return(gqlschema.Configuration{}, errors.New("error")) - connectorTokenClientMock.On("SignCSR", requestIDCtxMatcher, mock.AnythingOfType("string"), connectorTokenHeadersFunc).Return(gqlschema.CertificationResult{}, errors.New("error")) - }, - waitFunction: func() bool { - return mockFunctionCalled(&connectorTokenClientMock.Mock, "Configuration", requestIDCtxMatcher, connectorTokenHeaders) - }, - }, - { - description: "failed to get Connector client", - setupFunc: func() { - clearMockCalls(&clientsProviderMock.Mock) - clientsProviderMock.On("GetConnectorTokensClient", connectorURL).Return(nil, errors.New("error")) - }, - waitFunction: func() bool { - return mockFunctionCalled(&connectorTokenClientMock.Mock, "GetConnectorTokensClient", connectorURL) - }, - }, - { - description: "connector URL is empty", - setupFunc: func() { - clearMockCalls(&configProviderMock.Mock) - configProviderMock.On("GetConnectionConfig").Return(config.ConnectionConfig{Token: token}, nil) - }, - waitFunction: func() bool { - - return mockFunctionCalled(&configProviderMock.Mock, "GetConnectionConfig") - - }, - }, - { - description: "failed to get connection config", - setupFunc: func() { - clearMockCalls(&configProviderMock.Mock) - configProviderMock.On("GetConnectionConfig").Return(config.ConnectionConfig{}, errors.New("error")) - }, - waitFunction: func() bool { - fakeT := &testing.T{} - called := configProviderMock.AssertCalled(fakeT, "GetConnectionConfig") - return called - }, - }, - } { - t.Run("Compass Connection should be in ConnectionFailed state when "+test.description, func(t *testing.T) { - // given - test.setupFunc() - initConnectionIfNotExist() - - // when - test.waitFunction() - - // then - require.NoError(t, waitForResourceUpdate(v1alpha1.ConnectionFailed)) - }) - } -} - -func waitFor(interval, timeout time.Duration, isDone func() bool) error { - done := time.After(timeout) - - for { - if isDone() { - return nil - } - - select { - case <-done: - return errors.New("timeout waiting for condition") - default: - time.Sleep(interval) - } - } -} - -func clearMockCalls(mock *mock.Mock) { - mock.ExpectedCalls = nil - mock.Calls = nil -} - -func mockFunctionCalled(mock *mock.Mock, methodName string, arguments ...interface{}) bool { - fakeT := &testing.T{} - return mock.AssertCalled(fakeT, methodName, arguments...) -} - -func waitForResynchronization() { - time.Sleep(minimalConfigSyncTime * 2) -} - -func waitForResourceUpdate(expectedState v1alpha1.ConnectionState) error { - // Initial sleep in case if Connection will change from expected state to different - time.Sleep(2 * time.Second) - - return waitFor(1*time.Second, 4*time.Second, func() bool { - return isConnectionInState(expectedState) - }) -} - -func isConnectionInState(expectedState v1alpha1.ConnectionState) bool { - connectedConnection, err := compassConnectionCRClient.Get(context.Background(), compassConnectionName, v1.GetOptions{}) - if err != nil { - return false - } - - return connectedConnection.Status.State == expectedState -} - -func assertSynchronizationStatusError(t *testing.T) { - connectedConnection, err := compassConnectionCRClient.Get(context.Background(), compassConnectionName, v1.GetOptions{}) - require.NoError(t, err) - t.Logf("Synchronization status error: %s", connectedConnection.Status.SynchronizationStatus.Error) - assert.NotEmpty(t, connectedConnection.Status.SynchronizationStatus.Error) -} - -func assertManagementInfoSetInCR(t *testing.T) { - connectedConnection, err := compassConnectionCRClient.Get(context.Background(), compassConnectionName, v1.GetOptions{}) - require.NoError(t, err) - assert.Equal(t, directorURL, connectedConnection.Spec.ManagementInfo.DirectorURL) - assert.Equal(t, certSecuredConnectorURL, connectedConnection.Spec.ManagementInfo.ConnectorURL) -} - -func assertCompassConnectionState(t *testing.T, expectedState v1alpha1.ConnectionState) { - connectedConnection, err := compassConnectionCRClient.Get(context.Background(), compassConnectionName, v1.GetOptions{}) - require.NoError(t, err) - assert.Equal(t, expectedState, connectedConnection.Status.State) -} - -func assertConnectionStatusSet(t *testing.T) { - connectedConnection, err := compassConnectionCRClient.Get(context.Background(), compassConnectionName, v1.GetOptions{}) - require.NoError(t, err) - require.NotNil(t, connectedConnection.Status.ConnectionStatus) - assert.NotEmpty(t, connectedConnection.Status.ConnectionStatus) - assert.NotEmpty(t, connectedConnection.Status.ConnectionStatus.CertificateStatus) -} - -func assertRecreateSynchronizedConnection(t *testing.T) { - err := compassConnectionCRClient.Delete(context.Background(), compassConnectionName, v1.DeleteOptions{}) - require.NoError(t, err) - - // then - err = waitFor(checkInterval, testTimeout, func() bool { - return isConnectionInState(v1alpha1.Synchronized) - }) - require.NoError(t, err) - assertConnectionStatusSet(t) - assertManagementInfoSetInCR(t) -} - -func assertCertificateRenewed(t *testing.T) { - connectedConnection, err := compassConnectionCRClient.Get(context.Background(), compassConnectionName, v1.GetOptions{}) - require.NoError(t, err) - require.NotNil(t, connectedConnection.Status.ConnectionStatus) - assert.NotEmpty(t, connectedConnection.Status.ConnectionStatus.CertificateStatus) - assert.True(t, connectedConnection.Status.ConnectionStatus.Established.Unix() < connectedConnection.Status.ConnectionStatus.Renewed.Unix()) -} - -func clientsProviderMock(configClient *directorMocks.DirectorClient, connectorTokensClient, connectorCertsClient *connectorMocks.Client) *compassMocks.ClientsProvider { - clientsProviderMock := &compassMocks.ClientsProvider{} - clientsProviderMock.On("GetDirectorClient", runtimeConfig).Return(configClient, nil) - clientsProviderMock.On("GetConnectorCertSecuredClient").Return(connectorCertsClient, nil) - clientsProviderMock.On("GetConnectorTokensClient", connectorURL).Return(connectorTokensClient, nil) - - return clientsProviderMock -} - -func connectorCertClientMock(contextMatcher interface{}) *connectorMocks.Client { - connectorMock := &connectorMocks.Client{} - connectorMock.On("Configuration", contextMatcher, nilHeaders).Return(connectorConfigurationResponse, nil) - connectorMock.On("SignCSR", contextMatcher, mock.AnythingOfType("string"), nilHeaders).Return(connectorCertResponse, nil) - - return connectorMock -} - -func connectorTokensClientMock(contextMatcher interface{}) *connectorMocks.Client { - connectorMock := &connectorMocks.Client{} - connectorMock.On("Configuration", contextMatcher, connectorTokenHeadersFunc).Return(connectorConfigurationResponse, nil) - connectorMock.On("SignCSR", contextMatcher, mock.AnythingOfType("string"), connectorTokenHeadersFunc).Return(connectorCertResponse, nil) - - return connectorMock -} - -func configProviderMock() *configMocks.Provider { - providerMock := &configMocks.Provider{} - providerMock.On("GetConnectionConfig").Return(connectionConfig, nil) - providerMock.On("GetRuntimeConfig").Return(runtimeConfig, nil) - - return providerMock -} - -// StartTestManager -func StartTestManager(t *testing.T, mgr manager.Manager) (context.CancelFunc, *sync.WaitGroup) { - ctx, cancel := context.WithCancel(context.Background()) - - wg := &sync.WaitGroup{} - wg.Add(1) - go func() { - defer wg.Done() - err := mgr.Start(ctx) - require.NoError(t, err) - }() - return cancel, wg -} diff --git a/components/compass-runtime-agent/internal/compassconnection/supervisor.go b/components/compass-runtime-agent/internal/compassconnection/supervisor.go deleted file mode 100644 index a0814b16d3ae..000000000000 --- a/components/compass-runtime-agent/internal/compassconnection/supervisor.go +++ /dev/null @@ -1,358 +0,0 @@ -package compassconnection - -import ( - "context" - "fmt" - "time" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/compass/cache" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/compass/director" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/compass" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/config" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/certificates" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma" - "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/apis/compass/v1alpha1" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" - k8serrors "k8s.io/apimachinery/pkg/api/errors" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -const ( - DefaultCompassConnectionName = "compass-connection" -) - -//go:generate mockery --name=CRManager -type CRManager interface { - Create(ctx context.Context, cc *v1alpha1.CompassConnection, options metav1.CreateOptions) (*v1alpha1.CompassConnection, error) - Update(ctx context.Context, cc *v1alpha1.CompassConnection, options metav1.UpdateOptions) (*v1alpha1.CompassConnection, error) - Delete(ctx context.Context, name string, options metav1.DeleteOptions) error - Get(ctx context.Context, name string, options metav1.GetOptions) (*v1alpha1.CompassConnection, error) -} - -//go:generate mockery --name=Supervisor -type Supervisor interface { - InitializeCompassConnection(ctx context.Context) (*v1alpha1.CompassConnection, error) - SynchronizeWithCompass(ctx context.Context, connection *v1alpha1.CompassConnection) (*v1alpha1.CompassConnection, error) - MaintainCompassConnection(ctx context.Context, connection *v1alpha1.CompassConnection) error -} - -func NewSupervisor( - connector Connector, - crManager CRManager, - credManager certificates.Manager, - clientsProvider compass.ClientsProvider, - syncService kyma.Service, - configProvider config.Provider, - certValidityRenewalThreshold float64, - minimalCompassSyncTime time.Duration, - runtimeURLsConfig director.RuntimeURLsConfig, - connectionDataCache cache.ConnectionDataCache, -) Supervisor { - return &crSupervisor{ - compassConnector: connector, - crManager: crManager, - credentialsManager: credManager, - clientsProvider: clientsProvider, - syncService: syncService, - configProvider: configProvider, - certValidityRenewalThreshold: certValidityRenewalThreshold, - minimalCompassSyncTime: minimalCompassSyncTime, - runtimeURLsConfig: runtimeURLsConfig, - connectionDataCache: connectionDataCache, - log: logrus.WithField("Supervisor", "CompassConnection"), - } -} - -type crSupervisor struct { - compassConnector Connector - crManager CRManager - credentialsManager certificates.Manager - clientsProvider compass.ClientsProvider - syncService kyma.Service - configProvider config.Provider - certValidityRenewalThreshold float64 - minimalCompassSyncTime time.Duration - runtimeURLsConfig director.RuntimeURLsConfig - log *logrus.Entry - connectionDataCache cache.ConnectionDataCache -} - -func (s *crSupervisor) InitializeCompassConnection(ctx context.Context) (*v1alpha1.CompassConnection, error) { - compassConnectionCR, err := s.crManager.Get(context.Background(), DefaultCompassConnectionName, metav1.GetOptions{}) - if err != nil { - if k8serrors.IsNotFound(err) { - return s.newCompassConnection(ctx) - } - - return nil, errors.Wrap(err, "Connection failed while getting existing Compass Connection") - } - - s.log.Infof("Compass Connection exists with state %s", compassConnectionCR.Status.State) - - if !compassConnectionCR.Failed() { - s.log.Infof("Connection already initialized, skipping ") - - credentials, err := s.credentialsManager.GetClientCredentials() - if err != nil { - return nil, fmt.Errorf("failed to read credentials while initializing Compass Connection CR: %s", err.Error()) - } - - s.connectionDataCache.UpdateConnectionData( - credentials.AsTLSCertificate(), - compassConnectionCR.Spec.ManagementInfo.DirectorURL, - compassConnectionCR.Spec.ManagementInfo.ConnectorURL, - ) - - return compassConnectionCR, nil - } - - s.establishConnection(ctx, compassConnectionCR) - - return s.updateCompassConnection(compassConnectionCR) -} - -func (s *crSupervisor) MaintainCompassConnection(ctx context.Context, connection *v1alpha1.CompassConnection) error { - s.log = s.log.WithField("CompassConnection", connection.Name) - - s.log.Infof("Trying to maintain connection to Connector with %s url...", connection.Spec.ManagementInfo.ConnectorURL) - err := s.maintainCompassConnection(ctx, connection) - if err != nil { - errorMsg := fmt.Sprintf("Error while trying to maintain connection: %s", err.Error()) - s.setConnectionMaintenanceFailedStatus(connection, metav1.Now(), errorMsg) // save in ConnectionStatus.LastSync - _, updateErr := s.updateCompassConnection(connection) - - if updateErr != nil { - return updateErr - } - } - return err -} - -func (s *crSupervisor) SynchronizeWithCompass(ctx context.Context, connection *v1alpha1.CompassConnection) (*v1alpha1.CompassConnection, error) { - s.log = s.log.WithField("CompassConnection", connection.Name) - - s.log.Infof("Reading configuration required to fetch Runtime configuration...") - runtimeConfig, err := s.configProvider.GetRuntimeConfig() - if err != nil { - errorMsg := fmt.Sprintf("Failed to read Runtime config: %s", err.Error()) - s.setSyncFailedStatus(connection, metav1.Now(), errorMsg) // save in SynchronizationStatus.LastAttempt - return s.updateCompassConnection(connection) - } - - s.log.Infof("Fetching configuration from Director, from %s url...", connection.Spec.ManagementInfo.DirectorURL) - directorClient, err := s.clientsProvider.GetDirectorClient(runtimeConfig) - if err != nil { - errorMsg := fmt.Sprintf("Failed to prepare configuration client: %s", err.Error()) - s.setSyncFailedStatus(connection, metav1.Now(), errorMsg) // save in SynchronizationStatus.LastAttempt - return s.updateCompassConnection(connection) - } - - applicationsConfig, runtimeLabels, err := directorClient.FetchConfiguration(ctx) - if err != nil { - errorMsg := fmt.Sprintf("Failed to fetch configuration: %s", err.Error()) - s.setSyncFailedStatus(connection, metav1.Now(), errorMsg) // save in SynchronizationStatus.LastAttempt - return s.updateCompassConnection(connection) - } - - s.log.Infof("Applying configuration to the cluster...") - results, err := s.syncService.Apply(applicationsConfig) - if err != nil { - syncAttemptTime := metav1.Now() - connection.Status.State = v1alpha1.ResourceApplicationFailed - connection.Status.SynchronizationStatus = &v1alpha1.SynchronizationStatus{ - LastAttempt: syncAttemptTime, - LastSuccessfulFetch: syncAttemptTime, - Error: fmt.Sprintf("Failed to apply configuration: %s", err.Error()), - } - return s.updateCompassConnection(connection) - } - - // TODO: save result to CR and possibly log in better manner - s.log.Infof("Config application results: ") - for _, res := range results { - s.log.Info(res) - } - - s.log.Infof("Labeling Runtime with URLs...") - _, err = directorClient.SetURLsLabels(ctx, s.runtimeURLsConfig, runtimeLabels) - if err != nil { - syncAttemptTime := metav1.Now() - connection.Status.State = v1alpha1.MetadataUpdateFailed - connection.Status.SynchronizationStatus = &v1alpha1.SynchronizationStatus{ - LastAttempt: syncAttemptTime, - LastSuccessfulFetch: syncAttemptTime, - Error: fmt.Sprintf("Failed to reconcile Runtime labels with proper URLs: %s", err.Error()), - } - return s.updateCompassConnection(connection) - } - - // TODO: decide the approach of setting this status. Should it be success even if one App failed? - s.setConnectionSynchronizedStatus(connection, metav1.Now()) - connection.Spec.ResyncNow = false - - return s.updateCompassConnection(connection) -} - -func (s *crSupervisor) maintainCompassConnection(ctx context.Context, compassConnection *v1alpha1.CompassConnection) error { - shouldRenew := compassConnection.ShouldRenewCertificate(s.certValidityRenewalThreshold, s.minimalCompassSyncTime) - credentialsExist, err := s.credentialsManager.CredentialsExist() - if err != nil { - return errors.Wrap(err, "Failed to check whether credentials exist") - } - - s.log.Infof("Trying to maintain certificates connection... Renewal: %v, CreadentialsExist: %v", shouldRenew, credentialsExist) - newCreds, managementInfo, err := s.compassConnector.MaintainConnection(ctx, shouldRenew, credentialsExist) - if err != nil { - return errors.Wrap(err, "Failed to connect to Compass Connector") - } - - connectionTime := metav1.Now() - - if newCreds != nil { - s.log.Infof("Trying to save renewed certificates...") - err = s.credentialsManager.PreserveCredentials(*newCreds) - if err != nil { - return errors.Wrap(err, "Failed to preserve certificate") - } - - s.log.Infof("Successfully saved renewed certificates") - compassConnection.SetCertificateStatus(connectionTime, newCreds.ClientCertificate) - compassConnection.Spec.RefreshCredentialsNow = false - compassConnection.Status.ConnectionStatus.Renewed = connectionTime - - s.connectionDataCache.UpdateConnectionData((*newCreds).AsTLSCertificate(), managementInfo.DirectorURL, managementInfo.ConnectorURL) - s.log.Infof("Refreshed connection data cache") - } - - if s.urlsUpdated(compassConnection, managementInfo) { - s.log.Infof("Compass URLs modified. Updating cache. Connector: %s => %s, Director: %s => %s", - compassConnection.Spec.ManagementInfo.ConnectorURL, managementInfo.ConnectorURL, - compassConnection.Spec.ManagementInfo.DirectorURL, managementInfo.DirectorURL) - s.connectionDataCache.UpdateURLs(managementInfo.DirectorURL, managementInfo.ConnectorURL) - } - - s.log.Infof("Connection maintained. Director URL: %s , ConnectorURL: %s", managementInfo.DirectorURL, managementInfo.ConnectorURL) - - if compassConnection.Status.ConnectionStatus == nil { - compassConnection.Status.ConnectionStatus = &v1alpha1.ConnectionStatus{} - } - - compassConnection.Status.ConnectionStatus.LastSync = connectionTime - compassConnection.Status.ConnectionStatus.LastSuccess = connectionTime - // for alternative flow compassConnection.Status.State = v1alpha1.Connected - - return nil -} - -func (s *crSupervisor) urlsUpdated(compassConnectionCR *v1alpha1.CompassConnection, managementInfo v1alpha1.ManagementInfo) bool { - return compassConnectionCR.Spec.ManagementInfo.ConnectorURL != managementInfo.ConnectorURL || - compassConnectionCR.Spec.ManagementInfo.DirectorURL != managementInfo.DirectorURL -} - -func (s *crSupervisor) newCompassConnection(ctx context.Context) (*v1alpha1.CompassConnection, error) { - connectionCR := &v1alpha1.CompassConnection{ - ObjectMeta: metav1.ObjectMeta{ - Name: DefaultCompassConnectionName, - }, - Spec: v1alpha1.CompassConnectionSpec{}, - } - - s.establishConnection(ctx, connectionCR) - - return s.crManager.Create(context.Background(), connectionCR, metav1.CreateOptions{}) -} - -func (s *crSupervisor) establishConnection(ctx context.Context, connectionCR *v1alpha1.CompassConnection) { - connCfg, err := s.configProvider.GetConnectionConfig() - if err != nil { - s.setConnectionFailedStatus(connectionCR, err, fmt.Sprintf("Failed to retrieve certificate: %s", err.Error())) - return - } - - connection, err := s.compassConnector.EstablishConnection(ctx, connCfg.ConnectorURL, connCfg.Token) - if err != nil { - s.setConnectionFailedStatus(connectionCR, err, fmt.Sprintf("Failed to retrieve certificate: %s", err.Error())) - return - } - - connectionTime := metav1.Now() - - err = s.credentialsManager.PreserveCredentials(connection.Credentials) - if err != nil { - s.setConnectionFailedStatus(connectionCR, err, fmt.Sprintf("Failed to preserve certificate: %s", err.Error())) - return - } - - s.log.Infof("Connection established. Director URL: %s , ConnectorURL: %s", connection.ManagementInfo.DirectorURL, connection.ManagementInfo.ConnectorURL) - - connectionCR.Status.State = v1alpha1.Connected - connectionCR.Status.ConnectionStatus = &v1alpha1.ConnectionStatus{ - Established: connectionTime, - LastSync: connectionTime, - LastSuccess: connectionTime, - } - connectionCR.SetCertificateStatus(connectionTime, connection.Credentials.ClientCertificate) - - connectionCR.Spec.ManagementInfo = connection.ManagementInfo - - s.connectionDataCache.UpdateConnectionData( - connection.Credentials.AsTLSCertificate(), - connection.ManagementInfo.DirectorURL, - connection.ManagementInfo.ConnectorURL, - ) -} - -func (s *crSupervisor) setConnectionFailedStatus(connectionCR *v1alpha1.CompassConnection, err error, connStatusError string) { - s.log.Errorf("Error while establishing connection with Compass: %s", err.Error()) - s.log.Infof("Setting Compass Connection to ConnectionFailed state") - connectionCR.Status.State = v1alpha1.ConnectionFailed - if connectionCR.Status.ConnectionStatus == nil { - connectionCR.Status.ConnectionStatus = &v1alpha1.ConnectionStatus{} - } - connectionCR.Status.ConnectionStatus.LastSync = metav1.Now() - connectionCR.Status.ConnectionStatus.Error = connStatusError -} - -func (s *crSupervisor) setConnectionSynchronizedStatus(connectionCR *v1alpha1.CompassConnection, attemptTime metav1.Time) { - s.log.Infof("Setting Compass Connection to Synchronized state") - connectionCR.Status.State = v1alpha1.Synchronized - connectionCR.Status.SynchronizationStatus = &v1alpha1.SynchronizationStatus{ - LastAttempt: attemptTime, - LastSuccessfulFetch: attemptTime, - LastSuccessfulApplication: attemptTime, - } -} - -func (s *crSupervisor) setConnectionMaintenanceFailedStatus(connectionCR *v1alpha1.CompassConnection, attemptTime metav1.Time, errorMsg string) { - s.log.Error(errorMsg) - s.log.Infof("Setting Compass Connection to ConnectionMaintenanceFailed state") - connectionCR.Status.State = v1alpha1.ConnectionMaintenanceFailed - if connectionCR.Status.ConnectionStatus == nil { - connectionCR.Status.ConnectionStatus = &v1alpha1.ConnectionStatus{} - } - connectionCR.Status.ConnectionStatus.LastSync = attemptTime - connectionCR.Status.ConnectionStatus.Error = errorMsg -} - -func (s *crSupervisor) updateCompassConnection(connectionCR *v1alpha1.CompassConnection) (*v1alpha1.CompassConnection, error) { - // TODO: with retries - - return s.crManager.Update(context.Background(), connectionCR, metav1.UpdateOptions{}) -} - -func (s *crSupervisor) setSyncFailedStatus(connectionCR *v1alpha1.CompassConnection, attemptTime metav1.Time, errorMsg string) { - s.log.Error(errorMsg) - s.log.Infof("Setting Compass Connection to SynchronizationFailed state") - connectionCR.Status.State = v1alpha1.SynchronizationFailed - if connectionCR.Status.SynchronizationStatus == nil { - connectionCR.Status.SynchronizationStatus = &v1alpha1.SynchronizationStatus{} - } - connectionCR.Status.SynchronizationStatus.LastAttempt = attemptTime - connectionCR.Status.SynchronizationStatus.Error = errorMsg -} diff --git a/components/compass-runtime-agent/internal/compassconnection/testdata/compass-connection.crd.yaml b/components/compass-runtime-agent/internal/compassconnection/testdata/compass-connection.crd.yaml deleted file mode 100644 index 111f2ec94134..000000000000 --- a/components/compass-runtime-agent/internal/compassconnection/testdata/compass-connection.crd.yaml +++ /dev/null @@ -1,131 +0,0 @@ ---- -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - annotations: - "helm.sh/resource-policy": keep - name: compassconnections.compass.kyma-project.io -spec: - group: compass.kyma-project.io - names: - kind: CompassConnection - listKind: CompassConnectionList - plural: compassconnections - singular: compassconnection - scope: Cluster - versions: - - name: v1alpha1 - schema: - openAPIV3Schema: - properties: - apiVersion: - description: 'APIVersion defines the versioned schema of this representation - of an object. Servers should convert recognized schemas to the latest - internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' - type: string - kind: - description: 'Kind is a string value representing the REST resource this - object represents. Servers may infer this from the endpoint the client - submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' - type: string - metadata: - type: object - spec: - properties: - managementInfo: - properties: - connectorUrl: - type: string - directorUrl: - type: string - required: - - connectorUrl - - directorUrl - type: object - refreshCredentialsNow: - type: boolean - resyncNow: - type: boolean - required: - - managementInfo - type: object - status: - properties: - connectionState: - type: string - connectionStatus: - description: ConnectionStatus represents status of a connection to - Compass - properties: - certificateStatus: - description: CertificateStatus represents the status of the certificate - properties: - acquired: - format: date-time - nullable: true - type: string - notAfter: - format: date-time - nullable: true - type: string - notBefore: - format: date-time - nullable: true - type: string - type: object - error: - type: string - established: - format: date-time - nullable: true - type: string - lastSuccess: - format: date-time - nullable: true - type: string - lastSync: - format: date-time - nullable: true - type: string - renewed: - format: date-time - nullable: true - type: string - required: - - certificateStatus - type: object - synchronizationStatus: - description: SynchronizationStatus represent the status of Applications - synchronization with Compass - nullable: true - properties: - error: - type: string - lastAttempt: - format: date-time - nullable: true - type: string - lastSuccessfulApplication: - format: date-time - nullable: true - type: string - lastSuccessfulFetch: - format: date-time - nullable: true - type: string - type: object - required: - - connectionState - - connectionStatus - type: object - required: - - spec - type: object - served: true - storage: true -status: - acceptedNames: - kind: "" - plural: "" - conditions: [] - storedVersions: [] diff --git a/components/compass-runtime-agent/internal/config/mocks/ConfigMapManager.go b/components/compass-runtime-agent/internal/config/mocks/ConfigMapManager.go deleted file mode 100644 index 6b08390b816d..000000000000 --- a/components/compass-runtime-agent/internal/config/mocks/ConfigMapManager.go +++ /dev/null @@ -1,38 +0,0 @@ -// Code generated by mockery v1.0.0. DO NOT EDIT. - -package mocks - -import ( - mock "github.com/stretchr/testify/mock" - corev1 "k8s.io/api/core/v1" - - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// ConfigMapManager is an autogenerated mock type for the ConfigMapManager type -type ConfigMapManager struct { - mock.Mock -} - -// Get provides a mock function with given fields: name, options -func (_m *ConfigMapManager) Get(name string, options v1.GetOptions) (*corev1.ConfigMap, error) { - ret := _m.Called(name, options) - - var r0 *corev1.ConfigMap - if rf, ok := ret.Get(0).(func(string, v1.GetOptions) *corev1.ConfigMap); ok { - r0 = rf(name, options) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*corev1.ConfigMap) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(string, v1.GetOptions) error); ok { - r1 = rf(name, options) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} diff --git a/components/compass-runtime-agent/internal/config/mocks/Provider.go b/components/compass-runtime-agent/internal/config/mocks/Provider.go deleted file mode 100644 index 3c16e7200b5e..000000000000 --- a/components/compass-runtime-agent/internal/config/mocks/Provider.go +++ /dev/null @@ -1,55 +0,0 @@ -// Code generated by mockery v2.10.0. DO NOT EDIT. - -package mocks - -import ( - config "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/config" - mock "github.com/stretchr/testify/mock" -) - -// Provider is an autogenerated mock type for the Provider type -type Provider struct { - mock.Mock -} - -// GetConnectionConfig provides a mock function with given fields: -func (_m *Provider) GetConnectionConfig() (config.ConnectionConfig, error) { - ret := _m.Called() - - var r0 config.ConnectionConfig - if rf, ok := ret.Get(0).(func() config.ConnectionConfig); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(config.ConnectionConfig) - } - - var r1 error - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetRuntimeConfig provides a mock function with given fields: -func (_m *Provider) GetRuntimeConfig() (config.RuntimeConfig, error) { - ret := _m.Called() - - var r0 config.RuntimeConfig - if rf, ok := ret.Get(0).(func() config.RuntimeConfig); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(config.RuntimeConfig) - } - - var r1 error - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} diff --git a/components/compass-runtime-agent/internal/config/provider.go b/components/compass-runtime-agent/internal/config/provider.go deleted file mode 100644 index 9cf07d90ab1c..000000000000 --- a/components/compass-runtime-agent/internal/config/provider.go +++ /dev/null @@ -1,67 +0,0 @@ -package config - -import ( - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/secrets" - "k8s.io/apimachinery/pkg/types" - - "github.com/pkg/errors" -) - -const ( - connectorURLConfigKey = "CONNECTOR_URL" - tokenConfigKey = "TOKEN" - runtimeIdConfigKey = "RUNTIME_ID" - tenantConfigKey = "TENANT" -) - -type ConnectionConfig struct { - Token string `json:"token"` - ConnectorURL string `json:"connectorUrl"` -} - -type RuntimeConfig struct { - RuntimeId string `json:"runtimeId"` - Tenant string `json:"tenant"` // TODO: after full implementation of certs in Director it will no longer be needed -} - -//go:generate mockery --name=Provider -type Provider interface { - GetConnectionConfig() (ConnectionConfig, error) - GetRuntimeConfig() (RuntimeConfig, error) -} - -func NewConfigProvider(secretName types.NamespacedName, secretsRepo secrets.Repository) Provider { - return &provider{ - secretName: secretName, - secretsRepo: secretsRepo, - } -} - -type provider struct { - secretName types.NamespacedName - secretsRepo secrets.Repository -} - -func (p *provider) GetConnectionConfig() (ConnectionConfig, error) { - configSecret, err := p.secretsRepo.Get(p.secretName) - if err != nil { - return ConnectionConfig{}, errors.WithMessagef(err, "Failed to read Connection config from %s Secret", p.secretName.String()) - } - - return ConnectionConfig{ - Token: string(configSecret[tokenConfigKey]), - ConnectorURL: string(configSecret[connectorURLConfigKey]), - }, nil -} - -func (p *provider) GetRuntimeConfig() (RuntimeConfig, error) { - configSecret, err := p.secretsRepo.Get(p.secretName) - if err != nil { - return RuntimeConfig{}, errors.WithMessagef(err, "Failed to read Runtime config from %s Secret", p.secretName) - } - - return RuntimeConfig{ - RuntimeId: string(configSecret[runtimeIdConfigKey]), - Tenant: string(configSecret[tenantConfigKey]), - }, nil -} diff --git a/components/compass-runtime-agent/internal/config/provider_test.go b/components/compass-runtime-agent/internal/config/provider_test.go deleted file mode 100644 index e0136276b891..000000000000 --- a/components/compass-runtime-agent/internal/config/provider_test.go +++ /dev/null @@ -1,104 +0,0 @@ -package config_test - -import ( - "errors" - "testing" - - mocks2 "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/secrets/mocks" - - "k8s.io/apimachinery/pkg/types" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/secrets" - "k8s.io/client-go/kubernetes/fake" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/config" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - v1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -const ( - runtimeId = "runtimeId" - tenant = "tenant" - connectorURL = "https://connector.com" - token = "token" - secretName = "compass-agent-configuration" -) - -var ( - secretNamespacedName = types.NamespacedName{ - Namespace: "kyma-system", - Name: secretName, - } -) - -func TestProvider(t *testing.T) { - - configMapData := map[string][]byte{ - "CONNECTOR_URL": []byte(connectorURL), - "TOKEN": []byte(token), - "TENANT": []byte(tenant), - "RUNTIME_ID": []byte(runtimeId), - } - - validConfigSecret := &v1.Secret{ - ObjectMeta: metav1.ObjectMeta{Name: secretName, Namespace: "kyma-system"}, - Data: configMapData, - } - - fakeClient := fake.NewSimpleClientset(validConfigSecret) - secretsRepo := secrets.NewRepository(func(namespace string) secrets.Manager { - return fakeClient.CoreV1().Secrets(namespace) - }) - - configProvider := config.NewConfigProvider(secretNamespacedName, secretsRepo) - - t.Run("should get Connection config", func(t *testing.T) { - // when - connectionConfig, err := configProvider.GetConnectionConfig() - - // then - require.NoError(t, err) - assert.Equal(t, connectorURL, connectionConfig.ConnectorURL) - assert.Equal(t, token, connectionConfig.Token) - - }) - - t.Run("should get Runtime config", func(t *testing.T) { - // when - runtimeConfig, err := configProvider.GetRuntimeConfig() - - // then - require.NoError(t, err) - assert.Equal(t, runtimeId, runtimeConfig.RuntimeId) - assert.Equal(t, tenant, runtimeConfig.Tenant) - }) - -} - -func TestProvider_Errors(t *testing.T) { - - secretsRepo := &mocks2.Repository{} - secretsRepo.On("Get", secretNamespacedName).Return(nil, errors.New("error")) - configProvider := config.NewConfigProvider(secretNamespacedName, secretsRepo) - - t.Run("should return error when failed to get config map for Connection config", func(t *testing.T) { - // when - connectionConfig, err := configProvider.GetConnectionConfig() - - // then - require.Error(t, err) - assert.Empty(t, connectionConfig) - }) - - t.Run("should return error when failed to get config map for Runtime config", func(t *testing.T) { - // when - runtimeConfig, err := configProvider.GetRuntimeConfig() - - // then - require.Error(t, err) - assert.Empty(t, runtimeConfig) - }) -} diff --git a/components/compass-runtime-agent/internal/graphql/client.go b/components/compass-runtime-agent/internal/graphql/client.go deleted file mode 100644 index ccc1ce4515b9..000000000000 --- a/components/compass-runtime-agent/internal/graphql/client.go +++ /dev/null @@ -1,70 +0,0 @@ -package graphql - -import ( - "context" - "net/http" - "time" - - "github.com/sirupsen/logrus" - - "github.com/machinebox/graphql" -) - -const ( - timeout = 30 * time.Second -) - -type ClientConstructor func(httpClient *http.Client, graphqlEndpoint string, enableLogging bool) (Client, error) - -//go:generate mockery --name=Client -type Client interface { - Do(ctx context.Context, req *graphql.Request, res interface{}) error -} - -type client struct { - gqlClient *graphql.Client - logs []string - logging bool -} - -func New(httpClient *http.Client, graphqlEndpoint string, enableLogging bool) (Client, error) { - gqlClient := graphql.NewClient(graphqlEndpoint, graphql.WithHTTPClient(httpClient)) - - client := &client{ - gqlClient: gqlClient, - logging: enableLogging, - logs: []string{}, - } - - client.gqlClient.Log = client.addLog - - return client, nil -} - -func (c *client) Do(ctx context.Context, req *graphql.Request, res interface{}) error { - ctx, cancel := context.WithTimeout(ctx, timeout) - defer cancel() - - c.clearLogs() - err := c.gqlClient.Run(ctx, req, res) - if err != nil { - for _, l := range c.logs { - if l != "" { - logrus.Info(l) - } - } - } - return err -} - -func (c *client) addLog(log string) { - if !c.logging { - return - } - - c.logs = append(c.logs, log) -} - -func (c *client) clearLogs() { - c.logs = []string{} -} diff --git a/components/compass-runtime-agent/internal/graphql/mocks/Client.go b/components/compass-runtime-agent/internal/graphql/mocks/Client.go deleted file mode 100644 index 2e57381c6e05..000000000000 --- a/components/compass-runtime-agent/internal/graphql/mocks/Client.go +++ /dev/null @@ -1,30 +0,0 @@ -// Code generated by mockery v2.10.0. DO NOT EDIT. - -package mocks - -import ( - context "context" - - graphql "github.com/machinebox/graphql" - - mock "github.com/stretchr/testify/mock" -) - -// Client is an autogenerated mock type for the Client type -type Client struct { - mock.Mock -} - -// Do provides a mock function with given fields: ctx, req, res -func (_m *Client) Do(ctx context.Context, req *graphql.Request, res interface{}) error { - ret := _m.Called(ctx, req, res) - - var r0 error - if rf, ok := ret.Get(0).(func(context.Context, *graphql.Request, interface{}) error); ok { - r0 = rf(ctx, req, res) - } else { - r0 = ret.Error(0) - } - - return r0 -} diff --git a/components/compass-runtime-agent/internal/healthz/handler.go b/components/compass-runtime-agent/internal/healthz/handler.go deleted file mode 100644 index 5102041ffcfc..000000000000 --- a/components/compass-runtime-agent/internal/healthz/handler.go +++ /dev/null @@ -1,18 +0,0 @@ -package healthz - -import ( - "net/http" - - "github.com/pkg/errors" - "github.com/sirupsen/logrus" -) - -func newHTTPHandler(log *logrus.Logger) func(writer http.ResponseWriter, request *http.Request) { - return func(writer http.ResponseWriter, request *http.Request) { - writer.WriteHeader(200) - _, err := writer.Write([]byte("ok")) - if err != nil { - log.Errorf(errors.Wrapf(err, "while writing to response body").Error()) - } - } -} diff --git a/components/compass-runtime-agent/internal/healthz/handler_test.go b/components/compass-runtime-agent/internal/healthz/handler_test.go deleted file mode 100644 index c0b1598cb024..000000000000 --- a/components/compass-runtime-agent/internal/healthz/handler_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package healthz - -import ( - "net/http" - "net/http/httptest" - "testing" - - "github.com/sirupsen/logrus" - - "github.com/stretchr/testify/require" -) - -func TestNewHTTPHandler(t *testing.T) { - t.Run("should return 200 with ok inside response body", func(t *testing.T) { - req, err := http.NewRequest("GET", "/healthz", nil) - require.NoError(t, err) - - rr := httptest.NewRecorder() - handler := http.HandlerFunc(newHTTPHandler(logrus.StandardLogger())) - - handler.ServeHTTP(rr, req) - - require.Equal(t, http.StatusOK, rr.Code) - require.Equal(t, "ok", rr.Body.String()) - }) -} diff --git a/components/compass-runtime-agent/internal/healthz/server.go b/components/compass-runtime-agent/internal/healthz/server.go deleted file mode 100644 index 629e799a8603..000000000000 --- a/components/compass-runtime-agent/internal/healthz/server.go +++ /dev/null @@ -1,21 +0,0 @@ -package healthz - -import ( - "fmt" - "net/http" - - "github.com/gorilla/mux" - "github.com/sirupsen/logrus" -) - -func StartHealthCheckServer(log *logrus.Logger, port string) { - router := mux.NewRouter() - router.HandleFunc("/healthz", newHTTPHandler(log)) - - server := http.Server{ - Addr: fmt.Sprintf(":%s", port), - Handler: router, - } - - log.Info(server.ListenAndServe()) -} diff --git a/components/compass-runtime-agent/internal/httpconsts/httpconsts.go b/components/compass-runtime-agent/internal/httpconsts/httpconsts.go deleted file mode 100644 index 0536bf1968ef..000000000000 --- a/components/compass-runtime-agent/internal/httpconsts/httpconsts.go +++ /dev/null @@ -1,9 +0,0 @@ -package httpconsts - -const ( - HeaderContentType = "Content-Type" -) - -const ( - ContentTypeApplicationJson = "application/json;charset=UTF-8" -) diff --git a/components/compass-runtime-agent/internal/k8sconsts/k8sconsts.go b/components/compass-runtime-agent/internal/k8sconsts/k8sconsts.go deleted file mode 100644 index 80627a2287ce..000000000000 --- a/components/compass-runtime-agent/internal/k8sconsts/k8sconsts.go +++ /dev/null @@ -1,8 +0,0 @@ -package k8sconsts - -const ( - LabelApplication = "app" - LabelBundleId = "bundleId" - KindApplication = "Application" - APIVersionApplication = "applicationconnector.kyma-project.io/v1alpha1" -) diff --git a/components/compass-runtime-agent/internal/k8sconsts/mocks/NameResolver.go b/components/compass-runtime-agent/internal/k8sconsts/mocks/NameResolver.go deleted file mode 100644 index 7ef841343b53..000000000000 --- a/components/compass-runtime-agent/internal/k8sconsts/mocks/NameResolver.go +++ /dev/null @@ -1,38 +0,0 @@ -// Code generated by mockery v2.10.0. DO NOT EDIT. - -package mocks - -import mock "github.com/stretchr/testify/mock" - -// NameResolver is an autogenerated mock type for the NameResolver type -type NameResolver struct { - mock.Mock -} - -// GetCredentialsSecretName provides a mock function with given fields: application, bundleID -func (_m *NameResolver) GetCredentialsSecretName(application string, bundleID string) string { - ret := _m.Called(application, bundleID) - - var r0 string - if rf, ok := ret.Get(0).(func(string, string) string); ok { - r0 = rf(application, bundleID) - } else { - r0 = ret.Get(0).(string) - } - - return r0 -} - -// GetRequestParametersSecretName provides a mock function with given fields: application, bundleID -func (_m *NameResolver) GetRequestParametersSecretName(application string, bundleID string) string { - ret := _m.Called(application, bundleID) - - var r0 string - if rf, ok := ret.Get(0).(func(string, string) string); ok { - r0 = rf(application, bundleID) - } else { - r0 = ret.Get(0).(string) - } - - return r0 -} diff --git a/components/compass-runtime-agent/internal/k8sconsts/nameresolver.go b/components/compass-runtime-agent/internal/k8sconsts/nameresolver.go deleted file mode 100644 index aec011af45a8..000000000000 --- a/components/compass-runtime-agent/internal/k8sconsts/nameresolver.go +++ /dev/null @@ -1,62 +0,0 @@ -package k8sconsts - -import ( - "fmt" -) - -const ( - resourceNamePrefixFormat = "%s-" - maxResourceNameLength = 63 // Kubernetes limit for services - uuidLength = 36 // UUID has 36 characters -) - -// NameResolver provides names for Kubernetes resources -//go:generate mockery --name NameResolver -type NameResolver interface { - // GetCredentialsSecretName returns credential secret name - GetCredentialsSecretName(application, bundleID string) string - - // GetRequestParametersSecretName returns request parameters secret name - GetRequestParametersSecretName(application, bundleID string) string -} - -type nameResolver struct{} - -// NewNameResolver creates NameResolver -func NewNameResolver() NameResolver { - return nameResolver{} -} - -// GetCredentialsSecretName returns credential secret name -func (resolver nameResolver) GetCredentialsSecretName(application, packageID string) string { - return getResourceName(application, packageID) -} - -// GetRequestParametersSecretName returns request parameters secret name -func (resolver nameResolver) GetRequestParametersSecretName(application, packageID string) string { - return getResourceName(fmt.Sprintf("params-%s", application), packageID) -} - -// GetResourceName returns resource name with given ID -func getResourceName(application, id string) string { - return getResourceNamePrefix(application) + id -} - -func getResourceNamePrefix(application string) string { - truncatedApplicaton := truncateApplication(application) - return fmt.Sprintf(resourceNamePrefixFormat, truncatedApplicaton) -} - -func truncateApplication(application string) string { - maxResourceNamePrefixLength := maxResourceNameLength - uuidLength - testResourceNamePrefix := fmt.Sprintf(resourceNamePrefixFormat, application) - testResourceNamePrefixLength := len(testResourceNamePrefix) - - overflowLength := testResourceNamePrefixLength - maxResourceNamePrefixLength - - if overflowLength > 0 { - newApplicationLength := len(application) - overflowLength - return application[0:newApplicationLength] - } - return application -} diff --git a/components/compass-runtime-agent/internal/k8sconsts/nameresolver_test.go b/components/compass-runtime-agent/internal/k8sconsts/nameresolver_test.go deleted file mode 100644 index 81c57a3c557e..000000000000 --- a/components/compass-runtime-agent/internal/k8sconsts/nameresolver_test.go +++ /dev/null @@ -1,55 +0,0 @@ -package k8sconsts - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestNameResolver(t *testing.T) { - testCases := []struct { - application string - id string - credentialsSecretName string - requestParametersSecretName string - }{ - { - application: "short_application", - id: "c687e68a-9038-4f38-845b-9c61592e59e6", - credentialsSecretName: "short_application-c687e68a-9038-4f38-845b-9c61592e59e6", - requestParametersSecretName: "params-short_application-c687e68a-9038-4f38-845b-9c61592e59e6", - }, - { - application: "max_application_aaaaaaaaaa", - id: "c687e68a-9038-4f38-845b-9c61592e59e6", - credentialsSecretName: "max_application_aaaaaaaaaa-c687e68a-9038-4f38-845b-9c61592e59e6", - requestParametersSecretName: "params-max_application_aaa-c687e68a-9038-4f38-845b-9c61592e59e6", - }, - { - application: "toolong_application_aaaaaxxxx", - id: "c687e68a-9038-4f38-845b-9c61592e59e6", - credentialsSecretName: "toolong_application_aaaaax-c687e68a-9038-4f38-845b-9c61592e59e6", - requestParametersSecretName: "params-toolong_application-c687e68a-9038-4f38-845b-9c61592e59e6", - }, - } - - t.Run("should get credentials secret secret name with truncated application name if needed", func(t *testing.T) { - for _, testCase := range testCases { - resolver := NewNameResolver() - - result := resolver.GetCredentialsSecretName(testCase.application, testCase.id) - - assert.Equal(t, testCase.credentialsSecretName, result) - } - }) - - t.Run("should get request parameters secret name with truncated application name if needed", func(t *testing.T) { - for _, testCase := range testCases { - resolver := NewNameResolver() - - result := resolver.GetRequestParametersSecretName(testCase.application, testCase.id) - - assert.Equal(t, testCase.requestParametersSecretName, result) - } - }) -} diff --git a/components/compass-runtime-agent/internal/k8sconsts/util.go b/components/compass-runtime-agent/internal/k8sconsts/util.go deleted file mode 100644 index e8b81ce1865c..000000000000 --- a/components/compass-runtime-agent/internal/k8sconsts/util.go +++ /dev/null @@ -1,17 +0,0 @@ -package k8sconsts - -import ( - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" -) - -func CreateOwnerReferenceForApplication(applicationName string, applicationUID types.UID) []v1.OwnerReference { - return []v1.OwnerReference{ - { - APIVersion: APIVersionApplication, - Kind: KindApplication, - Name: applicationName, - UID: applicationUID, - }, - } -} diff --git a/components/compass-runtime-agent/internal/kyma/applications/converter.go b/components/compass-runtime-agent/internal/kyma/applications/converter.go deleted file mode 100644 index a7288d5ef996..000000000000 --- a/components/compass-runtime-agent/internal/kyma/applications/converter.go +++ /dev/null @@ -1,189 +0,0 @@ -package applications - -import ( - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/normalization" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/k8sconsts" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/model" -) - -const defaultDescription = "Description not provided" - -const ( - connectedAppLabelKey = "connected-app" - managedByLabelKey = "applicationconnector.kyma-project.io/managed-by" - managedByLabelValue = "compass-runtime-agent" -) - -const ( - SpecAPIType = "API" - SpecEventsType = "Events" -) - -//go:generate mockery --name=Converter -type Converter interface { - Do(application model.Application) v1alpha1.Application -} - -type converter struct { - nameResolver k8sconsts.NameResolver - centralGatewayServiceUrl string - appSkipTLSVerify bool -} - -func NewConverter(nameResolver k8sconsts.NameResolver, centralGatewayServiceUrl string, skipVerify bool) Converter { - return converter{nameResolver: nameResolver, - centralGatewayServiceUrl: centralGatewayServiceUrl, - appSkipTLSVerify: skipVerify, - } -} - -func (c converter) Do(application model.Application) v1alpha1.Application { - prepareLabels := func(directorLabels model.Labels) map[string]string { - labels := make(map[string]string) - labels[connectedAppLabelKey] = application.Name - return labels - } - - description := application.Description - if description == "" { - description = defaultDescription - } - - return v1alpha1.Application{ - TypeMeta: metav1.TypeMeta{ - Kind: "Application", - APIVersion: "applicationconnector.kyma-project.io/v1alpha1", - }, - ObjectMeta: metav1.ObjectMeta{ - Name: application.Name, - Labels: map[string]string{managedByLabelKey: managedByLabelValue}, - }, - Spec: v1alpha1.ApplicationSpec{ - Description: description, - SkipInstallation: false, - SkipVerify: c.appSkipTLSVerify, // Taken from config. Maybe later we use value from labels of the Director's app - Labels: prepareLabels(application.Labels), - Services: c.toServices(application.Name, application.ApiBundles), - CompassMetadata: c.toCompassMetadata(application.ID, application.SystemAuthsIDs), - }, - } -} - -func (c converter) toServices(applicationName string, bundles []model.APIBundle) []v1alpha1.Service { - services := make([]v1alpha1.Service, 0, len(bundles)) - - for _, p := range bundles { - services = append(services, c.toService(applicationName, p)) - } - - return services -} - -func (c converter) toService(applicationName string, apiBundle model.APIBundle) v1alpha1.Service { - description := defaultDescription - if apiBundle.Description != nil && *apiBundle.Description != "" { - description = *apiBundle.Description - } - - return v1alpha1.Service{ - ID: apiBundle.ID, - Identifier: "", // not available in the Director's API - Name: normalization.NormalizeServiceNameWithId(apiBundle.Name, apiBundle.ID), - AuthCreateParameterSchema: apiBundle.InstanceAuthRequestInputSchema, - DisplayName: apiBundle.Name, - Description: description, - Entries: c.toServiceEntries(applicationName, apiBundle), - } -} - -func (c converter) toServiceEntries(applicationName string, apiBundle model.APIBundle) []v1alpha1.Entry { - entries := make([]v1alpha1.Entry, 0, len(apiBundle.APIDefinitions)+len(apiBundle.EventDefinitions)) - - for _, apiDefinition := range apiBundle.APIDefinitions { - entries = append(entries, c.toAPIEntry(applicationName, apiBundle, apiDefinition)) - } - - for _, eventAPIDefinition := range apiBundle.EventDefinitions { - entries = append(entries, c.toEventServiceEntry(eventAPIDefinition)) - } - - return entries -} - -func (c converter) toAPIEntry(applicationName string, apiBundle model.APIBundle, apiDefinition model.APIDefinition) v1alpha1.Entry { - - entry := v1alpha1.Entry{ - ID: apiDefinition.ID, - Name: apiDefinition.Name, - Type: SpecAPIType, - TargetUrl: apiDefinition.TargetUrl, - CentralGatewayUrl: c.toCentralGatewayURL(applicationName, apiBundle.Name, apiDefinition.Name), - SpecificationUrl: "", // Director returns BLOB here - Credentials: c.toCredential(applicationName, apiBundle), - RequestParametersSecretName: c.toRequestParametersSecretName(applicationName, apiBundle), - } - - return entry -} - -func (c converter) toRequestParametersSecretName(applicationName string, apiBundle model.APIBundle) string { - if apiBundle.DefaultInstanceAuth != nil && apiBundle.DefaultInstanceAuth.RequestParameters != nil && !apiBundle.DefaultInstanceAuth.RequestParameters.IsEmpty() { - return c.nameResolver.GetRequestParametersSecretName(applicationName, apiBundle.ID) - } - return "" -} - -func (c converter) toCentralGatewayURL(applicationName string, apiBundleName string, apiDefinitionName string) string { - return c.centralGatewayServiceUrl + "/" + applicationName + - "/" + normalization.NormalizeName(apiBundleName) + - "/" + normalization.NormalizeName(apiDefinitionName) -} - -func (c converter) toCredential(applicationName string, apiBundle model.APIBundle) v1alpha1.Credentials { - result := v1alpha1.Credentials{} - - if apiBundle.DefaultInstanceAuth != nil && apiBundle.DefaultInstanceAuth.Credentials != nil { - csrfInfo := func(csrfInfo *model.CSRFInfo) *v1alpha1.CSRFInfo { - if csrfInfo != nil { - return &v1alpha1.CSRFInfo{TokenEndpointURL: csrfInfo.TokenEndpointURL} - } - return nil - } - if apiBundle.DefaultInstanceAuth.Credentials.Oauth != nil { - return v1alpha1.Credentials{ - Type: CredentialsOAuthType, - SecretName: c.nameResolver.GetCredentialsSecretName(applicationName, apiBundle.ID), - AuthenticationUrl: apiBundle.DefaultInstanceAuth.Credentials.Oauth.URL, - CSRFInfo: csrfInfo(apiBundle.DefaultInstanceAuth.Credentials.CSRFInfo), - } - } else if apiBundle.DefaultInstanceAuth.Credentials.Basic != nil { - return v1alpha1.Credentials{ - Type: CredentialsBasicType, - SecretName: c.nameResolver.GetCredentialsSecretName(applicationName, apiBundle.ID), - CSRFInfo: csrfInfo(apiBundle.DefaultInstanceAuth.Credentials.CSRFInfo), - } - } - } - return result -} - -func (c converter) toEventServiceEntry(eventsDefinition model.EventAPIDefinition) v1alpha1.Entry { - return v1alpha1.Entry{ - ID: eventsDefinition.ID, - Name: eventsDefinition.Name, - Type: SpecEventsType, - SpecificationUrl: "", // Director returns BLOB here - } -} - -func (c converter) toCompassMetadata(applicationID string, systemAuthsIDs []string) *v1alpha1.CompassMetadata { - return &v1alpha1.CompassMetadata{ - ApplicationID: applicationID, - Authentication: v1alpha1.Authentication{ - ClientIds: systemAuthsIDs, - }, - } -} diff --git a/components/compass-runtime-agent/internal/kyma/applications/converter_test.go b/components/compass-runtime-agent/internal/kyma/applications/converter_test.go deleted file mode 100644 index 2d839a4decd8..000000000000 --- a/components/compass-runtime-agent/internal/kyma/applications/converter_test.go +++ /dev/null @@ -1,319 +0,0 @@ -package applications - -import ( - "testing" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" - "github.com/stretchr/testify/assert" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/k8sconsts" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/model" -) - -const ( - centralGatewayServiceUrl = "http://central-application-gateway.kyma-system.svc.cluster.local:8082" -) - -func TestConverter(t *testing.T) { - t.Run("should convert application without API bundles", func(t *testing.T) { - // given - converter := NewConverter(k8sconsts.NewNameResolver(), centralGatewayServiceUrl, false) - - directorApp := model.Application{ - ID: "App1", - Name: "Appname1", - Labels: map[string]interface{}{ - "keySlice": []string{"value1", "value2"}, - "key": "value", - }, - ApiBundles: []model.APIBundle{}, - SystemAuthsIDs: []string{"auth1", "auth2"}, - } - - expected := v1alpha1.Application{ - TypeMeta: metav1.TypeMeta{ - Kind: "Application", - APIVersion: "applicationconnector.kyma-project.io/v1alpha1", - }, - ObjectMeta: metav1.ObjectMeta{ - Name: "Appname1", - Labels: map[string]string{managedByLabelKey: managedByLabelValue}, - }, - Spec: v1alpha1.ApplicationSpec{ - Description: "Description not provided", - SkipInstallation: false, - Services: []v1alpha1.Service{}, - Labels: map[string]string{ - connectedAppLabelKey: "Appname1", - }, - CompassMetadata: &v1alpha1.CompassMetadata{ApplicationID: "App1", Authentication: v1alpha1.Authentication{ClientIds: []string{"auth1", "auth2"}}}, - }, - } - - // when - application := converter.Do(directorApp) - - // then - assert.Equal(t, expected, application) - }) - - t.Run("should convert application containing API Bundles with API Definitions", func(t *testing.T) { - // given - converter := NewConverter(k8sconsts.NewNameResolver(), centralGatewayServiceUrl, false) - instanceAuthRequestInputSchema := "{}" - - emptyDescription := "" - description := "description" - directorApp := model.Application{ - ID: "App1", - Name: "Appname1", - Description: "Description", - ProviderDisplayName: "provider", - Labels: nil, - ApiBundles: []model.APIBundle{ - { - ID: "bundle1", - Name: "bundleName1", - InstanceAuthRequestInputSchema: &instanceAuthRequestInputSchema, - APIDefinitions: []model.APIDefinition{ - { - ID: "serviceId1", - Name: "serviceName1", - Description: "", - TargetUrl: "www.example.com/1", - }, - { - ID: "serviceId2", - Name: "serviceName2", - Description: "API 2 description", - TargetUrl: "www.example.com/2", - }, - }, - DefaultInstanceAuth: &model.Auth{ - Credentials: &model.Credentials{ - Oauth: &model.Oauth{ - URL: "https://oauth.example.com", - ClientID: "test-client", - ClientSecret: "test-secret", - }, - CSRFInfo: &model.CSRFInfo{ - TokenEndpointURL: "https://tokern.example.com", - }, - }, - }, - }, - { - ID: "bundle2", - Name: "bundleName2", - Description: &description, - APIDefinitions: []model.APIDefinition{ - { - ID: "serviceId3", - Name: "serviceName3", - Description: "", - TargetUrl: "www.example.com/3", - }, - }, - DefaultInstanceAuth: &model.Auth{ - Credentials: &model.Credentials{ - Basic: &model.Basic{ - Username: "my-username", - Password: "my-password", - }, - }, - RequestParameters: &model.RequestParameters{ - Headers: &map[string][]string{"header": {"header-value"}}, - QueryParameters: &map[string][]string{"query-param": {"query-param-value"}}, - }, - }, - }, - { - ID: "bundle3", - Name: "bundleName3", - Description: &emptyDescription, - APIDefinitions: []model.APIDefinition{}, - }, - }, - SystemAuthsIDs: []string{"auth1", "auth2"}, - } - - expected := v1alpha1.Application{ - TypeMeta: metav1.TypeMeta{ - Kind: "Application", - APIVersion: "applicationconnector.kyma-project.io/v1alpha1", - }, - ObjectMeta: metav1.ObjectMeta{ - Name: "Appname1", - Labels: map[string]string{managedByLabelKey: managedByLabelValue}, - }, - Spec: v1alpha1.ApplicationSpec{ - Description: "Description", - SkipInstallation: false, - Labels: map[string]string{ - connectedAppLabelKey: "Appname1", - }, - CompassMetadata: &v1alpha1.CompassMetadata{ApplicationID: "App1", Authentication: v1alpha1.Authentication{ClientIds: []string{"auth1", "auth2"}}}, - Services: []v1alpha1.Service{ - { - ID: "bundle1", - Identifier: "", - Name: "bundlename1-43857", - DisplayName: "bundleName1", - Description: "Description not provided", - AuthCreateParameterSchema: &instanceAuthRequestInputSchema, - Entries: []v1alpha1.Entry{ - { - ID: "serviceId1", - Name: "serviceName1", - Type: SpecAPIType, - TargetUrl: "www.example.com/1", - CentralGatewayUrl: "http://central-application-gateway.kyma-system.svc.cluster.local:8082/Appname1/bundlename1/servicename1", - Credentials: v1alpha1.Credentials{ - Type: "OAuth", - SecretName: "Appname1-bundle1", - AuthenticationUrl: "https://oauth.example.com", - CSRFInfo: &v1alpha1.CSRFInfo{ - TokenEndpointURL: "https://tokern.example.com", - }, - }, - }, - { - ID: "serviceId2", - Name: "serviceName2", - Type: SpecAPIType, - TargetUrl: "www.example.com/2", - CentralGatewayUrl: "http://central-application-gateway.kyma-system.svc.cluster.local:8082/Appname1/bundlename1/servicename2", - Credentials: v1alpha1.Credentials{ - Type: "OAuth", - SecretName: "Appname1-bundle1", - AuthenticationUrl: "https://oauth.example.com", - CSRFInfo: &v1alpha1.CSRFInfo{ - TokenEndpointURL: "https://tokern.example.com", - }, - }, - }, - }, - }, - { - ID: "bundle2", - Identifier: "", - Name: "bundlename2-4b91a", - DisplayName: "bundleName2", - Description: "description", - Entries: []v1alpha1.Entry{ - { - ID: "serviceId3", - Name: "serviceName3", - Type: SpecAPIType, - TargetUrl: "www.example.com/3", - CentralGatewayUrl: "http://central-application-gateway.kyma-system.svc.cluster.local:8082/Appname1/bundlename2/servicename3", - Credentials: v1alpha1.Credentials{ - Type: "Basic", - SecretName: "Appname1-bundle2", - }, - RequestParametersSecretName: "params-Appname1-bundle2", - }, - }, - }, - { - ID: "bundle3", - Identifier: "", - Name: "bundlename3-16aa4", - DisplayName: "bundleName3", - Description: "Description not provided", - Entries: []v1alpha1.Entry{}, - }, - }, - }, - } - - // when - application := converter.Do(directorApp) - - // then - assert.Equal(t, expected, application) - }) - - t.Run("should convert application with services containing events and API, and no System Auths", func(t *testing.T) { - // given - converter := NewConverter(k8sconsts.NewNameResolver(), centralGatewayServiceUrl, false) - - directorApp := model.Application{ - ID: "App1", - Name: "Appname1", - Description: "Description", - ProviderDisplayName: "provider", - Labels: nil, - ApiBundles: []model.APIBundle{ - { - ID: "bundle1", - Name: "bundleName1", - APIDefinitions: []model.APIDefinition{ - { - ID: "serviceId1", - Name: "veryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryverylongserviceName1", - Description: "API 1 description", - TargetUrl: "www.example.com/1", - }, - }, - EventDefinitions: []model.EventAPIDefinition{ - { - ID: "serviceId2", - Name: "serviceName2", - Description: "Events 1 description", - }, - }, - }, - }, - } - - expected := v1alpha1.Application{ - TypeMeta: metav1.TypeMeta{ - Kind: "Application", - APIVersion: "applicationconnector.kyma-project.io/v1alpha1", - }, - ObjectMeta: metav1.ObjectMeta{ - Name: "Appname1", - Labels: map[string]string{managedByLabelKey: managedByLabelValue}, - }, - Spec: v1alpha1.ApplicationSpec{ - Description: "Description", - SkipInstallation: false, - Labels: map[string]string{ - connectedAppLabelKey: "Appname1", - }, - CompassMetadata: &v1alpha1.CompassMetadata{ApplicationID: "App1", Authentication: v1alpha1.Authentication{ClientIds: nil}}, - Services: []v1alpha1.Service{ - { - ID: "bundle1", - Identifier: "", - Name: "bundlename1-43857", - DisplayName: "bundleName1", - Description: "Description not provided", - Entries: []v1alpha1.Entry{ - { - ID: "serviceId1", - Name: "veryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryverylongserviceName1", - Type: SpecAPIType, - TargetUrl: "www.example.com/1", - CentralGatewayUrl: "http://central-application-gateway.kyma-system.svc.cluster.local:8082/Appname1/bundlename1/veryveryveryveryveryveryveryveryveryveryveryveryveryveryv", - }, - { - ID: "serviceId2", - Name: "serviceName2", - Type: SpecEventsType, - }, - }, - }, - }, - }, - } - - // when - application := converter.Do(directorApp) - - // then - assert.Equal(t, expected, application) - }) -} diff --git a/components/compass-runtime-agent/internal/kyma/applications/mocks/Converter.go b/components/compass-runtime-agent/internal/kyma/applications/mocks/Converter.go deleted file mode 100644 index d583abe33cb7..000000000000 --- a/components/compass-runtime-agent/internal/kyma/applications/mocks/Converter.go +++ /dev/null @@ -1,28 +0,0 @@ -// Code generated by mockery v2.10.0. DO NOT EDIT. - -package mocks - -import ( - v1alpha1 "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" - model "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/model" - mock "github.com/stretchr/testify/mock" -) - -// Converter is an autogenerated mock type for the Converter type -type Converter struct { - mock.Mock -} - -// Do provides a mock function with given fields: application -func (_m *Converter) Do(application model.Application) v1alpha1.Application { - ret := _m.Called(application) - - var r0 v1alpha1.Application - if rf, ok := ret.Get(0).(func(model.Application) v1alpha1.Application); ok { - r0 = rf(application) - } else { - r0 = ret.Get(0).(v1alpha1.Application) - } - - return r0 -} diff --git a/components/compass-runtime-agent/internal/kyma/applications/mocks/Repository.go b/components/compass-runtime-agent/internal/kyma/applications/mocks/Repository.go deleted file mode 100644 index 28e03e86c3cb..000000000000 --- a/components/compass-runtime-agent/internal/kyma/applications/mocks/Repository.go +++ /dev/null @@ -1,134 +0,0 @@ -// Code generated by mockery v2.10.0. DO NOT EDIT. - -package mocks - -import ( - apperrors "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/apperrors" - - mock "github.com/stretchr/testify/mock" - - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - v1alpha1 "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" -) - -// Repository is an autogenerated mock type for the Repository type -type Repository struct { - mock.Mock -} - -// Create provides a mock function with given fields: _a0 -func (_m *Repository) Create(_a0 *v1alpha1.Application) (*v1alpha1.Application, apperrors.AppError) { - ret := _m.Called(_a0) - - var r0 *v1alpha1.Application - if rf, ok := ret.Get(0).(func(*v1alpha1.Application) *v1alpha1.Application); ok { - r0 = rf(_a0) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*v1alpha1.Application) - } - } - - var r1 apperrors.AppError - if rf, ok := ret.Get(1).(func(*v1alpha1.Application) apperrors.AppError); ok { - r1 = rf(_a0) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(apperrors.AppError) - } - } - - return r0, r1 -} - -// Delete provides a mock function with given fields: name, options -func (_m *Repository) Delete(name string, options *v1.DeleteOptions) apperrors.AppError { - ret := _m.Called(name, options) - - var r0 apperrors.AppError - if rf, ok := ret.Get(0).(func(string, *v1.DeleteOptions) apperrors.AppError); ok { - r0 = rf(name, options) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(apperrors.AppError) - } - } - - return r0 -} - -// Get provides a mock function with given fields: name, options -func (_m *Repository) Get(name string, options v1.GetOptions) (*v1alpha1.Application, apperrors.AppError) { - ret := _m.Called(name, options) - - var r0 *v1alpha1.Application - if rf, ok := ret.Get(0).(func(string, v1.GetOptions) *v1alpha1.Application); ok { - r0 = rf(name, options) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*v1alpha1.Application) - } - } - - var r1 apperrors.AppError - if rf, ok := ret.Get(1).(func(string, v1.GetOptions) apperrors.AppError); ok { - r1 = rf(name, options) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(apperrors.AppError) - } - } - - return r0, r1 -} - -// List provides a mock function with given fields: opts -func (_m *Repository) List(opts v1.ListOptions) (*v1alpha1.ApplicationList, apperrors.AppError) { - ret := _m.Called(opts) - - var r0 *v1alpha1.ApplicationList - if rf, ok := ret.Get(0).(func(v1.ListOptions) *v1alpha1.ApplicationList); ok { - r0 = rf(opts) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*v1alpha1.ApplicationList) - } - } - - var r1 apperrors.AppError - if rf, ok := ret.Get(1).(func(v1.ListOptions) apperrors.AppError); ok { - r1 = rf(opts) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(apperrors.AppError) - } - } - - return r0, r1 -} - -// Update provides a mock function with given fields: _a0 -func (_m *Repository) Update(_a0 *v1alpha1.Application) (*v1alpha1.Application, apperrors.AppError) { - ret := _m.Called(_a0) - - var r0 *v1alpha1.Application - if rf, ok := ret.Get(0).(func(*v1alpha1.Application) *v1alpha1.Application); ok { - r0 = rf(_a0) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*v1alpha1.Application) - } - } - - var r1 apperrors.AppError - if rf, ok := ret.Get(1).(func(*v1alpha1.Application) apperrors.AppError); ok { - r1 = rf(_a0) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(apperrors.AppError) - } - } - - return r0, r1 -} diff --git a/components/compass-runtime-agent/internal/kyma/applications/repository.go b/components/compass-runtime-agent/internal/kyma/applications/repository.go deleted file mode 100644 index f53356cdd117..000000000000 --- a/components/compass-runtime-agent/internal/kyma/applications/repository.go +++ /dev/null @@ -1,93 +0,0 @@ -package applications - -import ( - "context" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" - v1alpha12 "github.com/kyma-project/kyma/components/central-application-gateway/pkg/client/clientset/versioned/typed/applicationconnector/v1alpha1" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/apperrors" - k8serrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -type manager struct { - applicationsInterface v1alpha12.ApplicationInterface -} - -//go:generate mockery --name=Repository -// Repository contains operations for managing Application CRD -type Repository interface { - Create(*v1alpha1.Application) (*v1alpha1.Application, apperrors.AppError) - Update(*v1alpha1.Application) (*v1alpha1.Application, apperrors.AppError) - Delete(name string, options *metav1.DeleteOptions) apperrors.AppError - Get(name string, options metav1.GetOptions) (*v1alpha1.Application, apperrors.AppError) - List(opts metav1.ListOptions) (*v1alpha1.ApplicationList, apperrors.AppError) -} - -func NewRepository(applicationsInterface v1alpha12.ApplicationInterface) Repository { - return manager{ - applicationsInterface: applicationsInterface, - } -} - -func (m manager) Create(application *v1alpha1.Application) (*v1alpha1.Application, apperrors.AppError) { - - app, err := m.applicationsInterface.Create(context.Background(), application, metav1.CreateOptions{}) - if err != nil { - return nil, apperrors.Internal("Failed to create application: %s", err) - } - - return app, nil -} - -func (m manager) Update(application *v1alpha1.Application) (*v1alpha1.Application, apperrors.AppError) { - currentApp, err := m.applicationsInterface.Get(context.Background(), application.Name, metav1.GetOptions{}) - if err != nil { - if k8serrors.IsNotFound(err) { - return nil, apperrors.NotFound("Failed to update application: %s", err) - } - } - - currentApp.Labels = application.Labels - currentApp.Spec.Description = application.Spec.Description - currentApp.Spec.Labels = application.Spec.Labels - currentApp.Spec.Services = application.Spec.Services - currentApp.Spec.CompassMetadata = application.Spec.CompassMetadata - - newApp, err := m.applicationsInterface.Update(context.Background(), currentApp, metav1.UpdateOptions{}) - if err != nil { - return nil, apperrors.Internal("Failed to update application: %s", err) - } - - return newApp, nil -} - -func (m manager) Delete(name string, options *metav1.DeleteOptions) apperrors.AppError { - if options == nil { - options = &metav1.DeleteOptions{} - } - err := m.applicationsInterface.Delete(context.Background(), name, *options) - if err != nil { - return apperrors.Internal("Failed to delete application: %s", err) - } - - return nil -} - -func (m manager) Get(name string, options metav1.GetOptions) (*v1alpha1.Application, apperrors.AppError) { - app, err := m.applicationsInterface.Get(context.Background(), name, options) - if err != nil { - return nil, apperrors.Internal("Failed to get application: %s", err) - } - - return app, nil -} - -func (m manager) List(opts metav1.ListOptions) (*v1alpha1.ApplicationList, apperrors.AppError) { - apps, err := m.applicationsInterface.List(context.Background(), opts) - if err != nil { - return nil, apperrors.Internal("Failed to list applications: %s", err) - } - - return apps, nil -} diff --git a/components/compass-runtime-agent/internal/kyma/applications/types.go b/components/compass-runtime-agent/internal/kyma/applications/types.go deleted file mode 100644 index 199027877d01..000000000000 --- a/components/compass-runtime-agent/internal/kyma/applications/types.go +++ /dev/null @@ -1,17 +0,0 @@ -package applications - -const ( - CredentialsOAuthType = "OAuth" - CredentialsBasicType = "Basic" -) - -type Credentials struct { - Type string - SecretName string - AuthenticationUrl string - CSRFInfo *CSRFInfo -} - -type CSRFInfo struct { - TokenEndpointURL string -} diff --git a/components/compass-runtime-agent/internal/kyma/mocks/Service.go b/components/compass-runtime-agent/internal/kyma/mocks/Service.go deleted file mode 100644 index a93ea211abd9..000000000000 --- a/components/compass-runtime-agent/internal/kyma/mocks/Service.go +++ /dev/null @@ -1,42 +0,0 @@ -// Code generated by mockery v2.10.0. DO NOT EDIT. - -package mocks - -import ( - apperrors "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/apperrors" - kyma "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma" - - mock "github.com/stretchr/testify/mock" - - model "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/model" -) - -// Service is an autogenerated mock type for the Service type -type Service struct { - mock.Mock -} - -// Apply provides a mock function with given fields: applications -func (_m *Service) Apply(applications []model.Application) ([]kyma.Result, apperrors.AppError) { - ret := _m.Called(applications) - - var r0 []kyma.Result - if rf, ok := ret.Get(0).(func([]model.Application) []kyma.Result); ok { - r0 = rf(applications) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]kyma.Result) - } - } - - var r1 apperrors.AppError - if rf, ok := ret.Get(1).(func([]model.Application) apperrors.AppError); ok { - r1 = rf(applications) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(apperrors.AppError) - } - } - - return r0, r1 -} diff --git a/components/compass-runtime-agent/internal/kyma/model/types.go b/components/compass-runtime-agent/internal/kyma/model/types.go deleted file mode 100644 index 7fb0248763b8..000000000000 --- a/components/compass-runtime-agent/internal/kyma/model/types.go +++ /dev/null @@ -1,94 +0,0 @@ -package model - -type Labels map[string]interface{} - -// Application contains all associated APIs, and EventAPIs -type Application struct { - ID string - Name string - ProviderDisplayName string - Description string - Labels Labels - SystemAuthsIDs []string - ApiBundles []APIBundle -} - -type APIBundle struct { - ID string - Name string - Description *string - InstanceAuthRequestInputSchema *string - APIDefinitions []APIDefinition - EventDefinitions []EventAPIDefinition - DefaultInstanceAuth *Auth -} - -// APIDefinition contains API data such as URL, and credentials -type APIDefinition struct { - ID string - Name string - Description string - TargetUrl string - Credentials *Credentials -} - -// EventAPIDefinition contains Event API details -type EventAPIDefinition struct { - ID string - Name string - Description string -} - -// Credentials contains OAuth or BasicAuth configuration along with optional CSRF data. -type Credentials struct { - // OAuth configuration - Oauth *Oauth - // BasicAuth configuration - Basic *Basic - // Optional CSRF Data - CSRFInfo *CSRFInfo -} - -// Oauth contains data for performing Oauth token request -type Oauth struct { - // URL to OAuth token provider. - URL string - // ClientID to use for authentication. - ClientID string - // ClientSecret to use for authentication. - ClientSecret string -} - -// Basic contains user and password for Basic Auth -type Basic struct { - // Username to use for authentication. - Username string - // Password to use for authentication. - Password string -} - -// CSRFInfo contains data for performing CSRF token request -type CSRFInfo struct { - TokenEndpointURL string -} - -// RequestParameters contains additional headers and query parameters -type RequestParameters struct { - // Additional headers - Headers *map[string][]string `json:"headers"` - // Additional query parameters - QueryParameters *map[string][]string `json:"queryParameters"` -} - -// IsEmpty returns true if additional headers and query parameters contain no data, otherwise false -func (r RequestParameters) IsEmpty() bool { - return (r.Headers == nil || len(*r.Headers) == 0) && (r.QueryParameters == nil || len(*r.QueryParameters) == 0) -} - -// Auth contains authentication data -type Auth struct { - // Credentials - Credentials *Credentials - // Additional request parameters - RequestParameters *RequestParameters -} diff --git a/components/compass-runtime-agent/internal/kyma/model/types_test.go b/components/compass-runtime-agent/internal/kyma/model/types_test.go deleted file mode 100644 index e48f0a9cb2b8..000000000000 --- a/components/compass-runtime-agent/internal/kyma/model/types_test.go +++ /dev/null @@ -1,27 +0,0 @@ -package model - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestRequestParametersIsEmpty(t *testing.T) { - tests := []struct { - name string - rp RequestParameters - empty bool - }{ - {name: "nil values", rp: RequestParameters{}, empty: true}, - {name: "empty values", rp: RequestParameters{Headers: &map[string][]string{}, QueryParameters: &map[string][]string{}}, empty: true}, - {name: "has header", rp: RequestParameters{Headers: &map[string][]string{"header": {}}, QueryParameters: &map[string][]string{}}, empty: false}, - {name: "has param", rp: RequestParameters{Headers: &map[string][]string{}, QueryParameters: &map[string][]string{"param": {}}}, empty: false}, - {name: "has header and param", rp: RequestParameters{Headers: &map[string][]string{"header": {}}, QueryParameters: &map[string][]string{"param": {}}}, empty: false}, - } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - a := assert.New(t) - a.Equal(tc.empty, tc.rp.IsEmpty()) - }) - } -} diff --git a/components/compass-runtime-agent/internal/kyma/secrets/credentialsservice.go b/components/compass-runtime-agent/internal/kyma/secrets/credentialsservice.go deleted file mode 100644 index d16c651e0953..000000000000 --- a/components/compass-runtime-agent/internal/kyma/secrets/credentialsservice.go +++ /dev/null @@ -1,111 +0,0 @@ -package appsecrets - -import ( - "k8s.io/apimachinery/pkg/types" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/apperrors" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/k8sconsts" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/applications" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/model" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/secrets/strategy" -) - -type modificationFunction func(modStrategy strategy.ModificationStrategy, application string, appUID types.UID, name, bundleID string, newData strategy.SecretData) apperrors.AppError - -//go:generate mockery --name CredentialsService -type CredentialsService interface { - Get(application string, credentials applications.Credentials) (model.Credentials, apperrors.AppError) - Create(application string, appUID types.UID, bundleID string, credentials *model.Credentials) (applications.Credentials, apperrors.AppError) - Upsert(application string, appUID types.UID, bundleID string, credentials *model.Credentials) (applications.Credentials, apperrors.AppError) - Delete(name string) apperrors.AppError -} - -type credentialsService struct { - repository Repository - strategyFactory strategy.Factory - nameResolver k8sconsts.NameResolver -} - -func NewCredentialsService(repository Repository, strategyFactory strategy.Factory, nameResolver k8sconsts.NameResolver) CredentialsService { - return &credentialsService{ - repository: repository, - strategyFactory: strategyFactory, - nameResolver: nameResolver, - } -} - -func (s *credentialsService) Create(application string, appUID types.UID, bundleID string, credentials *model.Credentials) (applications.Credentials, apperrors.AppError) { - return s.modifySecret(application, appUID, bundleID, credentials, s.createSecret) -} - -func (s *credentialsService) Get(application string, credentials applications.Credentials) (model.Credentials, apperrors.AppError) { - accessStrategy, err := s.strategyFactory.NewSecretAccessStrategy(&credentials) - if err != nil { - return model.Credentials{}, err.Append("Failed to initialize strategy") - } - - data, err := s.repository.Get(credentials.SecretName) - if err != nil { - return model.Credentials{}, err - } - - return accessStrategy.ToCredentials(data, &credentials) -} - -func (s *credentialsService) Upsert(application string, appUID types.UID, bundleID string, credentials *model.Credentials) (applications.Credentials, apperrors.AppError) { - return s.modifySecret(application, appUID, bundleID, credentials, s.upsertSecret) -} - -func (s *credentialsService) Delete(name string) apperrors.AppError { - return s.repository.Delete(name) -} - -func (s *credentialsService) modifySecret(application string, appUID types.UID, bundleID string, credentials *model.Credentials, modFunction modificationFunction) (applications.Credentials, apperrors.AppError) { - if credentials == nil { - return applications.Credentials{}, nil - } - - modStrategy, err := s.strategyFactory.NewSecretModificationStrategy(credentials) - if err != nil { - return applications.Credentials{}, err.Append("Failed to initialize strategy") - } - - if !modStrategy.CredentialsProvided(credentials) { - return applications.Credentials{}, nil - } - - name := s.nameResolver.GetCredentialsSecretName(application, bundleID) - - secretData, err := modStrategy.CreateSecretData(credentials) - if err != nil { - return applications.Credentials{}, err.Append("Failed to create secret data") - } - - err = modFunction(modStrategy, application, appUID, name, bundleID, secretData) - if err != nil { - return applications.Credentials{}, err - } - - return modStrategy.ToCredentialsInfo(credentials, name), nil -} - -func (s *credentialsService) upsertSecret(modStrategy strategy.ModificationStrategy, application string, appUID types.UID, name, bundleID string, newData strategy.SecretData) apperrors.AppError { - currentData, err := s.repository.Get(name) - if err != nil { - if err.Code() == apperrors.CodeNotFound { - return s.repository.Create(application, appUID, name, bundleID, newData) - } - - return err - } - - if modStrategy.ShouldUpdate(currentData, newData) { - return s.repository.Upsert(application, appUID, name, bundleID, newData) - } - - return nil -} - -func (s *credentialsService) createSecret(_ strategy.ModificationStrategy, application string, appUID types.UID, name, bundleID string, newData strategy.SecretData) apperrors.AppError { - return s.repository.Create(application, appUID, name, bundleID, newData) -} diff --git a/components/compass-runtime-agent/internal/kyma/secrets/credentialsservice_test.go b/components/compass-runtime-agent/internal/kyma/secrets/credentialsservice_test.go deleted file mode 100644 index 37500abed010..000000000000 --- a/components/compass-runtime-agent/internal/kyma/secrets/credentialsservice_test.go +++ /dev/null @@ -1,434 +0,0 @@ -package appsecrets - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" - "k8s.io/apimachinery/pkg/types" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/apperrors" - k8smocks "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/k8sconsts/mocks" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/applications" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/model" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/secrets/mocks" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/secrets/strategy" - strategyMocks "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/secrets/strategy/mocks" -) - -const ( - appName = "app" - appUID = types.UID("appUID") - bundleID = "bundleID" - secretName = "secretName" -) - -var ( - credentials = &model.Credentials{ - Oauth: &model.Oauth{ - ClientID: "clientID", - ClientSecret: "clientSecret", - URL: "http://oauth.com", - }, - } - - secretData = strategy.SecretData{ - "key": []byte("value"), - "key2": []byte("value2"), - } - - appCredentials = applications.Credentials{ - Type: applications.CredentialsBasicType, - SecretName: secretName, - } -) - -func TestService_Create(t *testing.T) { - t.Run("should create secret", func(t *testing.T) { - // given - nameResolver := &k8smocks.NameResolver{} - nameResolver.On("GetCredentialsSecretName", appName, bundleID).Return(secretName) - - modStrategy := &strategyMocks.ModificationStrategy{} - modStrategy.On("CredentialsProvided", credentials).Return(true) - modStrategy.On("CreateSecretData", credentials).Return(secretData, nil) - modStrategy.On("ToCredentialsInfo", credentials, secretName).Return(appCredentials) - - strategyFactory := &strategyMocks.Factory{} - strategyFactory.On("NewSecretModificationStrategy", credentials).Return(modStrategy, nil) - - secretsRepository := &mocks.Repository{} - secretsRepository.On("Create", appName, appUID, secretName, bundleID, secretData).Return(nil) - - service := NewCredentialsService(secretsRepository, strategyFactory, nameResolver) - - // when - createdCredentials, err := service.Create(appName, appUID, bundleID, credentials) - - // then - require.NoError(t, err) - assert.Equal(t, appCredentials.Type, createdCredentials.Type) - assert.Equal(t, appCredentials.SecretName, createdCredentials.SecretName) - assertExpectations(t, &nameResolver.Mock, &modStrategy.Mock, &strategyFactory.Mock, &secretsRepository.Mock) - }) - - t.Run("should return empty app credentials if credentials are nil", func(t *testing.T) { - // given - nameResolver := &k8smocks.NameResolver{} - modStrategy := &strategyMocks.ModificationStrategy{} - strategyFactory := &strategyMocks.Factory{} - secretsRepository := &mocks.Repository{} - - service := NewCredentialsService(secretsRepository, strategyFactory, nameResolver) - - // when - createdCredentials, err := service.Create(appName, appUID, bundleID, nil) - - // then - assert.NoError(t, err) - assert.Empty(t, createdCredentials) - assertExpectations(t, &nameResolver.Mock, &modStrategy.Mock, &strategyFactory.Mock, &secretsRepository.Mock) - }) - - t.Run("should return error when failed to initialize strategy", func(t *testing.T) { - // given - nameResolver := &k8smocks.NameResolver{} - modStrategy := &strategyMocks.ModificationStrategy{} - strategyFactory := &strategyMocks.Factory{} - strategyFactory.On("NewSecretModificationStrategy", credentials).Return(nil, apperrors.Internal("error")) - - secretsRepository := &mocks.Repository{} - - service := NewCredentialsService(secretsRepository, strategyFactory, nameResolver) - - // when - createdCredentials, err := service.Create(appName, appUID, bundleID, credentials) - - // then - require.Error(t, err) - assert.Empty(t, createdCredentials) - assertExpectations(t, &nameResolver.Mock, &modStrategy.Mock, &strategyFactory.Mock, &secretsRepository.Mock) - }) - - t.Run("should return empty app credentials if credentials not provided", func(t *testing.T) { - // given - nameResolver := &k8smocks.NameResolver{} - modStrategy := &strategyMocks.ModificationStrategy{} - modStrategy.On("CredentialsProvided", credentials).Return(false) - strategyFactory := &strategyMocks.Factory{} - strategyFactory.On("NewSecretModificationStrategy", credentials).Return(modStrategy, nil) - - secretsRepository := &mocks.Repository{} - - service := NewCredentialsService(secretsRepository, strategyFactory, nameResolver) - - // when - createdCredentials, err := service.Create(appName, appUID, bundleID, credentials) - - // then - require.NoError(t, err) - assert.Empty(t, createdCredentials) - assertExpectations(t, &nameResolver.Mock, &modStrategy.Mock, &strategyFactory.Mock, &secretsRepository.Mock) - }) - - t.Run("should return error when failed to create secret data", func(t *testing.T) { - // given - nameResolver := &k8smocks.NameResolver{} - nameResolver.On("GetCredentialsSecretName", appName, bundleID).Return(secretName) - - modStrategy := &strategyMocks.ModificationStrategy{} - modStrategy.On("CredentialsProvided", credentials).Return(true) - modStrategy.On("CreateSecretData", credentials).Return(nil, apperrors.Internal("error")) - - strategyFactory := &strategyMocks.Factory{} - strategyFactory.On("NewSecretModificationStrategy", credentials).Return(modStrategy, nil) - - secretsRepository := &mocks.Repository{} - - service := NewCredentialsService(secretsRepository, strategyFactory, nameResolver) - - // when - createdCredentials, err := service.Create(appName, appUID, bundleID, credentials) - - // then - require.Error(t, err) - assert.Empty(t, createdCredentials) - assertExpectations(t, &nameResolver.Mock, &modStrategy.Mock, &strategyFactory.Mock, &secretsRepository.Mock) - }) - - t.Run("should return error when failed to create secret", func(t *testing.T) { - // given - nameResolver := &k8smocks.NameResolver{} - nameResolver.On("GetCredentialsSecretName", appName, bundleID).Return(secretName) - - modStrategy := &strategyMocks.ModificationStrategy{} - modStrategy.On("CredentialsProvided", credentials).Return(true) - modStrategy.On("CreateSecretData", credentials).Return(secretData, nil) - - strategyFactory := &strategyMocks.Factory{} - strategyFactory.On("NewSecretModificationStrategy", credentials).Return(modStrategy, nil) - - secretsRepository := &mocks.Repository{} - secretsRepository.On("Create", appName, appUID, secretName, bundleID, secretData).Return(apperrors.Internal("error")) - - service := NewCredentialsService(secretsRepository, strategyFactory, nameResolver) - - // when - createdCredentials, err := service.Create(appName, appUID, bundleID, credentials) - - // then - require.Error(t, err) - assert.Empty(t, createdCredentials) - assertExpectations(t, &nameResolver.Mock, &modStrategy.Mock, &strategyFactory.Mock, &secretsRepository.Mock) - }) -} - -func TestService_Get(t *testing.T) { - t.Run("should return credentials", func(t *testing.T) { - // given - nameResolver := &k8smocks.NameResolver{} - modStrategy := &strategyMocks.AccessStrategy{} - modStrategy.On("ToCredentials", secretData, &appCredentials).Return(*credentials, nil) - strategyFactory := &strategyMocks.Factory{} - strategyFactory.On("NewSecretAccessStrategy", &appCredentials).Return(modStrategy, nil) - secretsRepository := &mocks.Repository{} - secretsRepository.On("Get", secretName).Return(secretData, nil) - - service := NewCredentialsService(secretsRepository, strategyFactory, nameResolver) - - // when - createdCredentials, err := service.Get(appName, appCredentials) - - // then - require.NoError(t, err) - assert.Equal(t, credentials.Oauth.ClientID, createdCredentials.Oauth.ClientID) - assert.Equal(t, credentials.Oauth.ClientSecret, createdCredentials.Oauth.ClientSecret) - assert.Equal(t, credentials.Oauth.URL, createdCredentials.Oauth.URL) - assertExpectations(t, &nameResolver.Mock, &modStrategy.Mock, &strategyFactory.Mock, &secretsRepository.Mock) - }) - - t.Run("should return error when failed to initialize strategy", func(t *testing.T) { - // given - nameResolver := &k8smocks.NameResolver{} - modStrategy := &strategyMocks.AccessStrategy{} - strategyFactory := &strategyMocks.Factory{} - strategyFactory.On("NewSecretAccessStrategy", &appCredentials).Return(nil, apperrors.Internal("")) - secretsRepository := &mocks.Repository{} - - service := NewCredentialsService(secretsRepository, strategyFactory, nameResolver) - - // when - createdCredentials, err := service.Get(appName, appCredentials) - - // then - require.Error(t, err) - assert.Empty(t, createdCredentials) - assertExpectations(t, &nameResolver.Mock, &modStrategy.Mock, &strategyFactory.Mock, &secretsRepository.Mock) - }) - - t.Run("should return error when failed to get secret", func(t *testing.T) { - // given - nameResolver := &k8smocks.NameResolver{} - modStrategy := &strategyMocks.AccessStrategy{} - strategyFactory := &strategyMocks.Factory{} - strategyFactory.On("NewSecretAccessStrategy", &appCredentials).Return(modStrategy, nil) - secretsRepository := &mocks.Repository{} - secretsRepository.On("Get", secretName).Return(nil, apperrors.Internal("")) - service := NewCredentialsService(secretsRepository, strategyFactory, nameResolver) - - // when - createdCredentials, err := service.Get(appName, appCredentials) - - // then - require.Error(t, err) - assert.Empty(t, createdCredentials) - assertExpectations(t, &nameResolver.Mock, &modStrategy.Mock, &strategyFactory.Mock, &secretsRepository.Mock) - }) -} - -func TestService_Update(t *testing.T) { - t.Run("should update secret", func(t *testing.T) { - // given - nameResolver := &k8smocks.NameResolver{} - nameResolver.On("GetCredentialsSecretName", appName, bundleID).Return(secretName) - - modStrategy := &strategyMocks.ModificationStrategy{} - modStrategy.On("CredentialsProvided", credentials).Return(true) - modStrategy.On("CreateSecretData", credentials).Return(secretData, nil) - modStrategy.On("ShouldUpdate", strategy.SecretData{}, secretData).Return(true) - modStrategy.On("ToCredentialsInfo", credentials, secretName).Return(appCredentials) - - strategyFactory := &strategyMocks.Factory{} - strategyFactory.On("NewSecretModificationStrategy", credentials).Return(modStrategy, nil) - - secretsRepository := &mocks.Repository{} - secretsRepository.On("Get", secretName).Return(strategy.SecretData{}, nil) - secretsRepository.On("Upsert", appName, appUID, secretName, bundleID, secretData).Return(nil) - - service := NewCredentialsService(secretsRepository, strategyFactory, nameResolver) - - // when - createdCredentials, err := service.Upsert(appName, appUID, bundleID, credentials) - - // then - require.NoError(t, err) - assert.Equal(t, appCredentials.Type, createdCredentials.Type) - assert.Equal(t, appCredentials.SecretName, createdCredentials.SecretName) - assertExpectations(t, &nameResolver.Mock, &modStrategy.Mock, &strategyFactory.Mock, &secretsRepository.Mock) - }) - - t.Run("should not updated if content the same", func(t *testing.T) { - // given - nameResolver := &k8smocks.NameResolver{} - nameResolver.On("GetCredentialsSecretName", appName, bundleID).Return(secretName) - - modStrategy := &strategyMocks.ModificationStrategy{} - modStrategy.On("CredentialsProvided", credentials).Return(true) - modStrategy.On("CreateSecretData", credentials).Return(secretData, nil) - modStrategy.On("ShouldUpdate", secretData, secretData).Return(false) - modStrategy.On("ToCredentialsInfo", credentials, secretName).Return(appCredentials) - - strategyFactory := &strategyMocks.Factory{} - strategyFactory.On("NewSecretModificationStrategy", credentials).Return(modStrategy, nil) - - secretsRepository := &mocks.Repository{} - secretsRepository.On("Get", secretName).Return(secretData, nil) - - service := NewCredentialsService(secretsRepository, strategyFactory, nameResolver) - - // when - createdCredentials, err := service.Upsert(appName, appUID, bundleID, credentials) - - // then - require.NoError(t, err) - assert.Equal(t, appCredentials.Type, createdCredentials.Type) - assert.Equal(t, appCredentials.SecretName, createdCredentials.SecretName) - assertExpectations(t, &nameResolver.Mock, &modStrategy.Mock, &strategyFactory.Mock, &secretsRepository.Mock) - }) - - t.Run("should create secret if not found", func(t *testing.T) { - // given - nameResolver := &k8smocks.NameResolver{} - nameResolver.On("GetCredentialsSecretName", appName, bundleID).Return(secretName) - - modStrategy := &strategyMocks.ModificationStrategy{} - modStrategy.On("CredentialsProvided", credentials).Return(true) - modStrategy.On("CreateSecretData", credentials).Return(secretData, nil) - modStrategy.On("ToCredentialsInfo", credentials, secretName).Return(appCredentials) - - strategyFactory := &strategyMocks.Factory{} - strategyFactory.On("NewSecretModificationStrategy", credentials).Return(modStrategy, nil) - - secretsRepository := &mocks.Repository{} - secretsRepository.On("Get", secretName).Return(strategy.SecretData{}, apperrors.NotFound("error")) - secretsRepository.On("Create", appName, appUID, secretName, bundleID, secretData).Return(nil) - - service := NewCredentialsService(secretsRepository, strategyFactory, nameResolver) - - // when - createdCredentials, err := service.Upsert(appName, appUID, bundleID, credentials) - - // then - require.NoError(t, err) - assert.Equal(t, appCredentials.Type, createdCredentials.Type) - assert.Equal(t, appCredentials.SecretName, createdCredentials.SecretName) - assertExpectations(t, &nameResolver.Mock, &modStrategy.Mock, &strategyFactory.Mock, &secretsRepository.Mock) - }) - - t.Run("should return error when failed to get secret", func(t *testing.T) { - // given - nameResolver := &k8smocks.NameResolver{} - nameResolver.On("GetCredentialsSecretName", appName, bundleID).Return(secretName) - - modStrategy := &strategyMocks.ModificationStrategy{} - modStrategy.On("CredentialsProvided", credentials).Return(true) - modStrategy.On("CreateSecretData", credentials).Return(secretData, nil) - - strategyFactory := &strategyMocks.Factory{} - strategyFactory.On("NewSecretModificationStrategy", credentials).Return(modStrategy, nil) - - secretsRepository := &mocks.Repository{} - secretsRepository.On("Get", secretName).Return(nil, apperrors.Internal("")) - - service := NewCredentialsService(secretsRepository, strategyFactory, nameResolver) - - // when - createdCredentials, err := service.Upsert(appName, appUID, bundleID, credentials) - - // then - require.Error(t, err) - assert.Empty(t, createdCredentials) - assertExpectations(t, &nameResolver.Mock, &modStrategy.Mock, &strategyFactory.Mock, &secretsRepository.Mock) - }) - - t.Run("should return error when failed to update secret", func(t *testing.T) { - // given - nameResolver := &k8smocks.NameResolver{} - nameResolver.On("GetCredentialsSecretName", appName, bundleID).Return(secretName) - - modStrategy := &strategyMocks.ModificationStrategy{} - modStrategy.On("CredentialsProvided", credentials).Return(true) - modStrategy.On("CreateSecretData", credentials).Return(secretData, nil) - modStrategy.On("ShouldUpdate", strategy.SecretData{}, secretData).Return(true) - - strategyFactory := &strategyMocks.Factory{} - strategyFactory.On("NewSecretModificationStrategy", credentials).Return(modStrategy, nil) - - secretsRepository := &mocks.Repository{} - secretsRepository.On("Get", secretName).Return(strategy.SecretData{}, nil) - secretsRepository.On("Upsert", appName, appUID, secretName, bundleID, secretData).Return(apperrors.Internal("error")) - - service := NewCredentialsService(secretsRepository, strategyFactory, nameResolver) - - // when - createdCredentials, err := service.Upsert(appName, appUID, bundleID, credentials) - - // then - require.Error(t, err) - assert.Empty(t, createdCredentials) - assertExpectations(t, &nameResolver.Mock, &modStrategy.Mock, &strategyFactory.Mock, &secretsRepository.Mock) - }) -} - -func TestService_Delete(t *testing.T) { - t.Run("should delete a secret", func(t *testing.T) { - // given - nameResolver := &k8smocks.NameResolver{} - strategyFactory := &strategyMocks.Factory{} - secretsRepository := &mocks.Repository{} - secretsRepository.On("Delete", secretName).Return(nil) - - service := NewCredentialsService(secretsRepository, strategyFactory, nameResolver) - - // when - err := service.Delete(secretName) - - // then - require.NoError(t, err) - assertExpectations(t, &nameResolver.Mock, &strategyFactory.Mock, &secretsRepository.Mock) - }) - - t.Run("should return an error failed to delete secret", func(t *testing.T) { - // given - nameResolver := &k8smocks.NameResolver{} - strategyFactory := &strategyMocks.Factory{} - secretsRepository := &mocks.Repository{} - secretsRepository.On("Delete", secretName).Return(apperrors.Internal("error")) - - service := NewCredentialsService(secretsRepository, strategyFactory, nameResolver) - - // when - err := service.Delete(secretName) - - // then - require.Error(t, err) - assertExpectations(t, &nameResolver.Mock, &strategyFactory.Mock, &secretsRepository.Mock) - }) -} - -func assertExpectations(t *testing.T, mocks ...*mock.Mock) { - for _, m := range mocks { - m.AssertExpectations(t) - } -} diff --git a/components/compass-runtime-agent/internal/kyma/secrets/mocks/CredentialsService.go b/components/compass-runtime-agent/internal/kyma/secrets/mocks/CredentialsService.go deleted file mode 100644 index 594beebf0a5a..000000000000 --- a/components/compass-runtime-agent/internal/kyma/secrets/mocks/CredentialsService.go +++ /dev/null @@ -1,104 +0,0 @@ -// Code generated by mockery v2.10.0. DO NOT EDIT. - -package mocks - -import ( - apperrors "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/apperrors" - applications "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/applications" - - mock "github.com/stretchr/testify/mock" - - model "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/model" - - types "k8s.io/apimachinery/pkg/types" -) - -// CredentialsService is an autogenerated mock type for the CredentialsService type -type CredentialsService struct { - mock.Mock -} - -// Create provides a mock function with given fields: application, appUID, bundleID, credentials -func (_m *CredentialsService) Create(application string, appUID types.UID, bundleID string, credentials *model.Credentials) (applications.Credentials, apperrors.AppError) { - ret := _m.Called(application, appUID, bundleID, credentials) - - var r0 applications.Credentials - if rf, ok := ret.Get(0).(func(string, types.UID, string, *model.Credentials) applications.Credentials); ok { - r0 = rf(application, appUID, bundleID, credentials) - } else { - r0 = ret.Get(0).(applications.Credentials) - } - - var r1 apperrors.AppError - if rf, ok := ret.Get(1).(func(string, types.UID, string, *model.Credentials) apperrors.AppError); ok { - r1 = rf(application, appUID, bundleID, credentials) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(apperrors.AppError) - } - } - - return r0, r1 -} - -// Delete provides a mock function with given fields: name -func (_m *CredentialsService) Delete(name string) apperrors.AppError { - ret := _m.Called(name) - - var r0 apperrors.AppError - if rf, ok := ret.Get(0).(func(string) apperrors.AppError); ok { - r0 = rf(name) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(apperrors.AppError) - } - } - - return r0 -} - -// Get provides a mock function with given fields: application, credentials -func (_m *CredentialsService) Get(application string, credentials applications.Credentials) (model.Credentials, apperrors.AppError) { - ret := _m.Called(application, credentials) - - var r0 model.Credentials - if rf, ok := ret.Get(0).(func(string, applications.Credentials) model.Credentials); ok { - r0 = rf(application, credentials) - } else { - r0 = ret.Get(0).(model.Credentials) - } - - var r1 apperrors.AppError - if rf, ok := ret.Get(1).(func(string, applications.Credentials) apperrors.AppError); ok { - r1 = rf(application, credentials) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(apperrors.AppError) - } - } - - return r0, r1 -} - -// Upsert provides a mock function with given fields: application, appUID, bundleID, credentials -func (_m *CredentialsService) Upsert(application string, appUID types.UID, bundleID string, credentials *model.Credentials) (applications.Credentials, apperrors.AppError) { - ret := _m.Called(application, appUID, bundleID, credentials) - - var r0 applications.Credentials - if rf, ok := ret.Get(0).(func(string, types.UID, string, *model.Credentials) applications.Credentials); ok { - r0 = rf(application, appUID, bundleID, credentials) - } else { - r0 = ret.Get(0).(applications.Credentials) - } - - var r1 apperrors.AppError - if rf, ok := ret.Get(1).(func(string, types.UID, string, *model.Credentials) apperrors.AppError); ok { - r1 = rf(application, appUID, bundleID, credentials) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(apperrors.AppError) - } - } - - return r0, r1 -} diff --git a/components/compass-runtime-agent/internal/kyma/secrets/mocks/Repository.go b/components/compass-runtime-agent/internal/kyma/secrets/mocks/Repository.go deleted file mode 100644 index 0f4d208286fa..000000000000 --- a/components/compass-runtime-agent/internal/kyma/secrets/mocks/Repository.go +++ /dev/null @@ -1,91 +0,0 @@ -// Code generated by mockery v2.10.0. DO NOT EDIT. - -package mocks - -import ( - apperrors "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/apperrors" - - mock "github.com/stretchr/testify/mock" - - strategy "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/secrets/strategy" - - types "k8s.io/apimachinery/pkg/types" -) - -// Repository is an autogenerated mock type for the Repository type -type Repository struct { - mock.Mock -} - -// Create provides a mock function with given fields: application, appUID, name, bundleID, data -func (_m *Repository) Create(application string, appUID types.UID, name string, bundleID string, data strategy.SecretData) apperrors.AppError { - ret := _m.Called(application, appUID, name, bundleID, data) - - var r0 apperrors.AppError - if rf, ok := ret.Get(0).(func(string, types.UID, string, string, strategy.SecretData) apperrors.AppError); ok { - r0 = rf(application, appUID, name, bundleID, data) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(apperrors.AppError) - } - } - - return r0 -} - -// Delete provides a mock function with given fields: name -func (_m *Repository) Delete(name string) apperrors.AppError { - ret := _m.Called(name) - - var r0 apperrors.AppError - if rf, ok := ret.Get(0).(func(string) apperrors.AppError); ok { - r0 = rf(name) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(apperrors.AppError) - } - } - - return r0 -} - -// Get provides a mock function with given fields: name -func (_m *Repository) Get(name string) (strategy.SecretData, apperrors.AppError) { - ret := _m.Called(name) - - var r0 strategy.SecretData - if rf, ok := ret.Get(0).(func(string) strategy.SecretData); ok { - r0 = rf(name) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(strategy.SecretData) - } - } - - var r1 apperrors.AppError - if rf, ok := ret.Get(1).(func(string) apperrors.AppError); ok { - r1 = rf(name) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(apperrors.AppError) - } - } - - return r0, r1 -} - -// Upsert provides a mock function with given fields: application, appUID, name, bundleID, data -func (_m *Repository) Upsert(application string, appUID types.UID, name string, bundleID string, data strategy.SecretData) apperrors.AppError { - ret := _m.Called(application, appUID, name, bundleID, data) - - var r0 apperrors.AppError - if rf, ok := ret.Get(0).(func(string, types.UID, string, string, strategy.SecretData) apperrors.AppError); ok { - r0 = rf(application, appUID, name, bundleID, data) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(apperrors.AppError) - } - } - - return r0 -} diff --git a/components/compass-runtime-agent/internal/kyma/secrets/mocks/RequestParametersService.go b/components/compass-runtime-agent/internal/kyma/secrets/mocks/RequestParametersService.go deleted file mode 100644 index 51581e6ad635..000000000000 --- a/components/compass-runtime-agent/internal/kyma/secrets/mocks/RequestParametersService.go +++ /dev/null @@ -1,105 +0,0 @@ -// Code generated by mockery v2.10.0. DO NOT EDIT. - -package mocks - -import ( - apperrors "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/apperrors" - - mock "github.com/stretchr/testify/mock" - - model "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/model" - - types "k8s.io/apimachinery/pkg/types" -) - -// RequestParametersService is an autogenerated mock type for the RequestParametersService type -type RequestParametersService struct { - mock.Mock -} - -// Create provides a mock function with given fields: application, appUID, bundleID, requestParameters -func (_m *RequestParametersService) Create(application string, appUID types.UID, bundleID string, requestParameters *model.RequestParameters) (string, apperrors.AppError) { - ret := _m.Called(application, appUID, bundleID, requestParameters) - - var r0 string - if rf, ok := ret.Get(0).(func(string, types.UID, string, *model.RequestParameters) string); ok { - r0 = rf(application, appUID, bundleID, requestParameters) - } else { - r0 = ret.Get(0).(string) - } - - var r1 apperrors.AppError - if rf, ok := ret.Get(1).(func(string, types.UID, string, *model.RequestParameters) apperrors.AppError); ok { - r1 = rf(application, appUID, bundleID, requestParameters) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(apperrors.AppError) - } - } - - return r0, r1 -} - -// Delete provides a mock function with given fields: secretName -func (_m *RequestParametersService) Delete(secretName string) apperrors.AppError { - ret := _m.Called(secretName) - - var r0 apperrors.AppError - if rf, ok := ret.Get(0).(func(string) apperrors.AppError); ok { - r0 = rf(secretName) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(apperrors.AppError) - } - } - - return r0 -} - -// Get provides a mock function with given fields: secretName -func (_m *RequestParametersService) Get(secretName string) (*model.RequestParameters, apperrors.AppError) { - ret := _m.Called(secretName) - - var r0 *model.RequestParameters - if rf, ok := ret.Get(0).(func(string) *model.RequestParameters); ok { - r0 = rf(secretName) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*model.RequestParameters) - } - } - - var r1 apperrors.AppError - if rf, ok := ret.Get(1).(func(string) apperrors.AppError); ok { - r1 = rf(secretName) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(apperrors.AppError) - } - } - - return r0, r1 -} - -// Upsert provides a mock function with given fields: application, appUID, bundleID, requestParameters -func (_m *RequestParametersService) Upsert(application string, appUID types.UID, bundleID string, requestParameters *model.RequestParameters) (string, apperrors.AppError) { - ret := _m.Called(application, appUID, bundleID, requestParameters) - - var r0 string - if rf, ok := ret.Get(0).(func(string, types.UID, string, *model.RequestParameters) string); ok { - r0 = rf(application, appUID, bundleID, requestParameters) - } else { - r0 = ret.Get(0).(string) - } - - var r1 apperrors.AppError - if rf, ok := ret.Get(1).(func(string, types.UID, string, *model.RequestParameters) apperrors.AppError); ok { - r1 = rf(application, appUID, bundleID, requestParameters) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(apperrors.AppError) - } - } - - return r0, r1 -} diff --git a/components/compass-runtime-agent/internal/kyma/secrets/repository.go b/components/compass-runtime-agent/internal/kyma/secrets/repository.go deleted file mode 100644 index 8a9ff1536f91..000000000000 --- a/components/compass-runtime-agent/internal/kyma/secrets/repository.go +++ /dev/null @@ -1,100 +0,0 @@ -// Package appsecrets contains components for accessing/modifying client secrets -package appsecrets - -import ( - "context" - - v1 "k8s.io/api/core/v1" - k8serrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/apperrors" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/k8sconsts" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/secrets/strategy" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/secrets" -) - -// Repository contains operations for managing client credentials -//go:generate mockery --name Repository -type Repository interface { - Create(application string, appUID types.UID, name, bundleID string, data strategy.SecretData) apperrors.AppError - Get(name string) (strategy.SecretData, apperrors.AppError) - Delete(name string) apperrors.AppError - Upsert(application string, appUID types.UID, name, bundleID string, data strategy.SecretData) apperrors.AppError -} - -type repository struct { - secretsManager secrets.Manager -} - -// NewRepository creates a new secrets repository -func NewRepository(secretsManager secrets.Manager) Repository { - return &repository{ - secretsManager: secretsManager, - } -} - -// Create adds a new secret with one entry containing specified clientId and clientSecret -func (r *repository) Create(application string, appUID types.UID, name, bundleID string, data strategy.SecretData) apperrors.AppError { - secret := makeSecret(name, bundleID, application, appUID, data) - return r.create(secret, name) -} - -func (r *repository) Get(name string) (data strategy.SecretData, error apperrors.AppError) { - secret, err := r.secretsManager.Get(context.Background(), name, metav1.GetOptions{}) - if err != nil { - if k8serrors.IsNotFound(err) { - return strategy.SecretData{}, apperrors.NotFound("Secret %s not found", name) - } - return strategy.SecretData{}, apperrors.Internal("Getting %s secret failed, %s", name, err.Error()) - } - - return secret.Data, nil -} - -func (r *repository) Delete(name string) apperrors.AppError { - err := r.secretsManager.Delete(context.Background(), name, metav1.DeleteOptions{}) - if err != nil && !k8serrors.IsNotFound(err) { - return apperrors.Internal("Deleting %s secret failed, %s", name, err.Error()) - } - return nil -} - -func (r *repository) Upsert(application string, appUID types.UID, name, bundleID string, data strategy.SecretData) apperrors.AppError { - secret := makeSecret(name, bundleID, application, appUID, data) - - _, err := r.secretsManager.Update(context.Background(), secret, metav1.UpdateOptions{}) - if err != nil { - if k8serrors.IsNotFound(err) { - return r.create(secret, name) - } - return apperrors.Internal("Updating %s secret failed, %s", name, err.Error()) - } - return nil -} - -func (r *repository) create(secret *v1.Secret, name string) apperrors.AppError { - _, err := r.secretsManager.Create(context.Background(), secret, metav1.CreateOptions{}) - if err != nil { - if k8serrors.IsAlreadyExists(err) { - return apperrors.AlreadyExists("Secret %s already exists", name) - } - return apperrors.Internal("Creating %s secret failed, %s", name, err.Error()) - } - return nil -} - -func makeSecret(name, bundleID, application string, appUID types.UID, data strategy.SecretData) *v1.Secret { - return &v1.Secret{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - Labels: map[string]string{ - k8sconsts.LabelApplication: application, - k8sconsts.LabelBundleId: bundleID, - }, - OwnerReferences: k8sconsts.CreateOwnerReferenceForApplication(application, appUID), - }, - Data: data, - } -} diff --git a/components/compass-runtime-agent/internal/kyma/secrets/repository_test.go b/components/compass-runtime-agent/internal/kyma/secrets/repository_test.go deleted file mode 100644 index dd83767a23e1..000000000000 --- a/components/compass-runtime-agent/internal/kyma/secrets/repository_test.go +++ /dev/null @@ -1,316 +0,0 @@ -package appsecrets - -import ( - "context" - "errors" - "testing" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/apperrors" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/secrets/mocks" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" - k8serrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -func TestRepository_Create(t *testing.T) { - - t.Run("should create secret", func(t *testing.T) { - // given - secretsManagerMock := &mocks.Manager{} - repository := NewRepository(secretsManagerMock) - - secret := makeSecret("new-secret", "secretId", "app", "appUID", map[string][]byte{ - "testKey1": []byte("testValue1"), - "testKey2": []byte("testValue2"), - }) - secretsManagerMock.On("Create", context.Background(), secret, metav1.CreateOptions{}).Return(secret, nil) - - // when - err := repository.Create("app", "appUID", "new-secret", "secretId", map[string][]byte{ - "testKey1": []byte("testValue1"), - "testKey2": []byte("testValue2"), - }) - - // then - assert.NoError(t, err) - secretsManagerMock.AssertExpectations(t) - }) - - t.Run("should fail if unable to create secret", func(t *testing.T) { - // given - secretsManagerMock := &mocks.Manager{} - repository := NewRepository(secretsManagerMock) - - secret := makeSecret("new-secret", "secretId", "app", "appUID", map[string][]byte{ - "testKey1": []byte("testValue1"), - "testKey2": []byte("testValue2"), - }) - secretsManagerMock.On("Create", context.Background(), secret, metav1.CreateOptions{}).Return(nil, errors.New("some error")) - - // when - err := repository.Create("app", "appUID", "new-secret", "secretId", map[string][]byte{ - "testKey1": []byte("testValue1"), - "testKey2": []byte("testValue2"), - }) - - // then - require.Error(t, err) - assert.Equal(t, apperrors.CodeInternal, err.Code()) - secretsManagerMock.AssertExpectations(t) - }) - - t.Run("should return already exists if secret was already created", func(t *testing.T) { - // given - secretsManagerMock := &mocks.Manager{} - repository := NewRepository(secretsManagerMock) - - secret := makeSecret("new-secret", "secretId", "app", "appUID", map[string][]byte{ - "testKey1": []byte("testValue1"), - "testKey2": []byte("testValue2"), - }) - secretsManagerMock.On("Create", context.Background(), secret, metav1.CreateOptions{}).Return(nil, k8serrors.NewAlreadyExists(schema.GroupResource{}, "")) - - // when - err := repository.Create("app", "appUID", "new-secret", "secretId", map[string][]byte{ - "testKey1": []byte("testValue1"), - "testKey2": []byte("testValue2"), - }) - - // then - require.Error(t, err) - assert.Equal(t, apperrors.CodeAlreadyExists, err.Code()) - secretsManagerMock.AssertExpectations(t) - }) -} - -func TestRepository_Get(t *testing.T) { - t.Run("should get given secret", func(t *testing.T) { - // given - secretsManagerMock := &mocks.Manager{} - repository := NewRepository(secretsManagerMock) - - secret := makeSecret("new-secret", "secretId", "app", "appUID", map[string][]byte{ - "testKey1": []byte("testValue1"), - "testKey2": []byte("testValue2"), - }) - secretsManagerMock.On("Get", context.Background(), "new-secret", metav1.GetOptions{}).Return(secret, nil) - - // when - data, err := repository.Get("new-secret") - - // then - assert.NoError(t, err) - assert.Equal(t, []byte("testValue1"), data["testKey1"]) - assert.Equal(t, []byte("testValue2"), data["testKey2"]) - - secretsManagerMock.AssertExpectations(t) - }) - - t.Run("should return an error in case fetching fails", func(t *testing.T) { - // given - secretsManagerMock := &mocks.Manager{} - repository := NewRepository(secretsManagerMock) - - secretsManagerMock.On("Get", context.Background(), "secret-name", metav1.GetOptions{}).Return( - nil, - errors.New("some error")) - - // when - data, err := repository.Get("secret-name") - - // then - assert.Error(t, err) - assert.Equal(t, apperrors.CodeInternal, err.Code()) - assert.NotEmpty(t, err.Error()) - - assert.Equal(t, []byte(nil), data["testKey1"]) - assert.Equal(t, []byte(nil), data["testKey2"]) - - secretsManagerMock.AssertExpectations(t) - }) - - t.Run("should return not found if secret does not exist", func(t *testing.T) { - // given - secretsManagerMock := &mocks.Manager{} - repository := NewRepository(secretsManagerMock) - - secretsManagerMock.On("Get", context.Background(), "secret-name", metav1.GetOptions{}).Return( - nil, - k8serrors.NewNotFound(schema.GroupResource{}, - "")) - - // when - data, err := repository.Get("secret-name") - - // then - assert.Error(t, err) - assert.Equal(t, apperrors.CodeNotFound, err.Code()) - assert.NotEmpty(t, err.Error()) - - assert.Equal(t, []byte(nil), data["testKey1"]) - assert.Equal(t, []byte(nil), data["testKey2"]) - - secretsManagerMock.AssertExpectations(t) - }) -} - -func TestRepository_Delete(t *testing.T) { - - t.Run("should delete given secret", func(t *testing.T) { - // given - secretsManagerMock := &mocks.Manager{} - repository := NewRepository(secretsManagerMock) - - secretsManagerMock.On("Delete", context.Background(), "test-secret", metav1.DeleteOptions{}).Return( - nil) - - // when - err := repository.Delete("test-secret") - - // then - assert.NoError(t, err) - secretsManagerMock.AssertExpectations(t) - - }) - - t.Run("should return error if deletion fails", func(t *testing.T) { - // given - secretsManagerMock := &mocks.Manager{} - repository := NewRepository(secretsManagerMock) - - secretsManagerMock.On("Delete", context.Background(), "test-secret", metav1.DeleteOptions{}).Return( - errors.New("some error")) - - // when - err := repository.Delete("test-secret") - - // then - assert.Error(t, err) - assert.Equal(t, apperrors.CodeInternal, err.Code()) - assert.NotEmpty(t, err.Error()) - - secretsManagerMock.AssertExpectations(t) - }) - - t.Run("should not return error if secret does not exist", func(t *testing.T) { - // given - secretsManagerMock := &mocks.Manager{} - repository := NewRepository(secretsManagerMock) - - secretsManagerMock.On("Delete", context.Background(), "test-secret", metav1.DeleteOptions{}).Return( - k8serrors.NewNotFound(schema.GroupResource{}, "")) - - // when - err := repository.Delete("test-secret") - - // then - assert.NoError(t, err) - secretsManagerMock.AssertExpectations(t) - }) -} - -func TestRepository_Upsert(t *testing.T) { - - t.Run("should update secret if it exists", func(t *testing.T) { - // given - secretsManagerMock := &mocks.Manager{} - repository := NewRepository(secretsManagerMock) - - secret := makeSecret("new-secret", "secretId", "app", "appUID", map[string][]byte{ - "testKey1": []byte("testValue1"), - "testKey2": []byte("testValue2"), - }) - secretsManagerMock.On("Update", context.Background(), secret, metav1.UpdateOptions{}).Return( - secret, nil) - - // when - err := repository.Upsert("app", "appUID", "new-secret", "secretId", map[string][]byte{ - "testKey1": []byte("testValue1"), - "testKey2": []byte("testValue2"), - }) - - // then - assert.NoError(t, err) - secretsManagerMock.AssertExpectations(t) - }) - - t.Run("should create secret if it does not exist", func(t *testing.T) { - // given - secretsManagerMock := &mocks.Manager{} - repository := NewRepository(secretsManagerMock) - - secret := makeSecret("new-secret", "secretId", "app", "appUID", map[string][]byte{ - "testKey1": []byte("testValue1"), - "testKey2": []byte("testValue2"), - }) - secretsManagerMock.On("Update", context.Background(), secret, metav1.UpdateOptions{}).Return( - nil, k8serrors.NewNotFound(schema.GroupResource{}, "")) - secretsManagerMock.On("Create", context.Background(), secret, metav1.CreateOptions{}).Return(secret, nil) - - // when - err := repository.Upsert("app", "appUID", "new-secret", "secretId", map[string][]byte{ - "testKey1": []byte("testValue1"), - "testKey2": []byte("testValue2"), - }) - - // then - assert.NoError(t, err) - secretsManagerMock.AssertExpectations(t) - }) - - t.Run("should return an error if update fails", func(t *testing.T) { - // given - secretsManagerMock := &mocks.Manager{} - repository := NewRepository(secretsManagerMock) - - secret := makeSecret("new-secret", "secretId", "app", "appUID", map[string][]byte{ - "testKey1": []byte("testValue1"), - "testKey2": []byte("testValue2"), - }) - secretsManagerMock.On("Update", context.Background(), secret, metav1.UpdateOptions{}).Return(nil, errors.New("some error")) - - // when - err := repository.Upsert("app", "appUID", "new-secret", "secretId", map[string][]byte{ - "testKey1": []byte("testValue1"), - "testKey2": []byte("testValue2"), - }) - - // then - assert.Error(t, err) - assert.Equal(t, apperrors.CodeInternal, err.Code()) - assert.NotEmpty(t, err.Error()) - - secretsManagerMock.AssertNotCalled(t, "Create", mock.AnythingOfType("*v1.Secret")) - secretsManagerMock.AssertExpectations(t) - }) - - t.Run("should return an error if create fails", func(t *testing.T) { - // given - secretsManagerMock := &mocks.Manager{} - repository := NewRepository(secretsManagerMock) - - secret := makeSecret("new-secret", "secretId", "app", "appUID", map[string][]byte{ - "testKey1": []byte("testValue1"), - "testKey2": []byte("testValue2"), - }) - secretsManagerMock.On("Update", context.Background(), secret, metav1.UpdateOptions{}).Return( - nil, k8serrors.NewNotFound(schema.GroupResource{}, "")) - secretsManagerMock.On("Create", context.Background(), secret, metav1.CreateOptions{}).Return(secret, errors.New("some error")) - - // when - err := repository.Upsert("app", "appUID", "new-secret", "secretId", map[string][]byte{ - "testKey1": []byte("testValue1"), - "testKey2": []byte("testValue2"), - }) - - // then - assert.Error(t, err) - assert.Equal(t, apperrors.CodeInternal, err.Code()) - assert.NotEmpty(t, err.Error()) - - secretsManagerMock.AssertExpectations(t) - }) -} diff --git a/components/compass-runtime-agent/internal/kyma/secrets/requestparameters.go b/components/compass-runtime-agent/internal/kyma/secrets/requestparameters.go deleted file mode 100644 index bff7e081fa69..000000000000 --- a/components/compass-runtime-agent/internal/kyma/secrets/requestparameters.go +++ /dev/null @@ -1,67 +0,0 @@ -package appsecrets - -import ( - "encoding/json" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/apperrors" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/model" -) - -const ( - requestParametersHeadersKey = "headers" - requestParametersQueryParametersKey = "queryParameters" -) - -func MapToRequestParameters(data map[string][]byte) (*model.RequestParameters, apperrors.AppError) { - requestParameters := &model.RequestParameters{} - - headersData := data[requestParametersHeadersKey] - if headersData != nil { - var headers = &map[string][]string{} - err := json.Unmarshal(headersData, headers) - if err != nil { - return nil, apperrors.Internal("Failed to unmarshal headers, %v", err) - } - - requestParameters.Headers = headers - } - - queryParamsData := data[requestParametersQueryParametersKey] - if queryParamsData != nil { - var queryParameters = &map[string][]string{} - err := json.Unmarshal(queryParamsData, queryParameters) - if err != nil { - return nil, apperrors.Internal("Failed to unmarshal query parameters, %v", err) - } - - requestParameters.QueryParameters = queryParameters - } - - if requestParameters.Headers == nil && requestParameters.QueryParameters == nil { - return nil, nil - } - - return requestParameters, nil -} - -func RequestParametersToMap(requestParameters *model.RequestParameters) (map[string][]byte, apperrors.AppError) { - data := make(map[string][]byte) - if requestParameters == nil { - return map[string][]byte{}, nil - } - if requestParameters.Headers != nil { - headers, err := json.Marshal(requestParameters.Headers) - if err != nil { - return map[string][]byte{}, apperrors.Internal("Failed to marshall headers from request parameters: %v", err) - } - data[requestParametersHeadersKey] = headers - } - if requestParameters.QueryParameters != nil { - queryParameters, err := json.Marshal(requestParameters.QueryParameters) - if err != nil { - return map[string][]byte{}, apperrors.Internal("Failed to marshall query parameters from request parameters: %v", err) - } - data[requestParametersQueryParametersKey] = queryParameters - } - return data, nil -} diff --git a/components/compass-runtime-agent/internal/kyma/secrets/requestparameters_test.go b/components/compass-runtime-agent/internal/kyma/secrets/requestparameters_test.go deleted file mode 100644 index bbcb6b1c4a8c..000000000000 --- a/components/compass-runtime-agent/internal/kyma/secrets/requestparameters_test.go +++ /dev/null @@ -1,64 +0,0 @@ -package appsecrets - -import ( - "testing" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/model" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -var ( - requestParameters = &model.RequestParameters{ - Headers: &map[string][]string{ - "TestHeader": { - "header value", - }, - }, - QueryParameters: &map[string][]string{ - "testQueryParam": { - "query parameter value", - }, - }, - } - - requestParametersJsonMap = map[string][]byte{ - "headers": []byte(`{"TestHeader":["header value"]}`), - "queryParameters": []byte(`{"testQueryParam":["query parameter value"]}`), - } -) - -func TestMapToRequestParameters(t *testing.T) { - t.Run("convert map to request parameters", func(t *testing.T) { - // when - convertedRequestParameters, err := MapToRequestParameters(requestParametersJsonMap) - - // then - require.NoError(t, err) - assert.Equal(t, requestParameters, convertedRequestParameters) - }) - - t.Run("return nil if request parameters are empty", func(t *testing.T) { - // given - jsonMap := map[string][]byte{"some key": []byte(`{"key":["value"]}`)} - - // when - convertedRequestParameters, err := MapToRequestParameters(jsonMap) - - // then - require.NoError(t, err) - assert.Nil(t, convertedRequestParameters) - }) -} - -func TestRequestParametersToMap(t *testing.T) { - t.Run("convert request parameters to map", func(t *testing.T) { - // when - convertedJsonMap, err := RequestParametersToMap(requestParameters) - - // then - require.NoError(t, err) - assert.Equal(t, requestParametersJsonMap, convertedJsonMap) - }) -} diff --git a/components/compass-runtime-agent/internal/kyma/secrets/requestparametersservice.go b/components/compass-runtime-agent/internal/kyma/secrets/requestparametersservice.go deleted file mode 100644 index 816d1abf6abb..000000000000 --- a/components/compass-runtime-agent/internal/kyma/secrets/requestparametersservice.go +++ /dev/null @@ -1,84 +0,0 @@ -package appsecrets - -import ( - "k8s.io/apimachinery/pkg/types" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/apperrors" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/k8sconsts" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/model" -) - -type requestParametersSecretModificationFunction func(application string, appUID types.UID, name, bundleID string, newData map[string][]byte) apperrors.AppError - -//go:generate mockery --name RequestParametersService -type RequestParametersService interface { - Get(secretName string) (*model.RequestParameters, apperrors.AppError) - Create(application string, appUID types.UID, bundleID string, requestParameters *model.RequestParameters) (string, apperrors.AppError) - Upsert(application string, appUID types.UID, bundleID string, requestParameters *model.RequestParameters) (string, apperrors.AppError) - Delete(secretName string) apperrors.AppError -} - -type requestParametersService struct { - repository Repository - nameResolver k8sconsts.NameResolver -} - -func NewRequestParametersService(repository Repository, nameResolver k8sconsts.NameResolver) RequestParametersService { - return &requestParametersService{ - repository: repository, - nameResolver: nameResolver, - } -} - -func (s *requestParametersService) Create(application string, appUID types.UID, bundleID string, requestParameters *model.RequestParameters) (string, apperrors.AppError) { - return s.modifySecret(application, appUID, bundleID, requestParameters, s.createSecret) -} - -func (s *requestParametersService) Get(secretName string) (*model.RequestParameters, apperrors.AppError) { - data, err := s.repository.Get(secretName) - if err != nil { - return nil, err - } - - return MapToRequestParameters(data) -} - -func (s *requestParametersService) Upsert(application string, appUID types.UID, bundleID string, requestParameters *model.RequestParameters) (string, apperrors.AppError) { - return s.modifySecret(application, appUID, bundleID, requestParameters, s.upsertSecret) -} - -func (s *requestParametersService) Delete(secretName string) apperrors.AppError { - return s.repository.Delete(secretName) -} - -func (s *requestParametersService) modifySecret(application string, appUID types.UID, bundleID string, requestParameters *model.RequestParameters, modFunction requestParametersSecretModificationFunction) (string, apperrors.AppError) { - if requestParameters == nil || requestParameters.IsEmpty() { - return "", nil - } - - name := s.createSecretName(application, bundleID) - - secretData, err := RequestParametersToMap(requestParameters) - if err != nil { - return "", err.Append("Failed to create request parameters secret data") - } - - err = modFunction(application, appUID, name, bundleID, secretData) - if err != nil { - return "", err - } - - return name, nil -} - -func (s *requestParametersService) upsertSecret(application string, appUID types.UID, name, bundleID string, newData map[string][]byte) apperrors.AppError { - return s.repository.Upsert(application, appUID, name, bundleID, newData) -} - -func (s *requestParametersService) createSecret(application string, appUID types.UID, name, bundleID string, newData map[string][]byte) apperrors.AppError { - return s.repository.Create(application, appUID, name, bundleID, newData) -} - -func (s *requestParametersService) createSecretName(application, bundleID string) string { - return s.nameResolver.GetRequestParametersSecretName(application, bundleID) -} diff --git a/components/compass-runtime-agent/internal/kyma/secrets/requestparametersservice_test.go b/components/compass-runtime-agent/internal/kyma/secrets/requestparametersservice_test.go deleted file mode 100644 index e0ba9ef8f957..000000000000 --- a/components/compass-runtime-agent/internal/kyma/secrets/requestparametersservice_test.go +++ /dev/null @@ -1,212 +0,0 @@ -package appsecrets - -import ( - "fmt" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/apperrors" - k8smocks "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/k8sconsts/mocks" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/secrets/mocks" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/secrets/strategy" -) - -var ( - requestParamsSecretData = strategy.SecretData{ - "headers": []byte(`{"TestHeader":["header value"]}`), - "queryParameters": []byte(`{"testQueryParam":["query parameter value"]}`), - } - - requestParametersSecretName = fmt.Sprintf("params-%s-%s", appName, bundleID) -) - -func TestRequestParametersService_Create(t *testing.T) { - t.Run("should create the secret", func(t *testing.T) { - // given - nameResolver := &k8smocks.NameResolver{} - nameResolver.On("GetRequestParametersSecretName", appName, bundleID).Return(requestParametersSecretName) - - secretsRepository := &mocks.Repository{} - secretsRepository.On("Create", appName, appUID, requestParametersSecretName, bundleID, requestParamsSecretData).Return(nil) - - service := NewRequestParametersService(secretsRepository, nameResolver) - - // when - createdSecret, err := service.Create(appName, appUID, bundleID, requestParameters) - - // then - require.NoError(t, err) - assert.Equal(t, requestParametersSecretName, createdSecret) - assertExpectations(t, &nameResolver.Mock, &secretsRepository.Mock) - }) - - t.Run("should return empty app requestParameters if requestParameters are nil", func(t *testing.T) { - // given - nameResolver := &k8smocks.NameResolver{} - secretsRepository := &mocks.Repository{} - - service := NewRequestParametersService(secretsRepository, nameResolver) - - // when - createdRequestParameters, err := service.Create(appName, appUID, bundleID, nil) - - // then - assert.NoError(t, err) - assert.Empty(t, createdRequestParameters) - assertExpectations(t, &nameResolver.Mock, &secretsRepository.Mock) - }) - - t.Run("should return error when failed to create the secret", func(t *testing.T) { - // given - nameResolver := &k8smocks.NameResolver{} - nameResolver.On("GetRequestParametersSecretName", appName, bundleID).Return(requestParametersSecretName) - - secretsRepository := &mocks.Repository{} - secretsRepository.On("Create", appName, appUID, requestParametersSecretName, bundleID, requestParamsSecretData).Return(apperrors.Internal("error")) - - service := NewRequestParametersService(secretsRepository, nameResolver) - - // when - createdRequestParameters, err := service.Create(appName, appUID, bundleID, requestParameters) - - // then - require.Error(t, err) - assert.Empty(t, createdRequestParameters) - assertExpectations(t, &nameResolver.Mock, &secretsRepository.Mock) - }) -} - -func TestRequestParametersService_Get(t *testing.T) { - t.Run("should return request parameters", func(t *testing.T) { - // given - nameResolver := &k8smocks.NameResolver{} - - secretsRepository := &mocks.Repository{} - secretsRepository.On("Get", requestParametersSecretName).Return(requestParamsSecretData, nil) - - service := NewRequestParametersService(secretsRepository, nameResolver) - - // when - createdRequestParameters, err := service.Get(requestParametersSecretName) - - // then - require.NoError(t, err) - assert.Equal(t, requestParameters.QueryParameters, createdRequestParameters.QueryParameters) - assert.Equal(t, requestParameters.Headers, createdRequestParameters.Headers) - assertExpectations(t, &nameResolver.Mock, &secretsRepository.Mock) - }) - - t.Run("should return error when failed to get the secret", func(t *testing.T) { - // given - nameResolver := &k8smocks.NameResolver{} - - secretsRepository := &mocks.Repository{} - secretsRepository.On("Get", requestParametersSecretName).Return(nil, apperrors.Internal("")) - service := NewRequestParametersService(secretsRepository, nameResolver) - - // when - createdRequestParameters, err := service.Get(requestParametersSecretName) - - // then - require.Error(t, err) - assert.Nil(t, createdRequestParameters) - assertExpectations(t, &nameResolver.Mock, &secretsRepository.Mock) - }) -} - -func TestRequestParametersService_Upsert(t *testing.T) { - t.Run("should upsert the secret", func(t *testing.T) { - // given - nameResolver := &k8smocks.NameResolver{} - nameResolver.On("GetRequestParametersSecretName", appName, bundleID).Return(requestParametersSecretName) - - secretsRepository := &mocks.Repository{} - secretsRepository.On("Upsert", appName, appUID, requestParametersSecretName, bundleID, requestParamsSecretData).Return(nil) - - service := NewRequestParametersService(secretsRepository, nameResolver) - - // when - createdSecret, err := service.Upsert(appName, appUID, bundleID, requestParameters) - - // then - require.NoError(t, err) - assert.Equal(t, requestParametersSecretName, createdSecret) - assertExpectations(t, &nameResolver.Mock, &secretsRepository.Mock) - }) - - t.Run("should create the secret if not found", func(t *testing.T) { - // given - nameResolver := &k8smocks.NameResolver{} - nameResolver.On("GetRequestParametersSecretName", appName, bundleID).Return(requestParametersSecretName) - - secretsRepository := &mocks.Repository{} - secretsRepository.On("Upsert", appName, appUID, requestParametersSecretName, bundleID, requestParamsSecretData).Return(nil) - - service := NewRequestParametersService(secretsRepository, nameResolver) - - // when - createdSecret, err := service.Upsert(appName, appUID, bundleID, requestParameters) - - // then - require.NoError(t, err) - assert.Equal(t, requestParametersSecretName, createdSecret) - assertExpectations(t, &nameResolver.Mock, &secretsRepository.Mock) - }) - - t.Run("should return error when failed to update secret", func(t *testing.T) { - // given - nameResolver := &k8smocks.NameResolver{} - nameResolver.On("GetRequestParametersSecretName", appName, bundleID).Return(requestParametersSecretName) - - secretsRepository := &mocks.Repository{} - secretsRepository.On("Upsert", appName, appUID, requestParametersSecretName, bundleID, requestParamsSecretData).Return(apperrors.Internal("error")) - - service := NewRequestParametersService(secretsRepository, nameResolver) - - // when - createdRequestParameters, err := service.Upsert(appName, appUID, bundleID, requestParameters) - - // then - require.Error(t, err) - assert.Empty(t, createdRequestParameters) - assertExpectations(t, &nameResolver.Mock, &secretsRepository.Mock) - }) -} - -func TestRequestParametersService_Delete(t *testing.T) { - t.Run("should delete a secret", func(t *testing.T) { - // given - nameResolver := &k8smocks.NameResolver{} - - secretsRepository := &mocks.Repository{} - secretsRepository.On("Delete", requestParametersSecretName).Return(nil) - - service := NewRequestParametersService(secretsRepository, nameResolver) - - // when - err := service.Delete(requestParametersSecretName) - - // then - require.NoError(t, err) - assertExpectations(t, &nameResolver.Mock, &secretsRepository.Mock) - }) - - t.Run("should return an error failed to delete secret", func(t *testing.T) { - // given - nameResolver := &k8smocks.NameResolver{} - - secretsRepository := &mocks.Repository{} - secretsRepository.On("Delete", requestParametersSecretName).Return(apperrors.Internal("error")) - - service := NewRequestParametersService(secretsRepository, nameResolver) - - // when - err := service.Delete(requestParametersSecretName) - - // then - require.Error(t, err) - assertExpectations(t, &nameResolver.Mock, &secretsRepository.Mock) - }) -} diff --git a/components/compass-runtime-agent/internal/kyma/secrets/strategy/basicauth.go b/components/compass-runtime-agent/internal/kyma/secrets/strategy/basicauth.go deleted file mode 100644 index b9f301cc8f28..000000000000 --- a/components/compass-runtime-agent/internal/kyma/secrets/strategy/basicauth.go +++ /dev/null @@ -1,63 +0,0 @@ -package strategy - -import ( - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/apperrors" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/applications" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/model" -) - -const ( - BasicAuthUsernameKey = "username" - BasicAuthPasswordKey = "password" -) - -type basicAuth struct{} - -func (svc *basicAuth) ToCredentials(secretData SecretData, appCredentials *applications.Credentials) (model.Credentials, apperrors.AppError) { - username, password := svc.readBasicAuthMap(secretData) - return model.Credentials{ - Basic: &model.Basic{ - Username: username, - Password: password, - }, - CSRFInfo: convertToModelCSRInfo(appCredentials), - }, nil -} - -func (svc *basicAuth) CredentialsProvided(credentials *model.Credentials) bool { - return svc.basicCredentialsProvided(credentials) -} - -func (svc *basicAuth) CreateSecretData(credentials *model.Credentials) (SecretData, apperrors.AppError) { - return svc.makeBasicAuthMap(credentials.Basic.Username, credentials.Basic.Password), nil -} - -func (svc *basicAuth) ToCredentialsInfo(credentials *model.Credentials, secretName string) applications.Credentials { - applicationCredentials := applications.Credentials{ - Type: applications.CredentialsBasicType, - SecretName: secretName, - CSRFInfo: toAppCSRFInfo(credentials), - } - - return applicationCredentials -} - -func (svc *basicAuth) ShouldUpdate(currentData SecretData, newData SecretData) bool { - return string(currentData[BasicAuthUsernameKey]) != string(newData[BasicAuthUsernameKey]) || - string(currentData[BasicAuthPasswordKey]) != string(newData[BasicAuthPasswordKey]) -} - -func (svc *basicAuth) makeBasicAuthMap(username, password string) map[string][]byte { - return map[string][]byte{ - BasicAuthUsernameKey: []byte(username), - BasicAuthPasswordKey: []byte(password), - } -} - -func (svc *basicAuth) readBasicAuthMap(data map[string][]byte) (username, password string) { - return string(data[BasicAuthUsernameKey]), string(data[BasicAuthPasswordKey]) -} - -func (svc *basicAuth) basicCredentialsProvided(credentials *model.Credentials) bool { - return credentials != nil && credentials.Basic != nil && credentials.Basic.Username != "" && credentials.Basic.Password != "" -} diff --git a/components/compass-runtime-agent/internal/kyma/secrets/strategy/basicauth_test.go b/components/compass-runtime-agent/internal/kyma/secrets/strategy/basicauth_test.go deleted file mode 100644 index b1606053585d..000000000000 --- a/components/compass-runtime-agent/internal/kyma/secrets/strategy/basicauth_test.go +++ /dev/null @@ -1,214 +0,0 @@ -package strategy - -import ( - "testing" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/applications" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/model" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -const ( - username = "username" - password = "password" - secretName = "secretName" -) - -var ( - basicCredentials = &model.Credentials{ - Basic: &model.Basic{ - Username: username, Password: password, - }, - } -) - -func TestBasicAuth_ToCredentials(t *testing.T) { - - secretData := map[string][]byte{ - BasicAuthUsernameKey: []byte(username), - BasicAuthPasswordKey: []byte(password), - } - - t.Run("should convert to credentials", func(t *testing.T) { - // given - basicAuthStrategy := basicAuth{} - - // when - credentials, err := basicAuthStrategy.ToCredentials(secretData, nil) - - // then - require.NoError(t, err) - assert.Equal(t, username, credentials.Basic.Username) - assert.Equal(t, password, credentials.Basic.Password) - - }) - - t.Run("should convert to credentials with CSRFInfo", func(t *testing.T) { - // given - basicAuthStrategy := basicAuth{} - - // when - credentials, err := basicAuthStrategy.ToCredentials(secretData, &applications.Credentials{CSRFInfo: &applications.CSRFInfo{TokenEndpointURL: "https://test.it"}}) - - // then - require.NoError(t, err) - assert.Equal(t, username, credentials.Basic.Username) - assert.Equal(t, password, credentials.Basic.Password) - assert.NotNil(t, credentials.Basic) - assert.NotNil(t, credentials.CSRFInfo) - assert.Equal(t, "https://test.it", credentials.CSRFInfo.TokenEndpointURL) - - }) -} - -func TestBasicAuth_CredentialsProvided(t *testing.T) { - - testCases := []struct { - credentials *model.Credentials - result bool - }{ - { - credentials: &model.Credentials{ - Basic: &model.Basic{ - Username: username, - Password: password}, - }, - result: true, - }, - { - credentials: &model.Credentials{ - Basic: &model.Basic{ - Username: "", - Password: password}, - }, - result: false, - }, - { - credentials: &model.Credentials{ - Basic: &model.Basic{ - Username: username, - Password: ""}, - }, - result: false, - }, - { - credentials: nil, - result: false, - }, - } - - t.Run("should check if credentials provided", func(t *testing.T) { - // given - basicAuthStrategy := basicAuth{} - - for _, test := range testCases { - // when - result := basicAuthStrategy.CredentialsProvided(test.credentials) - - // then - assert.Equal(t, test.result, result) - } - }) -} - -func TestBasicAuth_CreateSecretData(t *testing.T) { - t.Run("should create secret data", func(t *testing.T) { - // given - basicAuthStrategy := basicAuth{} - - // when - secretData, err := basicAuthStrategy.CreateSecretData(basicCredentials) - - //then - require.NoError(t, err) - assert.Equal(t, []byte(username), secretData[BasicAuthUsernameKey]) - assert.Equal(t, []byte(password), secretData[BasicAuthPasswordKey]) - }) -} - -func TestBasicAuth_ToCredentialsInfo(t *testing.T) { - t.Run("should convert to app credentials", func(t *testing.T) { - // given - basicAuthStrategy := basicAuth{} - - // when - appCredentials := basicAuthStrategy.ToCredentialsInfo(basicCredentials, secretName) - - // then - assert.Equal(t, applications.CredentialsBasicType, appCredentials.Type) - assert.Equal(t, secretName, appCredentials.SecretName) - assert.Equal(t, "", appCredentials.AuthenticationUrl) - }) -} - -func TestBasicAuth_ShouldUpdate(t *testing.T) { - testCases := []struct { - currentData SecretData - newData SecretData - result bool - }{ - { - currentData: SecretData{ - BasicAuthUsernameKey: []byte(username), - BasicAuthPasswordKey: []byte(password), - }, - newData: SecretData{ - BasicAuthUsernameKey: []byte("changed username"), - BasicAuthPasswordKey: []byte(password), - }, - result: true, - }, - { - currentData: SecretData{ - BasicAuthUsernameKey: []byte(username), - BasicAuthPasswordKey: []byte(password), - }, - newData: SecretData{ - BasicAuthUsernameKey: []byte(username), - BasicAuthPasswordKey: []byte("changed password"), - }, - result: true, - }, - { - currentData: SecretData{}, - newData: SecretData{ - BasicAuthUsernameKey: []byte(username), - BasicAuthPasswordKey: []byte(password), - }, - result: true, - }, - { - currentData: SecretData{ - BasicAuthUsernameKey: []byte(username), - BasicAuthPasswordKey: []byte(password), - }, - newData: SecretData{}, - result: true, - }, - { - currentData: SecretData{ - BasicAuthUsernameKey: []byte(username), - BasicAuthPasswordKey: []byte(password), - }, - newData: SecretData{ - BasicAuthUsernameKey: []byte(username), - BasicAuthPasswordKey: []byte(password), - }, - result: false, - }, - } - - t.Run("should return true when update needed", func(t *testing.T) { - // given - basicAuthStrategy := basicAuth{} - - for _, test := range testCases { - // when - result := basicAuthStrategy.ShouldUpdate(test.currentData, test.newData) - - // then - assert.Equal(t, test.result, result) - } - }) -} diff --git a/components/compass-runtime-agent/internal/kyma/secrets/strategy/csrf.go b/components/compass-runtime-agent/internal/kyma/secrets/strategy/csrf.go deleted file mode 100644 index 2cbcefbf84c2..000000000000 --- a/components/compass-runtime-agent/internal/kyma/secrets/strategy/csrf.go +++ /dev/null @@ -1,35 +0,0 @@ -package strategy - -import ( - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/applications" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/model" -) - -func convertToModelCSRInfo(appCredentials *applications.Credentials) *model.CSRFInfo { - if appCredentials == nil || appCredentials.CSRFInfo == nil { - return nil - } - - return &model.CSRFInfo{ - TokenEndpointURL: appCredentials.CSRFInfo.TokenEndpointURL, - } -} - -func toAppCSRFInfo(credentials *model.Credentials) *applications.CSRFInfo { - - convertFromModel := func(csrfInfo *model.CSRFInfo) *applications.CSRFInfo { - if csrfInfo == nil { - return nil - } - - return &applications.CSRFInfo{ - TokenEndpointURL: csrfInfo.TokenEndpointURL, - } - } - - if credentials == nil { - return nil - } - - return convertFromModel(credentials.CSRFInfo) -} diff --git a/components/compass-runtime-agent/internal/kyma/secrets/strategy/factory.go b/components/compass-runtime-agent/internal/kyma/secrets/strategy/factory.go deleted file mode 100644 index 3a2762ce9d26..000000000000 --- a/components/compass-runtime-agent/internal/kyma/secrets/strategy/factory.go +++ /dev/null @@ -1,75 +0,0 @@ -package strategy - -import ( - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/apperrors" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/applications" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/model" -) - -type SecretData map[string][]byte - -//go:generate mockery --name ModificationStrategy -type ModificationStrategy interface { - CredentialsProvided(credentials *model.Credentials) bool - CreateSecretData(credentials *model.Credentials) (SecretData, apperrors.AppError) - ToCredentialsInfo(credentials *model.Credentials, secretName string) applications.Credentials - ShouldUpdate(currentData SecretData, newData SecretData) bool -} - -//go:generate mockery --name AccessStrategy -type AccessStrategy interface { - ToCredentials(secretData SecretData, appCredentials *applications.Credentials) (model.Credentials, apperrors.AppError) -} - -//go:generate mockery --name Factory -type Factory interface { - NewSecretModificationStrategy(credentials *model.Credentials) (ModificationStrategy, apperrors.AppError) - NewSecretAccessStrategy(credentials *applications.Credentials) (AccessStrategy, apperrors.AppError) -} - -type factory struct { -} - -func NewSecretsStrategyFactory() Factory { - return &factory{} -} - -func (s *factory) NewSecretModificationStrategy(credentials *model.Credentials) (ModificationStrategy, apperrors.AppError) { - if !credentialsValid(credentials) { - return nil, apperrors.WrongInput("Error: only one credential type have to be provided.") - } - - if credentials.Basic != nil { - return &basicAuth{}, nil - } - - if credentials.Oauth != nil { - return &oauth{}, nil - } - - return nil, apperrors.WrongInput("Invalid credential type provided") -} - -func credentialsValid(credentials *model.Credentials) bool { - credentialsCount := 0 - - if credentials.Basic != nil { - credentialsCount++ - } - - if credentials.Oauth != nil { - credentialsCount++ - } - return credentialsCount == 1 -} - -func (s *factory) NewSecretAccessStrategy(credentials *applications.Credentials) (AccessStrategy, apperrors.AppError) { - switch credentials.Type { - case applications.CredentialsBasicType: - return &basicAuth{}, nil - case applications.CredentialsOAuthType: - return &oauth{}, nil - default: - return nil, apperrors.Internal("Failed to initialize secret access strategy") - } -} diff --git a/components/compass-runtime-agent/internal/kyma/secrets/strategy/factory_test.go b/components/compass-runtime-agent/internal/kyma/secrets/strategy/factory_test.go deleted file mode 100644 index 7ae268250961..000000000000 --- a/components/compass-runtime-agent/internal/kyma/secrets/strategy/factory_test.go +++ /dev/null @@ -1,96 +0,0 @@ -package strategy - -import ( - "testing" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/applications" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/model" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestFactory_NewSecretModificationStrategy(t *testing.T) { - - testCases := []struct { - credentials *model.Credentials - strategy ModificationStrategy - }{ - { - credentials: basicCredentials, - strategy: &basicAuth{}, - }, - { - credentials: oauthCredentials, - strategy: &oauth{}, - }, - } - - t.Run("should create new modification strategy", func(t *testing.T) { - // given - factory := &factory{} - - for _, test := range testCases { - // when - strategy, err := factory.NewSecretModificationStrategy(test.credentials) - - // then - require.NoError(t, err) - assert.IsType(t, test.strategy, strategy) - } - }) - - t.Run("should return error when no credentials provided", func(t *testing.T) { - // given - factory := &factory{} - - // when - _, err := factory.NewSecretModificationStrategy(&model.Credentials{}) - - // then - require.Error(t, err) - - }) - -} - -func TestFactory_NewSecretAccessStrategy(t *testing.T) { - testCases := []struct { - credentials *applications.Credentials - strategy AccessStrategy - }{ - { - credentials: &applications.Credentials{Type: applications.CredentialsBasicType}, - strategy: &basicAuth{}, - }, - { - credentials: &applications.Credentials{Type: applications.CredentialsOAuthType}, - strategy: &oauth{}, - }, - } - - t.Run("should create new access strategy", func(t *testing.T) { - // given - factory := &factory{} - - for _, test := range testCases { - // when - strategy, err := factory.NewSecretAccessStrategy(test.credentials) - - // then - require.NoError(t, err) - assert.IsType(t, test.strategy, strategy) - } - }) - - t.Run("should return error when no credentials provided", func(t *testing.T) { - // given - factory := &factory{} - - // when - _, err := factory.NewSecretAccessStrategy(&applications.Credentials{}) - - // then - require.Error(t, err) - }) -} diff --git a/components/compass-runtime-agent/internal/kyma/secrets/strategy/mocks/AccessStrategy.go b/components/compass-runtime-agent/internal/kyma/secrets/strategy/mocks/AccessStrategy.go deleted file mode 100644 index 21974b26acef..000000000000 --- a/components/compass-runtime-agent/internal/kyma/secrets/strategy/mocks/AccessStrategy.go +++ /dev/null @@ -1,42 +0,0 @@ -// Code generated by mockery v2.10.0. DO NOT EDIT. - -package mocks - -import ( - apperrors "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/apperrors" - applications "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/applications" - - mock "github.com/stretchr/testify/mock" - - model "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/model" - - strategy "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/secrets/strategy" -) - -// AccessStrategy is an autogenerated mock type for the AccessStrategy type -type AccessStrategy struct { - mock.Mock -} - -// ToCredentials provides a mock function with given fields: secretData, appCredentials -func (_m *AccessStrategy) ToCredentials(secretData strategy.SecretData, appCredentials *applications.Credentials) (model.Credentials, apperrors.AppError) { - ret := _m.Called(secretData, appCredentials) - - var r0 model.Credentials - if rf, ok := ret.Get(0).(func(strategy.SecretData, *applications.Credentials) model.Credentials); ok { - r0 = rf(secretData, appCredentials) - } else { - r0 = ret.Get(0).(model.Credentials) - } - - var r1 apperrors.AppError - if rf, ok := ret.Get(1).(func(strategy.SecretData, *applications.Credentials) apperrors.AppError); ok { - r1 = rf(secretData, appCredentials) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(apperrors.AppError) - } - } - - return r0, r1 -} diff --git a/components/compass-runtime-agent/internal/kyma/secrets/strategy/mocks/Factory.go b/components/compass-runtime-agent/internal/kyma/secrets/strategy/mocks/Factory.go deleted file mode 100644 index fd96b5009544..000000000000 --- a/components/compass-runtime-agent/internal/kyma/secrets/strategy/mocks/Factory.go +++ /dev/null @@ -1,69 +0,0 @@ -// Code generated by mockery v2.10.0. DO NOT EDIT. - -package mocks - -import ( - apperrors "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/apperrors" - applications "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/applications" - - mock "github.com/stretchr/testify/mock" - - model "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/model" - - strategy "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/secrets/strategy" -) - -// Factory is an autogenerated mock type for the Factory type -type Factory struct { - mock.Mock -} - -// NewSecretAccessStrategy provides a mock function with given fields: credentials -func (_m *Factory) NewSecretAccessStrategy(credentials *applications.Credentials) (strategy.AccessStrategy, apperrors.AppError) { - ret := _m.Called(credentials) - - var r0 strategy.AccessStrategy - if rf, ok := ret.Get(0).(func(*applications.Credentials) strategy.AccessStrategy); ok { - r0 = rf(credentials) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(strategy.AccessStrategy) - } - } - - var r1 apperrors.AppError - if rf, ok := ret.Get(1).(func(*applications.Credentials) apperrors.AppError); ok { - r1 = rf(credentials) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(apperrors.AppError) - } - } - - return r0, r1 -} - -// NewSecretModificationStrategy provides a mock function with given fields: credentials -func (_m *Factory) NewSecretModificationStrategy(credentials *model.Credentials) (strategy.ModificationStrategy, apperrors.AppError) { - ret := _m.Called(credentials) - - var r0 strategy.ModificationStrategy - if rf, ok := ret.Get(0).(func(*model.Credentials) strategy.ModificationStrategy); ok { - r0 = rf(credentials) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(strategy.ModificationStrategy) - } - } - - var r1 apperrors.AppError - if rf, ok := ret.Get(1).(func(*model.Credentials) apperrors.AppError); ok { - r1 = rf(credentials) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(apperrors.AppError) - } - } - - return r0, r1 -} diff --git a/components/compass-runtime-agent/internal/kyma/secrets/strategy/mocks/ModificationStrategy.go b/components/compass-runtime-agent/internal/kyma/secrets/strategy/mocks/ModificationStrategy.go deleted file mode 100644 index 78ea9aeea2ea..000000000000 --- a/components/compass-runtime-agent/internal/kyma/secrets/strategy/mocks/ModificationStrategy.go +++ /dev/null @@ -1,86 +0,0 @@ -// Code generated by mockery v2.10.0. DO NOT EDIT. - -package mocks - -import ( - apperrors "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/apperrors" - applications "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/applications" - - mock "github.com/stretchr/testify/mock" - - model "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/model" - - strategy "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/secrets/strategy" -) - -// ModificationStrategy is an autogenerated mock type for the ModificationStrategy type -type ModificationStrategy struct { - mock.Mock -} - -// CreateSecretData provides a mock function with given fields: credentials -func (_m *ModificationStrategy) CreateSecretData(credentials *model.Credentials) (strategy.SecretData, apperrors.AppError) { - ret := _m.Called(credentials) - - var r0 strategy.SecretData - if rf, ok := ret.Get(0).(func(*model.Credentials) strategy.SecretData); ok { - r0 = rf(credentials) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(strategy.SecretData) - } - } - - var r1 apperrors.AppError - if rf, ok := ret.Get(1).(func(*model.Credentials) apperrors.AppError); ok { - r1 = rf(credentials) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(apperrors.AppError) - } - } - - return r0, r1 -} - -// CredentialsProvided provides a mock function with given fields: credentials -func (_m *ModificationStrategy) CredentialsProvided(credentials *model.Credentials) bool { - ret := _m.Called(credentials) - - var r0 bool - if rf, ok := ret.Get(0).(func(*model.Credentials) bool); ok { - r0 = rf(credentials) - } else { - r0 = ret.Get(0).(bool) - } - - return r0 -} - -// ShouldUpdate provides a mock function with given fields: currentData, newData -func (_m *ModificationStrategy) ShouldUpdate(currentData strategy.SecretData, newData strategy.SecretData) bool { - ret := _m.Called(currentData, newData) - - var r0 bool - if rf, ok := ret.Get(0).(func(strategy.SecretData, strategy.SecretData) bool); ok { - r0 = rf(currentData, newData) - } else { - r0 = ret.Get(0).(bool) - } - - return r0 -} - -// ToCredentialsInfo provides a mock function with given fields: credentials, secretName -func (_m *ModificationStrategy) ToCredentialsInfo(credentials *model.Credentials, secretName string) applications.Credentials { - ret := _m.Called(credentials, secretName) - - var r0 applications.Credentials - if rf, ok := ret.Get(0).(func(*model.Credentials, string) applications.Credentials); ok { - r0 = rf(credentials, secretName) - } else { - r0 = ret.Get(0).(applications.Credentials) - } - - return r0 -} diff --git a/components/compass-runtime-agent/internal/kyma/secrets/strategy/oauth.go b/components/compass-runtime-agent/internal/kyma/secrets/strategy/oauth.go deleted file mode 100644 index 176409a92f5b..000000000000 --- a/components/compass-runtime-agent/internal/kyma/secrets/strategy/oauth.go +++ /dev/null @@ -1,67 +0,0 @@ -package strategy - -import ( - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/apperrors" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/applications" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/model" -) - -const ( - OauthClientIDKey = "clientId" - OauthClientSecretKey = "clientSecret" -) - -type oauth struct{} - -func (svc *oauth) ToCredentials(secretData SecretData, appCredentials *applications.Credentials) (model.Credentials, apperrors.AppError) { - clientId, clientSecret := svc.readOauthMap(secretData) - return model.Credentials{ - Oauth: &model.Oauth{ - ClientID: clientId, - ClientSecret: clientSecret, - URL: appCredentials.AuthenticationUrl, - }, - CSRFInfo: convertToModelCSRInfo(appCredentials), - }, nil -} - -func (svc *oauth) CredentialsProvided(credentials *model.Credentials) bool { - return svc.oauthCredentialsProvided(credentials) -} - -func (svc *oauth) CreateSecretData(credentials *model.Credentials) (SecretData, apperrors.AppError) { - return svc.makeOauthMap(credentials.Oauth.ClientID, credentials.Oauth.ClientSecret) -} - -func (svc *oauth) ToCredentialsInfo(credentials *model.Credentials, secretName string) applications.Credentials { - - applicationCredentials := applications.Credentials{ - AuthenticationUrl: credentials.Oauth.URL, - Type: applications.CredentialsOAuthType, - SecretName: secretName, - CSRFInfo: toAppCSRFInfo(credentials), - } - - return applicationCredentials -} - -func (svc *oauth) ShouldUpdate(currentData SecretData, newData SecretData) bool { - return string(currentData[OauthClientIDKey]) != string(newData[OauthClientIDKey]) || - string(currentData[OauthClientSecretKey]) != string(newData[OauthClientSecretKey]) -} - -func (svc *oauth) oauthCredentialsProvided(credentials *model.Credentials) bool { - return credentials != nil && credentials.Oauth != nil && credentials.Oauth.ClientID != "" && credentials.Oauth.ClientSecret != "" -} - -func (svc *oauth) makeOauthMap(clientID, clientSecret string) (map[string][]byte, apperrors.AppError) { - m := map[string][]byte{ - OauthClientIDKey: []byte(clientID), - OauthClientSecretKey: []byte(clientSecret), - } - return m, nil -} - -func (svc *oauth) readOauthMap(data map[string][]byte) (clientID, clientSecret string) { - return string(data[OauthClientIDKey]), string(data[OauthClientSecretKey]) -} diff --git a/components/compass-runtime-agent/internal/kyma/secrets/strategy/oauth_test.go b/components/compass-runtime-agent/internal/kyma/secrets/strategy/oauth_test.go deleted file mode 100644 index 395ae0a55648..000000000000 --- a/components/compass-runtime-agent/internal/kyma/secrets/strategy/oauth_test.go +++ /dev/null @@ -1,245 +0,0 @@ -package strategy - -import ( - "testing" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/applications" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/model" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -const ( - clientId = "clientId" - clientSecret = "clientSecret" - oauthUrl = "oauthUrl" -) - -var ( - oauthCredentials = &model.Credentials{ - Oauth: &model.Oauth{ - ClientID: clientId, - ClientSecret: clientSecret, - URL: oauthUrl, - }, - } -) - -func TestOauth_ToCredentials(t *testing.T) { - - secretData := map[string][]byte{ - OauthClientIDKey: []byte(clientId), - OauthClientSecretKey: []byte(clientSecret), - } - - appCredentials := &applications.Credentials{ - AuthenticationUrl: oauthUrl, - } - - t.Run("should convert to credentials", func(t *testing.T) { - // given - oauthStrategy := oauth{} - - // when - credentials, err := oauthStrategy.ToCredentials(secretData, appCredentials) - - // then - require.NoError(t, err) - assert.Equal(t, clientId, credentials.Oauth.ClientID) - assert.Equal(t, clientSecret, credentials.Oauth.ClientSecret) - assert.Equal(t, oauthUrl, credentials.Oauth.URL) - }) - - t.Run("should convert to credentials with additional headers and query parameters", func(t *testing.T) { - // given - secretData := map[string][]byte{ - OauthClientIDKey: []byte(clientId), - OauthClientSecretKey: []byte(clientSecret), - } - - oauthStrategy := oauth{} - - // when - credentials, err := oauthStrategy.ToCredentials(secretData, appCredentials) - - // then - require.NoError(t, err) - assert.Equal(t, clientId, credentials.Oauth.ClientID) - assert.Equal(t, clientSecret, credentials.Oauth.ClientSecret) - assert.Equal(t, oauthUrl, credentials.Oauth.URL) - }) - - t.Run("should convert to credentials with CSRF", func(t *testing.T) { - // given - oauthStrategy := oauth{} - - c := &applications.Credentials{ - AuthenticationUrl: oauthUrl, - CSRFInfo: &applications.CSRFInfo{TokenEndpointURL: "https://test.it"}, - } - // when - credentials, err := oauthStrategy.ToCredentials(secretData, c) - - // then - require.NoError(t, err) - assert.Equal(t, clientId, credentials.Oauth.ClientID) - assert.Equal(t, clientSecret, credentials.Oauth.ClientSecret) - assert.Equal(t, oauthUrl, credentials.Oauth.URL) - assert.Equal(t, "https://test.it", credentials.CSRFInfo.TokenEndpointURL) - }) -} - -func TestOauth_CredentialsProvided(t *testing.T) { - - testCases := []struct { - credentials *model.Credentials - result bool - }{ - { - credentials: &model.Credentials{ - Oauth: &model.Oauth{ - ClientID: clientId, - ClientSecret: clientSecret, - }, - }, - result: true, - }, - { - credentials: &model.Credentials{ - Oauth: &model.Oauth{ - ClientID: "", - ClientSecret: clientSecret, - }, - }, - result: false, - }, - { - credentials: &model.Credentials{ - Oauth: &model.Oauth{ - ClientID: clientId, - ClientSecret: "", - }, - }, - result: false, - }, - { - credentials: nil, - result: false, - }, - } - - t.Run("should check if credentials provided", func(t *testing.T) { - // given - oauthStrategy := oauth{} - - for _, test := range testCases { - // when - result := oauthStrategy.CredentialsProvided(test.credentials) - - // then - assert.Equal(t, test.result, result) - assert.Equal(t, test.result, result) - } - }) -} - -func TestOauth_CreateSecretData(t *testing.T) { - t.Run("should create secret data", func(t *testing.T) { - // given - oauthStrategy := oauth{} - - // when - secretData, err := oauthStrategy.CreateSecretData(oauthCredentials) - - //then - require.NoError(t, err) - assert.Equal(t, []byte(clientId), secretData[OauthClientIDKey]) - assert.Equal(t, []byte(clientSecret), secretData[OauthClientSecretKey]) - }) -} - -func TestOauth_ToCredentialsInfo(t *testing.T) { - t.Run("should convert to app credentials", func(t *testing.T) { - // given - oauthStrategy := oauth{} - - // when - appCredentials := oauthStrategy.ToCredentialsInfo(oauthCredentials, secretName) - - // then - assert.Equal(t, applications.CredentialsOAuthType, appCredentials.Type) - assert.Equal(t, secretName, appCredentials.SecretName) - assert.Equal(t, oauthUrl, appCredentials.AuthenticationUrl) - }) -} - -func TestOauth_ShouldUpdate(t *testing.T) { - testCases := []struct { - currentData SecretData - newData SecretData - result bool - }{ - { - currentData: SecretData{ - OauthClientIDKey: []byte(clientId), - OauthClientSecretKey: []byte(clientSecret), - }, - newData: SecretData{ - OauthClientIDKey: []byte("changed client id"), - OauthClientSecretKey: []byte(clientSecret), - }, - result: true, - }, - { - currentData: SecretData{ - OauthClientIDKey: []byte(clientId), - OauthClientSecretKey: []byte(clientSecret), - }, - newData: SecretData{ - OauthClientIDKey: []byte(username), - OauthClientSecretKey: []byte("changed secret"), - }, - result: true, - }, - { - currentData: SecretData{}, - newData: SecretData{ - OauthClientIDKey: []byte(clientId), - OauthClientSecretKey: []byte(clientSecret), - }, - result: true, - }, - { - currentData: SecretData{ - OauthClientIDKey: []byte(clientId), - OauthClientSecretKey: []byte(clientSecret), - }, - newData: SecretData{}, - result: true, - }, - { - currentData: SecretData{ - OauthClientIDKey: []byte(clientId), - OauthClientSecretKey: []byte(clientSecret), - }, - newData: SecretData{ - OauthClientIDKey: []byte(clientId), - OauthClientSecretKey: []byte(clientSecret), - }, - result: false, - }, - } - - t.Run("should return true when update needed", func(t *testing.T) { - // given - oauthStrategy := oauth{} - - for _, test := range testCases { - // when - result := oauthStrategy.ShouldUpdate(test.currentData, test.newData) - - // then - assert.Equal(t, test.result, result) - } - }) -} diff --git a/components/compass-runtime-agent/internal/kyma/service.go b/components/compass-runtime-agent/internal/kyma/service.go deleted file mode 100644 index 3a6e5a84f4fa..000000000000 --- a/components/compass-runtime-agent/internal/kyma/service.go +++ /dev/null @@ -1,387 +0,0 @@ -package kyma - -import ( - "fmt" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" - log "github.com/sirupsen/logrus" - k8serrors "k8s.io/apimachinery/pkg/api/errors" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/apperrors" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/applications" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/model" - appsecrets "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/secrets" -) - -type service struct { - applicationRepository applications.Repository - converter applications.Converter - credentialsService appsecrets.CredentialsService - requestParametersService appsecrets.RequestParametersService -} - -//go:generate mockery --name=Service -type Service interface { - Apply(applications []model.Application) ([]Result, apperrors.AppError) -} - -type Operation int - -const ( - Create Operation = iota - Update - Delete -) - -type Result struct { - ApplicationName string - ApplicationID string - Operation Operation - Error apperrors.AppError -} - -func NewService(applicationRepository applications.Repository, converter applications.Converter, credentialsService appsecrets.CredentialsService, requestParametersService appsecrets.RequestParametersService) Service { - return &service{ - applicationRepository: applicationRepository, - converter: converter, - credentialsService: credentialsService, - requestParametersService: requestParametersService, - } -} - -func (s *service) Apply(directorApplications []model.Application) ([]Result, apperrors.AppError) { - log.Infof("Applications passed to Sync service: %d", len(directorApplications)) - - currentApplications, err := s.getExistingRuntimeApplications() - if err != nil { - log.Errorf("Failed to get existing applications: %s.", err) - return nil, err - } - - compassCurrentApplications := s.filterCompassApplications(currentApplications) - - return s.apply(compassCurrentApplications, directorApplications), nil -} - -func (s *service) apply(runtimeApplications []v1alpha1.Application, directorApplications []model.Application) []Result { - log.Infof("Applying configuration from the Compass Director.") - results := make([]Result, 0) - - created := s.createApplications(directorApplications, runtimeApplications) - deleted := s.deleteApplications(directorApplications, runtimeApplications) - updated := s.updateApplications(directorApplications, runtimeApplications) - - results = append(results, created...) - results = append(results, deleted...) - results = append(results, updated...) - - return results -} - -func (s *service) getExistingRuntimeApplications() ([]v1alpha1.Application, apperrors.AppError) { - applicationList, err := s.applicationRepository.List(v1.ListOptions{}) - if err != nil { - return nil, apperrors.Internal("Failed to get application list: %s", err) - } - - return applicationList.Items, nil -} - -func (s *service) getApplicationUID(application string) (types.UID, apperrors.AppError) { - app, err := s.applicationRepository.Get(application, v1.GetOptions{}) - if err != nil { - if k8serrors.IsNotFound(err) { - message := fmt.Sprintf("Application %s not found", application) - return "", apperrors.NotFound(message) - } - - message := fmt.Sprintf("Getting Application %s failed, %s", application, err.Error()) - return "", apperrors.Internal(message) - } - - return app.UID, nil -} - -func (s *service) filterCompassApplications(applications []v1alpha1.Application) []v1alpha1.Application { - var compassApplications []v1alpha1.Application - - for _, application := range applications { - if application.Spec.CompassMetadata != nil { - compassApplications = append(compassApplications, application) - } - } - return compassApplications -} - -func (s *service) createApplications(directorApplications []model.Application, runtimeApplications []v1alpha1.Application) []Result { - log.Infof("Creating applications.") - results := make([]Result, 0) - - for _, directorApplication := range directorApplications { - if !ApplicationExists(directorApplication.Name, runtimeApplications) { - result := s.createApplication(directorApplication, s.converter.Do(directorApplication)) - results = append(results, result) - } - } - - return results -} - -func (s *service) createApplication(directorApplication model.Application, runtimeApplication v1alpha1.Application) Result { - log.Infof("Creating application '%s'.", directorApplication.Name) - _, err := s.applicationRepository.Create(&runtimeApplication) - if err != nil { - log.Warningf("Failed to create application '%s': %s.", directorApplication.Name, err) - return newResult(runtimeApplication, directorApplication.ID, Create, err) - } - - log.Infof("Creating credentials secrets for application '%s'.", directorApplication.Name) - err = s.upsertCredentialsSecrets(directorApplication) - if err != nil { - log.Warningf("Failed to create credentials secrets for application '%s': %s.", directorApplication.Name, err) - return newResult(runtimeApplication, directorApplication.ID, Create, err) - } - - log.Infof("Creating request parameters secrets for application '%s'.", directorApplication.Name) - err = s.upsertRequestParametersSecrets(directorApplication) - if err != nil { - log.Warningf("Failed to create request parameters secrets for application '%s': %s.", directorApplication.Name, err) - return newResult(runtimeApplication, directorApplication.ID, Create, err) - } - - return newResult(runtimeApplication, directorApplication.ID, Create, nil) -} - -func (s *service) upsertCredentialsSecrets(directorApplication model.Application) apperrors.AppError { - var appendedErr apperrors.AppError - - getApplicationUIDFunc := cachingGetApplicationUIDFunc(s.getApplicationUID) - for _, apiBundle := range directorApplication.ApiBundles { - if apiBundle.DefaultInstanceAuth != nil && apiBundle.DefaultInstanceAuth.Credentials != nil { - credentials := apiBundle.DefaultInstanceAuth.Credentials - if credentials.Basic == nil && credentials.Oauth == nil { - continue - } - r, _ := getApplicationUIDFunc(directorApplication.Name) - if r.AppError != nil { - return r.AppError - } - _, err := s.credentialsService.Upsert(directorApplication.Name, r.AppUID, apiBundle.ID, credentials) - if err != nil { - appendedErr = apperrors.AppendError(appendedErr, err) - } - } - } - return appendedErr -} - -func (s *service) upsertRequestParametersSecrets(directorApplication model.Application) apperrors.AppError { - var appendedErr apperrors.AppError - - getApplicationUIDFunc := cachingGetApplicationUIDFunc(s.getApplicationUID) - for _, apiBundle := range directorApplication.ApiBundles { - if apiBundle.DefaultInstanceAuth != nil && apiBundle.DefaultInstanceAuth.RequestParameters != nil && !apiBundle.DefaultInstanceAuth.RequestParameters.IsEmpty() { - r, _ := getApplicationUIDFunc(directorApplication.Name) - if r.AppError != nil { - return r.AppError - } - requestParameters := apiBundle.DefaultInstanceAuth.RequestParameters - if requestParameters != nil && !requestParameters.IsEmpty() { - _, err := s.requestParametersService.Upsert(directorApplication.Name, r.AppUID, apiBundle.ID, requestParameters) - if err != nil { - appendedErr = apperrors.AppendError(appendedErr, err) - } - } - } - } - return appendedErr -} - -func (s *service) deleteApplications(directorApplications []model.Application, runtimeApplications []v1alpha1.Application) []Result { - log.Info("Deleting applications.") - results := make([]Result, 0) - - for _, runtimeApplication := range runtimeApplications { - existsInDirector := false - for _, directorApp := range directorApplications { - if directorApp.Name == runtimeApplication.Name { - existsInDirector = true - break - } - } - - if !existsInDirector { - result := s.deleteApplication(runtimeApplication, runtimeApplication.GetApplicationID()) - results = append(results, result) - } - } - return results -} - -func (s *service) deleteApplication(runtimeApplication v1alpha1.Application, applicationID string) Result { - log.Infof("Deleting request parameters secrets for application '%s'.", runtimeApplication.Name) - if err := s.deleteRequestParametersSecrets(runtimeApplication); err != nil { - log.Warningf("Failed to delete request parameters secrets secrets for application '%s': %s.", runtimeApplication.Name, err) - } - - log.Infof("Deleting credentials secrets for application '%s'.", runtimeApplication.Name) - if err := s.deleteCredentialsSecrets(runtimeApplication); err != nil { - log.Warningf("Failed to delete credentials secrets for application '%s': %s.", runtimeApplication.Name, err) - } - - log.Infof("Deleting application '%s'.", runtimeApplication.Name) - err := s.applicationRepository.Delete(runtimeApplication.Name, &v1.DeleteOptions{}) - if err != nil { - log.Warningf("Failed to delete application '%s'", runtimeApplication.Name) - } - - return newResult(runtimeApplication, applicationID, Delete, err) -} - -func (s *service) deleteCredentialsSecrets(runtimeApplication v1alpha1.Application) apperrors.AppError { - var appendedErr apperrors.AppError - - secretNames := s.getCredentialsSecretNames(runtimeApplication) - - for secretName := range secretNames { - err := s.credentialsService.Delete(secretName) - if err != nil { - appendedErr = apperrors.AppendError(appendedErr, err) - } - } - return appendedErr -} - -func (s *service) getCredentialsSecretNames(runtimeApplication v1alpha1.Application) map[string]struct{} { - secretNames := make(map[string]struct{}) - for _, service := range runtimeApplication.Spec.Services { - for _, entry := range service.Entries { - if entry.Credentials.SecretName != "" { - secretNames[entry.Credentials.SecretName] = struct{}{} - } - } - } - return secretNames -} - -func (s *service) deleteRequestParametersSecrets(runtimeApplication v1alpha1.Application) apperrors.AppError { - var appendedErr apperrors.AppError - - secretNames := s.getRequestParametersSecretNames(runtimeApplication) - - for secretName := range secretNames { - err := s.requestParametersService.Delete(secretName) - if err != nil { - appendedErr = apperrors.AppendError(appendedErr, err) - } - } - return appendedErr -} - -func (s *service) getRequestParametersSecretNames(runtimeApplication v1alpha1.Application) map[string]struct{} { - secretNames := make(map[string]struct{}) - for _, service := range runtimeApplication.Spec.Services { - for _, entry := range service.Entries { - if entry.RequestParametersSecretName != "" { - secretNames[entry.RequestParametersSecretName] = struct{}{} - } - } - } - return secretNames -} - -func (s *service) updateApplications(directorApplications []model.Application, runtimeApplications []v1alpha1.Application) []Result { - log.Info("Updating applications.") - results := make([]Result, 0) - - for _, directorApplication := range directorApplications { - if ApplicationExists(directorApplication.Name, runtimeApplications) { - existentApplication := GetApplication(directorApplication.Name, runtimeApplications) - result := s.updateApplication(directorApplication, existentApplication, s.converter.Do(directorApplication)) - results = append(results, result) - } - } - - return results -} - -func (s *service) updateApplication(directorApplication model.Application, existentRuntimeApplication v1alpha1.Application, newRuntimeApplication v1alpha1.Application) Result { - log.Infof("Updating Application '%s'.", directorApplication.Name) - updatedRuntimeApplication, err := s.applicationRepository.Update(&newRuntimeApplication) - if err != nil { - log.Warningf("Failed to update application '%s': %s.", directorApplication.Name, err) - return newResult(existentRuntimeApplication, directorApplication.ID, Update, err) - } - - log.Infof("Updating credentials secrets for application '%s'.", directorApplication.Name) - appendedErr := s.updateCredentialsSecrets(directorApplication, existentRuntimeApplication, *updatedRuntimeApplication) - if appendedErr != nil { - log.Warningf("Failed to update credentials secrets for application '%s': %s.", directorApplication.Name, appendedErr) - } - - log.Infof("Updating request paramters secrets for application '%s'.", directorApplication.Name) - appendedErr = s.updateRequestParametersSecrets(directorApplication, existentRuntimeApplication, *updatedRuntimeApplication) - if appendedErr != nil { - log.Warningf("Failed to request paramters secrets for application '%s': %s.", directorApplication.Name, appendedErr) - } - - return newResult(existentRuntimeApplication, directorApplication.ID, Update, appendedErr) -} - -func (s *service) updateCredentialsSecrets(directorApplication model.Application, existentRuntimeApplication v1alpha1.Application, newRuntimeApplication v1alpha1.Application) apperrors.AppError { - var appendedErr apperrors.AppError - - // delete - existentSecretNames := s.getCredentialsSecretNames(existentRuntimeApplication) - newSecretNames := s.getCredentialsSecretNames(newRuntimeApplication) - deletedSecretNames := make(map[string]struct{}) - for secretName := range existentSecretNames { - if _, ok := newSecretNames[secretName]; !ok { - deletedSecretNames[secretName] = struct{}{} - } - } - for secretName := range deletedSecretNames { - log.Infof("Deleting credentials secret '%s' for application '%s'", secretName, directorApplication.Name) - err := s.credentialsService.Delete(secretName) - if err != nil { - appendedErr = apperrors.AppendError(appendedErr, err) - } - } - - // create + update - err := s.upsertCredentialsSecrets(directorApplication) - if err != nil { - appendedErr = apperrors.AppendError(appendedErr, err) - } - return appendedErr -} - -func (s *service) updateRequestParametersSecrets(directorApplication model.Application, existentRuntimeApplication v1alpha1.Application, newRuntimeApplication v1alpha1.Application) apperrors.AppError { - var appendedErr apperrors.AppError - - // delete - existentSecretNames := s.getRequestParametersSecretNames(existentRuntimeApplication) - newSecretNames := s.getRequestParametersSecretNames(newRuntimeApplication) - deletedSecretNames := make(map[string]struct{}) - for secretName := range existentSecretNames { - if _, ok := newSecretNames[secretName]; !ok { - deletedSecretNames[secretName] = struct{}{} - } - } - for secretName := range deletedSecretNames { - log.Infof("Deleting request parameters secret '%s' for application '%s'", secretName, directorApplication.Name) - err := s.requestParametersService.Delete(secretName) - if err != nil { - appendedErr = apperrors.AppendError(appendedErr, err) - } - } - - // create + update - err := s.upsertRequestParametersSecrets(directorApplication) - if err != nil { - appendedErr = apperrors.AppendError(appendedErr, err) - } - return appendedErr -} diff --git a/components/compass-runtime-agent/internal/kyma/service_test.go b/components/compass-runtime-agent/internal/kyma/service_test.go deleted file mode 100644 index 798f443ff90c..000000000000 --- a/components/compass-runtime-agent/internal/kyma/service_test.go +++ /dev/null @@ -1,922 +0,0 @@ -package kyma - -import ( - "fmt" - "testing" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/applications" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/apperrors" - appMocks "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/applications/mocks" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/model" - appSecrets "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/kyma/secrets/mocks" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" -) - -func TestKymaUpsertCredentialsSecrets(t *testing.T) { - type upsert struct { - bundleID string - credentials *model.Credentials - } - - tests := []struct { - name string - application model.Application - upserts []upsert - }{ - { - name: "DefaultInstanceAuth is null", - application: model.Application{ - Name: "", - ApiBundles: []model.APIBundle{ - { - DefaultInstanceAuth: nil, - }, - }, - }, - }, - { - name: "Credentials are nil", - application: model.Application{ - ApiBundles: []model.APIBundle{ - { - DefaultInstanceAuth: &model.Auth{ - Credentials: nil, - }, - }, - }, - }, - }, - { - name: "Basic auth", - application: model.Application{ - ApiBundles: []model.APIBundle{ - { - ID: "bundle-1", - DefaultInstanceAuth: fixAuthBasic(), - }, - }, - }, - upserts: []upsert{{ - bundleID: "bundle-1", - credentials: fixAuthBasic().Credentials, - }}, - }, - { - name: "Oauths", - application: model.Application{ - ApiBundles: []model.APIBundle{ - { - ID: "bundle-1", - DefaultInstanceAuth: fixAuthOauth(), - }, - { - ID: "bundle-2", - DefaultInstanceAuth: &model.Auth{ - Credentials: &model.Credentials{ - Oauth: &model.Oauth{ - URL: "https://auth.expamle.com", - ClientID: "my-client-2", - ClientSecret: "my-secret-2", - }, - }, - }, - }, - }, - }, - upserts: []upsert{ - { - bundleID: "bundle-1", - credentials: fixAuthOauth().Credentials, - }, - { - bundleID: "bundle-2", - credentials: &model.Credentials{ - Oauth: &model.Oauth{ - URL: "https://auth.expamle.com", - ClientID: "my-client-2", - ClientSecret: "my-secret-2", - }, - }, - }, - }, - }, - } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - const UID = "f940c082-be4f-11eb-8529-0242ac130003" - tc.application.Name = "my-app" - - repositoryMock := &appMocks.Repository{} - repositoryMock.On("Get", tc.application.Name, metav1.GetOptions{}).Return(&v1alpha1.Application{ - ObjectMeta: metav1.ObjectMeta{ - UID: UID, - }, - }, nil) - credentialsServiceMock := &appSecrets.CredentialsService{} - for _, upsert := range tc.upserts { - credentialsServiceMock.On("Upsert", tc.application.Name, types.UID(UID), upsert.bundleID, upsert.credentials). - Return(applications.Credentials{}, nil).Once() - } - - service := &service{ - applicationRepository: repositoryMock, - credentialsService: credentialsServiceMock, - } - err := service.upsertCredentialsSecrets(tc.application) - assert.NoError(t, err) - - credentialsServiceMock.AssertExpectations(t) - }) - } -} - -func TestKymaRequestParametersSecrets(t *testing.T) { - type upsert struct { - bundleID string - requestParameters *model.RequestParameters - } - - tests := []struct { - name string - application model.Application - upserts []upsert - }{ - { - name: "DefaultInstanceAuth is null", - application: model.Application{ - Name: "", - ApiBundles: []model.APIBundle{ - { - DefaultInstanceAuth: nil, - }, - }, - }, - }, - { - name: "Credentials are nil", - application: model.Application{ - ApiBundles: []model.APIBundle{ - { - DefaultInstanceAuth: &model.Auth{ - Credentials: nil, - }, - }, - }, - }, - }, - { - name: "Request params are empty", - application: model.Application{ - ApiBundles: []model.APIBundle{ - { - DefaultInstanceAuth: &model.Auth{ - Credentials: &model.Credentials{ - Oauth: &model.Oauth{ - URL: "https://auth.expamle.com", - ClientID: "my-client-2", - ClientSecret: "my-secret-2", - }, - }, - }, - }, - }, - }, - }, - { - name: "Request params once", - application: model.Application{ - ApiBundles: []model.APIBundle{ - { - ID: "bundle-1", - DefaultInstanceAuth: fixAuthBasic(), - }, - }, - }, - upserts: []upsert{ - { - bundleID: "bundle-1", - requestParameters: fixAuthBasic().RequestParameters, - }, - }, - }, - { - name: "Request params twice", - application: model.Application{ - ApiBundles: []model.APIBundle{ - { - ID: "bundle-1", - DefaultInstanceAuth: fixAuthBasic(), - }, - { - ID: "bundle-2", - DefaultInstanceAuth: fixAuthOauth(), - }, - }, - }, - upserts: []upsert{ - { - bundleID: "bundle-1", - requestParameters: fixAuthBasic().RequestParameters, - }, - { - bundleID: "bundle-2", - requestParameters: fixAuthOauth().RequestParameters, - }, - }, - }, - } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - const UID = "f940c082-be4f-11eb-8529-0242ac130003" - tc.application.Name = "my-app" - - repositoryMock := &appMocks.Repository{} - repositoryMock.On("Get", tc.application.Name, metav1.GetOptions{}).Return(&v1alpha1.Application{ - ObjectMeta: metav1.ObjectMeta{ - UID: UID, - }, - }, nil) - requestParametersServiceMock := &appSecrets.RequestParametersService{} - for _, upsert := range tc.upserts { - requestParametersServiceMock.On("Upsert", tc.application.Name, types.UID(UID), upsert.bundleID, upsert.requestParameters). - Return("", nil).Once() - } - - service := &service{ - applicationRepository: repositoryMock, - requestParametersService: requestParametersServiceMock, - } - err := service.upsertRequestParametersSecrets(tc.application) - assert.NoError(t, err) - - requestParametersServiceMock.AssertExpectations(t) - }) - } -} - -func TestKymaService(t *testing.T) { - t.Run("should return error in case failed to determine differences between current and desired runtime state", func(t *testing.T) { - // given - applicationsManagerMock := &appMocks.Repository{} - converterMock := &appMocks.Converter{} - credentialsServiceMock := &appSecrets.CredentialsService{} - requestParametersServiceMock := &appSecrets.RequestParametersService{} - applicationsManagerMock.On("List", metav1.ListOptions{}).Return(nil, apperrors.Internal("some error")) - - directorApplication := getTestDirectorApplication("id1", "name1") - - directorApplications := []model.Application{ - directorApplication, - } - - // when - kymaService := NewService(applicationsManagerMock, converterMock, credentialsServiceMock, requestParametersServiceMock) - _, err := kymaService.Apply(directorApplications) - - // then - assert.Error(t, err) - converterMock.AssertExpectations(t) - applicationsManagerMock.AssertExpectations(t) - }) - - t.Run("should apply Create operation", func(t *testing.T) { - // given - applicationsManagerMock := &appMocks.Repository{} - converterMock := &appMocks.Converter{} - credentialsServiceMock := &appSecrets.CredentialsService{} - requestParametersServiceMock := &appSecrets.RequestParametersService{} - - api := fixDirectorAPiDefinition("API1", "name", "API description") - eventAPI := fixDirectorEventAPIDefinition("EventAPI1", "name", "Event API 1 description") - - apiBundle1 := fixAPIBundle("bundle1", []model.APIDefinition{api}, nil, nil) - apiBundle2 := fixAPIBundle("bundle2", nil, []model.EventAPIDefinition{eventAPI}, nil) - apiBundle3 := fixAPIBundle("bundle3", []model.APIDefinition{api}, []model.EventAPIDefinition{eventAPI}, nil) - directorApplication := fixDirectorApplication("id1", "name1", apiBundle1, apiBundle2, apiBundle3) - - entry1 := fixAPIEntry("API1", "api1") - entry2 := fixEventAPIEntry("EventAPI1", "eventapi1") - - newRuntimeService1 := fixService("bundle1", entry1) - newRuntimeService2 := fixService("bundle2", entry2) - newRuntimeService3 := fixService("bundle3", entry1, entry2) - - newRuntimeApplication := getTestApplication("name1", "id1", []v1alpha1.Service{newRuntimeService1, newRuntimeService2, newRuntimeService3}) - - directorApplications := []model.Application{ - directorApplication, - } - - existingRuntimeApplications := v1alpha1.ApplicationList{ - Items: []v1alpha1.Application{}, - } - - converterMock.On("Do", directorApplication).Return(newRuntimeApplication) - applicationsManagerMock.On("Create", &newRuntimeApplication).Return(&newRuntimeApplication, nil) - applicationsManagerMock.On("List", metav1.ListOptions{}).Return(&existingRuntimeApplications, nil) - - expectedResult := []Result{ - { - ApplicationName: "name1", - ApplicationID: "id1", - Operation: Create, - Error: nil, - }, - } - - // when - kymaService := NewService(applicationsManagerMock, converterMock, credentialsServiceMock, requestParametersServiceMock) - result, err := kymaService.Apply(directorApplications) - - // then - assert.NoError(t, err) - assert.Equal(t, expectedResult, result) - converterMock.AssertExpectations(t) - applicationsManagerMock.AssertExpectations(t) - }) - - t.Run("should apply Create operation and create credentials", func(t *testing.T) { - // given - applicationsManagerMock := &appMocks.Repository{} - converterMock := &appMocks.Converter{} - credentialsServiceMock := &appSecrets.CredentialsService{} - requestParametersServiceMock := &appSecrets.RequestParametersService{} - - api := fixDirectorAPiDefinition("API1", "name", "API description") - eventAPI := fixDirectorEventAPIDefinition("EventAPI1", "name", "Event API 1 description") - - authBundle1 := fixAuthOauth() - authBundle1.RequestParameters = nil - authBundle2 := fixAuthBasic() - authBundle4 := fixAuthRequestParameters() - - apiBundle1 := fixAPIBundle("bundle1", []model.APIDefinition{api}, nil, authBundle1) - apiBundle2 := fixAPIBundle("bundle2", nil, []model.EventAPIDefinition{eventAPI}, authBundle2) - apiBundle3 := fixAPIBundle("bundle3", []model.APIDefinition{api}, []model.EventAPIDefinition{eventAPI}, nil) - apiBundle4 := fixAPIBundle("bundle4", []model.APIDefinition{api}, nil, authBundle4) - directorApplication := fixDirectorApplication("id1", "name1", apiBundle1, apiBundle2, apiBundle3, apiBundle4) - - entry1 := fixAPIEntry("API1", "api1") - entry2 := fixEventAPIEntry("EventAPI1", "eventapi1") - - newRuntimeService1 := fixService("bundle1", entry1) - newRuntimeService2 := fixService("bundle2", entry2) - newRuntimeService3 := fixService("bundle3", entry1, entry2) - newRuntimeService4 := fixService("bundle4", entry1) - - newRuntimeApplication := getTestApplication("name1", "id1", []v1alpha1.Service{newRuntimeService1, newRuntimeService2, newRuntimeService3, newRuntimeService4}) - - directorApplications := []model.Application{ - directorApplication, - } - - existingRuntimeApplications := v1alpha1.ApplicationList{ - Items: []v1alpha1.Application{}, - } - - converterMock.On("Do", directorApplication).Return(newRuntimeApplication) - applicationsManagerMock.On("Get", "name1", metav1.GetOptions{}).Return(&newRuntimeApplication, nil) - applicationsManagerMock.On("Create", &newRuntimeApplication).Return(&newRuntimeApplication, nil) - applicationsManagerMock.On("List", metav1.ListOptions{}).Return(&existingRuntimeApplications, nil) - - credentialsServiceMock.On("Upsert", "name1", newRuntimeApplication.UID, "bundle1", authBundle1.Credentials).Return(applications.Credentials{}, nil) - credentialsServiceMock.On("Upsert", "name1", newRuntimeApplication.UID, "bundle2", authBundle2.Credentials).Return(applications.Credentials{}, nil) - requestParametersServiceMock.On("Upsert", "name1", newRuntimeApplication.UID, "bundle2", authBundle2.RequestParameters).Return("", nil) - requestParametersServiceMock.On("Upsert", "name1", newRuntimeApplication.UID, "bundle4", authBundle4.RequestParameters).Return("", nil) - - expectedResult := []Result{ - { - ApplicationName: "name1", - ApplicationID: "id1", - Operation: Create, - Error: nil, - }, - } - - // when - kymaService := NewService(applicationsManagerMock, converterMock, credentialsServiceMock, requestParametersServiceMock) - result, err := kymaService.Apply(directorApplications) - - // then - assert.NoError(t, err) - assert.Equal(t, expectedResult, result) - converterMock.AssertExpectations(t) - applicationsManagerMock.AssertExpectations(t) - }) - - t.Run("should apply Update operation", func(t *testing.T) { - // given - applicationsManagerMock := &appMocks.Repository{} - converterMock := &appMocks.Converter{} - credentialsServiceMock := &appSecrets.CredentialsService{} - requestParametersServiceMock := &appSecrets.RequestParametersService{} - - api1 := fixDirectorAPiDefinition("API1", "Name", "API 1 description") - eventAPI1 := fixDirectorEventAPIDefinition("EventAPI1", "Name", "Event API 1 description") - apiBundle1 := fixAPIBundle("bundle1", []model.APIDefinition{api1}, []model.EventAPIDefinition{eventAPI1}, nil) - - api2 := fixDirectorAPiDefinition("API2", "Name", "API 2 description") - eventAPI2 := fixDirectorEventAPIDefinition("EventAPI2", "Name", "Event API 2 description") - apiBundle2 := fixAPIBundle("bundle2", []model.APIDefinition{api2}, []model.EventAPIDefinition{eventAPI2}, nil) - - api3 := fixDirectorAPiDefinition("API3", "Name", "API 3 description") - eventAPI3 := fixDirectorEventAPIDefinition("EventAPI2", "Name", "Event API 3 description") - apiBundle3 := fixAPIBundle("bundle3", []model.APIDefinition{api3}, []model.EventAPIDefinition{eventAPI3}, nil) - - directorApplication := fixDirectorApplication("id1", "name1", apiBundle1, apiBundle2, apiBundle3) - - runtimeServiceToCreate := fixService("bundle1", fixServiceAPIEntry("API1"), fixEventAPIEntry("EventAPI1", "EventAPI1Name")) - runtimeServiceToUpdate1 := fixService("bundle2", fixServiceAPIEntry("API2"), fixEventAPIEntry("EventAPI2", "EventAPI2Name")) - runtimeServiceToUpdate2 := fixService("bundle3", fixServiceAPIEntry("API3"), fixEventAPIEntry("EventAPI3", "EventAPI3Name")) - runtimeServiceToDelete := fixService("bundle4", fixServiceAPIEntry("API4"), fixEventAPIEntry("EventAPI4", "EventAPI4Name")) - - newRuntimeApplication := getTestApplication("name1", "id1", []v1alpha1.Service{runtimeServiceToCreate, runtimeServiceToUpdate1, runtimeServiceToUpdate2}) - - directorApplications := []model.Application{ - directorApplication, - } - - existingRuntimeApplication := getTestApplication("name1", "id1", []v1alpha1.Service{runtimeServiceToUpdate1, runtimeServiceToUpdate2, runtimeServiceToDelete}) - existingRuntimeApplications := v1alpha1.ApplicationList{ - Items: []v1alpha1.Application{existingRuntimeApplication}, - } - - converterMock.On("Do", directorApplication).Return(newRuntimeApplication) - applicationsManagerMock.On("Update", &newRuntimeApplication).Return(&newRuntimeApplication, nil) - applicationsManagerMock.On("List", metav1.ListOptions{}).Return(&existingRuntimeApplications, nil) - - expectedResult := []Result{ - { - ApplicationName: "name1", - ApplicationID: "id1", - Operation: Update, - Error: nil, - }, - } - - // when - kymaService := NewService(applicationsManagerMock, converterMock, credentialsServiceMock, requestParametersServiceMock) - result, err := kymaService.Apply(directorApplications) - - // then - assert.NoError(t, err) - assert.Equal(t, expectedResult, result) - converterMock.AssertExpectations(t) - applicationsManagerMock.AssertExpectations(t) - }) - - t.Run("should apply Update operation and update credentials", func(t *testing.T) { - // given - applicationsManagerMock := &appMocks.Repository{} - converterMock := &appMocks.Converter{} - credentialsServiceMock := &appSecrets.CredentialsService{} - requestParametersServiceMock := &appSecrets.RequestParametersService{} - - authBundle1 := fixAuthOauth() - authBundle3 := fixAuthBasic() - - api1 := fixDirectorAPiDefinition("API1", "Name", "API 1 description") - eventAPI1 := fixDirectorEventAPIDefinition("EventAPI1", "Name", "Event API 1 description") - apiBundle1 := fixAPIBundle("bundle1", []model.APIDefinition{api1}, []model.EventAPIDefinition{eventAPI1}, authBundle1) - - api2 := fixDirectorAPiDefinition("API2", "Name", "API 2 description") - eventAPI2 := fixDirectorEventAPIDefinition("EventAPI2", "Name", "Event API 2 description") - apiBundle2 := fixAPIBundle("bundle2", []model.APIDefinition{api2}, []model.EventAPIDefinition{eventAPI2}, nil) - - api3 := fixDirectorAPiDefinition("API3", "Name", "API 3 description") - eventAPI3 := fixDirectorEventAPIDefinition("EventAPI2", "Name", "Event API 3 description") - apiBundle3 := fixAPIBundle("bundle3", []model.APIDefinition{api3}, []model.EventAPIDefinition{eventAPI3}, authBundle3) - - directorApplication := fixDirectorApplication("id1", "name1", apiBundle1, apiBundle2, apiBundle3) - - runtimeServiceToCreate := fixService("bundle1", fixServiceAPIEntryWithOauth("API1", "bundle1"), fixEventAPIEntry("EventAPI1", "EventAPI1Name")) - existingServiceToUpdate1 := fixService("bundle2", fixServiceAPIEntryWithOauth("API2", "bundle2"), fixEventAPIEntry("EventAPI2", "EventAPI2Name")) - runtimeServiceToUpdate1 := fixService("bundle2", fixServiceAPIEntry("API2"), fixEventAPIEntry("EventAPI2", "EventAPI2Name")) - existingServiceToUpdate2 := fixService("bundle3", fixServiceAPIEntry("API2"), fixEventAPIEntry("EventAPI3", "EventAPI3Name")) - runtimeServiceToUpdate2 := fixService("bundle3", fixServiceAPIEntryWithBasic("API3", "bundle3"), fixEventAPIEntry("EventAPI3", "EventAPI3Name")) - runtimeServiceToDelete1 := fixService("bundle4", fixServiceAPIEntry("API4"), fixEventAPIEntry("EventAPI4", "EventAPI4Name")) - runtimeServiceToDelete2 := fixService("bundle5", fixServiceAPIEntryWithBasic("API5", "bundle5"), fixEventAPIEntry("EventAPI5", "EventAPI5Name")) - - newRuntimeApplication := getTestApplication("name1", "id1", []v1alpha1.Service{runtimeServiceToCreate, runtimeServiceToUpdate1, runtimeServiceToUpdate2}) - - directorApplications := []model.Application{ - directorApplication, - } - - existingRuntimeApplication := getTestApplication("name1", "id1", []v1alpha1.Service{existingServiceToUpdate1, existingServiceToUpdate2, runtimeServiceToDelete1, runtimeServiceToDelete2}) - existingRuntimeApplications := v1alpha1.ApplicationList{ - Items: []v1alpha1.Application{existingRuntimeApplication}, - } - - converterMock.On("Do", directorApplication).Return(newRuntimeApplication) - applicationsManagerMock.On("Update", &newRuntimeApplication).Return(&newRuntimeApplication, nil) - applicationsManagerMock.On("List", metav1.ListOptions{}).Return(&existingRuntimeApplications, nil) - applicationsManagerMock.On("Get", "name1", metav1.GetOptions{}).Return(&existingRuntimeApplication, nil) - - credentialsServiceMock.On("Upsert", "name1", newRuntimeApplication.UID, "bundle1", authBundle1.Credentials).Return(applications.Credentials{}, nil) - credentialsServiceMock.On("Delete", "name1-bundle2").Return(nil) - credentialsServiceMock.On("Upsert", "name1", newRuntimeApplication.UID, "bundle3", authBundle3.Credentials).Return(applications.Credentials{}, nil) - credentialsServiceMock.On("Delete", "name1-bundle5").Return(nil) - - requestParametersServiceMock.On("Upsert", "name1", newRuntimeApplication.UID, "bundle1", authBundle1.RequestParameters).Return("", nil) - requestParametersServiceMock.On("Delete", "params-name1-bundle2").Return(nil) - requestParametersServiceMock.On("Upsert", "name1", newRuntimeApplication.UID, "bundle3", authBundle3.RequestParameters).Return("", nil) - requestParametersServiceMock.On("Delete", "params-name1-bundle5").Return(nil) - - expectedResult := []Result{ - { - ApplicationName: "name1", - ApplicationID: "id1", - Operation: Update, - Error: nil, - }, - } - - // when - kymaService := NewService(applicationsManagerMock, converterMock, credentialsServiceMock, requestParametersServiceMock) - result, err := kymaService.Apply(directorApplications) - - // then - assert.NoError(t, err) - assert.Equal(t, expectedResult, result) - converterMock.AssertExpectations(t) - applicationsManagerMock.AssertExpectations(t) - }) - - t.Run("should apply Delete operation", func(t *testing.T) { - // given - applicationsManagerMock := &appMocks.Repository{} - converterMock := &appMocks.Converter{} - credentialsServiceMock := &appSecrets.CredentialsService{} - requestParametersServiceMock := &appSecrets.RequestParametersService{} - - runtimeServiceToDelete := fixService("bundle1", fixServiceAPIEntry("API1"), fixEventAPIEntry("EventAPI1", "EventAPI1Name")) - runtimeApplicationToDelete := getTestApplication("name1", "id1", []v1alpha1.Service{runtimeServiceToDelete}) - - existingRuntimeApplications := v1alpha1.ApplicationList{ - Items: []v1alpha1.Application{ - runtimeApplicationToDelete, - }, - } - - applicationsManagerMock.On("Delete", runtimeApplicationToDelete.Name, &metav1.DeleteOptions{}).Return(nil) - applicationsManagerMock.On("List", metav1.ListOptions{}).Return(&existingRuntimeApplications, nil) - - expectedResult := []Result{ - { - ApplicationName: "name1", - ApplicationID: "", - Operation: Delete, - Error: nil, - }, - } - - // when - kymaService := NewService(applicationsManagerMock, converterMock, credentialsServiceMock, requestParametersServiceMock) - result, err := kymaService.Apply([]model.Application{}) - - // then - assert.NoError(t, err) - assert.Equal(t, expectedResult, result) - converterMock.AssertExpectations(t) - applicationsManagerMock.AssertExpectations(t) - }) - - t.Run("should apply Delete operation and delete credentials", func(t *testing.T) { - // given - applicationsManagerMock := &appMocks.Repository{} - converterMock := &appMocks.Converter{} - credentialsServiceMock := &appSecrets.CredentialsService{} - requestParametersServiceMock := &appSecrets.RequestParametersService{} - - runtimeServiceToDelete := fixService("bundle1", fixServiceAPIEntryWithBasic("API1", "bundle1"), fixEventAPIEntry("EventAPI1", "EventAPI1Name")) - runtimeApplicationToDelete := getTestApplication("name1", "id1", []v1alpha1.Service{runtimeServiceToDelete}) - - existingRuntimeApplications := v1alpha1.ApplicationList{ - Items: []v1alpha1.Application{ - runtimeApplicationToDelete, - }, - } - - applicationsManagerMock.On("Delete", runtimeApplicationToDelete.Name, &metav1.DeleteOptions{}).Return(nil) - applicationsManagerMock.On("List", metav1.ListOptions{}).Return(&existingRuntimeApplications, nil) - - credentialsServiceMock.On("Delete", "name1-bundle1").Return(nil) - requestParametersServiceMock.On("Delete", "params-name1-bundle1").Return(nil) - - expectedResult := []Result{ - { - ApplicationName: "name1", - ApplicationID: "", - Operation: Delete, - Error: nil, - }, - } - - // when - kymaService := NewService(applicationsManagerMock, converterMock, credentialsServiceMock, requestParametersServiceMock) - result, err := kymaService.Apply([]model.Application{}) - - // then - assert.NoError(t, err) - assert.Equal(t, expectedResult, result) - converterMock.AssertExpectations(t) - applicationsManagerMock.AssertExpectations(t) - }) - - t.Run("should manage only Applications with CompassMetadata in the Spec", func(t *testing.T) { - // given - applicationsManagerMock := &appMocks.Repository{} - converterMock := &appMocks.Converter{} - credentialsServiceMock := &appSecrets.CredentialsService{} - requestParametersServiceMock := &appSecrets.RequestParametersService{} - - runtimeServiceToDelete := fixService("bundle1", fixServiceAPIEntry("API1"), fixEventAPIEntry("EventAPI1", "EventAPI1Name")) - notManagedRuntimeService := fixService("bundle2", fixServiceAPIEntry("API2"), fixEventAPIEntry("EventAPI2", "EventAPI2Name")) - - runtimeApplicationToDelete := getTestApplication("name1", "id1", []v1alpha1.Service{runtimeServiceToDelete}) - notManagedRuntimeApplication := getTestApplicationNotManagedByCompass("id2", []v1alpha1.Service{notManagedRuntimeService}) - - existingRuntimeApplications := v1alpha1.ApplicationList{ - Items: []v1alpha1.Application{ - runtimeApplicationToDelete, - notManagedRuntimeApplication, - }, - } - - applicationsManagerMock.On("Delete", runtimeApplicationToDelete.Name, &metav1.DeleteOptions{}).Return(nil) - applicationsManagerMock.On("List", metav1.ListOptions{}).Return(&existingRuntimeApplications, nil) - - expectedResult := []Result{ - { - ApplicationName: "name1", - ApplicationID: "", - Operation: Delete, - Error: nil, - }, - } - - // when - kymaService := NewService(applicationsManagerMock, converterMock, credentialsServiceMock, requestParametersServiceMock) - result, err := kymaService.Apply([]model.Application{}) - - // then - assert.NoError(t, err) - assert.Equal(t, expectedResult, result) - converterMock.AssertExpectations(t) - applicationsManagerMock.AssertExpectations(t) - }) - - t.Run("should not break execution when error occurred when applying Application CR", func(t *testing.T) { - // given - applicationsManagerMock := &appMocks.Repository{} - converterMock := &appMocks.Converter{} - credentialsServiceMock := &appSecrets.CredentialsService{} - requestParametersServiceMock := &appSecrets.RequestParametersService{} - - newRuntimeService1 := fixService("bundle1", fixServiceAPIEntry("API1"), fixEventAPIEntry("EventAPI1", "EventAPI1Name")) - newRuntimeService2 := fixService("bundle2", fixServiceAPIEntry("API2"), fixEventAPIEntry("EventAPI2", "EventAPI2Name")) - - existingRuntimeService1 := fixService("bundle3", fixServiceAPIEntry("API3"), fixEventAPIEntry("EventAPI3", "EventAPI1Name")) - existingRuntimeService2 := fixService("bundle4", fixServiceAPIEntry("API4"), fixEventAPIEntry("EventAPI4", "EventAPI2Name")) - - runtimeServiceToBeDeleted1 := v1alpha1.Service{ - ID: "bundle5", - Entries: []v1alpha1.Entry{ - fixServiceAPIEntry("API1"), - fixServiceEventAPIEntry("EventAPI1"), - }, - } - - api := fixDirectorAPiDefinition("API1", "name", "API description") - eventAPI := fixDirectorEventAPIDefinition("EventAPI1", "name", "Event API 1 description") - - apiBundle1 := fixAPIBundle("bundle1", []model.APIDefinition{api}, nil, nil) - apiBundle2 := fixAPIBundle("bundle2", nil, []model.EventAPIDefinition{eventAPI}, nil) - newDirectorApplication := fixDirectorApplication("id1", "name1", apiBundle1, apiBundle2) - - newRuntimeApplication1 := getTestApplication("name1", "id1", []v1alpha1.Service{newRuntimeService1, newRuntimeService2}) - - apiBundle3 := fixAPIBundle("bundle3", []model.APIDefinition{api}, []model.EventAPIDefinition{eventAPI}, nil) - - existingDirectorApplication := fixDirectorApplication("id2", "name2", apiBundle3) - newRuntimeApplication2 := getTestApplication("name2", "id2", []v1alpha1.Service{newRuntimeService1, newRuntimeService2, existingRuntimeService1, existingRuntimeService2}) - - runtimeApplicationToBeDeleted := getTestApplication("name3", "id3", []v1alpha1.Service{runtimeServiceToBeDeleted1}) - - directorApplications := []model.Application{ - newDirectorApplication, - existingDirectorApplication, - } - - existingRuntimeApplication := getTestApplication("name2", "id2", []v1alpha1.Service{existingRuntimeService1, existingRuntimeService2, runtimeServiceToBeDeleted1}) - - existingRuntimeApplications := v1alpha1.ApplicationList{ - Items: []v1alpha1.Application{ - existingRuntimeApplication, - runtimeApplicationToBeDeleted, - }, - } - - converterMock.On("Do", newDirectorApplication).Return(newRuntimeApplication1) - converterMock.On("Do", existingDirectorApplication).Return(newRuntimeApplication2) - applicationsManagerMock.On("Create", &newRuntimeApplication1).Return(nil, apperrors.Internal("some error")) - applicationsManagerMock.On("Update", &newRuntimeApplication2).Return(nil, apperrors.Internal("some error")) - applicationsManagerMock.On("Delete", runtimeApplicationToBeDeleted.Name, &metav1.DeleteOptions{}).Return(apperrors.Internal("some error")) - applicationsManagerMock.On("List", metav1.ListOptions{}).Return(&existingRuntimeApplications, nil) - - // when - kymaService := NewService(applicationsManagerMock, converterMock, credentialsServiceMock, requestParametersServiceMock) - result, err := kymaService.Apply(directorApplications) - - // then - require.NoError(t, err) - require.Equal(t, 3, len(result)) - assert.NotNil(t, result[0].Error) - assert.NotNil(t, result[1].Error) - assert.NotNil(t, result[2].Error) - converterMock.AssertExpectations(t) - applicationsManagerMock.AssertExpectations(t) - }) -} - -func getTestApplication(name, id string, services []v1alpha1.Service) v1alpha1.Application { - testApplication := getTestApplicationNotManagedByCompass(name, services) - testApplication.Spec.CompassMetadata = &v1alpha1.CompassMetadata{Authentication: v1alpha1.Authentication{ClientIds: []string{id}}} - - return testApplication -} - -func getTestDirectorApplication(id, name string) model.Application { - return model.Application{ - ID: id, - Name: name, - } -} - -func getTestApplicationNotManagedByCompass(id string, services []v1alpha1.Service) v1alpha1.Application { - return v1alpha1.Application{ - TypeMeta: metav1.TypeMeta{ - Kind: "Application", - APIVersion: "applicationconnector.kyma-project.io/v1alpha1", - }, - ObjectMeta: metav1.ObjectMeta{ - Name: id, - UID: "11e912a4-b489-11eb-8529-0242ac130003", - }, - Spec: v1alpha1.ApplicationSpec{ - Description: "Description", - Services: services, - }, - } -} - -func fixDirectorAPiDefinition(id, name, description string) model.APIDefinition { - return model.APIDefinition{ - ID: id, - Name: name, - Description: description, - TargetUrl: "www.example.com", - } -} - -func fixDirectorEventAPIDefinition(id, name, description string) model.EventAPIDefinition { - return model.EventAPIDefinition{ - ID: id, - Name: name, - Description: description, - } -} - -func fixDirectorApplication(id, name string, apiBundles ...model.APIBundle) model.Application { - return model.Application{ - ID: id, - Name: name, - ApiBundles: apiBundles, - } -} - -func fixAPIBundle(id string, apiDefinitions []model.APIDefinition, eventAPIDefinitions []model.EventAPIDefinition, defaultInstanceAuth *model.Auth) model.APIBundle { - return model.APIBundle{ - ID: id, - APIDefinitions: apiDefinitions, - EventDefinitions: eventAPIDefinitions, - DefaultInstanceAuth: defaultInstanceAuth, - } -} - -func fixAPIEntry(id, name string) v1alpha1.Entry { - return v1alpha1.Entry{ - ID: id, - Name: name, - Type: applications.SpecAPIType, - TargetUrl: "www.example.com/1", - } -} - -func fixEventAPIEntry(id, name string) v1alpha1.Entry { - return v1alpha1.Entry{ - ID: id, - Name: name, - Type: applications.SpecEventsType, - } -} - -func fixServiceAPIEntry(id string) v1alpha1.Entry { - return v1alpha1.Entry{ - ID: id, - Name: "Name", - Type: applications.SpecAPIType, - TargetUrl: "www.example.com/1", - } -} - -func fixServiceAPIEntryWithOauth(id, bundleID string) v1alpha1.Entry { - application := "name1" - return v1alpha1.Entry{ - ID: id, - Name: "Name", - Type: applications.SpecAPIType, - TargetUrl: "www.example.com/1", - Credentials: v1alpha1.Credentials{ - Type: "OAuth", - SecretName: fmt.Sprintf("%s-%s", application, bundleID), - AuthenticationUrl: "https://dev-name.eu.auth0.com/oauth/token", - CSRFInfo: nil, - }, - RequestParametersSecretName: fmt.Sprintf("params-%s-%s", application, bundleID), - } -} - -func fixServiceAPIEntryWithBasic(id, bundleID string) v1alpha1.Entry { - application := "name1" - return v1alpha1.Entry{ - ID: id, - Name: "Name", - Type: applications.SpecAPIType, - TargetUrl: "www.example.com/1", - Credentials: v1alpha1.Credentials{ - Type: "Basic", - SecretName: fmt.Sprintf("%s-%s", application, bundleID), - }, - RequestParametersSecretName: fmt.Sprintf("params-%s-%s", application, bundleID), - } -} - -func fixServiceEventAPIEntry(id string) v1alpha1.Entry { - return v1alpha1.Entry{ - ID: id, - Name: "Name", - Type: applications.SpecEventsType, - } -} - -func fixService(serviceID string, entries ...v1alpha1.Entry) v1alpha1.Service { - return v1alpha1.Service{ - ID: serviceID, - Entries: entries, - } -} - -func fixAuthOauth() *model.Auth { - return &model.Auth{ - Credentials: &model.Credentials{ - Oauth: &model.Oauth{ - URL: "https://auth.example.com", - ClientID: "test-client", - ClientSecret: "test-secret", - }, - CSRFInfo: nil, - }, - RequestParameters: &model.RequestParameters{ - Headers: &map[string][]string{"header1": {"header-value1"}}, - }, - } -} - -func fixAuthBasic() *model.Auth { - return &model.Auth{ - Credentials: &model.Credentials{ - Basic: &model.Basic{ - Username: "my-user", - Password: "my-password", - }, - }, - RequestParameters: &model.RequestParameters{ - Headers: &map[string][]string{"header2": {"header-value2"}}, - }, - } -} - -func fixAuthRequestParameters() *model.Auth { - return &model.Auth{ - RequestParameters: &model.RequestParameters{ - Headers: &map[string][]string{"header3": {"header-value3"}}, - }, - } -} diff --git a/components/compass-runtime-agent/internal/kyma/util.go b/components/compass-runtime-agent/internal/kyma/util.go deleted file mode 100644 index 79e2eb5651d6..000000000000 --- a/components/compass-runtime-agent/internal/kyma/util.go +++ /dev/null @@ -1,67 +0,0 @@ -package kyma - -import ( - memoize "github.com/kofalt/go-memoize" - "k8s.io/apimachinery/pkg/types" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/apperrors" -) - -func newResult(application v1alpha1.Application, applicationID string, operation Operation, appError apperrors.AppError) Result { - return Result{ - ApplicationName: application.Name, - ApplicationID: applicationID, - Operation: operation, - Error: appError, - } -} - -func ApplicationExists(applicationName string, applicationList []v1alpha1.Application) bool { - if applicationList == nil { - return false - } - - for _, runtimeApplication := range applicationList { - if runtimeApplication.Name == applicationName { - return true - } - } - - return false -} - -func GetApplication(applicationName string, applicationList []v1alpha1.Application) v1alpha1.Application { - if applicationList == nil { - return v1alpha1.Application{} - } - - for _, runtimeApplication := range applicationList { - if runtimeApplication.Name == applicationName { - return runtimeApplication - } - } - - return v1alpha1.Application{} -} - -type getApplicationUIDResult struct { - AppUID types.UID - AppError apperrors.AppError -} - -// cachingGetApplicationUIDFunc provides a function which prevents duplicate function calls to input function for the same application parameter. -// Subsequent invocations return the cached result. -func cachingGetApplicationUIDFunc(f func(application string) (types.UID, apperrors.AppError)) func(application string) (getApplicationUIDResult, error) { - cache := memoize.NewMemoizer(0, 0) - return func(application string) (getApplicationUIDResult, error) { - v, err, _ := cache.Memoize(application, func() (interface{}, error) { - appUID, apperr := f(application) - return getApplicationUIDResult{ - AppUID: appUID, - AppError: apperr, - }, nil - }) - return v.(getApplicationUIDResult), err - } -} diff --git a/components/compass-runtime-agent/internal/kyma/util_test.go b/components/compass-runtime-agent/internal/kyma/util_test.go deleted file mode 100644 index 93fe448c20dc..000000000000 --- a/components/compass-runtime-agent/internal/kyma/util_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package kyma - -import ( - "testing" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/apperrors" - "github.com/stretchr/testify/assert" - "k8s.io/apimachinery/pkg/types" -) - -func TestCachingGetApplicationUIDFunc(t *testing.T) { - calls := make(map[string]int, 0) - - f := func(application string) (types.UID, apperrors.AppError) { - calls[application]++ - return types.UID("result-" + application), nil - } - - cachingFunc := cachingGetApplicationUIDFunc(f) - - for i := 0; i < 10; i++ { - result, _ := cachingFunc("app1") - assert.Equal(t, getApplicationUIDResult{AppUID: "result-app1"}, result) - assert.Equal(t, 1, calls["app1"]) - assert.Equal(t, 0, calls["app2"]) - } - - for i := 0; i < 10; i++ { - result, _ := cachingFunc("app2") - assert.Equal(t, getApplicationUIDResult{AppUID: "result-app2"}, result) - assert.Equal(t, 1, calls["app2"]) - assert.Equal(t, 1, calls["app1"]) - } -} diff --git a/components/compass-runtime-agent/internal/metrics/logger.go b/components/compass-runtime-agent/internal/metrics/logger.go deleted file mode 100644 index c4fb4ac8b8ef..000000000000 --- a/components/compass-runtime-agent/internal/metrics/logger.go +++ /dev/null @@ -1,92 +0,0 @@ -package metrics - -import ( - "context" - "time" - - "github.com/pkg/errors" - log "github.com/sirupsen/logrus" - "k8s.io/client-go/kubernetes" - clientset "k8s.io/metrics/pkg/client/clientset/versioned" -) - -type Logger interface { - Start(ctx context.Context) error -} - -type logger struct { - loggingTimeInterval time.Duration - resourcesFetcher ResourcesFetcher - metricsFetcher MetricsFetcher - volumesFetcher VolumesFetcher -} - -func NewMetricsLogger( - resourcesClientset kubernetes.Interface, - metricsClientset clientset.Interface, - loggingTimeInterval time.Duration) Logger { - - return &logger{ - loggingTimeInterval: loggingTimeInterval, - resourcesFetcher: newResourcesFetcher(resourcesClientset), - metricsFetcher: newMetricsFetcher(metricsClientset), - volumesFetcher: newVolumesFetcher(resourcesClientset), - } -} - -func (l *logger) Start(ctx context.Context) error { - tick := time.NewTicker(l.loggingTimeInterval) - for { - select { - case <-tick.C: - l.log() - case <-ctx.Done(): - log.Info("Logging stopped.") - return nil - } - } -} - -func (l *logger) log() { - clusterInfo, err := l.fetchClusterInfo() - if err != nil { - log.Error(errors.Wrap(err, "failed to fetch cluster info")) - return - } - - l.printLogs(clusterInfo) -} - -func (l *logger) fetchClusterInfo() (ClusterInfo, error) { - resources, err := l.resourcesFetcher.FetchNodesResources() - if err != nil { - return ClusterInfo{}, errors.Wrap(err, "failed to fetch nodes resources") - } - - metrics, err := l.metricsFetcher.FetchNodeMetrics() - if err != nil { - return ClusterInfo{}, errors.Wrap(err, "failed to fetch nodes metrics") - } - - volumes, err := l.volumesFetcher.FetchPersistentVolumesCapacity() - if err != nil { - return ClusterInfo{}, errors.Wrap(err, "failed to fetch persistent volumes capacity") - } - - return ClusterInfo{ - Resources: resources, - Usage: metrics, - Volumes: volumes, - }, nil -} - -func (l *logger) printLogs(clusterInfo ClusterInfo) { - log.SetFormatter(&log.JSONFormatter{}) - - log.WithFields(log.Fields{ - "clusterInfo": clusterInfo, - "metrics": true, - }).Info("Cluster metrics logged successfully.") - - log.SetFormatter(&log.TextFormatter{}) -} diff --git a/components/compass-runtime-agent/internal/metrics/logger_test.go b/components/compass-runtime-agent/internal/metrics/logger_test.go deleted file mode 100644 index cadfb94b27be..000000000000 --- a/components/compass-runtime-agent/internal/metrics/logger_test.go +++ /dev/null @@ -1,208 +0,0 @@ -package metrics - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "os" - "strings" - "testing" - "time" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/metrics/mocks" - log "github.com/sirupsen/logrus" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/resource" - meta "k8s.io/apimachinery/pkg/apis/meta/v1" - kubernetesFake "k8s.io/client-go/kubernetes/fake" - "k8s.io/metrics/pkg/apis/metrics/v1beta1" -) - -const ( - loggingInterval = time.Millisecond - loggingWaitTime = time.Millisecond * 10 -) - -type Log struct { - Level string `json:"level"` - Metrics bool `json:"metrics"` - Msg string `json:"msg"` - Time time.Time `json:"time"` - ClusterInfo ClusterInfo `json:"clusterInfo"` -} - -func Test_Log(t *testing.T) { - t.Run("should log metrics", func(t *testing.T) { - // given - resourcesClientset := kubernetesFake.NewSimpleClientset( - &corev1.Node{ - ObjectMeta: meta.ObjectMeta{ - Name: "somename", - Labels: map[string]string{"beta.kubernetes.io/instance-type": "somelabel"}, - }, - Status: corev1.NodeStatus{ - Capacity: corev1.ResourceList{ - corev1.ResourceCPU: *resource.NewQuantity(1, resource.DecimalSI), - corev1.ResourceMemory: *resource.NewQuantity(1, resource.BinarySI), - corev1.ResourceEphemeralStorage: *resource.NewQuantity(1, resource.BinarySI), - corev1.ResourcePods: *resource.NewQuantity(1, resource.DecimalSI), - }, - }, - }, - &corev1.PersistentVolume{ - ObjectMeta: meta.ObjectMeta{ - Name: "somename", - }, - Spec: corev1.PersistentVolumeSpec{ - Capacity: corev1.ResourceList{ - corev1.ResourceStorage: *resource.NewQuantity(1, resource.BinarySI), - }, - ClaimRef: &corev1.ObjectReference{ - Namespace: "claimnamespace", - Name: "claimname", - }, - }, - }, - ) - - metricsClientset := &mocks.MetricsClientsetInterface{} - metricsV1beta1 := &mocks.MetricsV1beta1Interface{} - nodeMetrics := &mocks.NodeMetricsInterface{} - metricsClientset.On("MetricsV1beta1").Return(metricsV1beta1) - metricsV1beta1.On("NodeMetricses").Return(nodeMetrics) - nodeMetrics.On("List", context.Background(), meta.ListOptions{}).Return(&v1beta1.NodeMetricsList{ - Items: []v1beta1.NodeMetrics{{ - ObjectMeta: meta.ObjectMeta{ - Name: "somename", - }, - Usage: corev1.ResourceList{ - corev1.ResourceCPU: *resource.NewQuantity(1, resource.DecimalSI), - corev1.ResourceMemory: *resource.NewQuantity(1, resource.BinarySI), - corev1.ResourceEphemeralStorage: *resource.NewQuantity(0, resource.BinarySI), - corev1.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), - }, - Timestamp: meta.Time{Time: time.Now()}, - }}, - }, nil) - - logger := NewMetricsLogger(resourcesClientset, metricsClientset, loggingInterval) - - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - - var buffer bytes.Buffer - log.SetOutput(&buffer) - defer func() { - log.SetOutput(os.Stderr) - }() - - // when - go func() { - err := logger.Start(ctx) - assert.NoError(t, err, "failed to finish gracefully") - }() - - time.Sleep(loggingWaitTime) - cancel() - time.Sleep(loggingWaitTime) - - // then - logs := buffer.String() - logsSlice := strings.Split(logs, "\n") - require.NotEqual(t, 0, len(logsSlice), "there are no logs") - - var singleLog Log - err := json.Unmarshal([]byte(logsSlice[0]), &singleLog) - require.NoError(t, err, "failed to unmarshal the first log") - - assert.Equal(t, true, singleLog.Metrics) - assert.Equal(t, "info", singleLog.Level) - assert.Equal(t, "Cluster metrics logged successfully.", singleLog.Msg) - assert.NotEqual(t, 0, len(singleLog.ClusterInfo.Resources)) - assert.NotEqual(t, 0, len(singleLog.ClusterInfo.Usage)) - assert.NotEqual(t, 0, len(singleLog.ClusterInfo.Volumes)) - - assert.Equal(t, true, strings.Contains(logs, "Logging stopped."), "did not finish gracefully") - assert.Equal(t, false, strings.Contains(logs, "error"), "logged an error") - }) - - t.Run("should represent empty array as [], not null", func(t *testing.T) { - // given - resourcesClientset := kubernetesFake.NewSimpleClientset() - metricsClientset := &mocks.MetricsClientsetInterface{} - metricsV1beta1 := &mocks.MetricsV1beta1Interface{} - nodeMetrics := &mocks.NodeMetricsInterface{} - metricsClientset.On("MetricsV1beta1").Return(metricsV1beta1) - metricsV1beta1.On("NodeMetricses").Return(nodeMetrics) - nodeMetrics.On("List", context.Background(), meta.ListOptions{}).Return(&v1beta1.NodeMetricsList{}, nil) - - logger := NewMetricsLogger(resourcesClientset, metricsClientset, loggingInterval) - - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - - var buffer bytes.Buffer - log.SetOutput(&buffer) - defer func() { - log.SetOutput(os.Stderr) - }() - - // when - go func() { - err := logger.Start(ctx) - assert.NoError(t, err, "failed to finish gracefully") - }() - - time.Sleep(loggingWaitTime) - cancel() - time.Sleep(loggingWaitTime) - - // then - logs := buffer.String() - assert.Equal(t, true, strings.Contains(logs, "\"resources\":[]"), "resources are not empty array") - assert.Equal(t, true, strings.Contains(logs, "\"usage\":[]"), "usage is not empty array") - assert.Equal(t, true, strings.Contains(logs, "\"persistentVolumes\":[]"), "persistentVolumes is not empty array") - assert.Equal(t, false, strings.Contains(logs, "error"), "logged an error") - }) - - t.Run("should log error if occurred", func(t *testing.T) { - // given - resourcesClientset := kubernetesFake.NewSimpleClientset() - metricsClientset := &mocks.MetricsClientsetInterface{} - metricsV1beta1 := &mocks.MetricsV1beta1Interface{} - nodeMetrics := &mocks.NodeMetricsInterface{} - metricsClientset.On("MetricsV1beta1").Return(metricsV1beta1) - metricsV1beta1.On("NodeMetricses").Return(nodeMetrics) - nodeMetrics.On("List", context.Background(), meta.ListOptions{}).Return(nil, fmt.Errorf("someerror")) - - logger := NewMetricsLogger(resourcesClientset, metricsClientset, loggingInterval) - - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - - var buffer bytes.Buffer - log.SetOutput(&buffer) - defer func() { - log.SetOutput(os.Stderr) - }() - - // when - go func() { - err := logger.Start(ctx) - assert.NoError(t, err, "failed to finish gracefully") - }() - - time.Sleep(loggingWaitTime) - cancel() - time.Sleep(loggingWaitTime) - - // then - logs := buffer.String() - assert.Equal(t, true, strings.Contains(logs, "error"), "did not log an error") - assert.Equal(t, false, strings.Contains(logs, "Cluster metrics logged successfully."), "did log metrics") - assert.Equal(t, true, strings.Contains(logs, "Logging stopped."), "did not finish gracefully") - }) -} diff --git a/components/compass-runtime-agent/internal/metrics/metrics_fetcher.go b/components/compass-runtime-agent/internal/metrics/metrics_fetcher.go deleted file mode 100644 index ae938f749160..000000000000 --- a/components/compass-runtime-agent/internal/metrics/metrics_fetcher.go +++ /dev/null @@ -1,48 +0,0 @@ -package metrics - -import ( - "context" - - "github.com/pkg/errors" - meta "k8s.io/apimachinery/pkg/apis/meta/v1" - clientset "k8s.io/metrics/pkg/client/clientset/versioned" - "k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1beta1" -) - -type MetricsFetcher interface { - FetchNodeMetrics() ([]NodeMetrics, error) -} - -type metricsFetcher struct { - metricsClientSet v1beta1.NodeMetricsInterface -} - -func newMetricsFetcher(c clientset.Interface) MetricsFetcher { - return &metricsFetcher{ - metricsClientSet: c.MetricsV1beta1().NodeMetricses(), - } -} - -func (m *metricsFetcher) FetchNodeMetrics() ([]NodeMetrics, error) { - metricList, err := m.metricsClientSet.List(context.Background(), meta.ListOptions{}) - if err != nil { - return nil, errors.Wrap(err, "failed to list metrics") - } - - clusterUsage := make([]NodeMetrics, 0) - - for _, metric := range metricList.Items { - clusterUsage = append(clusterUsage, NodeMetrics{ - Name: metric.Name, - Usage: NodeUsage{ - CPU: metric.Usage.Cpu().String(), - EphemeralStorage: metric.Usage.StorageEphemeral().String(), - Memory: metric.Usage.Memory().String(), - Pods: metric.Usage.Pods().String(), - }, - StartCollectingTimestamp: metric.Timestamp.Time, - }) - } - - return clusterUsage, nil -} diff --git a/components/compass-runtime-agent/internal/metrics/metrics_fetcher_test.go b/components/compass-runtime-agent/internal/metrics/metrics_fetcher_test.go deleted file mode 100644 index cddc2a13161c..000000000000 --- a/components/compass-runtime-agent/internal/metrics/metrics_fetcher_test.go +++ /dev/null @@ -1,94 +0,0 @@ -package metrics - -import ( - "context" - "fmt" - "testing" - "time" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/metrics/mocks" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/resource" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/metrics/pkg/apis/metrics/v1beta1" -) - -func Test_FetchNodeMetrics(t *testing.T) { - t.Run("should fetch nodes metrics", func(t *testing.T) { - // given - now := time.Now() - metricsClientset := &mocks.MetricsClientsetInterface{} - metricsV1beta1 := &mocks.MetricsV1beta1Interface{} - nodeMetrics := &mocks.NodeMetricsInterface{} - metricsClientset.On("MetricsV1beta1").Return(metricsV1beta1) - metricsV1beta1.On("NodeMetricses").Return(nodeMetrics) - nodeMetrics.On("List", context.Background(), v1.ListOptions{}).Return(&v1beta1.NodeMetricsList{ - Items: []v1beta1.NodeMetrics{{ - ObjectMeta: v1.ObjectMeta{ - Name: "somename", - }, - Usage: corev1.ResourceList{ - corev1.ResourceCPU: *resource.NewQuantity(1, resource.DecimalSI), - corev1.ResourceMemory: *resource.NewQuantity(1, resource.BinarySI), - corev1.ResourceEphemeralStorage: *resource.NewQuantity(0, resource.BinarySI), - corev1.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), - }, - Timestamp: v1.Time{Time: now}, - }}, - }, nil) - - metricsFetcher := newMetricsFetcher(metricsClientset) - - // when - metrics, err := metricsFetcher.FetchNodeMetrics() - require.NoError(t, err) - - // then - require.Equal(t, 1, len(metrics)) - assert.Equal(t, "somename", metrics[0].Name) - assert.Equal(t, "1", metrics[0].Usage.CPU) - assert.Equal(t, "1", metrics[0].Usage.Memory) - assert.Equal(t, "0", metrics[0].Usage.EphemeralStorage) - assert.Equal(t, "0", metrics[0].Usage.Pods) - assert.Equal(t, now, metrics[0].StartCollectingTimestamp) - }) - - t.Run("should not fail if no node metrics", func(t *testing.T) { - // given - metricsClientset := &mocks.MetricsClientsetInterface{} - metricsV1beta1 := &mocks.MetricsV1beta1Interface{} - nodeMetrics := &mocks.NodeMetricsInterface{} - metricsClientset.On("MetricsV1beta1").Return(metricsV1beta1) - metricsV1beta1.On("NodeMetricses").Return(nodeMetrics) - nodeMetrics.On("List", context.Background(), v1.ListOptions{}).Return(&v1beta1.NodeMetricsList{}, nil) - - metricsFetcher := newMetricsFetcher(metricsClientset) - - // when - metrics, err := metricsFetcher.FetchNodeMetrics() - require.NoError(t, err) - - // then - assert.Equal(t, 0, len(metrics)) - }) - - t.Run("should fail if list failed", func(t *testing.T) { - // given - metricsClientset := &mocks.MetricsClientsetInterface{} - metricsV1beta1 := &mocks.MetricsV1beta1Interface{} - nodeMetrics := &mocks.NodeMetricsInterface{} - metricsClientset.On("MetricsV1beta1").Return(metricsV1beta1) - metricsV1beta1.On("NodeMetricses").Return(nodeMetrics) - nodeMetrics.On("List", context.Background(), v1.ListOptions{}).Return(nil, fmt.Errorf("someerror")) - - metricsFetcher := newMetricsFetcher(metricsClientset) - - // when - _, err := metricsFetcher.FetchNodeMetrics() - - // then - assert.Error(t, err) - }) -} diff --git a/components/compass-runtime-agent/internal/metrics/mock_interfaces.go b/components/compass-runtime-agent/internal/metrics/mock_interfaces.go deleted file mode 100644 index 58444da9bbe9..000000000000 --- a/components/compass-runtime-agent/internal/metrics/mock_interfaces.go +++ /dev/null @@ -1,21 +0,0 @@ -package metrics - -import ( - clientset "k8s.io/metrics/pkg/client/clientset/versioned" - "k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1beta1" -) - -//go:generate mockery --name=MetricsClientsetInterface -type MetricsClientsetInterface interface { - clientset.Interface -} - -//go:generate mockery --name=MetricsV1beta1Interface -type MetricsV1beta1Interface interface { - v1beta1.MetricsV1beta1Interface -} - -//go:generate mockery --name=NodeMetricsInterface -type NodeMetricsInterface interface { - v1beta1.NodeMetricsInterface -} diff --git a/components/compass-runtime-agent/internal/metrics/mocks/MetricsClientsetInterface.go b/components/compass-runtime-agent/internal/metrics/mocks/MetricsClientsetInterface.go deleted file mode 100644 index eddb48dcf205..000000000000 --- a/components/compass-runtime-agent/internal/metrics/mocks/MetricsClientsetInterface.go +++ /dev/null @@ -1,66 +0,0 @@ -// Code generated by mockery v2.10.0. DO NOT EDIT. - -package mocks - -import ( - discovery "k8s.io/client-go/discovery" - - mock "github.com/stretchr/testify/mock" - - v1alpha1 "k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1alpha1" - - v1beta1 "k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1beta1" -) - -// MetricsClientsetInterface is an autogenerated mock type for the MetricsClientsetInterface type -type MetricsClientsetInterface struct { - mock.Mock -} - -// Discovery provides a mock function with given fields: -func (_m *MetricsClientsetInterface) Discovery() discovery.DiscoveryInterface { - ret := _m.Called() - - var r0 discovery.DiscoveryInterface - if rf, ok := ret.Get(0).(func() discovery.DiscoveryInterface); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(discovery.DiscoveryInterface) - } - } - - return r0 -} - -// MetricsV1alpha1 provides a mock function with given fields: -func (_m *MetricsClientsetInterface) MetricsV1alpha1() v1alpha1.MetricsV1alpha1Interface { - ret := _m.Called() - - var r0 v1alpha1.MetricsV1alpha1Interface - if rf, ok := ret.Get(0).(func() v1alpha1.MetricsV1alpha1Interface); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(v1alpha1.MetricsV1alpha1Interface) - } - } - - return r0 -} - -// MetricsV1beta1 provides a mock function with given fields: -func (_m *MetricsClientsetInterface) MetricsV1beta1() v1beta1.MetricsV1beta1Interface { - ret := _m.Called() - - var r0 v1beta1.MetricsV1beta1Interface - if rf, ok := ret.Get(0).(func() v1beta1.MetricsV1beta1Interface); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(v1beta1.MetricsV1beta1Interface) - } - } - - return r0 -} diff --git a/components/compass-runtime-agent/internal/metrics/mocks/MetricsV1beta1Interface.go b/components/compass-runtime-agent/internal/metrics/mocks/MetricsV1beta1Interface.go deleted file mode 100644 index fc07be9f155a..000000000000 --- a/components/compass-runtime-agent/internal/metrics/mocks/MetricsV1beta1Interface.go +++ /dev/null @@ -1,63 +0,0 @@ -// Code generated by mockery v2.10.0. DO NOT EDIT. - -package mocks - -import ( - mock "github.com/stretchr/testify/mock" - rest "k8s.io/client-go/rest" - - v1beta1 "k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1beta1" -) - -// MetricsV1beta1Interface is an autogenerated mock type for the MetricsV1beta1Interface type -type MetricsV1beta1Interface struct { - mock.Mock -} - -// NodeMetricses provides a mock function with given fields: -func (_m *MetricsV1beta1Interface) NodeMetricses() v1beta1.NodeMetricsInterface { - ret := _m.Called() - - var r0 v1beta1.NodeMetricsInterface - if rf, ok := ret.Get(0).(func() v1beta1.NodeMetricsInterface); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(v1beta1.NodeMetricsInterface) - } - } - - return r0 -} - -// PodMetricses provides a mock function with given fields: namespace -func (_m *MetricsV1beta1Interface) PodMetricses(namespace string) v1beta1.PodMetricsInterface { - ret := _m.Called(namespace) - - var r0 v1beta1.PodMetricsInterface - if rf, ok := ret.Get(0).(func(string) v1beta1.PodMetricsInterface); ok { - r0 = rf(namespace) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(v1beta1.PodMetricsInterface) - } - } - - return r0 -} - -// RESTClient provides a mock function with given fields: -func (_m *MetricsV1beta1Interface) RESTClient() rest.Interface { - ret := _m.Called() - - var r0 rest.Interface - if rf, ok := ret.Get(0).(func() rest.Interface); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(rest.Interface) - } - } - - return r0 -} diff --git a/components/compass-runtime-agent/internal/metrics/mocks/NodeMetricsInterface.go b/components/compass-runtime-agent/internal/metrics/mocks/NodeMetricsInterface.go deleted file mode 100644 index ce727c281a36..000000000000 --- a/components/compass-runtime-agent/internal/metrics/mocks/NodeMetricsInterface.go +++ /dev/null @@ -1,89 +0,0 @@ -// Code generated by mockery v2.10.0. DO NOT EDIT. - -package mocks - -import ( - context "context" - - mock "github.com/stretchr/testify/mock" - - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - v1beta1 "k8s.io/metrics/pkg/apis/metrics/v1beta1" - - watch "k8s.io/apimachinery/pkg/watch" -) - -// NodeMetricsInterface is an autogenerated mock type for the NodeMetricsInterface type -type NodeMetricsInterface struct { - mock.Mock -} - -// Get provides a mock function with given fields: ctx, name, opts -func (_m *NodeMetricsInterface) Get(ctx context.Context, name string, opts v1.GetOptions) (*v1beta1.NodeMetrics, error) { - ret := _m.Called(ctx, name, opts) - - var r0 *v1beta1.NodeMetrics - if rf, ok := ret.Get(0).(func(context.Context, string, v1.GetOptions) *v1beta1.NodeMetrics); ok { - r0 = rf(ctx, name, opts) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*v1beta1.NodeMetrics) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(context.Context, string, v1.GetOptions) error); ok { - r1 = rf(ctx, name, opts) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// List provides a mock function with given fields: ctx, opts -func (_m *NodeMetricsInterface) List(ctx context.Context, opts v1.ListOptions) (*v1beta1.NodeMetricsList, error) { - ret := _m.Called(ctx, opts) - - var r0 *v1beta1.NodeMetricsList - if rf, ok := ret.Get(0).(func(context.Context, v1.ListOptions) *v1beta1.NodeMetricsList); ok { - r0 = rf(ctx, opts) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*v1beta1.NodeMetricsList) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(context.Context, v1.ListOptions) error); ok { - r1 = rf(ctx, opts) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// Watch provides a mock function with given fields: ctx, opts -func (_m *NodeMetricsInterface) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - ret := _m.Called(ctx, opts) - - var r0 watch.Interface - if rf, ok := ret.Get(0).(func(context.Context, v1.ListOptions) watch.Interface); ok { - r0 = rf(ctx, opts) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(watch.Interface) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(context.Context, v1.ListOptions) error); ok { - r1 = rf(ctx, opts) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} diff --git a/components/compass-runtime-agent/internal/metrics/model.go b/components/compass-runtime-agent/internal/metrics/model.go deleted file mode 100644 index 024ad51023b3..000000000000 --- a/components/compass-runtime-agent/internal/metrics/model.go +++ /dev/null @@ -1,49 +0,0 @@ -package metrics - -import "time" - -type ClusterInfo struct { - Resources []NodeResources `json:"resources"` - Usage []NodeMetrics `json:"usage"` - Volumes []PersistentVolumes `json:"persistentVolumes"` -} - -type NodeResources struct { - Name string `json:"nodeName"` - InstanceType string `json:"instanceType"` - Capacity NodeCapacity `json:"capacity"` -} - -type NodeCapacity struct { - CPU string `json:"cpu"` - EphemeralStorage string `json:"ephemeralStorage"` - Memory string `json:"memory"` - Pods string `json:"pods"` -} - -type NodeMetrics struct { - Name string `json:"nodeName"` - StartCollectingTimestamp time.Time `json:"startCollectingTimestamp"` - Usage NodeUsage `json:"usage"` -} - -type NodeUsage struct { - CPU string `json:"cpu"` - Memory string `json:"memory"` - - // Deprecated: It's always set to 0. - EphemeralStorage string `json:"ephemeralStorage"` - // Deprecated: It's always set to 0. - Pods string `json:"pods"` -} - -type PersistentVolumes struct { - Name string `json:"name"` - Capacity string `json:"capacity"` - Claim *Claim `json:"claim,omitempty"` -} - -type Claim struct { - Name string `json:"name"` - Namespace string `json:"namespace"` -} diff --git a/components/compass-runtime-agent/internal/metrics/resources_fetcher.go b/components/compass-runtime-agent/internal/metrics/resources_fetcher.go deleted file mode 100644 index 44fb0f0d07fa..000000000000 --- a/components/compass-runtime-agent/internal/metrics/resources_fetcher.go +++ /dev/null @@ -1,48 +0,0 @@ -package metrics - -import ( - "context" - - "github.com/pkg/errors" - meta "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/client-go/kubernetes" - core "k8s.io/client-go/kubernetes/typed/core/v1" -) - -type ResourcesFetcher interface { - FetchNodesResources() ([]NodeResources, error) -} - -type resourcesFetcher struct { - nodeClientSet core.NodeInterface -} - -func newResourcesFetcher(clientset kubernetes.Interface) ResourcesFetcher { - return &resourcesFetcher{ - nodeClientSet: clientset.CoreV1().Nodes(), - } -} - -func (r *resourcesFetcher) FetchNodesResources() ([]NodeResources, error) { - nodes, err := r.nodeClientSet.List(context.Background(), meta.ListOptions{}) - if err != nil { - return nil, errors.Wrap(err, "failed to list nodes") - } - - clusterResources := make([]NodeResources, 0) - - for _, node := range nodes.Items { - clusterResources = append(clusterResources, NodeResources{ - Name: node.Name, - InstanceType: node.Labels["beta.kubernetes.io/instance-type"], - Capacity: NodeCapacity{ - CPU: node.Status.Capacity.Cpu().String(), - EphemeralStorage: node.Status.Capacity.StorageEphemeral().String(), - Memory: node.Status.Capacity.Memory().String(), - Pods: node.Status.Capacity.Pods().String(), - }, - }) - } - - return clusterResources, nil -} diff --git a/components/compass-runtime-agent/internal/metrics/resources_fetcher_test.go b/components/compass-runtime-agent/internal/metrics/resources_fetcher_test.go deleted file mode 100644 index ee22640df794..000000000000 --- a/components/compass-runtime-agent/internal/metrics/resources_fetcher_test.go +++ /dev/null @@ -1,59 +0,0 @@ -package metrics - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/resource" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - kubernetesFake "k8s.io/client-go/kubernetes/fake" -) - -func Test_FetchNodesResources(t *testing.T) { - t.Run("should fetch nodes resources", func(t *testing.T) { - // given - resourcesClientset := kubernetesFake.NewSimpleClientset(&corev1.Node{ - ObjectMeta: v1.ObjectMeta{ - Name: "somename", - Labels: map[string]string{"beta.kubernetes.io/instance-type": "somelabel"}, - }, - Status: corev1.NodeStatus{ - Capacity: corev1.ResourceList{ - corev1.ResourceCPU: *resource.NewQuantity(1, resource.DecimalSI), - corev1.ResourceMemory: *resource.NewQuantity(1, resource.BinarySI), - corev1.ResourceEphemeralStorage: *resource.NewQuantity(1, resource.BinarySI), - corev1.ResourcePods: *resource.NewQuantity(1, resource.DecimalSI), - }, - }, - }) - resourcesFetcher := newResourcesFetcher(resourcesClientset) - - // when - resources, err := resourcesFetcher.FetchNodesResources() - require.NoError(t, err) - - // then - require.Equal(t, 1, len(resources)) - assert.Equal(t, "somename", resources[0].Name) - assert.Equal(t, "somelabel", resources[0].InstanceType) - assert.Equal(t, "1", resources[0].Capacity.CPU) - assert.Equal(t, "1", resources[0].Capacity.Memory) - assert.Equal(t, "1", resources[0].Capacity.EphemeralStorage) - assert.Equal(t, "1", resources[0].Capacity.Pods) - }) - - t.Run("should not fail if no nodes", func(t *testing.T) { - // given - resourcesClientset := kubernetesFake.NewSimpleClientset() - resourcesFetcher := newResourcesFetcher(resourcesClientset) - - // when - resources, err := resourcesFetcher.FetchNodesResources() - require.NoError(t, err) - - // then - assert.Equal(t, 0, len(resources)) - }) -} diff --git a/components/compass-runtime-agent/internal/metrics/volumes_fetcher.go b/components/compass-runtime-agent/internal/metrics/volumes_fetcher.go deleted file mode 100644 index fa7a582cca11..000000000000 --- a/components/compass-runtime-agent/internal/metrics/volumes_fetcher.go +++ /dev/null @@ -1,59 +0,0 @@ -package metrics - -import ( - "context" - - "github.com/pkg/errors" - v1 "k8s.io/api/core/v1" - meta "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/client-go/kubernetes" - core "k8s.io/client-go/kubernetes/typed/core/v1" -) - -type VolumesFetcher interface { - FetchPersistentVolumesCapacity() ([]PersistentVolumes, error) -} - -type volumesFetcher struct { - persistentVolumesInterface core.PersistentVolumeInterface -} - -func newVolumesFetcher(clientset kubernetes.Interface) VolumesFetcher { - return &volumesFetcher{ - persistentVolumesInterface: clientset.CoreV1().PersistentVolumes(), - } -} - -func (v *volumesFetcher) FetchPersistentVolumesCapacity() ([]PersistentVolumes, error) { - persistentVolumes, err := v.persistentVolumesInterface.List(context.Background(), meta.ListOptions{}) - if err != nil { - return nil, errors.Wrap(err, "failed to list persistent volumes") - } - - persistentVolumesCapacity := make([]PersistentVolumes, 0) - - for _, persistentVolume := range persistentVolumes.Items { - persistentVolumesCapacity = append(persistentVolumesCapacity, PersistentVolumes{ - Name: persistentVolume.Name, - Capacity: getCapacity(persistentVolume), - Claim: getClaim(persistentVolume), - }) - } - - return persistentVolumesCapacity, nil -} - -func getCapacity(pv v1.PersistentVolume) string { - storage := pv.Spec.Capacity[v1.ResourceStorage] - return (&storage).String() -} - -func getClaim(pv v1.PersistentVolume) *Claim { - if pv.Spec.ClaimRef == nil { - return nil - } - return &Claim{ - Name: pv.Spec.ClaimRef.Name, - Namespace: pv.Spec.ClaimRef.Namespace, - } -} diff --git a/components/compass-runtime-agent/internal/metrics/volumes_fetcher_test.go b/components/compass-runtime-agent/internal/metrics/volumes_fetcher_test.go deleted file mode 100644 index 42777a6a547e..000000000000 --- a/components/compass-runtime-agent/internal/metrics/volumes_fetcher_test.go +++ /dev/null @@ -1,90 +0,0 @@ -package metrics - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/resource" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - kubernetesFake "k8s.io/client-go/kubernetes/fake" -) - -func Test_FetchPersistentVolumesCapacity(t *testing.T) { - t.Run("should fetch persistent volumes capacity", func(t *testing.T) { - // given - resourcesClientset := kubernetesFake.NewSimpleClientset(&corev1.PersistentVolume{ - ObjectMeta: v1.ObjectMeta{ - Name: "somename", - }, - Spec: corev1.PersistentVolumeSpec{ - Capacity: corev1.ResourceList{ - corev1.ResourceStorage: *resource.NewQuantity(1, resource.BinarySI), - }, - ClaimRef: &corev1.ObjectReference{ - Namespace: "claimnamespace", - Name: "claimname", - }, - }, - }) - volumesFetcher := newVolumesFetcher(resourcesClientset) - - // when - volumes, err := volumesFetcher.FetchPersistentVolumesCapacity() - require.NoError(t, err) - - // then - require.Equal(t, 1, len(volumes)) - assert.Equal(t, "somename", volumes[0].Name) - assert.Equal(t, "1", volumes[0].Capacity) - require.NotNil(t, volumes[0].Claim) - assert.Equal(t, "claimnamespace", volumes[0].Claim.Namespace) - assert.Equal(t, "claimname", volumes[0].Claim.Name) - }) - - t.Run("should not fail if no persistent volumes", func(t *testing.T) { - // given - resourcesClientset := kubernetesFake.NewSimpleClientset() - volumesFetcher := newVolumesFetcher(resourcesClientset) - - // when - volumes, err := volumesFetcher.FetchPersistentVolumesCapacity() - require.NoError(t, err) - - // then - assert.Equal(t, 0, len(volumes)) - }) - - t.Run("should return 0 capacity if none is allocated", func(t *testing.T) { - // given - resourcesClientset := kubernetesFake.NewSimpleClientset(&corev1.PersistentVolume{ - Spec: corev1.PersistentVolumeSpec{ - Capacity: corev1.ResourceList{}, - }, - }) - volumesFetcher := newVolumesFetcher(resourcesClientset) - - // when - volumes, err := volumesFetcher.FetchPersistentVolumesCapacity() - require.NoError(t, err) - - // then - require.Equal(t, 1, len(volumes)) - assert.Equal(t, "0", volumes[0].Capacity) - }) - - t.Run("should return nil claim if none is bound", func(t *testing.T) { - // given - resourcesClientset := kubernetesFake.NewSimpleClientset(&corev1.PersistentVolume{}) - volumesFetcher := newVolumesFetcher(resourcesClientset) - - // when - volumes, err := volumesFetcher.FetchPersistentVolumesCapacity() - require.NoError(t, err) - - // then - require.Equal(t, 1, len(volumes)) - assert.Nil(t, volumes[0].Claim) - }) -} diff --git a/components/compass-runtime-agent/internal/secrets/mocks/Manager.go b/components/compass-runtime-agent/internal/secrets/mocks/Manager.go deleted file mode 100644 index b997e2854e62..000000000000 --- a/components/compass-runtime-agent/internal/secrets/mocks/Manager.go +++ /dev/null @@ -1,100 +0,0 @@ -// Code generated by mockery v2.10.0. DO NOT EDIT. - -package mocks - -import ( - context "context" - - mock "github.com/stretchr/testify/mock" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - v1 "k8s.io/api/core/v1" -) - -// Manager is an autogenerated mock type for the Manager type -type Manager struct { - mock.Mock -} - -// Create provides a mock function with given fields: ctx, secret, options -func (_m *Manager) Create(ctx context.Context, secret *v1.Secret, options metav1.CreateOptions) (*v1.Secret, error) { - ret := _m.Called(ctx, secret, options) - - var r0 *v1.Secret - if rf, ok := ret.Get(0).(func(context.Context, *v1.Secret, metav1.CreateOptions) *v1.Secret); ok { - r0 = rf(ctx, secret, options) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*v1.Secret) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(context.Context, *v1.Secret, metav1.CreateOptions) error); ok { - r1 = rf(ctx, secret, options) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// Delete provides a mock function with given fields: ctx, name, options -func (_m *Manager) Delete(ctx context.Context, name string, options metav1.DeleteOptions) error { - ret := _m.Called(ctx, name, options) - - var r0 error - if rf, ok := ret.Get(0).(func(context.Context, string, metav1.DeleteOptions) error); ok { - r0 = rf(ctx, name, options) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// Get provides a mock function with given fields: ctx, name, options -func (_m *Manager) Get(ctx context.Context, name string, options metav1.GetOptions) (*v1.Secret, error) { - ret := _m.Called(ctx, name, options) - - var r0 *v1.Secret - if rf, ok := ret.Get(0).(func(context.Context, string, metav1.GetOptions) *v1.Secret); ok { - r0 = rf(ctx, name, options) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*v1.Secret) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(context.Context, string, metav1.GetOptions) error); ok { - r1 = rf(ctx, name, options) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// Update provides a mock function with given fields: ctx, secret, options -func (_m *Manager) Update(ctx context.Context, secret *v1.Secret, options metav1.UpdateOptions) (*v1.Secret, error) { - ret := _m.Called(ctx, secret, options) - - var r0 *v1.Secret - if rf, ok := ret.Get(0).(func(context.Context, *v1.Secret, metav1.UpdateOptions) *v1.Secret); ok { - r0 = rf(ctx, secret, options) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*v1.Secret) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(context.Context, *v1.Secret, metav1.UpdateOptions) error); ok { - r1 = rf(ctx, secret, options) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} diff --git a/components/compass-runtime-agent/internal/secrets/mocks/Repository.go b/components/compass-runtime-agent/internal/secrets/mocks/Repository.go deleted file mode 100644 index 1fce824ba3f1..000000000000 --- a/components/compass-runtime-agent/internal/secrets/mocks/Repository.go +++ /dev/null @@ -1,100 +0,0 @@ -// Code generated by mockery v2.10.0. DO NOT EDIT. - -package mocks - -import ( - mock "github.com/stretchr/testify/mock" - - types "k8s.io/apimachinery/pkg/types" -) - -// Repository is an autogenerated mock type for the Repository type -type Repository struct { - mock.Mock -} - -// Delete provides a mock function with given fields: secretName -func (_m *Repository) Delete(secretName types.NamespacedName) error { - ret := _m.Called(secretName) - - var r0 error - if rf, ok := ret.Get(0).(func(types.NamespacedName) error); ok { - r0 = rf(secretName) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// Exists provides a mock function with given fields: name -func (_m *Repository) Exists(name types.NamespacedName) (bool, error) { - ret := _m.Called(name) - - var r0 bool - if rf, ok := ret.Get(0).(func(types.NamespacedName) bool); ok { - r0 = rf(name) - } else { - r0 = ret.Get(0).(bool) - } - - var r1 error - if rf, ok := ret.Get(1).(func(types.NamespacedName) error); ok { - r1 = rf(name) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// Get provides a mock function with given fields: name -func (_m *Repository) Get(name types.NamespacedName) (map[string][]byte, error) { - ret := _m.Called(name) - - var r0 map[string][]byte - if rf, ok := ret.Get(0).(func(types.NamespacedName) map[string][]byte); ok { - r0 = rf(name) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(map[string][]byte) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(types.NamespacedName) error); ok { - r1 = rf(name) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// UpsertWithMerge provides a mock function with given fields: name, data -func (_m *Repository) UpsertWithMerge(name types.NamespacedName, data map[string][]byte) error { - ret := _m.Called(name, data) - - var r0 error - if rf, ok := ret.Get(0).(func(types.NamespacedName, map[string][]byte) error); ok { - r0 = rf(name, data) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// UpsertWithReplace provides a mock function with given fields: name, data -func (_m *Repository) UpsertWithReplace(name types.NamespacedName, data map[string][]byte) error { - ret := _m.Called(name, data) - - var r0 error - if rf, ok := ret.Get(0).(func(types.NamespacedName, map[string][]byte) error); ok { - r0 = rf(name, data) - } else { - r0 = ret.Error(0) - } - - return r0 -} diff --git a/components/compass-runtime-agent/internal/secrets/repository.go b/components/compass-runtime-agent/internal/secrets/repository.go deleted file mode 100644 index fdcf35b8c5c6..000000000000 --- a/components/compass-runtime-agent/internal/secrets/repository.go +++ /dev/null @@ -1,168 +0,0 @@ -package secrets - -import ( - "context" - "fmt" - - "k8s.io/apimachinery/pkg/types" - - "github.com/pkg/errors" - v1 "k8s.io/api/core/v1" - k8serrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// ManagerConstructor creates Secret Manager for specified namespace -type ManagerConstructor func(namespace string) Manager - -// Manager contains operations for managing k8s secrets -// -//go:generate mockery --name=Manager -type Manager interface { - Get(ctx context.Context, name string, options metav1.GetOptions) (*v1.Secret, error) - Create(ctx context.Context, secret *v1.Secret, options metav1.CreateOptions) (*v1.Secret, error) - Update(ctx context.Context, secret *v1.Secret, options metav1.UpdateOptions) (*v1.Secret, error) - Delete(ctx context.Context, name string, options metav1.DeleteOptions) error -} - -// Repository contains operations for managing client credentials -// -//go:generate mockery --name=Repository -type Repository interface { - Exists(name types.NamespacedName) (bool, error) - Get(name types.NamespacedName) (map[string][]byte, error) - UpsertWithReplace(name types.NamespacedName, data map[string][]byte) error - UpsertWithMerge(name types.NamespacedName, data map[string][]byte) error - Delete(secretName types.NamespacedName) error -} - -type repository struct { - secretsManagerConstructor ManagerConstructor -} - -// NewRepository creates a new secrets repository -func NewRepository(secretsManagerConstructor ManagerConstructor) Repository { - return &repository{ - secretsManagerConstructor: secretsManagerConstructor, - } -} - -func (r *repository) Exists(name types.NamespacedName) (bool, error) { - secretManager := r.secretsManagerConstructor(name.Namespace) - - _, err := secretManager.Get(context.Background(), name.Name, metav1.GetOptions{}) - if err != nil { - if k8serrors.IsNotFound(err) { - return false, nil - } - return false, err - } - - return true, nil -} - -// UpsertWithReplace creates a new Kubernetes secret, if secret with specified name already exists overrides it -func (r *repository) UpsertWithReplace(name types.NamespacedName, data map[string][]byte) error { - secretManager := r.secretsManagerConstructor(name.Namespace) - - secret := makeSecret(name, data) - - _, err := secretManager.Create(context.Background(), secret, metav1.CreateOptions{}) - if err != nil { - if k8serrors.IsAlreadyExists(err) { - return r.replace(secretManager, secret) - } - - return errors.Wrapf(err, fmt.Sprintf("Replacing %s secret failed", name)) - } - - return err -} - -func (r *repository) replace(secretManager Manager, secret *v1.Secret) error { - err := secretManager.Delete(context.Background(), secret.Name, metav1.DeleteOptions{}) - if err != nil { - return errors.Wrap(err, fmt.Sprintf("Deleting %s secret failed", secret.Name)) - } - - _, err = secretManager.Create(context.Background(), secret, metav1.CreateOptions{}) - if err != nil { - return err - } - - return nil -} - -// Get returns secret data for specified name -func (r *repository) Get(name types.NamespacedName) (map[string][]byte, error) { - secretManager := r.secretsManagerConstructor(name.Namespace) - - secret, err := secretManager.Get(context.Background(), name.Name, metav1.GetOptions{}) - if err != nil { - return nil, err - } - - return secret.Data, nil -} - -// UpsertWithMerge updates secrets data with the provided values. If provided value already exists it will be updated. -// If secret does not exist it will be created -func (r *repository) UpsertWithMerge(name types.NamespacedName, data map[string][]byte) error { - existingData, err := r.Get(name) - if err != nil { - if !k8serrors.IsNotFound(err) { - return errors.Wrap(err, "Failed to upsert secret data") - } - - existingData = map[string][]byte{} - } - - mergedData := mergeSecretData(existingData, data) - return r.upsert(name, mergedData) -} - -func (r *repository) Delete(name types.NamespacedName) error { - secretManager := r.secretsManagerConstructor(name.Namespace) - return secretManager.Delete(context.Background(), name.Name, metav1.DeleteOptions{}) -} - -func (r *repository) upsert(name types.NamespacedName, data map[string][]byte) error { - secretManager := r.secretsManagerConstructor(name.Namespace) - - secret := makeSecret(name, data) - - _, err := secretManager.Update(context.Background(), secret, metav1.UpdateOptions{}) - if err != nil { - if k8serrors.IsNotFound(err) { - _, err = secretManager.Create(context.Background(), secret, metav1.CreateOptions{}) - return err - } - return errors.Wrapf(err, fmt.Sprintf("Updating %s secret failed while upserting", name)) - } - return nil -} - -func makeSecret(name types.NamespacedName, data map[string][]byte) *v1.Secret { - return &v1.Secret{ - ObjectMeta: metav1.ObjectMeta{ - Name: name.Name, - Namespace: name.Namespace, - }, - Data: data, - } -} - -func mergeSecretData(oldData, newData map[string][]byte) map[string][]byte { - mergedMap := mergeMap(map[string][]byte{}, oldData) - mergedMap = mergeMap(mergedMap, newData) - - return mergedMap -} - -func mergeMap(base, merge map[string][]byte) map[string][]byte { - for k, v := range merge { - base[k] = v - } - - return base -} diff --git a/components/compass-runtime-agent/internal/secrets/repository_test.go b/components/compass-runtime-agent/internal/secrets/repository_test.go deleted file mode 100644 index 67ff42a236ab..000000000000 --- a/components/compass-runtime-agent/internal/secrets/repository_test.go +++ /dev/null @@ -1,329 +0,0 @@ -package secrets - -import ( - "context" - "errors" - "testing" - - "github.com/kyma-project/kyma/components/compass-runtime-agent/internal/secrets/mocks" - - "k8s.io/apimachinery/pkg/types" - - "k8s.io/apimachinery/pkg/runtime/schema" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - k8serrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -const ( - dataKey = "dataKey" - secretName = "secret-name" - namespace = "kyma-system" -) - -var ( - namespacedName = types.NamespacedName{ - Name: secretName, - Namespace: namespace, - } - - secretData = map[string][]byte{ - "testKey2": []byte("testValue2"), - "testKey1": []byte("testValue1"), - } -) - -func TestRepository_Exists(t *testing.T) { - t.Run("should return true if exists", func(t *testing.T) { - // given - secret := makeSecret(namespacedName, map[string][]byte{dataKey: []byte("data")}) - - secretsManagerMock := &mocks.Manager{} - secretsManagerMock.On("Get", context.Background(), secretName, metav1.GetOptions{}).Return(secret, nil) - - repository := NewRepository(prepareManagerConstructor(secretsManagerMock)) - - // when - exists, err := repository.Exists(namespacedName) - - // then - assert.NoError(t, err) - assert.Equal(t, true, exists) - }) - - t.Run("should return false if secret doesn't exist", func(t *testing.T) { - // given - secretsManagerMock := &mocks.Manager{} - secretsManagerMock.On("Get", context.Background(), secretName, metav1.GetOptions{}).Return(nil, k8serrors.NewNotFound(schema.GroupResource{}, "secret")) - - repository := NewRepository(prepareManagerConstructor(secretsManagerMock)) - - // when - exists, err := repository.Exists(namespacedName) - - // then - assert.NoError(t, err) - assert.Equal(t, false, exists) - }) - - t.Run("should return error if failed to read secret", func(t *testing.T) { - // given - secretsManagerMock := &mocks.Manager{} - secretsManagerMock.On("Get", context.Background(), secretName, metav1.GetOptions{}).Return(nil, errors.New("oh, no")) - - repository := NewRepository(prepareManagerConstructor(secretsManagerMock)) - - // when - exists, err := repository.Exists(namespacedName) - - // then - assert.Error(t, err) - assert.Equal(t, false, exists) - }) -} - -func TestRepository_Get(t *testing.T) { - t.Run("should get given secret", func(t *testing.T) { - // given - secret := makeSecret(namespacedName, map[string][]byte{dataKey: []byte("data")}) - - secretsManagerMock := &mocks.Manager{} - secretsManagerMock.On("Get", context.Background(), secretName, metav1.GetOptions{}).Return(secret, nil) - - repository := NewRepository(prepareManagerConstructor(secretsManagerMock)) - - // when - secrets, err := repository.Get(namespacedName) - - // then - assert.NoError(t, err) - assert.NotNil(t, secrets[dataKey]) - - secretsManagerMock.AssertExpectations(t) - }) - - t.Run("should return an error in case fetching fails", func(t *testing.T) { - // given - secretsManagerMock := &mocks.Manager{} - secretsManagerMock.On("Get", context.Background(), secretName, metav1.GetOptions{}).Return( - nil, - errors.New("some error")) - - repository := NewRepository(prepareManagerConstructor(secretsManagerMock)) - - // when - secretData, err := repository.Get(namespacedName) - - // then - assert.Error(t, err) - assert.NotEmpty(t, err.Error()) - assert.Nil(t, secretData) - - secretsManagerMock.AssertExpectations(t) - }) -} - -func TestRepository_Override(t *testing.T) { - - t.Run("should create secret", func(t *testing.T) { - // given - secret := makeSecret(namespacedName, secretData) - - secretsManagerMock := &mocks.Manager{} - secretsManagerMock.On("Create", context.Background(), secret, metav1.CreateOptions{}).Return(secret, nil) - - repository := NewRepository(prepareManagerConstructor(secretsManagerMock)) - - // when - err := repository.UpsertWithReplace(namespacedName, secretData) - - // then - assert.NoError(t, err) - secretsManagerMock.AssertExpectations(t) - }) - - t.Run("should fail if unable to create secret", func(t *testing.T) { - // given - secret := makeSecret(namespacedName, secretData) - - secretsManagerMock := &mocks.Manager{} - secretsManagerMock.On("Create", context.Background(), secret, metav1.CreateOptions{}).Return(nil, errors.New("some error")) - - repository := NewRepository(prepareManagerConstructor(secretsManagerMock)) - - // when - err := repository.UpsertWithReplace(namespacedName, secretData) - - // then - require.Error(t, err) - secretsManagerMock.AssertExpectations(t) - }) - - t.Run("should override secret if already exist", func(t *testing.T) { - // given - secret := makeSecret(namespacedName, secretData) - - secretsManagerMock := &mocks.Manager{} - secretsManagerMock.On("Create", context.Background(), secret, metav1.CreateOptions{}).Return(nil, k8serrors.NewAlreadyExists(schema.GroupResource{}, "error")).Once() - secretsManagerMock.On("Create", context.Background(), secret, metav1.CreateOptions{}).Return(nil, nil).Once() - secretsManagerMock.On("Delete", context.Background(), secretName, metav1.DeleteOptions{}).Return(nil) - - repository := NewRepository(prepareManagerConstructor(secretsManagerMock)) - - // when - err := repository.UpsertWithReplace(namespacedName, secretData) - - // then - require.NoError(t, err) - secretsManagerMock.AssertExpectations(t) - }) - - t.Run("should return error if failed to delete secret", func(t *testing.T) { - // given - secret := makeSecret(namespacedName, secretData) - - secretsManagerMock := &mocks.Manager{} - secretsManagerMock.On("Create", context.Background(), secret, metav1.CreateOptions{}).Return(nil, k8serrors.NewAlreadyExists(schema.GroupResource{}, "error")) - secretsManagerMock.On("Delete", context.Background(), secretName, metav1.DeleteOptions{}).Return(errors.New("error")) - - repository := NewRepository(prepareManagerConstructor(secretsManagerMock)) - - // when - err := repository.UpsertWithReplace(namespacedName, secretData) - - // then - require.Error(t, err) - secretsManagerMock.AssertExpectations(t) - }) - - t.Run("should return error if failed to create secret after deleting", func(t *testing.T) { - // given - secret := makeSecret(namespacedName, secretData) - - secretsManagerMock := &mocks.Manager{} - secretsManagerMock.On("Create", context.Background(), secret, metav1.CreateOptions{}).Return(nil, k8serrors.NewAlreadyExists(schema.GroupResource{}, "error")).Once() - secretsManagerMock.On("Create", context.Background(), secret, metav1.CreateOptions{}).Return(nil, errors.New("error")).Once() - secretsManagerMock.On("Delete", context.Background(), secretName, metav1.DeleteOptions{}).Return(nil) - - repository := NewRepository(prepareManagerConstructor(secretsManagerMock)) - - // when - err := repository.UpsertWithReplace(namespacedName, secretData) - - // then - require.Error(t, err) - secretsManagerMock.AssertExpectations(t) - }) -} - -func TestRepository_UpsertData(t *testing.T) { - - t.Run("should update secret data if it exists", func(t *testing.T) { - // given - secret := makeSecret(namespacedName, secretData) - - additionalSecretData := map[string][]byte{ - "testKey2": []byte("testValue2Modified"), - "testKey3": []byte("testValue3"), - } - - updatedSecret := makeSecret(namespacedName, map[string][]byte{ - "testKey1": []byte("testValue1"), - "testKey2": []byte("testValue2Modified"), - "testKey3": []byte("testValue3"), - }) - - secretsManagerMock := &mocks.Manager{} - secretsManagerMock.On("Get", context.Background(), secretName, metav1.GetOptions{}).Return(secret, nil) - secretsManagerMock.On("Update", context.Background(), updatedSecret, metav1.UpdateOptions{}).Return(secret, nil) - - repository := NewRepository(prepareManagerConstructor(secretsManagerMock)) - - // when - err := repository.UpsertWithMerge(namespacedName, additionalSecretData) - - // then - assert.NoError(t, err) - secretsManagerMock.AssertExpectations(t) - }) - - t.Run("should create new secret if it does not exists", func(t *testing.T) { - // given - secret := makeSecret(namespacedName, secretData) - - secretsManagerMock := &mocks.Manager{} - secretsManagerMock.On("Get", context.Background(), secretName, metav1.GetOptions{}).Return(nil, k8serrors.NewNotFound(schema.GroupResource{}, "error")) - secretsManagerMock.On("Update", context.Background(), secret, metav1.UpdateOptions{}).Return(nil, k8serrors.NewNotFound(schema.GroupResource{}, "error")) - secretsManagerMock.On("Create", context.Background(), secret, metav1.CreateOptions{}).Return(secret, nil) - - repository := NewRepository(prepareManagerConstructor(secretsManagerMock)) - - // when - err := repository.UpsertWithMerge(namespacedName, secretData) - - // then - assert.NoError(t, err) - secretsManagerMock.AssertExpectations(t) - }) - - t.Run("should return error when failed to get secret", func(t *testing.T) { - // given - secretsManagerMock := &mocks.Manager{} - secretsManagerMock.On("Get", context.Background(), secretName, metav1.GetOptions{}).Return(nil, errors.New("error")) - - repository := NewRepository(prepareManagerConstructor(secretsManagerMock)) - - // when - err := repository.UpsertWithMerge(namespacedName, secretData) - - // then - assert.Error(t, err) - secretsManagerMock.AssertExpectations(t) - }) - - t.Run("should return error when failed to update secret", func(t *testing.T) { - // given - secret := makeSecret(namespacedName, secretData) - - secretsManagerMock := &mocks.Manager{} - secretsManagerMock.On("Get", context.Background(), secretName, metav1.GetOptions{}).Return(nil, k8serrors.NewNotFound(schema.GroupResource{}, "error")) - secretsManagerMock.On("Update", context.Background(), secret, metav1.UpdateOptions{}).Return(nil, errors.New("error")) - - repository := NewRepository(prepareManagerConstructor(secretsManagerMock)) - - // when - err := repository.UpsertWithMerge(namespacedName, secretData) - - // then - assert.Error(t, err) - secretsManagerMock.AssertExpectations(t) - }) - - t.Run("should return error when failed to create secret", func(t *testing.T) { - // given - secret := makeSecret(namespacedName, secretData) - - secretsManagerMock := &mocks.Manager{} - secretsManagerMock.On("Get", context.Background(), secretName, metav1.GetOptions{}).Return(nil, k8serrors.NewNotFound(schema.GroupResource{}, "error")) - secretsManagerMock.On("Update", context.Background(), secret, metav1.UpdateOptions{}).Return(nil, k8serrors.NewNotFound(schema.GroupResource{}, "error")) - secretsManagerMock.On("Create", context.Background(), secret, metav1.CreateOptions{}).Return(nil, errors.New("error")) - - repository := NewRepository(prepareManagerConstructor(secretsManagerMock)) - - // when - err := repository.UpsertWithMerge(namespacedName, secretData) - - // then - assert.Error(t, err) - secretsManagerMock.AssertExpectations(t) - }) - -} - -func prepareManagerConstructor(manager Manager) ManagerConstructor { - return func(namespace string) Manager { - return manager - } -} diff --git a/components/compass-runtime-agent/internal/testutil/testdata/ca.crt.pem b/components/compass-runtime-agent/internal/testutil/testdata/ca.crt.pem deleted file mode 100644 index e69eb4f7c21f..000000000000 --- a/components/compass-runtime-agent/internal/testutil/testdata/ca.crt.pem +++ /dev/null @@ -1,17 +0,0 @@ ------BEGIN CERTIFICATE----- -MIICpjCCAY4CCQCl/E7ViyiX5TANBgkqhkiG9w0BAQsFADAUMRIwEAYDVQQDDAls -b2NhbGhvc3QwIBcNMTkwOTE3MDc1MzQ0WhgPMzAxOTAxMTgwNzUzNDRaMBQxEjAQ -BgNVBAMMCWxvY2FsaG9zdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB -AN6o/VxuOl4agAITuR/VWwF4ZMEXTYHeNb0TDU48BWwzYUTt0XhDFSnN0WLiwZol -PI6L+RLLBkV36xZd0uJzcCjxFTyw/smJ+Nr2oUtx9XZZE66ED6DIml1usu+TaJjc -KKa9ADxOCJhJ50flKGuzLtUadfyHSWguvJUx94tpJu3ZxBq+Tcv4T+F3d4Xi6dQ5 -62BWvl5nQWd5fKMxhhYG4fVTs4zYjyVYYVEosW+NI6qJRPjyAlV/gE83Y0eZlFLz -gvRMNR/mbOmxQqPx5lo1WFR89UoCIMkAz2gQAisz/AlbY16pgy8xTqxiGB0t85nG -aYRKXvQXFmQVf2kTskxenxcCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEADwIQDFeb -4EZDWTTklAi1DseNq/ha0nSPPaBMXHkFEtaNRv2K78dHZisbZj0Ff+Kt2kDFMXnW -ecy4CTRgynHc9O1eJL9iXrFdTRFD07tdp8NmfLjC60n6JxZuaTcVMLILp/DXJbbK -3AQ8XcqDNzXjAuGTt63Hen+C+9MrLaY+PhvHL9ijg74ojTO7KCUHJljDRAFTmCDR -l15t6u5zw/MYxZmCgrlpw/JHZ8JXBGLIQUBAqsDTGnqBw6DnPFDLMFMFb5YSHI69 -1aImBzwNIx7A36CUPCKxFiUIt1lmDgeZppuhxy8eGvhQdqDLtp6q8/qhk9KP0x7C -B6TwdKYHofTOuQ== ------END CERTIFICATE----- diff --git a/components/compass-runtime-agent/internal/testutil/testdata/ca.csr.pem b/components/compass-runtime-agent/internal/testutil/testdata/ca.csr.pem deleted file mode 100644 index dc265fdad3fa..000000000000 --- a/components/compass-runtime-agent/internal/testutil/testdata/ca.csr.pem +++ /dev/null @@ -1,15 +0,0 @@ ------BEGIN CERTIFICATE REQUEST----- -MIICWTCCAUECAQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0B -AQEFAAOCAQ8AMIIBCgKCAQEA3qj9XG46XhqAAhO5H9VbAXhkwRdNgd41vRMNTjwF -bDNhRO3ReEMVKc3RYuLBmiU8jov5EssGRXfrFl3S4nNwKPEVPLD+yYn42vahS3H1 -dlkTroQPoMiaXW6y75NomNwopr0APE4ImEnnR+Uoa7Mu1Rp1/IdJaC68lTH3i2km -7dnEGr5Ny/hP4Xd3heLp1DnrYFa+XmdBZ3l8ozGGFgbh9VOzjNiPJVhhUSixb40j -qolE+PICVX+ATzdjR5mUUvOC9Ew1H+Zs6bFCo/HmWjVYVHz1SgIgyQDPaBACKzP8 -CVtjXqmDLzFOrGIYHS3zmcZphEpe9BcWZBV/aROyTF6fFwIDAQABoAAwDQYJKoZI -hvcNAQELBQADggEBAA/0GJYqaNdaoCtWN5aEp1/C9uEoiIdNlcvDUmyk9TkBIvda -S6TUzzVWztKU32YAxOKlcA86OD+is1QwqNQ1tSQh82DEizg35ZBvVtVIaRy51Qox -dndPdgqRudTyVQW7mnCNnWn25Fw50qH0eU6p461hU/Q2XA/NyRDtGpKIUXgBjDBW -TYu4qNLbS0kvBaEzuSDqrF6BIbv6fpbZFIathLhaaVMjwPPAE6zunO+MJrZDnYKL -0Uww9yV/kQs9UqoJETmVv976qOMC3xHr1Z5/s2lEa/w+uWYyr3FH0zjPIlWsujr6 -BzKPys+A264jbG4Lmg9WRb6VzJddvoHru1Bk3TE= ------END CERTIFICATE REQUEST----- diff --git a/components/compass-runtime-agent/internal/testutil/testdata/ca.key.pem b/components/compass-runtime-agent/internal/testutil/testdata/ca.key.pem deleted file mode 100644 index 76675b04c2d3..000000000000 --- a/components/compass-runtime-agent/internal/testutil/testdata/ca.key.pem +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEpQIBAAKCAQEA3qj9XG46XhqAAhO5H9VbAXhkwRdNgd41vRMNTjwFbDNhRO3R -eEMVKc3RYuLBmiU8jov5EssGRXfrFl3S4nNwKPEVPLD+yYn42vahS3H1dlkTroQP -oMiaXW6y75NomNwopr0APE4ImEnnR+Uoa7Mu1Rp1/IdJaC68lTH3i2km7dnEGr5N -y/hP4Xd3heLp1DnrYFa+XmdBZ3l8ozGGFgbh9VOzjNiPJVhhUSixb40jqolE+PIC -VX+ATzdjR5mUUvOC9Ew1H+Zs6bFCo/HmWjVYVHz1SgIgyQDPaBACKzP8CVtjXqmD -LzFOrGIYHS3zmcZphEpe9BcWZBV/aROyTF6fFwIDAQABAoIBAQCfw0GIAM+AliMj -WmOKo9wYwfoJUl8awAZvFCyH5ik96d/xRXL3h6q3xCZpfarMn8tDvMuK4IIvdkwI -UGnwckQYHGPQmG84zPbypeQ17h7iPCgTIE7WXxnj0HozzOFQTSgd+58fph4kp2J8 -A8FtBbSk08e02p2hU2ec5a1pKpn0LuYYIrIeyjwNkSYZ1a/Mkw90Py2XMygzmTcK -OUCGWPIXL/u1kSBeRX5FbvtUhdH/gBYJtbusSEcwjkNMRigFEyNSRE+Cd/VmETKl -xcr8E9g8WC+ZU6Ig4Eo6oC3XdKdM+vtxGtO9pUMLpJKt9zlxqM5WgFiZ0iUlSlb/ -roNLvQABAoGBAO+bUvf26Fmf8Z2V3MV45cJ4KFo7lm+M2qBGoioqLV208NackQIg -HocG3DhKjqw6sPSVJw8bf6KDGzk2dRY2u3FKI1gFCGeV6SLk9qz/sch/LGCxFHSw -lX9jUPel+OZ0LmYTl9xQKDCgmLvCVo4IBEcNWPxe3CadP1xmvpWIVnABAoGBAO3k -2R5AZRdQK/CGY6PHPFCWOS6ef/103/T+T7bcSyRZSWmrT1uirc67ova65P8d3ktI -0Dvyo7Dj8muZaNijQd24k9F7r9AHtCEwWGvzechc7yH1rVOo6Y23V0DrTbs/GqbR -312+lXBa1gACo0SYdAB/ZjJyJ93K7uUF9fpkCo8XAoGBAIkoJX9R9EFRoFJvtdfI -U+VVOOwmDgA+5es3Y561VBC/Adon94366t6qW6dRbohCdIcdViV8vTw+xneip7WW -kQfRw5egEeaR1smlvVrcZ115BuM2mpoNdxZbuL56YJcyzFicQKLZs5faZnOcVEWr -ax9tEZItjuH/w4RWQCSCzdABAoGAEjUpyP70vcwNEOO4TJi7LQ/SYJcRBL0lRwMP -5tcFiUqsK8JI2KKi2ufRmUDEtiH7GZgBGBWCIc/Qhhu/wpT8PZQa/DWTR0DPsJqa -qeiAsa0rQFYlZfnPpmEZ9IYN9P7nc00s42fq2CabqnSJOn7QohkeIU5LbtZRYoYK -RZfSlxECgYEA11ex68ZXhRlqFUG/710vsSTSGTQmbV6E8q+G0ToawyWH/cmIBHNs -JHuts7hogTE+HdZKoN4JR+z5IbJqA7voaRd2EAUKB5I/kHydUp+yGa7365ioRKy6 -ieqzg/NFZIslYZzxAFlhMBt/lNOrpMe24Wk0PV5VHe4TuO6l8FlSN3U= ------END RSA PRIVATE KEY----- diff --git a/components/compass-runtime-agent/internal/testutil/testdata/cert.chain.pem b/components/compass-runtime-agent/internal/testutil/testdata/cert.chain.pem deleted file mode 100644 index 40d162f725ed..000000000000 --- a/components/compass-runtime-agent/internal/testutil/testdata/cert.chain.pem +++ /dev/null @@ -1,34 +0,0 @@ ------BEGIN CERTIFICATE----- -MIICpjCCAY4CCQDR/7hichr/MTANBgkqhkiG9w0BAQUFADAUMRIwEAYDVQQDDAls -b2NhbGhvc3QwIBcNMTkwOTE3MDc1MzQ0WhgPMjExOTA4MjQwNzUzNDRaMBQxEjAQ -BgNVBAMMCWxvY2FsaG9zdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB -AOEkg9Cmxg6VTDaNuHYiX1YA6pqBZ5lJvj96GHb95/fD35Vn/0PhnbspGUX9dEEi -ryl5HhHPlPCMMTqojp4roYWyg67PEq40CxPVnEJPRQWA34gwNgxl7G9PSPkZObs8 -nHP9e7rvtuM9z2O5vwYXejamb+Jf9cNK+pKMmw5LEJ/7VPcS2bn1MszWw/ehgh8g -GyizObAZBF8Dxsqdk7+O8FFKLplXmQ8fK3XkYuJwpcFOyByUcCJfsrFYrL+vlBuo -EJHSzr1ymCC1S8DFpOusacD5ErQV8jpDsrI3Fj9gYaiBCWB5H5pVsi4ggdZTmOm+ -SQ66TuPsBllR+HTMgPvIt2cCAwEAATANBgkqhkiG9w0BAQUFAAOCAQEAXtHXc8Pm -WeCrrHBK1mPhWLX/uyP9DjqbJhWIjTptk4VNil/zZNtA6i8IeLU3Klv2H3al/n9K -Ec5Jxefn9o9cayPHZWFblaW08jrwuI2Amg7npsSCJYLe6kQBThu/2A1a4rY7QnYq -dMm5HJPW6/eLnQiNdYBvzE69bvRm0I/DbKi+VG2NjlVHyS/jU1McY+8R04+go8vn -Vw0HywTa4Lv3h8p2Mtb1OASoWcnZ2wEmKkcz7QjqFkjaopYE2x9TNSuVv2xlKCu0 -CFqHNf72i7gzfo/gsJQrIa9o0ZrPLCXhpHwNpt4sIq4cpHJZTxyYAav/1MkPugcy -w2DtHY45UyF0Zg== ------END CERTIFICATE----- ------BEGIN CERTIFICATE----- -MIICpjCCAY4CCQCl/E7ViyiX5TANBgkqhkiG9w0BAQsFADAUMRIwEAYDVQQDDAls -b2NhbGhvc3QwIBcNMTkwOTE3MDc1MzQ0WhgPMzAxOTAxMTgwNzUzNDRaMBQxEjAQ -BgNVBAMMCWxvY2FsaG9zdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB -AN6o/VxuOl4agAITuR/VWwF4ZMEXTYHeNb0TDU48BWwzYUTt0XhDFSnN0WLiwZol -PI6L+RLLBkV36xZd0uJzcCjxFTyw/smJ+Nr2oUtx9XZZE66ED6DIml1usu+TaJjc -KKa9ADxOCJhJ50flKGuzLtUadfyHSWguvJUx94tpJu3ZxBq+Tcv4T+F3d4Xi6dQ5 -62BWvl5nQWd5fKMxhhYG4fVTs4zYjyVYYVEosW+NI6qJRPjyAlV/gE83Y0eZlFLz -gvRMNR/mbOmxQqPx5lo1WFR89UoCIMkAz2gQAisz/AlbY16pgy8xTqxiGB0t85nG -aYRKXvQXFmQVf2kTskxenxcCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEADwIQDFeb -4EZDWTTklAi1DseNq/ha0nSPPaBMXHkFEtaNRv2K78dHZisbZj0Ff+Kt2kDFMXnW -ecy4CTRgynHc9O1eJL9iXrFdTRFD07tdp8NmfLjC60n6JxZuaTcVMLILp/DXJbbK -3AQ8XcqDNzXjAuGTt63Hen+C+9MrLaY+PhvHL9ijg74ojTO7KCUHJljDRAFTmCDR -l15t6u5zw/MYxZmCgrlpw/JHZ8JXBGLIQUBAqsDTGnqBw6DnPFDLMFMFb5YSHI69 -1aImBzwNIx7A36CUPCKxFiUIt1lmDgeZppuhxy8eGvhQdqDLtp6q8/qhk9KP0x7C -B6TwdKYHofTOuQ== ------END CERTIFICATE----- diff --git a/components/compass-runtime-agent/internal/testutil/testdata/client.crt.pem b/components/compass-runtime-agent/internal/testutil/testdata/client.crt.pem deleted file mode 100644 index c024e246cb51..000000000000 --- a/components/compass-runtime-agent/internal/testutil/testdata/client.crt.pem +++ /dev/null @@ -1,17 +0,0 @@ ------BEGIN CERTIFICATE----- -MIICpjCCAY4CCQDR/7hichr/MTANBgkqhkiG9w0BAQUFADAUMRIwEAYDVQQDDAls -b2NhbGhvc3QwIBcNMTkwOTE3MDc1MzQ0WhgPMjExOTA4MjQwNzUzNDRaMBQxEjAQ -BgNVBAMMCWxvY2FsaG9zdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB -AOEkg9Cmxg6VTDaNuHYiX1YA6pqBZ5lJvj96GHb95/fD35Vn/0PhnbspGUX9dEEi -ryl5HhHPlPCMMTqojp4roYWyg67PEq40CxPVnEJPRQWA34gwNgxl7G9PSPkZObs8 -nHP9e7rvtuM9z2O5vwYXejamb+Jf9cNK+pKMmw5LEJ/7VPcS2bn1MszWw/ehgh8g -GyizObAZBF8Dxsqdk7+O8FFKLplXmQ8fK3XkYuJwpcFOyByUcCJfsrFYrL+vlBuo -EJHSzr1ymCC1S8DFpOusacD5ErQV8jpDsrI3Fj9gYaiBCWB5H5pVsi4ggdZTmOm+ -SQ66TuPsBllR+HTMgPvIt2cCAwEAATANBgkqhkiG9w0BAQUFAAOCAQEAXtHXc8Pm -WeCrrHBK1mPhWLX/uyP9DjqbJhWIjTptk4VNil/zZNtA6i8IeLU3Klv2H3al/n9K -Ec5Jxefn9o9cayPHZWFblaW08jrwuI2Amg7npsSCJYLe6kQBThu/2A1a4rY7QnYq -dMm5HJPW6/eLnQiNdYBvzE69bvRm0I/DbKi+VG2NjlVHyS/jU1McY+8R04+go8vn -Vw0HywTa4Lv3h8p2Mtb1OASoWcnZ2wEmKkcz7QjqFkjaopYE2x9TNSuVv2xlKCu0 -CFqHNf72i7gzfo/gsJQrIa9o0ZrPLCXhpHwNpt4sIq4cpHJZTxyYAav/1MkPugcy -w2DtHY45UyF0Zg== ------END CERTIFICATE----- diff --git a/components/compass-runtime-agent/internal/testutil/testdata/client.csr.pem b/components/compass-runtime-agent/internal/testutil/testdata/client.csr.pem deleted file mode 100644 index 3bac977eddee..000000000000 --- a/components/compass-runtime-agent/internal/testutil/testdata/client.csr.pem +++ /dev/null @@ -1,15 +0,0 @@ ------BEGIN CERTIFICATE REQUEST----- -MIICWTCCAUECAQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0B -AQEFAAOCAQ8AMIIBCgKCAQEA4SSD0KbGDpVMNo24diJfVgDqmoFnmUm+P3oYdv3n -98PflWf/Q+GduykZRf10QSKvKXkeEc+U8IwxOqiOniuhhbKDrs8SrjQLE9WcQk9F -BYDfiDA2DGXsb09I+Rk5uzycc/17uu+24z3PY7m/Bhd6NqZv4l/1w0r6koybDksQ -n/tU9xLZufUyzNbD96GCHyAbKLM5sBkEXwPGyp2Tv47wUUoumVeZDx8rdeRi4nCl -wU7IHJRwIl+ysVisv6+UG6gQkdLOvXKYILVLwMWk66xpwPkStBXyOkOysjcWP2Bh -qIEJYHkfmlWyLiCB1lOY6b5JDrpO4+wGWVH4dMyA+8i3ZwIDAQABoAAwDQYJKoZI -hvcNAQELBQADggEBAAxnMejr+3WQ+fGsKvuqR7n9Yyx0kFne81l7CWrJWnnP8NIU -Bkb/i4L8jW8YIm+s7TaIC6MF8HNkB1TXRrJzCbJ8DJbPefGqU77dBvRDPKlMhruJ -d8zVEvZ9YSYOd1HiZwF13KS6u4pDm3pe58/Bbgi85eEQbPvPiLuuaoMk80IKYko/ -vSwFQnp2c+d59hqY2avoMHuo8Cr8lvZwLVAHC/jxtZvvlH0o2acD+KTmlrM9Si14 -zenGjwTFQ5tbl6LrZ+MojikMyn1VCCeduGea9FIUFjxncPfnmin/FB9PDifyUS/E -lvtiskOGJGHliaYLTOZPehNSaa2wTUOSz3A9T08= ------END CERTIFICATE REQUEST----- diff --git a/components/compass-runtime-agent/internal/testutil/testdata/client.key.pem b/components/compass-runtime-agent/internal/testutil/testdata/client.key.pem deleted file mode 100644 index a25d8889d6a7..000000000000 --- a/components/compass-runtime-agent/internal/testutil/testdata/client.key.pem +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEpAIBAAKCAQEA4SSD0KbGDpVMNo24diJfVgDqmoFnmUm+P3oYdv3n98PflWf/ -Q+GduykZRf10QSKvKXkeEc+U8IwxOqiOniuhhbKDrs8SrjQLE9WcQk9FBYDfiDA2 -DGXsb09I+Rk5uzycc/17uu+24z3PY7m/Bhd6NqZv4l/1w0r6koybDksQn/tU9xLZ -ufUyzNbD96GCHyAbKLM5sBkEXwPGyp2Tv47wUUoumVeZDx8rdeRi4nClwU7IHJRw -Il+ysVisv6+UG6gQkdLOvXKYILVLwMWk66xpwPkStBXyOkOysjcWP2BhqIEJYHkf -mlWyLiCB1lOY6b5JDrpO4+wGWVH4dMyA+8i3ZwIDAQABAoIBADl0zSLxfLf6B/Ig -JsQXL4dOQpDdl2e6NxASA65SS+GiHiwN10omiM9bxLRk40dAJ72IyFC5TgQ5ctLK -c2MQNW9eSFbTR6wnYfBU4kTV4AJwihtCWni9hiI99JyFgIM1C6RaOzpQtLa3bna/ -z20pjqnlvcXiwWBugRXnRibWp058JfxvY8t31AnAOto0b7cus+LR7IzG3Qq+7Rt6 -rI/pjDEYeNTThneQ17ww/vvzrVtuNmSMqyBBJqBSPl2q94PtosuaCrG9GZMp6VOk -EabMKNUi1VWchOF+7/oEPqJ+7gHN4EXxnti6B6oYhqHFJeOtBs7TsClSzHrCmNiQ -vE38UkkCgYEA8/bASkNNgDOFKHz2TF8g+XVZJ8Pn150bfwOuO5JqLnxaZVY3hQ7x -5fXXX3DJw5SG6GJlSjg7cQrxPl9llr1n6XS/tLCJRL5ZT2xdXN9T+iATy9sTemHv -pJpLwOu5ZqOeFGh/AlpzpyG/lBvNiGWTL/MVz7zUerN+UEe3zpWF4GUCgYEA7EAN -folpRTHrdVQzBm2oLL5r2bTqDHOZo2E+DKknkmr9n9K5iS9wN5n3/rr5kGgF8bdK -Um1IaXxEdfREN2V8/BlPzXHzyl9SOluz1FlW9P0nDnuNA68v/GJ1S6RLDsikaeWv -/QodBzRbKYqmB5CRXkPAzGdw2KFq2DSGs32QLdsCgYB6RTsOfTjEfg3Iwwh2Ml9G -Z2ftpCP4TkdPmzqhpLoO3kg37cQZrenSxSnSLacRnMkYgugdEJ3KBB/wkMNLj1Yb -DWZfWvMRPw1n3vnT6CIghB8n1n6moZsHtkUtRXdAV9SMierN9SNtql5oDp8uMypX -p89QtGURshAmkCsxIINeeQKBgQDcOvWZYLUOePOa40vRkUV1uGlHgDuyMc0mHY8/ -NCycdDpL0597gApm+pPRFTFx6VapNokE/7TCCMK1BmjVDzmMtHfM944gt+0qU7P2 -nvXN2XOgL5KLvbLI3mujgNsrQ+TohuIgy122Cpt0xTfy01SAAD7pDQCIISk9tPFg -vws5gwKBgQCXMcEZFFrB9IMZx6N2M2bEuAuJ0D8AgWxgJvAXVzWRTKQI66TE4oiG -Aq1sCvZfejkZ/zbQ+4k0m/nrLpbliWnbcH/PW3pq0AHS5htAY/8gxHzpfvw2uVsQ -2llTtES2IkcTyMc05YcnrBPK4PUu5sDYjRJ6pXUHZoJZkW5neZBYhA== ------END RSA PRIVATE KEY----- diff --git a/components/compass-runtime-agent/internal/testutil/testdata/generate.sh b/components/compass-runtime-agent/internal/testutil/testdata/generate.sh deleted file mode 100755 index 42f27cc94dff..000000000000 --- a/components/compass-runtime-agent/internal/testutil/testdata/generate.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/usr/bin/env bash - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" - -openssl genrsa -out ${DIR}/ca.key.pem 2048 -openssl req -new -sha256 -key ${DIR}/ca.key.pem -out ${DIR}/ca.csr.pem -subj "/CN=localhost" -openssl req -x509 -sha256 -days 365000 -key ${DIR}/ca.key.pem -in ${DIR}/ca.csr.pem -out ${DIR}/ca.crt.pem - -openssl genrsa -out ${DIR}/client.key.pem 2048 -openssl req -new -key ${DIR}/client.key.pem -nodes -days 365000 -out ${DIR}/client.csr.pem -subj "/CN=localhost" -openssl x509 -req -days 36500 -in ${DIR}/client.csr.pem -CA ${DIR}/ca.crt.pem -CAkey ${DIR}/ca.key.pem -out ${DIR}/client.crt.pem -CAcreateserial - -cat ${DIR}/client.crt.pem ${DIR}/ca.crt.pem > cert.chain.pem \ No newline at end of file diff --git a/components/compass-runtime-agent/internal/testutil/testutil.go b/components/compass-runtime-agent/internal/testutil/testutil.go deleted file mode 100644 index eba70042d9b7..000000000000 --- a/components/compass-runtime-agent/internal/testutil/testutil.go +++ /dev/null @@ -1,44 +0,0 @@ -package testutil - -import ( - "os" - "path" - - "github.com/pkg/errors" -) - -type CertsTestData struct { - CertificateChain []byte - CACertificate []byte - ClientCertificate []byte - ClientKey []byte -} - -func LoadCertsTestData(testDataPath string) (CertsTestData, error) { - crtChain, err := os.ReadFile(path.Join(testDataPath, "cert.chain.pem")) - if err != nil { - return CertsTestData{}, errors.Errorf("Failed to read certificate chain testdata") - } - - caCRT, err := os.ReadFile(path.Join(testDataPath, "ca.crt.pem")) - if err != nil { - return CertsTestData{}, errors.Errorf("Failed to read CA certificate testdata") - } - - clientCRT, err := os.ReadFile(path.Join(testDataPath, "client.crt.pem")) - if err != nil { - return CertsTestData{}, errors.Errorf("Failed to read client certificate testdata") - } - - clientKey, err := os.ReadFile(path.Join(testDataPath, "client.key.pem")) - if err != nil { - return CertsTestData{}, errors.Errorf("Failed to read client key testdata") - } - - return CertsTestData{ - CertificateChain: crtChain, - CACertificate: caCRT, - ClientCertificate: clientCRT, - ClientKey: clientKey, - }, nil -} diff --git a/components/compass-runtime-agent/pkg/apis/compass/v1alpha1/doc.go b/components/compass-runtime-agent/pkg/apis/compass/v1alpha1/doc.go deleted file mode 100644 index 0412371ecb0c..000000000000 --- a/components/compass-runtime-agent/pkg/apis/compass/v1alpha1/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// +k8s:deepcopy-gen=package,register - -// +groupName=compass.kyma-project.io -package v1alpha1 diff --git a/components/compass-runtime-agent/pkg/apis/compass/v1alpha1/register.go b/components/compass-runtime-agent/pkg/apis/compass/v1alpha1/register.go deleted file mode 100644 index d242bbb6f64e..000000000000 --- a/components/compass-runtime-agent/pkg/apis/compass/v1alpha1/register.go +++ /dev/null @@ -1,39 +0,0 @@ -package v1alpha1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -// SchemeGroupVersion is group version used to register these objects -var SchemeGroupVersion = schema.GroupVersion{Group: "compass.kyma-project.io", Version: "v1alpha1"} - -// Resource takes an unqualified resource and returns a Group qualified GroupResource -func Resource(resource string) schema.GroupResource { - return SchemeGroupVersion.WithResource(resource).GroupResource() -} - -var ( - // localSchemeBuilder and AddToScheme will stay in k8s.io/kubernetes. - SchemeBuilder runtime.SchemeBuilder - localSchemeBuilder = &SchemeBuilder - AddToScheme = localSchemeBuilder.AddToScheme -) - -func init() { - // We only register manually written functions here. The registration of the - // generated functions takes place in the generated files. The separation - // makes the code compile even when the generated files are missing. - localSchemeBuilder.Register(addKnownTypes) -} - -// Adds the list of known types to api.Scheme. -func addKnownTypes(scheme *runtime.Scheme) error { - scheme.AddKnownTypes(SchemeGroupVersion, - &CompassConnection{}, - &CompassConnectionList{}, - ) - metav1.AddToGroupVersion(scheme, SchemeGroupVersion) - return nil -} diff --git a/components/compass-runtime-agent/pkg/apis/compass/v1alpha1/types.go b/components/compass-runtime-agent/pkg/apis/compass/v1alpha1/types.go deleted file mode 100644 index bed587c039cb..000000000000 --- a/components/compass-runtime-agent/pkg/apis/compass/v1alpha1/types.go +++ /dev/null @@ -1,153 +0,0 @@ -package v1alpha1 - -import ( - "crypto/x509" - "time" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// +genclient -// +genclient:nonNamespaced -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +kubebuilder:resource:scope=Cluster -type CompassConnection struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - Spec CompassConnectionSpec `json:"spec"` - Status CompassConnectionStatus `json:"status,omitempty"` -} - -type CompassConnectionSpec struct { - ManagementInfo ManagementInfo `json:"managementInfo"` - ResyncNow bool `json:"resyncNow,omitempty"` - RefreshCredentialsNow bool `json:"refreshCredentialsNow,omitempty"` -} - -type ManagementInfo struct { - DirectorURL string `json:"directorUrl"` - ConnectorURL string `json:"connectorUrl"` -} - -type CompassConnectionStatus struct { - State ConnectionState `json:"connectionState"` - ConnectionStatus *ConnectionStatus `json:"connectionStatus"` - // +optional - // +nullable - SynchronizationStatus *SynchronizationStatus `json:"synchronizationStatus"` -} - -func (in *CompassConnection) SetCertificateStatus(acquired metav1.Time, certificate *x509.Certificate) { - if in.Status.ConnectionStatus == nil { - in.Status.ConnectionStatus = &ConnectionStatus{} - } - - in.Status.ConnectionStatus.CertificateStatus = CertificateStatus{ - Acquired: acquired, - NotBefore: metav1.NewTime(certificate.NotBefore), - NotAfter: metav1.NewTime(certificate.NotAfter), - } -} - -func (in CompassConnection) Failed() bool { - return in.Status.State == ConnectionFailed -} - -func (in CompassConnection) ShouldRenewCertificate(certValidityRenewalThreshold float64, minimalSyncTime time.Duration) bool { - if in.Spec.RefreshCredentialsNow { - return true - } - - notBefore := in.Status.ConnectionStatus.CertificateStatus.NotBefore.Unix() - notAfter := in.Status.ConnectionStatus.CertificateStatus.NotAfter.Unix() - - certValidity := notAfter - notBefore - - timeLeft := float64(notAfter - time.Now().Unix()) - - return timeLeft < float64(certValidity)*certValidityRenewalThreshold || timeLeft < 2*minimalSyncTime.Seconds() -} - -func (s CompassConnectionStatus) String() string { - // TODO: return more detailed status - return string(s.State) -} - -type ConnectionProcessStatus struct { - ConnectionEstablished bool -} - -type ConnectionState string - -// TODO - consider reworking those states to some pipeline info - -const ( - // Connection was established successfully - Connected ConnectionState = "Connected" - // Connection process failed during authentication to Compass - ConnectionFailed ConnectionState = "ConnectionFailed" - // Connection was established but the error occurred during connection maintenance - ConnectionMaintenanceFailed ConnectionState = "ConnectionMaintenanceFailed" - // Connection was established but configuration fetching failed - SynchronizationFailed ConnectionState = "SynchronizationFailed" - // Connection was established but applying configuration failed - ResourceApplicationFailed ConnectionState = "ResourceApplicationFailed" - // Resources were applied successfully but Runtime metadata update failed - MetadataUpdateFailed ConnectionState = "MetadataUpdateFailed" - // Connection was successful and configuration has been applied - Synchronized ConnectionState = "Synchronized" -) - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -type CompassConnectionList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata"` - - Items []CompassConnection `json:"items"` -} - -// ConnectionStatus represents status of a connection to Compass -type ConnectionStatus struct { - // +optional - // +nullable - Established metav1.Time `json:"established"` - // +optional - // +nullable - Renewed metav1.Time `json:"renewed,omitempty"` - // +optional - // +nullable - LastSync metav1.Time `json:"lastSync"` - // +optional - // +nullable - LastSuccess metav1.Time `json:"lastSuccess"` - CertificateStatus CertificateStatus `json:"certificateStatus"` - Error string `json:"error,omitempty"` -} - -// CertificateStatus represents the status of the certificate -type CertificateStatus struct { - // +optional - // +nullable - Acquired metav1.Time `json:"acquired"` - // +optional - // +nullable - NotBefore metav1.Time `json:"notBefore"` - // +optional - // +nullable - NotAfter metav1.Time `json:"notAfter"` -} - -// SynchronizationStatus represent the status of Applications synchronization with Compass -type SynchronizationStatus struct { - // +optional - // +nullable - LastAttempt metav1.Time `json:"lastAttempt"` - // +optional - // +nullable - LastSuccessfulFetch metav1.Time `json:"lastSuccessfulFetch"` - // +optional - // +nullable - LastSuccessfulApplication metav1.Time `json:"lastSuccessfulApplication"` - Error string `json:"error,omitempty"` -} diff --git a/components/compass-runtime-agent/pkg/apis/compass/v1alpha1/types_test.go b/components/compass-runtime-agent/pkg/apis/compass/v1alpha1/types_test.go deleted file mode 100644 index 7a95712cddd2..000000000000 --- a/components/compass-runtime-agent/pkg/apis/compass/v1alpha1/types_test.go +++ /dev/null @@ -1,84 +0,0 @@ -package v1alpha1 - -import ( - "testing" - "time" - - "github.com/stretchr/testify/assert" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func TestCompassConnection_ShouldRenewCertificate(t *testing.T) { - - testCases := []struct { - renewNow bool - certStatus *CertificateStatus - minimalSyncTime time.Duration - certValidityRenewalThreshold float64 - shouldRenew bool - }{ - { - certStatus: &CertificateStatus{ - NotBefore: metav1.Now(), - NotAfter: metav1.NewTime(time.Now().Add(2000 * time.Hour)), - }, - minimalSyncTime: 10 * time.Minute, - certValidityRenewalThreshold: 0.3, - shouldRenew: false, - }, - { - certStatus: &CertificateStatus{ - NotBefore: metav1.Now(), - NotAfter: metav1.Now(), - }, - minimalSyncTime: 10 * time.Minute, - certValidityRenewalThreshold: 0.3, - shouldRenew: true, - }, - { - certStatus: &CertificateStatus{ - NotBefore: metav1.NewTime(time.Date(1970, 1, 1, 0, 0, 0, 0, time.Local)), - NotAfter: metav1.NewTime(time.Now().Add(3 * time.Hour)), - }, - minimalSyncTime: 10 * time.Minute, - shouldRenew: true, - certValidityRenewalThreshold: 0.3, - }, - { - certStatus: &CertificateStatus{ - NotBefore: metav1.NewTime(time.Now()), - NotAfter: metav1.NewTime(time.Now().Add(30 * time.Minute)), - }, - minimalSyncTime: 20 * time.Minute, - shouldRenew: true, - certValidityRenewalThreshold: 0.3, - }, - { - renewNow: true, - certStatus: &CertificateStatus{ - NotBefore: metav1.Now(), - NotAfter: metav1.NewTime(time.Now().Add(2000 * time.Hour)), - }, - minimalSyncTime: 10 * time.Minute, - shouldRenew: true, - certValidityRenewalThreshold: 0.3, - }, - } - - for _, testCase := range testCases { - connection := CompassConnection{ - ObjectMeta: metav1.ObjectMeta{Name: "test"}, - Spec: CompassConnectionSpec{RefreshCredentialsNow: testCase.renewNow}, - Status: CompassConnectionStatus{ - ConnectionStatus: &ConnectionStatus{ - CertificateStatus: *testCase.certStatus, - }, - }, - } - - willRenew := connection.ShouldRenewCertificate(testCase.certValidityRenewalThreshold, testCase.minimalSyncTime) - - assert.Equal(t, testCase.shouldRenew, willRenew) - } - -} diff --git a/components/compass-runtime-agent/pkg/apis/compass/v1alpha1/zz_generated.deepcopy.go b/components/compass-runtime-agent/pkg/apis/compass/v1alpha1/zz_generated.deepcopy.go deleted file mode 100644 index fe1b9dcf096a..000000000000 --- a/components/compass-runtime-agent/pkg/apis/compass/v1alpha1/zz_generated.deepcopy.go +++ /dev/null @@ -1,203 +0,0 @@ -//go:build !ignore_autogenerated -// +build !ignore_autogenerated - -// Code generated by deepcopy-gen. DO NOT EDIT. - -package v1alpha1 - -import runtime "k8s.io/apimachinery/pkg/runtime" - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CertificateStatus) DeepCopyInto(out *CertificateStatus) { - *out = *in - in.Acquired.DeepCopyInto(&out.Acquired) - in.NotBefore.DeepCopyInto(&out.NotBefore) - in.NotAfter.DeepCopyInto(&out.NotAfter) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CertificateStatus. -func (in *CertificateStatus) DeepCopy() *CertificateStatus { - if in == nil { - return nil - } - out := new(CertificateStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CompassConnection) DeepCopyInto(out *CompassConnection) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - out.Spec = in.Spec - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CompassConnection. -func (in *CompassConnection) DeepCopy() *CompassConnection { - if in == nil { - return nil - } - out := new(CompassConnection) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *CompassConnection) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CompassConnectionList) DeepCopyInto(out *CompassConnectionList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]CompassConnection, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CompassConnectionList. -func (in *CompassConnectionList) DeepCopy() *CompassConnectionList { - if in == nil { - return nil - } - out := new(CompassConnectionList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *CompassConnectionList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CompassConnectionSpec) DeepCopyInto(out *CompassConnectionSpec) { - *out = *in - out.ManagementInfo = in.ManagementInfo - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CompassConnectionSpec. -func (in *CompassConnectionSpec) DeepCopy() *CompassConnectionSpec { - if in == nil { - return nil - } - out := new(CompassConnectionSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CompassConnectionStatus) DeepCopyInto(out *CompassConnectionStatus) { - *out = *in - if in.ConnectionStatus != nil { - in, out := &in.ConnectionStatus, &out.ConnectionStatus - *out = new(ConnectionStatus) - (*in).DeepCopyInto(*out) - } - if in.SynchronizationStatus != nil { - in, out := &in.SynchronizationStatus, &out.SynchronizationStatus - *out = new(SynchronizationStatus) - (*in).DeepCopyInto(*out) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CompassConnectionStatus. -func (in *CompassConnectionStatus) DeepCopy() *CompassConnectionStatus { - if in == nil { - return nil - } - out := new(CompassConnectionStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ConnectionProcessStatus) DeepCopyInto(out *ConnectionProcessStatus) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConnectionProcessStatus. -func (in *ConnectionProcessStatus) DeepCopy() *ConnectionProcessStatus { - if in == nil { - return nil - } - out := new(ConnectionProcessStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ConnectionStatus) DeepCopyInto(out *ConnectionStatus) { - *out = *in - in.Established.DeepCopyInto(&out.Established) - in.Renewed.DeepCopyInto(&out.Renewed) - in.LastSync.DeepCopyInto(&out.LastSync) - in.LastSuccess.DeepCopyInto(&out.LastSuccess) - in.CertificateStatus.DeepCopyInto(&out.CertificateStatus) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConnectionStatus. -func (in *ConnectionStatus) DeepCopy() *ConnectionStatus { - if in == nil { - return nil - } - out := new(ConnectionStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ManagementInfo) DeepCopyInto(out *ManagementInfo) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ManagementInfo. -func (in *ManagementInfo) DeepCopy() *ManagementInfo { - if in == nil { - return nil - } - out := new(ManagementInfo) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *SynchronizationStatus) DeepCopyInto(out *SynchronizationStatus) { - *out = *in - in.LastAttempt.DeepCopyInto(&out.LastAttempt) - in.LastSuccessfulFetch.DeepCopyInto(&out.LastSuccessfulFetch) - in.LastSuccessfulApplication.DeepCopyInto(&out.LastSuccessfulApplication) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SynchronizationStatus. -func (in *SynchronizationStatus) DeepCopy() *SynchronizationStatus { - if in == nil { - return nil - } - out := new(SynchronizationStatus) - in.DeepCopyInto(out) - return out -} diff --git a/components/compass-runtime-agent/pkg/client/clientset/versioned/clientset.go b/components/compass-runtime-agent/pkg/client/clientset/versioned/clientset.go deleted file mode 100644 index d2a977bf069e..000000000000 --- a/components/compass-runtime-agent/pkg/client/clientset/versioned/clientset.go +++ /dev/null @@ -1,81 +0,0 @@ -// Code generated by client-gen. DO NOT EDIT. - -package versioned - -import ( - "fmt" - - compassv1alpha1 "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/client/clientset/versioned/typed/compass/v1alpha1" - discovery "k8s.io/client-go/discovery" - rest "k8s.io/client-go/rest" - flowcontrol "k8s.io/client-go/util/flowcontrol" -) - -type Interface interface { - Discovery() discovery.DiscoveryInterface - CompassV1alpha1() compassv1alpha1.CompassV1alpha1Interface -} - -// Clientset contains the clients for groups. Each group has exactly one -// version included in a Clientset. -type Clientset struct { - *discovery.DiscoveryClient - compassV1alpha1 *compassv1alpha1.CompassV1alpha1Client -} - -// CompassV1alpha1 retrieves the CompassV1alpha1Client -func (c *Clientset) CompassV1alpha1() compassv1alpha1.CompassV1alpha1Interface { - return c.compassV1alpha1 -} - -// Discovery retrieves the DiscoveryClient -func (c *Clientset) Discovery() discovery.DiscoveryInterface { - if c == nil { - return nil - } - return c.DiscoveryClient -} - -// NewForConfig creates a new Clientset for the given config. -// If config's RateLimiter is not set and QPS and Burst are acceptable, -// NewForConfig will generate a rate-limiter in configShallowCopy. -func NewForConfig(c *rest.Config) (*Clientset, error) { - configShallowCopy := *c - if configShallowCopy.RateLimiter == nil && configShallowCopy.QPS > 0 { - if configShallowCopy.Burst <= 0 { - return nil, fmt.Errorf("burst is required to be greater than 0 when RateLimiter is not set and QPS is set to greater than 0") - } - configShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst) - } - var cs Clientset - var err error - cs.compassV1alpha1, err = compassv1alpha1.NewForConfig(&configShallowCopy) - if err != nil { - return nil, err - } - - cs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfig(&configShallowCopy) - if err != nil { - return nil, err - } - return &cs, nil -} - -// NewForConfigOrDie creates a new Clientset for the given config and -// panics if there is an error in the config. -func NewForConfigOrDie(c *rest.Config) *Clientset { - var cs Clientset - cs.compassV1alpha1 = compassv1alpha1.NewForConfigOrDie(c) - - cs.DiscoveryClient = discovery.NewDiscoveryClientForConfigOrDie(c) - return &cs -} - -// New creates a new Clientset for the given RESTClient. -func New(c rest.Interface) *Clientset { - var cs Clientset - cs.compassV1alpha1 = compassv1alpha1.New(c) - - cs.DiscoveryClient = discovery.NewDiscoveryClient(c) - return &cs -} diff --git a/components/compass-runtime-agent/pkg/client/clientset/versioned/doc.go b/components/compass-runtime-agent/pkg/client/clientset/versioned/doc.go deleted file mode 100644 index 0e0c2a8900e2..000000000000 --- a/components/compass-runtime-agent/pkg/client/clientset/versioned/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// Code generated by client-gen. DO NOT EDIT. - -// This package has the automatically generated clientset. -package versioned diff --git a/components/compass-runtime-agent/pkg/client/clientset/versioned/fake/clientset_generated.go b/components/compass-runtime-agent/pkg/client/clientset/versioned/fake/clientset_generated.go deleted file mode 100644 index 214320c05986..000000000000 --- a/components/compass-runtime-agent/pkg/client/clientset/versioned/fake/clientset_generated.go +++ /dev/null @@ -1,66 +0,0 @@ -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - clientset "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/client/clientset/versioned" - compassv1alpha1 "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/client/clientset/versioned/typed/compass/v1alpha1" - fakecompassv1alpha1 "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/client/clientset/versioned/typed/compass/v1alpha1/fake" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/discovery" - fakediscovery "k8s.io/client-go/discovery/fake" - "k8s.io/client-go/testing" -) - -// NewSimpleClientset returns a clientset that will respond with the provided objects. -// It's backed by a very simple object tracker that processes creates, updates and deletions as-is, -// without applying any validations and/or defaults. It shouldn't be considered a replacement -// for a real clientset and is mostly useful in simple unit tests. -func NewSimpleClientset(objects ...runtime.Object) *Clientset { - o := testing.NewObjectTracker(scheme, codecs.UniversalDecoder()) - for _, obj := range objects { - if err := o.Add(obj); err != nil { - panic(err) - } - } - - cs := &Clientset{tracker: o} - cs.discovery = &fakediscovery.FakeDiscovery{Fake: &cs.Fake} - cs.AddReactor("*", "*", testing.ObjectReaction(o)) - cs.AddWatchReactor("*", func(action testing.Action) (handled bool, ret watch.Interface, err error) { - gvr := action.GetResource() - ns := action.GetNamespace() - watch, err := o.Watch(gvr, ns) - if err != nil { - return false, nil, err - } - return true, watch, nil - }) - - return cs -} - -// Clientset implements clientset.Interface. Meant to be embedded into a -// struct to get a default implementation. This makes faking out just the method -// you want to test easier. -type Clientset struct { - testing.Fake - discovery *fakediscovery.FakeDiscovery - tracker testing.ObjectTracker -} - -func (c *Clientset) Discovery() discovery.DiscoveryInterface { - return c.discovery -} - -func (c *Clientset) Tracker() testing.ObjectTracker { - return c.tracker -} - -var _ clientset.Interface = &Clientset{} - -// CompassV1alpha1 retrieves the CompassV1alpha1Client -func (c *Clientset) CompassV1alpha1() compassv1alpha1.CompassV1alpha1Interface { - return &fakecompassv1alpha1.FakeCompassV1alpha1{Fake: &c.Fake} -} diff --git a/components/compass-runtime-agent/pkg/client/clientset/versioned/fake/doc.go b/components/compass-runtime-agent/pkg/client/clientset/versioned/fake/doc.go deleted file mode 100644 index 3630ed1cd17d..000000000000 --- a/components/compass-runtime-agent/pkg/client/clientset/versioned/fake/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// Code generated by client-gen. DO NOT EDIT. - -// This package has the automatically generated fake clientset. -package fake diff --git a/components/compass-runtime-agent/pkg/client/clientset/versioned/fake/register.go b/components/compass-runtime-agent/pkg/client/clientset/versioned/fake/register.go deleted file mode 100644 index 38a8c711644b..000000000000 --- a/components/compass-runtime-agent/pkg/client/clientset/versioned/fake/register.go +++ /dev/null @@ -1,40 +0,0 @@ -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - compassv1alpha1 "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/apis/compass/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - schema "k8s.io/apimachinery/pkg/runtime/schema" - serializer "k8s.io/apimachinery/pkg/runtime/serializer" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" -) - -var scheme = runtime.NewScheme() -var codecs = serializer.NewCodecFactory(scheme) - -var localSchemeBuilder = runtime.SchemeBuilder{ - compassv1alpha1.AddToScheme, -} - -// AddToScheme adds all types of this clientset into the given scheme. This allows composition -// of clientsets, like in: -// -// import ( -// "k8s.io/client-go/kubernetes" -// clientsetscheme "k8s.io/client-go/kubernetes/scheme" -// aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme" -// ) -// -// kclientset, _ := kubernetes.NewForConfig(c) -// _ = aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme) -// -// After this, RawExtensions in Kubernetes types will serialize kube-aggregator types -// correctly. -var AddToScheme = localSchemeBuilder.AddToScheme - -func init() { - v1.AddToGroupVersion(scheme, schema.GroupVersion{Version: "v1"}) - utilruntime.Must(AddToScheme(scheme)) -} diff --git a/components/compass-runtime-agent/pkg/client/clientset/versioned/scheme/doc.go b/components/compass-runtime-agent/pkg/client/clientset/versioned/scheme/doc.go deleted file mode 100644 index 14db57a58f8d..000000000000 --- a/components/compass-runtime-agent/pkg/client/clientset/versioned/scheme/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// Code generated by client-gen. DO NOT EDIT. - -// This package contains the scheme of the automatically generated clientset. -package scheme diff --git a/components/compass-runtime-agent/pkg/client/clientset/versioned/scheme/register.go b/components/compass-runtime-agent/pkg/client/clientset/versioned/scheme/register.go deleted file mode 100644 index f2812c09e03e..000000000000 --- a/components/compass-runtime-agent/pkg/client/clientset/versioned/scheme/register.go +++ /dev/null @@ -1,40 +0,0 @@ -// Code generated by client-gen. DO NOT EDIT. - -package scheme - -import ( - compassv1alpha1 "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/apis/compass/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - schema "k8s.io/apimachinery/pkg/runtime/schema" - serializer "k8s.io/apimachinery/pkg/runtime/serializer" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" -) - -var Scheme = runtime.NewScheme() -var Codecs = serializer.NewCodecFactory(Scheme) -var ParameterCodec = runtime.NewParameterCodec(Scheme) -var localSchemeBuilder = runtime.SchemeBuilder{ - compassv1alpha1.AddToScheme, -} - -// AddToScheme adds all types of this clientset into the given scheme. This allows composition -// of clientsets, like in: -// -// import ( -// "k8s.io/client-go/kubernetes" -// clientsetscheme "k8s.io/client-go/kubernetes/scheme" -// aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme" -// ) -// -// kclientset, _ := kubernetes.NewForConfig(c) -// _ = aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme) -// -// After this, RawExtensions in Kubernetes types will serialize kube-aggregator types -// correctly. -var AddToScheme = localSchemeBuilder.AddToScheme - -func init() { - v1.AddToGroupVersion(Scheme, schema.GroupVersion{Version: "v1"}) - utilruntime.Must(AddToScheme(Scheme)) -} diff --git a/components/compass-runtime-agent/pkg/client/clientset/versioned/typed/compass/v1alpha1/compass_client.go b/components/compass-runtime-agent/pkg/client/clientset/versioned/typed/compass/v1alpha1/compass_client.go deleted file mode 100644 index 983b923d18b1..000000000000 --- a/components/compass-runtime-agent/pkg/client/clientset/versioned/typed/compass/v1alpha1/compass_client.go +++ /dev/null @@ -1,73 +0,0 @@ -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/apis/compass/v1alpha1" - "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/client/clientset/versioned/scheme" - rest "k8s.io/client-go/rest" -) - -type CompassV1alpha1Interface interface { - RESTClient() rest.Interface - CompassConnectionsGetter -} - -// CompassV1alpha1Client is used to interact with features provided by the compass.kyma-project.io group. -type CompassV1alpha1Client struct { - restClient rest.Interface -} - -func (c *CompassV1alpha1Client) CompassConnections() CompassConnectionInterface { - return newCompassConnections(c) -} - -// NewForConfig creates a new CompassV1alpha1Client for the given config. -func NewForConfig(c *rest.Config) (*CompassV1alpha1Client, error) { - config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } - client, err := rest.RESTClientFor(&config) - if err != nil { - return nil, err - } - return &CompassV1alpha1Client{client}, nil -} - -// NewForConfigOrDie creates a new CompassV1alpha1Client for the given config and -// panics if there is an error in the config. -func NewForConfigOrDie(c *rest.Config) *CompassV1alpha1Client { - client, err := NewForConfig(c) - if err != nil { - panic(err) - } - return client -} - -// New creates a new CompassV1alpha1Client for the given RESTClient. -func New(c rest.Interface) *CompassV1alpha1Client { - return &CompassV1alpha1Client{c} -} - -func setConfigDefaults(config *rest.Config) error { - gv := v1alpha1.SchemeGroupVersion - config.GroupVersion = &gv - config.APIPath = "/apis" - config.NegotiatedSerializer = scheme.Codecs.WithoutConversion() - - if config.UserAgent == "" { - config.UserAgent = rest.DefaultKubernetesUserAgent() - } - - return nil -} - -// RESTClient returns a RESTClient that is used to communicate -// with API server by this client implementation. -func (c *CompassV1alpha1Client) RESTClient() rest.Interface { - if c == nil { - return nil - } - return c.restClient -} diff --git a/components/compass-runtime-agent/pkg/client/clientset/versioned/typed/compass/v1alpha1/compassconnection.go b/components/compass-runtime-agent/pkg/client/clientset/versioned/typed/compass/v1alpha1/compassconnection.go deleted file mode 100644 index 10c10e57994e..000000000000 --- a/components/compass-runtime-agent/pkg/client/clientset/versioned/typed/compass/v1alpha1/compassconnection.go +++ /dev/null @@ -1,168 +0,0 @@ -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - "context" - "time" - - v1alpha1 "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/apis/compass/v1alpha1" - scheme "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" -) - -// CompassConnectionsGetter has a method to return a CompassConnectionInterface. -// A group's client should implement this interface. -type CompassConnectionsGetter interface { - CompassConnections() CompassConnectionInterface -} - -// CompassConnectionInterface has methods to work with CompassConnection resources. -type CompassConnectionInterface interface { - Create(ctx context.Context, compassConnection *v1alpha1.CompassConnection, opts v1.CreateOptions) (*v1alpha1.CompassConnection, error) - Update(ctx context.Context, compassConnection *v1alpha1.CompassConnection, opts v1.UpdateOptions) (*v1alpha1.CompassConnection, error) - UpdateStatus(ctx context.Context, compassConnection *v1alpha1.CompassConnection, opts v1.UpdateOptions) (*v1alpha1.CompassConnection, error) - Delete(ctx context.Context, name string, opts v1.DeleteOptions) error - DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.CompassConnection, error) - List(ctx context.Context, opts v1.ListOptions) (*v1alpha1.CompassConnectionList, error) - Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.CompassConnection, err error) - CompassConnectionExpansion -} - -// compassConnections implements CompassConnectionInterface -type compassConnections struct { - client rest.Interface -} - -// newCompassConnections returns a CompassConnections -func newCompassConnections(c *CompassV1alpha1Client) *compassConnections { - return &compassConnections{ - client: c.RESTClient(), - } -} - -// Get takes name of the compassConnection, and returns the corresponding compassConnection object, and an error if there is any. -func (c *compassConnections) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.CompassConnection, err error) { - result = &v1alpha1.CompassConnection{} - err = c.client.Get(). - Resource("compassconnections"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(ctx). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of CompassConnections that match those selectors. -func (c *compassConnections) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.CompassConnectionList, err error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - result = &v1alpha1.CompassConnectionList{} - err = c.client.Get(). - Resource("compassconnections"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Do(ctx). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested compassConnections. -func (c *compassConnections) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - opts.Watch = true - return c.client.Get(). - Resource("compassconnections"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Watch(ctx) -} - -// Create takes the representation of a compassConnection and creates it. Returns the server's representation of the compassConnection, and an error, if there is any. -func (c *compassConnections) Create(ctx context.Context, compassConnection *v1alpha1.CompassConnection, opts v1.CreateOptions) (result *v1alpha1.CompassConnection, err error) { - result = &v1alpha1.CompassConnection{} - err = c.client.Post(). - Resource("compassconnections"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(compassConnection). - Do(ctx). - Into(result) - return -} - -// Update takes the representation of a compassConnection and updates it. Returns the server's representation of the compassConnection, and an error, if there is any. -func (c *compassConnections) Update(ctx context.Context, compassConnection *v1alpha1.CompassConnection, opts v1.UpdateOptions) (result *v1alpha1.CompassConnection, err error) { - result = &v1alpha1.CompassConnection{} - err = c.client.Put(). - Resource("compassconnections"). - Name(compassConnection.Name). - VersionedParams(&opts, scheme.ParameterCodec). - Body(compassConnection). - Do(ctx). - Into(result) - return -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). -func (c *compassConnections) UpdateStatus(ctx context.Context, compassConnection *v1alpha1.CompassConnection, opts v1.UpdateOptions) (result *v1alpha1.CompassConnection, err error) { - result = &v1alpha1.CompassConnection{} - err = c.client.Put(). - Resource("compassconnections"). - Name(compassConnection.Name). - SubResource("status"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(compassConnection). - Do(ctx). - Into(result) - return -} - -// Delete takes name of the compassConnection and deletes it. Returns an error if one occurs. -func (c *compassConnections) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - return c.client.Delete(). - Resource("compassconnections"). - Name(name). - Body(&opts). - Do(ctx). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *compassConnections) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - var timeout time.Duration - if listOpts.TimeoutSeconds != nil { - timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second - } - return c.client.Delete(). - Resource("compassconnections"). - VersionedParams(&listOpts, scheme.ParameterCodec). - Timeout(timeout). - Body(&opts). - Do(ctx). - Error() -} - -// Patch applies the patch and returns the patched compassConnection. -func (c *compassConnections) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.CompassConnection, err error) { - result = &v1alpha1.CompassConnection{} - err = c.client.Patch(pt). - Resource("compassconnections"). - Name(name). - SubResource(subresources...). - VersionedParams(&opts, scheme.ParameterCodec). - Body(data). - Do(ctx). - Into(result) - return -} diff --git a/components/compass-runtime-agent/pkg/client/clientset/versioned/typed/compass/v1alpha1/doc.go b/components/compass-runtime-agent/pkg/client/clientset/versioned/typed/compass/v1alpha1/doc.go deleted file mode 100644 index 93a7ca4e0e2b..000000000000 --- a/components/compass-runtime-agent/pkg/client/clientset/versioned/typed/compass/v1alpha1/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// Code generated by client-gen. DO NOT EDIT. - -// This package has the automatically generated typed clients. -package v1alpha1 diff --git a/components/compass-runtime-agent/pkg/client/clientset/versioned/typed/compass/v1alpha1/fake/doc.go b/components/compass-runtime-agent/pkg/client/clientset/versioned/typed/compass/v1alpha1/fake/doc.go deleted file mode 100644 index 2b5ba4c8e442..000000000000 --- a/components/compass-runtime-agent/pkg/client/clientset/versioned/typed/compass/v1alpha1/fake/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// Code generated by client-gen. DO NOT EDIT. - -// Package fake has the automatically generated clients. -package fake diff --git a/components/compass-runtime-agent/pkg/client/clientset/versioned/typed/compass/v1alpha1/fake/fake_compass_client.go b/components/compass-runtime-agent/pkg/client/clientset/versioned/typed/compass/v1alpha1/fake/fake_compass_client.go deleted file mode 100644 index fe0cf4f735e0..000000000000 --- a/components/compass-runtime-agent/pkg/client/clientset/versioned/typed/compass/v1alpha1/fake/fake_compass_client.go +++ /dev/null @@ -1,24 +0,0 @@ -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha1 "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/client/clientset/versioned/typed/compass/v1alpha1" - rest "k8s.io/client-go/rest" - testing "k8s.io/client-go/testing" -) - -type FakeCompassV1alpha1 struct { - *testing.Fake -} - -func (c *FakeCompassV1alpha1) CompassConnections() v1alpha1.CompassConnectionInterface { - return &FakeCompassConnections{c} -} - -// RESTClient returns a RESTClient that is used to communicate -// with API server by this client implementation. -func (c *FakeCompassV1alpha1) RESTClient() rest.Interface { - var ret *rest.RESTClient - return ret -} diff --git a/components/compass-runtime-agent/pkg/client/clientset/versioned/typed/compass/v1alpha1/fake/fake_compassconnection.go b/components/compass-runtime-agent/pkg/client/clientset/versioned/typed/compass/v1alpha1/fake/fake_compassconnection.go deleted file mode 100644 index df556d56cfdd..000000000000 --- a/components/compass-runtime-agent/pkg/client/clientset/versioned/typed/compass/v1alpha1/fake/fake_compassconnection.go +++ /dev/null @@ -1,117 +0,0 @@ -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - "context" - - v1alpha1 "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/apis/compass/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - schema "k8s.io/apimachinery/pkg/runtime/schema" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" -) - -// FakeCompassConnections implements CompassConnectionInterface -type FakeCompassConnections struct { - Fake *FakeCompassV1alpha1 -} - -var compassconnectionsResource = schema.GroupVersionResource{Group: "compass.kyma-project.io", Version: "v1alpha1", Resource: "compassconnections"} - -var compassconnectionsKind = schema.GroupVersionKind{Group: "compass.kyma-project.io", Version: "v1alpha1", Kind: "CompassConnection"} - -// Get takes name of the compassConnection, and returns the corresponding compassConnection object, and an error if there is any. -func (c *FakeCompassConnections) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.CompassConnection, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootGetAction(compassconnectionsResource, name), &v1alpha1.CompassConnection{}) - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.CompassConnection), err -} - -// List takes label and field selectors, and returns the list of CompassConnections that match those selectors. -func (c *FakeCompassConnections) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.CompassConnectionList, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootListAction(compassconnectionsResource, compassconnectionsKind, opts), &v1alpha1.CompassConnectionList{}) - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1alpha1.CompassConnectionList{ListMeta: obj.(*v1alpha1.CompassConnectionList).ListMeta} - for _, item := range obj.(*v1alpha1.CompassConnectionList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested compassConnections. -func (c *FakeCompassConnections) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewRootWatchAction(compassconnectionsResource, opts)) -} - -// Create takes the representation of a compassConnection and creates it. Returns the server's representation of the compassConnection, and an error, if there is any. -func (c *FakeCompassConnections) Create(ctx context.Context, compassConnection *v1alpha1.CompassConnection, opts v1.CreateOptions) (result *v1alpha1.CompassConnection, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootCreateAction(compassconnectionsResource, compassConnection), &v1alpha1.CompassConnection{}) - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.CompassConnection), err -} - -// Update takes the representation of a compassConnection and updates it. Returns the server's representation of the compassConnection, and an error, if there is any. -func (c *FakeCompassConnections) Update(ctx context.Context, compassConnection *v1alpha1.CompassConnection, opts v1.UpdateOptions) (result *v1alpha1.CompassConnection, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootUpdateAction(compassconnectionsResource, compassConnection), &v1alpha1.CompassConnection{}) - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.CompassConnection), err -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). -func (c *FakeCompassConnections) UpdateStatus(ctx context.Context, compassConnection *v1alpha1.CompassConnection, opts v1.UpdateOptions) (*v1alpha1.CompassConnection, error) { - obj, err := c.Fake. - Invokes(testing.NewRootUpdateSubresourceAction(compassconnectionsResource, "status", compassConnection), &v1alpha1.CompassConnection{}) - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.CompassConnection), err -} - -// Delete takes name of the compassConnection and deletes it. Returns an error if one occurs. -func (c *FakeCompassConnections) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewRootDeleteAction(compassconnectionsResource, name), &v1alpha1.CompassConnection{}) - return err -} - -// DeleteCollection deletes a collection of objects. -func (c *FakeCompassConnections) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - action := testing.NewRootDeleteCollectionAction(compassconnectionsResource, listOpts) - - _, err := c.Fake.Invokes(action, &v1alpha1.CompassConnectionList{}) - return err -} - -// Patch applies the patch and returns the patched compassConnection. -func (c *FakeCompassConnections) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.CompassConnection, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootPatchSubresourceAction(compassconnectionsResource, name, pt, data, subresources...), &v1alpha1.CompassConnection{}) - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.CompassConnection), err -} diff --git a/components/compass-runtime-agent/pkg/client/clientset/versioned/typed/compass/v1alpha1/generated_expansion.go b/components/compass-runtime-agent/pkg/client/clientset/versioned/typed/compass/v1alpha1/generated_expansion.go deleted file mode 100644 index cf508a796874..000000000000 --- a/components/compass-runtime-agent/pkg/client/clientset/versioned/typed/compass/v1alpha1/generated_expansion.go +++ /dev/null @@ -1,5 +0,0 @@ -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -type CompassConnectionExpansion interface{} diff --git a/components/compass-runtime-agent/pkg/client/informers/externalversions/compass/interface.go b/components/compass-runtime-agent/pkg/client/informers/externalversions/compass/interface.go deleted file mode 100644 index 6170182924af..000000000000 --- a/components/compass-runtime-agent/pkg/client/informers/externalversions/compass/interface.go +++ /dev/null @@ -1,30 +0,0 @@ -// Code generated by informer-gen. DO NOT EDIT. - -package compass - -import ( - v1alpha1 "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/client/informers/externalversions/compass/v1alpha1" - internalinterfaces "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/client/informers/externalversions/internalinterfaces" -) - -// Interface provides access to each of this group's versions. -type Interface interface { - // V1alpha1 provides access to shared informers for resources in V1alpha1. - V1alpha1() v1alpha1.Interface -} - -type group struct { - factory internalinterfaces.SharedInformerFactory - namespace string - tweakListOptions internalinterfaces.TweakListOptionsFunc -} - -// New returns a new Interface. -func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { - return &group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} -} - -// V1alpha1 returns a new v1alpha1.Interface. -func (g *group) V1alpha1() v1alpha1.Interface { - return v1alpha1.New(g.factory, g.namespace, g.tweakListOptions) -} diff --git a/components/compass-runtime-agent/pkg/client/informers/externalversions/compass/v1alpha1/compassconnection.go b/components/compass-runtime-agent/pkg/client/informers/externalversions/compass/v1alpha1/compassconnection.go deleted file mode 100644 index f0774fcb8e74..000000000000 --- a/components/compass-runtime-agent/pkg/client/informers/externalversions/compass/v1alpha1/compassconnection.go +++ /dev/null @@ -1,73 +0,0 @@ -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - "context" - time "time" - - compassv1alpha1 "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/apis/compass/v1alpha1" - versioned "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/client/clientset/versioned" - internalinterfaces "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/client/informers/externalversions/internalinterfaces" - v1alpha1 "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/client/listers/compass/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// CompassConnectionInformer provides access to a shared informer and lister for -// CompassConnections. -type CompassConnectionInformer interface { - Informer() cache.SharedIndexInformer - Lister() v1alpha1.CompassConnectionLister -} - -type compassConnectionInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc -} - -// NewCompassConnectionInformer constructs a new informer for CompassConnection type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewCompassConnectionInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredCompassConnectionInformer(client, resyncPeriod, indexers, nil) -} - -// NewFilteredCompassConnectionInformer constructs a new informer for CompassConnection type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredCompassConnectionInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - &cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.CompassV1alpha1().CompassConnections().List(context.TODO(), options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.CompassV1alpha1().CompassConnections().Watch(context.TODO(), options) - }, - }, - &compassv1alpha1.CompassConnection{}, - resyncPeriod, - indexers, - ) -} - -func (f *compassConnectionInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredCompassConnectionInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *compassConnectionInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&compassv1alpha1.CompassConnection{}, f.defaultInformer) -} - -func (f *compassConnectionInformer) Lister() v1alpha1.CompassConnectionLister { - return v1alpha1.NewCompassConnectionLister(f.Informer().GetIndexer()) -} diff --git a/components/compass-runtime-agent/pkg/client/informers/externalversions/compass/v1alpha1/interface.go b/components/compass-runtime-agent/pkg/client/informers/externalversions/compass/v1alpha1/interface.go deleted file mode 100644 index d7880c9fb4ae..000000000000 --- a/components/compass-runtime-agent/pkg/client/informers/externalversions/compass/v1alpha1/interface.go +++ /dev/null @@ -1,29 +0,0 @@ -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - internalinterfaces "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/client/informers/externalversions/internalinterfaces" -) - -// Interface provides access to all the informers in this group version. -type Interface interface { - // CompassConnections returns a CompassConnectionInformer. - CompassConnections() CompassConnectionInformer -} - -type version struct { - factory internalinterfaces.SharedInformerFactory - namespace string - tweakListOptions internalinterfaces.TweakListOptionsFunc -} - -// New returns a new Interface. -func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { - return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} -} - -// CompassConnections returns a CompassConnectionInformer. -func (v *version) CompassConnections() CompassConnectionInformer { - return &compassConnectionInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} -} diff --git a/components/compass-runtime-agent/pkg/client/informers/externalversions/factory.go b/components/compass-runtime-agent/pkg/client/informers/externalversions/factory.go deleted file mode 100644 index 6ce803b5f93d..000000000000 --- a/components/compass-runtime-agent/pkg/client/informers/externalversions/factory.go +++ /dev/null @@ -1,164 +0,0 @@ -// Code generated by informer-gen. DO NOT EDIT. - -package externalversions - -import ( - reflect "reflect" - sync "sync" - time "time" - - versioned "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/client/clientset/versioned" - compass "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/client/informers/externalversions/compass" - internalinterfaces "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/client/informers/externalversions/internalinterfaces" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - schema "k8s.io/apimachinery/pkg/runtime/schema" - cache "k8s.io/client-go/tools/cache" -) - -// SharedInformerOption defines the functional option type for SharedInformerFactory. -type SharedInformerOption func(*sharedInformerFactory) *sharedInformerFactory - -type sharedInformerFactory struct { - client versioned.Interface - namespace string - tweakListOptions internalinterfaces.TweakListOptionsFunc - lock sync.Mutex - defaultResync time.Duration - customResync map[reflect.Type]time.Duration - - informers map[reflect.Type]cache.SharedIndexInformer - // startedInformers is used for tracking which informers have been started. - // This allows Start() to be called multiple times safely. - startedInformers map[reflect.Type]bool -} - -// WithCustomResyncConfig sets a custom resync period for the specified informer types. -func WithCustomResyncConfig(resyncConfig map[v1.Object]time.Duration) SharedInformerOption { - return func(factory *sharedInformerFactory) *sharedInformerFactory { - for k, v := range resyncConfig { - factory.customResync[reflect.TypeOf(k)] = v - } - return factory - } -} - -// WithTweakListOptions sets a custom filter on all listers of the configured SharedInformerFactory. -func WithTweakListOptions(tweakListOptions internalinterfaces.TweakListOptionsFunc) SharedInformerOption { - return func(factory *sharedInformerFactory) *sharedInformerFactory { - factory.tweakListOptions = tweakListOptions - return factory - } -} - -// WithNamespace limits the SharedInformerFactory to the specified namespace. -func WithNamespace(namespace string) SharedInformerOption { - return func(factory *sharedInformerFactory) *sharedInformerFactory { - factory.namespace = namespace - return factory - } -} - -// NewSharedInformerFactory constructs a new instance of sharedInformerFactory for all namespaces. -func NewSharedInformerFactory(client versioned.Interface, defaultResync time.Duration) SharedInformerFactory { - return NewSharedInformerFactoryWithOptions(client, defaultResync) -} - -// NewFilteredSharedInformerFactory constructs a new instance of sharedInformerFactory. -// Listers obtained via this SharedInformerFactory will be subject to the same filters -// as specified here. -// Deprecated: Please use NewSharedInformerFactoryWithOptions instead -func NewFilteredSharedInformerFactory(client versioned.Interface, defaultResync time.Duration, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) SharedInformerFactory { - return NewSharedInformerFactoryWithOptions(client, defaultResync, WithNamespace(namespace), WithTweakListOptions(tweakListOptions)) -} - -// NewSharedInformerFactoryWithOptions constructs a new instance of a SharedInformerFactory with additional options. -func NewSharedInformerFactoryWithOptions(client versioned.Interface, defaultResync time.Duration, options ...SharedInformerOption) SharedInformerFactory { - factory := &sharedInformerFactory{ - client: client, - namespace: v1.NamespaceAll, - defaultResync: defaultResync, - informers: make(map[reflect.Type]cache.SharedIndexInformer), - startedInformers: make(map[reflect.Type]bool), - customResync: make(map[reflect.Type]time.Duration), - } - - // Apply all options - for _, opt := range options { - factory = opt(factory) - } - - return factory -} - -// Start initializes all requested informers. -func (f *sharedInformerFactory) Start(stopCh <-chan struct{}) { - f.lock.Lock() - defer f.lock.Unlock() - - for informerType, informer := range f.informers { - if !f.startedInformers[informerType] { - go informer.Run(stopCh) - f.startedInformers[informerType] = true - } - } -} - -// WaitForCacheSync waits for all started informers' cache were synced. -func (f *sharedInformerFactory) WaitForCacheSync(stopCh <-chan struct{}) map[reflect.Type]bool { - informers := func() map[reflect.Type]cache.SharedIndexInformer { - f.lock.Lock() - defer f.lock.Unlock() - - informers := map[reflect.Type]cache.SharedIndexInformer{} - for informerType, informer := range f.informers { - if f.startedInformers[informerType] { - informers[informerType] = informer - } - } - return informers - }() - - res := map[reflect.Type]bool{} - for informType, informer := range informers { - res[informType] = cache.WaitForCacheSync(stopCh, informer.HasSynced) - } - return res -} - -// InternalInformerFor returns the SharedIndexInformer for obj using an internal -// client. -func (f *sharedInformerFactory) InformerFor(obj runtime.Object, newFunc internalinterfaces.NewInformerFunc) cache.SharedIndexInformer { - f.lock.Lock() - defer f.lock.Unlock() - - informerType := reflect.TypeOf(obj) - informer, exists := f.informers[informerType] - if exists { - return informer - } - - resyncPeriod, exists := f.customResync[informerType] - if !exists { - resyncPeriod = f.defaultResync - } - - informer = newFunc(f.client, resyncPeriod) - f.informers[informerType] = informer - - return informer -} - -// SharedInformerFactory provides shared informers for resources in all known -// API group versions. -type SharedInformerFactory interface { - internalinterfaces.SharedInformerFactory - ForResource(resource schema.GroupVersionResource) (GenericInformer, error) - WaitForCacheSync(stopCh <-chan struct{}) map[reflect.Type]bool - - Compass() compass.Interface -} - -func (f *sharedInformerFactory) Compass() compass.Interface { - return compass.New(f, f.namespace, f.tweakListOptions) -} diff --git a/components/compass-runtime-agent/pkg/client/informers/externalversions/generic.go b/components/compass-runtime-agent/pkg/client/informers/externalversions/generic.go deleted file mode 100644 index f4cd44a509fd..000000000000 --- a/components/compass-runtime-agent/pkg/client/informers/externalversions/generic.go +++ /dev/null @@ -1,46 +0,0 @@ -// Code generated by informer-gen. DO NOT EDIT. - -package externalversions - -import ( - "fmt" - - v1alpha1 "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/apis/compass/v1alpha1" - schema "k8s.io/apimachinery/pkg/runtime/schema" - cache "k8s.io/client-go/tools/cache" -) - -// GenericInformer is type of SharedIndexInformer which will locate and delegate to other -// sharedInformers based on type -type GenericInformer interface { - Informer() cache.SharedIndexInformer - Lister() cache.GenericLister -} - -type genericInformer struct { - informer cache.SharedIndexInformer - resource schema.GroupResource -} - -// Informer returns the SharedIndexInformer. -func (f *genericInformer) Informer() cache.SharedIndexInformer { - return f.informer -} - -// Lister returns the GenericLister. -func (f *genericInformer) Lister() cache.GenericLister { - return cache.NewGenericLister(f.Informer().GetIndexer(), f.resource) -} - -// ForResource gives generic access to a shared informer of the matching type -// TODO extend this to unknown resources with a client pool -func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) { - switch resource { - // Group=compass.kyma-project.io, Version=v1alpha1 - case v1alpha1.SchemeGroupVersion.WithResource("compassconnections"): - return &genericInformer{resource: resource.GroupResource(), informer: f.Compass().V1alpha1().CompassConnections().Informer()}, nil - - } - - return nil, fmt.Errorf("no informer found for %v", resource) -} diff --git a/components/compass-runtime-agent/pkg/client/informers/externalversions/internalinterfaces/factory_interfaces.go b/components/compass-runtime-agent/pkg/client/informers/externalversions/internalinterfaces/factory_interfaces.go deleted file mode 100644 index 319981a72449..000000000000 --- a/components/compass-runtime-agent/pkg/client/informers/externalversions/internalinterfaces/factory_interfaces.go +++ /dev/null @@ -1,24 +0,0 @@ -// Code generated by informer-gen. DO NOT EDIT. - -package internalinterfaces - -import ( - time "time" - - versioned "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/client/clientset/versioned" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - cache "k8s.io/client-go/tools/cache" -) - -// NewInformerFunc takes versioned.Interface and time.Duration to return a SharedIndexInformer. -type NewInformerFunc func(versioned.Interface, time.Duration) cache.SharedIndexInformer - -// SharedInformerFactory a small interface to allow for adding an informer without an import cycle -type SharedInformerFactory interface { - Start(stopCh <-chan struct{}) - InformerFor(obj runtime.Object, newFunc NewInformerFunc) cache.SharedIndexInformer -} - -// TweakListOptionsFunc is a function that transforms a v1.ListOptions. -type TweakListOptionsFunc func(*v1.ListOptions) diff --git a/components/compass-runtime-agent/pkg/client/listers/compass/v1alpha1/compassconnection.go b/components/compass-runtime-agent/pkg/client/listers/compass/v1alpha1/compassconnection.go deleted file mode 100644 index ee3c57db2c5d..000000000000 --- a/components/compass-runtime-agent/pkg/client/listers/compass/v1alpha1/compassconnection.go +++ /dev/null @@ -1,52 +0,0 @@ -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/apis/compass/v1alpha1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" -) - -// CompassConnectionLister helps list CompassConnections. -// All objects returned here must be treated as read-only. -type CompassConnectionLister interface { - // List lists all CompassConnections in the indexer. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1alpha1.CompassConnection, err error) - // Get retrieves the CompassConnection from the index for a given name. - // Objects returned here must be treated as read-only. - Get(name string) (*v1alpha1.CompassConnection, error) - CompassConnectionListerExpansion -} - -// compassConnectionLister implements the CompassConnectionLister interface. -type compassConnectionLister struct { - indexer cache.Indexer -} - -// NewCompassConnectionLister returns a new CompassConnectionLister. -func NewCompassConnectionLister(indexer cache.Indexer) CompassConnectionLister { - return &compassConnectionLister{indexer: indexer} -} - -// List lists all CompassConnections in the indexer. -func (s *compassConnectionLister) List(selector labels.Selector) (ret []*v1alpha1.CompassConnection, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.CompassConnection)) - }) - return ret, err -} - -// Get retrieves the CompassConnection from the index for a given name. -func (s *compassConnectionLister) Get(name string) (*v1alpha1.CompassConnection, error) { - obj, exists, err := s.indexer.GetByKey(name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("compassconnection"), name) - } - return obj.(*v1alpha1.CompassConnection), nil -} diff --git a/components/compass-runtime-agent/pkg/client/listers/compass/v1alpha1/expansion_generated.go b/components/compass-runtime-agent/pkg/client/listers/compass/v1alpha1/expansion_generated.go deleted file mode 100644 index 707fb6fd6ef7..000000000000 --- a/components/compass-runtime-agent/pkg/client/listers/compass/v1alpha1/expansion_generated.go +++ /dev/null @@ -1,7 +0,0 @@ -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha1 - -// CompassConnectionListerExpansion allows custom methods to be added to -// CompassConnectionLister. -type CompassConnectionListerExpansion interface{} diff --git a/components/compass-runtime-agent/scripts/patch-local-changes.sh b/components/compass-runtime-agent/scripts/patch-local-changes.sh deleted file mode 100755 index 8009b48522d2..000000000000 --- a/components/compass-runtime-agent/scripts/patch-local-changes.sh +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env bash - -CURRENT_DIR="$( cd "$(dirname "$0")" ; pwd -P )" - -eval $(minikube docker-env) - -echo "" -echo "------------------------" -echo "Building component image" -echo "------------------------" - -docker build $CURRENT_DIR/.. -t compass-runtime-agent - -echo "" -echo "------------------------" -echo "Updating deployment" -echo "------------------------" - -kubectl -n kyma-system patch deployment compass-runtime-agent --patch 'spec: - template: - spec: - containers: - - name: compass-runtime-agent - image: compass-runtime-agent - imagePullPolicy: Never' - -echo "" -echo "------------------------" -echo "Removing old pods" -echo "------------------------" - -kubectl -n kyma-system delete po -l app=compass-runtime-agent --now --wait=false diff --git a/components/compass-runtime-agent/scripts/update_mocks.sh b/components/compass-runtime-agent/scripts/update_mocks.sh deleted file mode 100755 index 40fa87190f6b..000000000000 --- a/components/compass-runtime-agent/scripts/update_mocks.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/usr/bin/env bash - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" - -go generate ${GOPATH}/src/github.com/kyma-project/kyma/components/compass-runtime-agent/internal/... diff --git a/installation/README.md b/installation/README.md deleted file mode 100644 index 80349294cf68..000000000000 --- a/installation/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# Installation Resources - -## Overview - -This folder is going to be removed soon. With the modular Kyma you can install only the components you need. Please refer to the [Kyma installation](https://kyma-project.io/#/02-get-started/01-quick-install) document for more information. diff --git a/installation/resources/components.yaml b/installation/resources/components.yaml deleted file mode 100644 index 482f0192a66c..000000000000 --- a/installation/resources/components.yaml +++ /dev/null @@ -1,2 +0,0 @@ ---- -defaultNamespace: kyma-system diff --git a/resources/README.md b/resources/README.md deleted file mode 100644 index 090a1bba9d5c..000000000000 --- a/resources/README.md +++ /dev/null @@ -1,25 +0,0 @@ -# Resources - -## Overview - -Resources are all components in Kyma that are available for local and cluster installation. You can find more details about each component in the corresponding README.md files. - -Resources currently include, but are not limited to, the following: - -- Elements which are essential for the installation of `core` components in Kyma, such as certificates, users, and permissions -- Examples of the use of specific components -- Scripts for the installation of Helm, Istio deployment, as well as scripts for validating Pods, starting Kyma, and testing - -## Development - -Every component, test, or tool in the `kyma` repository contains a Makefile. A Makefile is used to build an image of a given component and to push it to the external repository. Every time you create a new component, test, or tool, ensure that its Makefile contains a path to the `values.yaml` file which informs about the actual image version used in Kyma. -To do so, add this entry to the Makefile: - -``` -.PHONY: path-to-referenced-charts -path-to-referenced-charts: - @echo "{path to the referenced charts}" -``` - -The version of the actual component image is located under the **global.{name_of_component}.version** property. -**{name_of_component}** is a directory name of the component where dashes are replaced by underscores. diff --git a/tests/README.md b/tests/README.md deleted file mode 100644 index 14ef0321d20f..000000000000 --- a/tests/README.md +++ /dev/null @@ -1,27 +0,0 @@ -# Tests - -## Overview - -The `tests` directory contains the sources for all Kyma tests. -A Kyma test is Pod, container, or image referenced in a Kyma module or chart test section. It provides the module's test functionality. -A Kyma test runs against a running Kyma cluster. It ensures the integrity and functional correctness of the cluster with all installed modules. -Each subdirectory in the tests directory defines sources for one test suite, usually focusing on one component. The resulting Docker images are then referenced by the related Kyma modules or charts. - -## Details - -Every Kyma test resides in a dedicated folder which contains its sources and a `README.md ` file. This file provides instructions on how to build and develop the test suite. - -The test name, which is also the folder name, is the component's name without any prefix or suffix, such as `api-gateway`. - -The Docker image created from the sources of a test suite resides in a component folder marked with a suffix indicating the testing nature, such as `-integration-tests`. -Example: The api-gateway component has its integration tests in `tests/integration/api-gateway` folder and produces the `XX/api-gateway-integration-tests:0.5.1` Docker image. - -Bundle the real e2e scenarios, such as **kubeless-integration** into one `end-to-end` subfolder. This folder contains one test project which executes all end-to-end tests divided into different packages by scenarios. - -Bundle integration tests, such as **api-gateway** into one `integration` subfolder. - -Bundle performance tests into one `perf` subfolder. - -## Development - -Follow [this](https://github.com/kyma-project/kyma/blob/main/resources/README.md) development guide when you add a new test to the `kyma` repository. diff --git a/tests/components/application-connector/.dockerignore b/tests/components/application-connector/.dockerignore deleted file mode 100644 index 63055f9747cb..000000000000 --- a/tests/components/application-connector/.dockerignore +++ /dev/null @@ -1,2 +0,0 @@ -deployments/ -README.md diff --git a/tests/components/application-connector/.gitignore b/tests/components/application-connector/.gitignore deleted file mode 100644 index 9dc57812081d..000000000000 --- a/tests/components/application-connector/.gitignore +++ /dev/null @@ -1 +0,0 @@ -resources/charts/gateway-test/certs/ \ No newline at end of file diff --git a/tests/components/application-connector/Dockerfile.compass-runtime-agent b/tests/components/application-connector/Dockerfile.compass-runtime-agent deleted file mode 100644 index 08813029bcae..000000000000 --- a/tests/components/application-connector/Dockerfile.compass-runtime-agent +++ /dev/null @@ -1,17 +0,0 @@ -# image builder base on golang:1.21.1-alpine3.18 -FROM golang@sha256:0c860c7ceba62231d0f99fb92e9d7c1577f26fea794a12c75756a8f64b146e45 as builder - -WORKDIR /compass-test/ - -COPY go.mod go.sum ./ -RUN go mod download && go mod verify - -COPY . . - -RUN CGO_ENABLED=0 go test -v -c -o compass-test ./test/compass-runtime-agent/ - -FROM scratch - -COPY --from=builder /compass-test/compass-test / -ENTRYPOINT [ "/compass-test" ] -CMD ["-test.v", "-test.parallel", "1"] diff --git a/tests/components/application-connector/Dockerfile.connectivity-validator b/tests/components/application-connector/Dockerfile.connectivity-validator deleted file mode 100644 index 85aa6c1709d3..000000000000 --- a/tests/components/application-connector/Dockerfile.connectivity-validator +++ /dev/null @@ -1,17 +0,0 @@ -# image builder base on golang:1.21.1-alpine3.18 -FROM golang@sha256:0c860c7ceba62231d0f99fb92e9d7c1577f26fea794a12c75756a8f64b146e45 as builder - -WORKDIR /validator-test/ - -COPY go.mod go.sum ./ -RUN go mod download && go mod verify - -COPY . . - -RUN CGO_ENABLED=0 go test -v -c -o validator-test ./test/application-connectivity-validator/ - -FROM scratch - -COPY --from=builder /validator-test/validator-test / -ENTRYPOINT [ "/validator-test" ] -CMD ["-test.v"] diff --git a/tests/components/application-connector/Dockerfile.gateway b/tests/components/application-connector/Dockerfile.gateway deleted file mode 100644 index 9e620a90ad75..000000000000 --- a/tests/components/application-connector/Dockerfile.gateway +++ /dev/null @@ -1,17 +0,0 @@ -# image builder base on golang:1.21.1-alpine3.18 -FROM golang@sha256:0c860c7ceba62231d0f99fb92e9d7c1577f26fea794a12c75756a8f64b146e45 as builder - -WORKDIR /gateway-test/ - -COPY go.mod go.sum ./ -RUN go mod download && go mod verify - -COPY . . - -RUN CGO_ENABLED=0 go test -v -c -o gateway-test ./test/application-gateway/ - -FROM scratch - -COPY --from=builder /gateway-test/gateway-test / -ENTRYPOINT [ "/gateway-test" ] -CMD ["-test.v"] diff --git a/tests/components/application-connector/Dockerfile.mockapp b/tests/components/application-connector/Dockerfile.mockapp deleted file mode 100644 index 14203dcfbe87..000000000000 --- a/tests/components/application-connector/Dockerfile.mockapp +++ /dev/null @@ -1,17 +0,0 @@ -# image builder base on golang:1.21.1-alpine3.18 -FROM golang@sha256:0c860c7ceba62231d0f99fb92e9d7c1577f26fea794a12c75756a8f64b146e45 as builder - -WORKDIR /mock-app/ - -COPY go.mod go.sum ./ -RUN go mod download && go mod verify - -COPY . . - - -RUN CGO_ENABLED=0 go build -v -o mock-app ./tools/external-api-mock-app - -FROM scratch -COPY --from=builder /mock-app/mock-app . -ENTRYPOINT [ "/mock-app" ] -CMD [] diff --git a/tests/components/application-connector/Makefile b/tests/components/application-connector/Makefile deleted file mode 100644 index 0be826ebbdac..000000000000 --- a/tests/components/application-connector/Makefile +++ /dev/null @@ -1,33 +0,0 @@ -GATEWAY_TEST_IMAGE = "$(DOCKER_PUSH_REPOSITORY)$(DOCKER_PUSH_DIRECTORY)/gateway-test:$(DOCKER_TAG)" -VALIDATOR_TEST_IMAGE = "$(DOCKER_PUSH_REPOSITORY)$(DOCKER_PUSH_DIRECTORY)/connectivity-validator-test:$(DOCKER_TAG)" -COMPASS_TEST_IMAGE = "$(DOCKER_PUSH_REPOSITORY)$(DOCKER_PUSH_DIRECTORY)/compass-runtime-agent-test:$(DOCKER_TAG)" -MOCK_APP_IMAGE = "$(DOCKER_PUSH_REPOSITORY)$(DOCKER_PUSH_DIRECTORY)/mock-app:$(DOCKER_TAG)" - -.PHONY: release image - -release: publish-gateway-test publish-mock-app publish-validator-test publish-compass-runtime-agent-test -image: image-gateway-test image-validator-test image-compass-runtime-agent-test - -publish-gateway-test: image-gateway-test - docker push $(GATEWAY_TEST_IMAGE) - -image-gateway-test: - docker build -t $(GATEWAY_TEST_IMAGE) -f Dockerfile.gateway . - -publish-mock-app: image-mock-app - docker push $(MOCK_APP_IMAGE) - -image-mock-app: - docker build -t $(MOCK_APP_IMAGE) -f Dockerfile.mockapp . - -publish-validator-test: image-validator-test - docker push $(VALIDATOR_TEST_IMAGE) - -image-validator-test: - docker build -t $(VALIDATOR_TEST_IMAGE) -f Dockerfile.connectivity-validator . - -publish-compass-runtime-agent-test: image-compass-runtime-agent-test - docker push $(COMPASS_TEST_IMAGE) - -image-compass-runtime-agent-test: - docker build -t $(COMPASS_TEST_IMAGE) -f Dockerfile.compass-runtime-agent . diff --git a/tests/components/application-connector/Makefile.test-application-conn-validator b/tests/components/application-connector/Makefile.test-application-conn-validator deleted file mode 100644 index f408cdd7d07c..000000000000 --- a/tests/components/application-connector/Makefile.test-application-conn-validator +++ /dev/null @@ -1,59 +0,0 @@ -# -*- mode: Makefile -*- - -NAMESPACE ?= test -GOPATH ?= $(shell go env GOPATH) - -VALIDATOR_TEST_IMAGE = "$(DOCKER_PUSH_REPOSITORY)$(DOCKER_PUSH_DIRECTORY)/connectivity-validator-test:$(DOCKER_TAG)" -TEST_TIMEOUT = "3m" -MAKEFILE_NAME=Makefile.test-application-conn-validator - -.PHONY: test clean -.PHONY: patch-for-validator-test unpatch-after-validator-test test-validator test-validator-debug validator-create-resources clean-validator-test publish-validator-test - -test: test-validator -clean: clean-validator-test - -patch-for-validator-test: - kubectl -n kyma-system patch deployment central-application-connectivity-validator --type json --patch-file resources/patches/central-application-connectivity-validator.json - kubectl rollout status deploy central-application-connectivity-validator -n kyma-system --timeout=1m - -unpatch-after-validator-test: - kubectl rollout undo deployment/central-application-connectivity-validator -n kyma-system - -test-validator: patch-for-validator-test validator-create-resources - if kubectl wait --for=condition=complete --timeout=$(TEST_TIMEOUT) -n $(NAMESPACE) job/application-connectivity-validator-test; then \ - echo "Success! Results:"; \ - ./scripts/check-pod-logs.sh application-connectivity-validator-test; \ - $(MAKE) clean-validator-test -f $(MAKEFILE_NAME); \ - else \ - echo "Tests failed! Results:"; \ - ./scripts/check-pod-logs.sh application-connectivity-validator-test; \ - $(MAKE) clean-validator-test -f $(MAKEFILE_NAME); \ - exit 1; \ - fi - -test-validator-debug: patch-for-validator-test validator-create-resources - kubectl wait --for=condition=complete --timeout=$(TEST_TIMEOUT) -n $(NAMESPACE) job/application-connectivity-validator-test; \ - echo "Results:"; \ - ./scripts/check-pod-logs.sh application-connectivity-validator-test; \ - -validator-create-resources: - kubectl create namespace $(NAMESPACE) --dry-run=client -o yaml | kubectl apply -f - - kubectl label namespace $(NAMESPACE) istio-injection=enabled --overwrite - - helm template resources/charts/application-connectivity-validator-test/charts/echoserver \ - --set global.namespace=$(NAMESPACE) \ - | kubectl apply -f - - kubectl rollout status deployment echoserver -n test --timeout=90s - - @helm template resources/charts/application-connectivity-validator-test/charts/test \ - --set namespace=$(NAMESPACE) \ - --values resources/charts/application-connectivity-validator-test/values.yaml \ - | kubectl apply -f - - -clean-validator-test: unpatch-after-validator-test - helm template resources/charts/application-connectivity-validator-test --set namespace=$(NAMESPACE) | kubectl delete -f - - kubectl delete ns $(NAMESPACE) --ignore-not-found - - - diff --git a/tests/components/application-connector/Makefile.test-application-gateway b/tests/components/application-connector/Makefile.test-application-gateway deleted file mode 100644 index cf2b5cc68d25..000000000000 --- a/tests/components/application-connector/Makefile.test-application-gateway +++ /dev/null @@ -1,66 +0,0 @@ -# -*- mode: makefile -*- - -NAMESPACE ?= test -GOPATH ?= $(shell go env GOPATH) - -MOCK_SERVICE_NAME="mock-application" -APP_URL = "$(MOCK_SERVICE_NAME).$(NAMESPACE).svc.cluster.local" -TEST_TIMEOUT = "3m" -MAKEFILE_NAME=Makefile.test-application-gateway - -.PHONY: test clean -.PHONY: test-gateway test-gateway-debug clean-gateway-test disable-sidecar-for-mtls-test enable-sidecar-after-mtls-test generate-certs - -test: test-gateway -clean: clean-gateway-test - -test-gateway: disable-sidecar-for-mtls-test generate-certs create-resources - if kubectl wait --for=condition=complete --timeout=$(TEST_TIMEOUT) -n $(NAMESPACE) job/application-gateway-test; then \ - echo "Success! Results:"; \ - ./scripts/check-pod-logs.sh application-gateway-test; \ - $(MAKE) clean-gateway-test -f $(MAKEFILE_NAME); \ - else \ - echo "Tests failed! Results:"; \ - ./scripts/check-pod-logs.sh application-gateway-test; \ - $(MAKE) clean-gateway-test -f $(MAKEFILE_NAME); \ - exit 1; \ - fi - -test-gateway-debug: disable-sidecar-for-mtls-test generate-certs create-resources - kubectl wait --for=condition=complete --timeout=$(TEST_TIMEOUT) -n $(NAMESPACE) job/application-gateway-test; \ - echo "Results:"; \ - ./scripts/check-pod-logs.sh application-gateway-test; \ - -create-resources: - kubectl create namespace $(NAMESPACE) --dry-run=client -o yaml | kubectl apply -f - - kubectl label namespace $(NAMESPACE) istio-injection=enabled --overwrite - - @helm template resources/charts/gateway-test/charts/mock-app \ - --set global.namespace=$(NAMESPACE) \ - --set mockServiceName=$(MOCK_SERVICE_NAME) \ - --values resources/charts/gateway-test/values.yaml \ - | kubectl apply -f - - kubectl rollout status deployment mock-application -n test --timeout=90s - - helm template resources/charts/gateway-test/charts/test \ - --set namespace=$(NAMESPACE) \ - --set mockServiceName=$(MOCK_SERVICE_NAME) \ - --values resources/charts/gateway-test/values.yaml \ - | kubectl apply -f - - -clean-gateway-test: - helm template resources/charts/gateway-test --set namespace=$(NAMESPACE) | kubectl delete -f - - kubectl delete ns $(NAMESPACE) --ignore-not-found - -disable-sidecar-for-mtls-test: - kubectl -n kyma-system patch deployment central-application-gateway -p '{"spec":{"template":{"metadata":{"annotations":{"traffic.sidecar.istio.io/excludeOutboundPorts": "8090,8091"}}}}}' - kubectl rollout status deploy central-application-gateway -n kyma-system --timeout=1m - -enable-sidecar-after-mtls-test: - kubectl -n kyma-system patch deployment central-application-gateway --type=json --patch '[{ "op": "remove", "path": "/spec/template/metadata/annotations/traffic.sidecar.istio.io~1excludeOutboundPorts"}]' - -generate-certs: - ./scripts/generate-self-signed-certs.sh $(APP_URL) ./resources/charts/gateway-test/charts/test/certs/positive - ./scripts/generate-self-signed-certs.sh $(APP_URL) ./resources/charts/gateway-test/charts/test/certs/negative - ./scripts/generate-self-signed-certs.sh test-other-ca ./resources/charts/gateway-test/charts/test/certs/invalid-ca - cp -p -R ./resources/charts/gateway-test/charts/test/certs ./resources/charts/gateway-test/charts/mock-app diff --git a/tests/components/application-connector/Makefile.test-compass-runtime-agent b/tests/components/application-connector/Makefile.test-compass-runtime-agent deleted file mode 100644 index f2adc01d0133..000000000000 --- a/tests/components/application-connector/Makefile.test-compass-runtime-agent +++ /dev/null @@ -1,38 +0,0 @@ -# -*- mode: Makefile -*- - -NAMESPACE ?= test -GOPATH ?= $(shell go env GOPATH) -DIRECTOR_URL=https://compass-gateway-auth-oauth.$(COMPASS_HOST)/director/graphql -TOKENS_ENDPOINT=https://oauth2.${COMPASS_HOST}/oauth2/token - -COMPASS_TEST_IMAGE = "$(DOCKER_PUSH_REPOSITORY)$(DOCKER_PUSH_DIRECTORY)/compass-runtime-agent-test:$(DOCKER_TAG)" - -.PHONY: release test image clean -.PHONY: test-compass-runtime-agent test-compass-runtime-agent-debug clean-compass-runtime-agent-test image-compass-runtime-agent-test publish-compass-runtime-agent-test - -test: test-compass-runtime-agent -clean: clean-compass-runtime-agent-test - -test-compass-runtime-agent: test-compass-runtime-agent-debug clean-compass-runtime-agent-test - -test-compass-runtime-agent-debug: - @echo $(GOPATH)/bin/go-junit-report --help - kubectl create namespace $(NAMESPACE) --dry-run=client -o yaml | kubectl apply -f - - kubectl label namespace $(NAMESPACE) istio-injection=enabled --overwrite - - @helm template resources/charts/compass-runtime-agent-test \ - --set namespace=$(NAMESPACE) \ - --set compassCredentials.clientID=$(COMPASS_CLIENT_ID) \ - --set compassCredentials.clientSecret=$(COMPASS_CLIENT_SECRET) \ - --set compassCredentials.tokensEndpoint=$(TOKENS_ENDPOINT) \ - --set directorUrl=$(DIRECTOR_URL) \ - | kubectl apply -f - - - @echo "" - @echo "Compass test results:" - - ./scripts/check-pod-logs.sh compass-runtime-agent-test - -clean-compass-runtime-agent-test: - helm template resources/charts/compass-runtime-agent-test | kubectl delete -f - - kubectl delete ns $(NAMESPACE) --ignore-not-found diff --git a/tests/components/application-connector/README.md b/tests/components/application-connector/README.md deleted file mode 100644 index 861a55c32e25..000000000000 --- a/tests/components/application-connector/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# Component tests for Application Connector - -There are the following component tests for Application Connector: -- [Application Gateway](docs/application-gateway-tests.md) -- [Application Connectivity Validator](docs/application-connectivity-validator-tests.md) -- [Compass Runtime Agent](docs/compass-runtime-agent-tests.md) diff --git a/tests/components/application-connector/docs/application-connectivity-validator-tests.md b/tests/components/application-connector/docs/application-connectivity-validator-tests.md deleted file mode 100644 index c7f16db5d341..000000000000 --- a/tests/components/application-connector/docs/application-connectivity-validator-tests.md +++ /dev/null @@ -1,88 +0,0 @@ -# Application Connectivity Validator - -**Table of Contents** - -- [Application Connectivity Validator](#application-connectivity-validator) - - [Design and Architecture](#design-and-architecture) - - [Building](#building) - - [Running](#running) - - [Deploy a Kyma Cluster Locally](#deploy-a-kyma-cluster-locally) - - [Run the Tests](#run-the-tests) - - [Debugging](#debugging) - - [Running Without Cleanup](#running-without-cleanup) - -## Design and Architecture - -The tests consist of: -- [Test resources](../resources/charts/application-connectivity-validator-test/) used to perform the test -- [Test runner](../test/application-connectivity-validator/) with all the test cases - -The tests are executed as a Kubernetes Job in a Kyma cluster where the tested Application Connectivity Validator is installed. The test Job is deployed in the `test` namespace. - -![Connectivity Validator tests architecture](assets/connectivity-validator-tests-architecture.svg) - -> **NOTE:** Port `8080` must be excluded from redirection to Envoy, otherwise the Connectivity Validator test Pod cannot pass the `X-Forwarded-Client-Cert` header to Connectivity Validator. - -## Building - -Pipelines build the Application Connectivity Validator test using the **release** target from the `Makefile`. - -To build **and push** the Docker images of the tests, run: - -``` sh -./scripts/local-build.sh {DOCKER_TAG} {DOCKER_PUSH_REPOSITORY} -``` - -This will build the following images: -- `{DOCKER_PUSH_REPOSITORY}/connectivity-validator-test:{DOCKER_TAG}` - -## Running - -Tests can be run on any Kyma cluster with Application Connectivity Validator. - -Pipelines run the tests using the **test-validator** target from the `Makefile`. - -### Deploy a Kyma Cluster Locally - -1. Provision a local Kubernetes cluster with k3d: - ```sh - k3d registry create kyma-registry --port 5001 - k3d cluster create kyma --kubeconfig-switch-context -p 80:80@loadbalancer -p 443:443@loadbalancer --registry-use kyma-registry - kubectl create ns kyma-system - ``` - -2. Install the minimal set of components required to run Application Connectivity Validator **for Kyma SKR (Compass mode)**: - - ```bash - kyma deploy --components-file ./resources/installation-config/mini-kyma-skr.yaml --value global.disableLegacyConnectivity=true - ``` - - >**TIP:** Read more about Kyma installation in the [official Kyma documentation](https://kyma-project.io/#/02-get-started/01-quick-install). - -### Run the Tests - -``` sh -make -f Makefile.test-application-conn-validator test-validator -``` - -By default, the tests clean up after themselves, removing all the previously created resources and the `test` namespace. - -> **CAUTION:** If the names of your existing resources are the same as the names used in the tests, running this command overrides or removes the existing resources. - -## Debugging - -### Running Without Cleanup - -To run the tests without removing all the created resources afterwards, run them in the debugging mode. - -1. To start the tests in the debugging mode, run: - - ``` shell - make -f Makefile.test-application-conn-validator test-validator-debug - ``` - -2. Once you've finished debugging, run: - - ``` shell - make -f Makefile.test-application-conn-validator clean-validator-test - ``` diff --git a/tests/components/application-connector/docs/application-gateway-tests.md b/tests/components/application-connector/docs/application-gateway-tests.md deleted file mode 100644 index 87a88f58d4e6..000000000000 --- a/tests/components/application-connector/docs/application-gateway-tests.md +++ /dev/null @@ -1,235 +0,0 @@ -# Application Gateway - -**Table of Contents** - -- [Application Gateway](#application-gateway) - - [Design and Architecture](#design-and-architecture) - - [Mock Application](#mock-application) - - [Certificates](#certificates) - - [API Exposed on Port `8080`](#api-exposed-on-port-8080) - - [API Exposed on Port `8090`](#api-exposed-on-port-8090) - - [API Exposed on Port `8091`](#api-exposed-on-port-8091) - - [Building](#building) - - [Running](#running) - - [Deploy a Kyma Cluster Locally](#deploy-a-kyma-cluster-locally) - - [Run the Tests](#run-the-tests) - - [Debugging](#debugging) - - [Running Locally](#running-locally) - - [Running Without Cleanup](#running-without-cleanup) - -## Design and Architecture - -The tests consist of: -- [Application CRs](../resources/charts/gateway-test/charts/test/templates/applications/) describing the test cases -- [Secrets](../resources/charts/gateway-test/charts/test/templates/applications/credentials) referenced by the Application CRs -- [Test runners](../test/application-gateway/) with various checks for the subsets of cases, grouped by the Application CRs -- [Mock application](../tools/external-api-mock-app/) which simulates the remote endpoints - -Additionally, the following resources are created in the cluster: -- [Service Account](../resources/charts/gateway-test/charts/test/templates/service-account.yml) used by the tests to read the Application CRs -- [Secrets](../resources/charts/gateway-test/charts/test/templates/applications/credentials) used by the Mock application to configure mTLS servers - -The tests are executed as a Kubernetes Job in a Kyma cluster where the tested Application Gateway is installed. -The test Job and the mock application deployment are in the `test` namespace. - -![Application Gateway tests architecture](assets/app-gateway-tests-architecture.svg) - -## Mock Application - -Mock application exposes the following APIs: -- API on port `8080` implementing various authentication methods and returning the `OAuth` and `CSRF` tokens -- API on port `8090` implementing the `mTLS` authentication and returning the `OAuth` tokens -- API on port `8091` implementing the `mTLS` authentication and using an expired server certificate - -### Certificates - -To test mTLS-related authentication methods, you need: -- Server certificate, key, and the CA certificate for the mock application -- Client certificate and key stored in a Secret accessed by Application Gateway - -All certificates are generated using the **generate-certs** target from the `Makefile`. -The target is executed before the tests are run, and it invokes [`generate-self-signed-certs.sh`](../scripts/generate-self-signed-certs.sh), which creates the CA root, server, and client certificates and keys. - -> **NOTE:** Since self-signed certificates are used, Application CRs have the **skipVerify: true** property set to `true` to force Application Gateway to skip certificate verification. - -### API Exposed on Port `8080` - -To get tokens for the `OAuth` and `CSRF` protected endpoints, we have the following API: -![8080 token API](assets/api-tokens.png) - -To test authentication methods, we have the following API: -![8080 authorisation methods API](assets/api-auth-methods.png) - -The credentials used for authentication, such as `user` and `password`, are [hardcoded](../tools/external-api-mock-app/config.go). - -### API Exposed on Port `8090` - -To get tokens for the `OAuth` protected endpoints, we have the following API: -![8090 token API](assets/api-tokens-mtls.png) - -To test authentication methods, we have the following API: -![8090 authorisation methods API](assets/api-auth-methods-mtls.png) - -The credentials used for authentication, such as `clientID`, are [hardcoded](../tools/external-api-mock-app/config.go). -The server key, server certificate, and the CA root certificate for port `8090` are defined in [this Secret](../resources/charts/gateway-test/charts/mock-app/templates/credentials/mtls-cert-secret.yml). - -> **NOTE:** Port `8090` must be excluded from redirection to Envoy, otherwise Application Gateway cannot pass the client certificate to the mock application. - -### API Exposed on Port `8091` - -This API is identical to the one exposed on port `8090`. -The HTTPS server on port `8091` uses an expired server certificate. -The server key, server certificate, and the CA root certificate for port `8091` are defined in [this Secret](../resources/charts/gateway-test/charts/mock-app/templates/credentials/expired-mtls-cert-secret.yaml). - -> **NOTE:** Port `8091` must be excluded from redirection to Envoy, otherwise Application Gateway cannot pass the client certificate to the mock application. - -## Building - -Pipelines build the mock application and the Gateway test using the **release** target from the `Makefile`. - -To build **and push** the Docker images of the tests and the mock application, run: - -``` sh -./scripts/local-build.sh {DOCKER_TAG} {DOCKER_PUSH_REPOSITORY} -``` - -This will build the following images: -- `{DOCKER_PUSH_REPOSITORY}/gateway-test:{DOCKER_TAG}` -- `{DOCKER_PUSH_REPOSITORY}/mock-app:{DOCKER_TAG}` - -## Running - -Tests can be run on any Kyma cluster with Application Gateway. - -Pipelines run the tests using the **test-gateway** target from the `Makefile`. - -### Deploy a Kyma Cluster Locally - -1. Provision a local Kubernetes cluster with k3d: - ```sh - k3d registry create kyma-registry --port 5001 - k3d cluster create kyma --kubeconfig-switch-context -p 80:80@loadbalancer -p 443:443@loadbalancer --registry-use kyma-registry - kubectl create ns kyma-system - ``` - -2. Install the minimal set of components required to run Application Gateway for either Kyma OS or SKR: - -
-
- - Kyma OS (standalone mode) - - - ```sh - kyma deploy --components-file ./resources/installation-config/mini-kyma-os.yaml - ``` - -
-
- - SKR (Compass mode) - - - ```bash - kyma deploy --components-file ./resources/installation-config/mini-kyma-skr.yaml - ``` - -
-
- - >**TIP:** Read more about Kyma installation in the [official Kyma documentation](https://kyma-project.io/#/02-get-started/01-quick-install). - -### Run the Tests - -``` sh -make -f Makefile.test-application-gateway test-gateway -``` - -By default, the tests clean up after themselves, removing all the previously created resources and the `test` namespace. - -> **CAUTION:** If the names of your existing resources are the same as the names used in the tests, running this command overrides or removes the existing resources. - -## Debugging - -### Running Locally - -> **CAUTION:** Because of the way it accesses the Application CRs, the test Job must run **on a cluster**. -> Application Gateway and the mock application can both be run locally. - -To run the mock application locally, follow these steps: - -1. Change all the **targetUrl** values in the [Application CRs](../resources/charts/gateway-test/charts/test/templates/applications/) to reflect the new application URL. For example, `http://localhost:8081/v1/api/unsecure/ok`. -2. Change all the **centralGatewayUrl** values to reflect the new Application Gateway URL. For example, `http://localhost:8080/positive-authorisation/unsecure-always-ok`. -3. Deploy all the resources in the cluster. - > **NOTE:** You can omit the test Job and the Central Gateway, but it's easier to just let them fail. -4. Build the mock application: - -
-
- - Docker - - - ```shell - export DOCKER_TAG="local" - export DOCKER_PUSH_REPOSITORY="{DOCKER_USERNAME}" - make image-mock-app - ``` - -
-
- - Local - - - Change the hardcoded application port in [`config.go`](../tools/external-api-mock-app/config.go), and run: - ```shell - go build ./tools/external-api-mock-app/ - ``` -
-
-5. Run the mock application: - -
-
- - Docker - - - ```shell - docker run -p 8180:8080 -p 8190:8090 -v "$PWD/resources/charts/gateway-test/charts/test/certs/positive:/etc/secret-volume:ro" -v "$PWD/resources/charts/gateway-test/charts/test/certs/negative:/etc/expired-server-cert-volume:ro" "$DOCKER_PUSH_REPOSITORY/mock-app:$DOCKER_TAG" - ``` - -
-
- - Local - - - ```shell - ./external-api-mock-app - ``` - > **CAUTION:** For the certificates to work, you must copy them from `./k8s/gateway-test/certs` to `/etc/secret-volume`. - -
-
-6. Run [Application Gateway](https://github.com/kyma-project/kyma/tree/main/components/central-application-gateway) with the `-kubeConfig {PATH_TO_YOUR_KUBECONFIG_FILE}` parameter. - -You can now send requests to Application Gateway, and debug its behavior locally. - -### Running Without Cleanup - -To run the tests without removing all the created resources afterwards, run them in the debugging mode. - -1. To start the tests in the debugging mode, run: - - ``` shell - make disable-sidecar-for-mtls-test test-gateway-debug - ``` - -2. Once you've finished debugging, run: - - ``` shell - make clean-gateway-test enable-sidecar-after-mtls-test - ``` - diff --git a/tests/components/application-connector/docs/assets/api-auth-methods-mtls.png b/tests/components/application-connector/docs/assets/api-auth-methods-mtls.png deleted file mode 100644 index 743a1d4c28be..000000000000 Binary files a/tests/components/application-connector/docs/assets/api-auth-methods-mtls.png and /dev/null differ diff --git a/tests/components/application-connector/docs/assets/api-auth-methods.png b/tests/components/application-connector/docs/assets/api-auth-methods.png deleted file mode 100644 index 29566ba072b0..000000000000 Binary files a/tests/components/application-connector/docs/assets/api-auth-methods.png and /dev/null differ diff --git a/tests/components/application-connector/docs/assets/api-tokens-mtls.png b/tests/components/application-connector/docs/assets/api-tokens-mtls.png deleted file mode 100644 index 61fe10fce4ae..000000000000 Binary files a/tests/components/application-connector/docs/assets/api-tokens-mtls.png and /dev/null differ diff --git a/tests/components/application-connector/docs/assets/api-tokens.png b/tests/components/application-connector/docs/assets/api-tokens.png deleted file mode 100644 index 386096e8b250..000000000000 Binary files a/tests/components/application-connector/docs/assets/api-tokens.png and /dev/null differ diff --git a/tests/components/application-connector/docs/assets/app-gateway-tests-architecture.svg b/tests/components/application-connector/docs/assets/app-gateway-tests-architecture.svg deleted file mode 100644 index e148166ac865..000000000000 --- a/tests/components/application-connector/docs/assets/app-gateway-tests-architecture.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - -
Kyma cluster
Kyma cluster
4
4
kyma-system Namespace
kyma-system Namespace
Application Gateway
Application Gateway
test Namespace
test Namespace
Application CR
- service 1 (test case 1)
- service 2 (test case 2)
- ...                                
Application CR...
mock application (remote endpoints)
mock application (remo...
App Gateway test Pod
App Gateway test...
1
1
2
2
Text is not SVG - cannot display
\ No newline at end of file diff --git a/tests/components/application-connector/docs/assets/compass-runtime-agent-tests-architecture.svg b/tests/components/application-connector/docs/assets/compass-runtime-agent-tests-architecture.svg deleted file mode 100644 index dc02a5e511ea..000000000000 --- a/tests/components/application-connector/docs/assets/compass-runtime-agent-tests-architecture.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - -
Kyma cluster
Kyma cluster
4
4
kyma-system Namespace
kyma-system Namespace
Compass Runtime Agent
Compass Runtime Agent
test Namespace
test Namespace
Application CR
- service 1 (test case 1)
- service 2 (test case 2)
- ...                                
Application CR...
Compass Runtime Agent test Pod
Compass Runtime Agent test Pod
CompassConnection CR
CompassConnection CR
Compass Runtime Agent certificates Secret
Compass Runtime Agent certi...
1
1
3
3
4
4
5
5
2
2
6
6
CA root certificate Secret
CA root certificate Secret
7
7
4
4
Compass test environment
Compass test environment
Connector
Connector
Director
Director
Text is not SVG - cannot display
\ No newline at end of file diff --git a/tests/components/application-connector/docs/assets/connectivity-validator-tests-architecture.svg b/tests/components/application-connector/docs/assets/connectivity-validator-tests-architecture.svg deleted file mode 100644 index 8b852313c2c5..000000000000 --- a/tests/components/application-connector/docs/assets/connectivity-validator-tests-architecture.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - -
Kyma cluster
Kyma cluster
4
4
kyma-system Namespace
kyma-system Namespace
Connectivity Validator
Connectivity Validator
test Namespace
test Namespace
mock service (echoservice)
mock service (echose...
Connectivity Validator test Pod
Connectivity Validat...
1
1
2
2
Text is not SVG - cannot display
\ No newline at end of file diff --git a/tests/components/application-connector/docs/assets/mock-app-mtls-spec.yaml b/tests/components/application-connector/docs/assets/mock-app-mtls-spec.yaml deleted file mode 100644 index 2852c73d8a38..000000000000 --- a/tests/components/application-connector/docs/assets/mock-app-mtls-spec.yaml +++ /dev/null @@ -1,51 +0,0 @@ -openapi: 3.0.3 -info: - title: Mock Application for testing Application Gateway - description: |- - This is an API of Mock Application supporting Application Gateway Tests. - version: 1.0.11 -tags: - - name: OAuth tokens - description: Endpoints returning OAuth tokens - - name: CSRF - description: Endpoints protected by CSRF method - - name: No authentication - description: Endpoints not protected by any authentication method -paths: - /v1/api/mtls-oauth/token: - post: - tags: - - OAuth tokens - summary: Returns valid OAuth token - operationId: oauthToken - responses: - '200': - description: client_id and grant_type values correct - '401': - description: Bad client_id or grant_type value - - /v1/api/mtls/ok: - get: - tags: - - No authentication - summary: Returns status 200 OK if authorisation is successful - operationId: onBasicAuth - responses: - '200': - description: Authorisation successful - '401': - description: Client certificate is not valid - /v1/api/csrf-mtls/ok: - get: - tags: - - CSRF - summary: Returns status 200 OK if authorisation is successful - operationId: onCsrfOAuth - responses: - '200': - description: Authorisation successful - '401': - description: Client certificate is not valid - '403': - description: Username or password doesn't match or invalid CSRF token passed - diff --git a/tests/components/application-connector/docs/assets/mock-app-spec.yaml b/tests/components/application-connector/docs/assets/mock-app-spec.yaml deleted file mode 100644 index 53877cb2c928..000000000000 --- a/tests/components/application-connector/docs/assets/mock-app-spec.yaml +++ /dev/null @@ -1,186 +0,0 @@ -openapi: 3.0.3 -info: - title: Mock Application for testing Application Gateway - description: |- - This is an API of Mock Application supporting Application Gateway Tests. - version: 1.0.11 -tags: - - name: OAuth tokens - description: Endpoints returning OAuth tokens - - name: CSRF tokens - description: Endpoints returning CSRF tokens - - name: No authentication - description: Endpoints not protected by any authentication method - - name: Basic Authentication - description: Endpoints protected by Basic Authentication - - name: OAuth - description: Endpoints protected by OAuth method expecting valid OAuth token - - name: Basic Authentication and CSRF token - description: Endpoints protected by Basic Authentication and CSRF methods - - name: OAuth and CSRF - description: Endpoints protected by OAuth and CSRF methods - - name: Basic Authentication and request parameters - description: Endpoints protected by Basic Authentication and additional request parameters -paths: - /v1/api/oauth/token: - post: - tags: - - OAuth tokens - summary: Returns valid OAuth token - operationId: oauthToken - responses: - '200': - description: client_id, client_secret and grant_type values correct - '401': - description: Bad client_id, client_secret or grant_type value - /v1/api/oauth/bad-token: - post: - tags: - - OAuth tokens - summary: Returns invalid OAuth token - operationId: oauthBadToken - responses: - '200': - description: client_id, client_secret and grant_type values correct - '401': - description: Bad client_id, client_secret or grant_type value - /v1/api/csrf/token: - get: - tags: - - CSRF tokens - summary: Returns valid CSRF token - operationId: csrfToken - responses: - '200': - description: Token generated successfully - /v1/api/csrf/bad-token: - get: - tags: - - CSRF tokens - summary: Returns invalid CSRF token - responses: - '200': - description: Token generated successfully - - - /v1/api/unsecure/ok: - get: - tags: - - No authentication - summary: Returns status 200 OK - operationId: okNoAuth - responses: - '200': - description: Successful operation - /v1/api/unsecure/echo: - put: - tags: - - No authentication - summary: Responds with request body sent to the endpoint - operationId: echoNoAuthPut - responses: - '200': - description: Successful operation - post: - tags: - - No authentication - summary: Responds with request body sent to the endpoint - operationId: echoNoAuthPost - responses: - '200': - description: Successful operation - delete: - tags: - - No authentication - summary: Responds with request body sent to the endpoint - operationId: echoNoAuthDelete - responses: - '200': - description: Successful operation - /v1/api/unsecure/code/{code}: - get: - tags: - - No authentication - parameters: - - in: path - name: code - schema: - type: integer - required: true - summary: Responds with status code specified in the {code} parameter - operationId: codeNoAuth - responses: - '200': - description: Successful operation - /v1/api/unsecure/timeout: - get: - tags: - - No authentication - summary: Sleeps for 2 minutes before responding - operationId: timeoutNoAuth - responses: - '200': - description: Successful operation - /v1/api/basic/ok: - get: - tags: - - Basic Authentication - summary: Returns status 200 OK if authentication is successful - operationId: onBasicAuth - responses: - '200': - description: Authentication successful - '403': - description: Username or password doesn't match - /v1/api/oauth/ok: - get: - tags: - - OAuth - summary: Returns status 200 OK if authentication is successful - operationId: onOAuth - responses: - '200': - description: Authentication successful - '401': - description: Authorization header missing or contains invalid token - - /v1/api/csrf-basic/ok: - get: - tags: - - Basic Authentication and CSRF token - summary: Returns status 200 OK if authentication is successful - operationId: onCsrfBasic - responses: - '200': - description: Authentication successful - '403': - description: Username or password doesn't match or invalid CSRF token passed - - /v1/api/csrf-oauth/ok: - get: - tags: - - OAuth and CSRF - summary: Returns status 200 OK if authentication is successful - operationId: onCsrfOAuth - responses: - '200': - description: Authentication successful - '401': - description: Authorization header missing or contains invalid token - '403': - description: Username or password doesn't match or invalid CSRF token passed - - /v1/api/request-parameters-basic/ok: - get: - tags: - - Basic Authentication and request parameters - summary: Returns status 200 OK if authentication is successful - operationId: onRequestParamsBasic - responses: - '200': - description: Authentication successful - '400': - description: Expected headers and request params not passed - '403': - description: Username or password doesn't match - diff --git a/tests/components/application-connector/docs/compass-runtime-agent-tests.md b/tests/components/application-connector/docs/compass-runtime-agent-tests.md deleted file mode 100644 index 0bd25c9c7632..000000000000 --- a/tests/components/application-connector/docs/compass-runtime-agent-tests.md +++ /dev/null @@ -1,140 +0,0 @@ -# Compass Runtime Agent - -**Table of Contents** - -- [Compass Runtime Agent](#compass-runtime-agent) - - [Design and Architecture](#design-and-architecture) - - [Building](#building) - - [Running](#running) - - [Deploy a Kyma Cluster Locally](#deploy-a-kyma-cluster-locally) - - [Test Setup - Compass Runtime Agent Configuration](#test-setup---compass-runtime-agent-configuration) - - [Run the Tests](#run-the-tests) - - [Debugging](#debugging) - - [Running Without Cleanup](#running-without-cleanup) - - [Debugging in the IDE](#debugging-in-the-ide) - -## Design and Architecture - -The tests consist of: -- [Test resources](../resources/charts/compass-runtime-agent-test/) used to perform the test -- [Test runner](../test/application-connectivity-validator/) with all the test cases - -The tests are executed as a Kubernetes Job in a Kyma cluster where the tested Compass Runtime Agent is installed. The test Job is deployed in the `test` namespace. - -![Compass Runtime Agent tests architecture](assets/compass-runtime-agent-tests-architecture.svg) - -The interactions between components are the following: - -1. Compass Runtime Agent periodically fetches certificates from Compass Connector. -2. Compass Runtime Agent periodically fetches applications from Compass Director. -3. Compass Runtime Agent Test sends GraphQL mutations to Compass Director to create, modify, or delete Applications. -4. Compass Runtime Agent Test verifies whether corresponding Application CRs were created, modified, or deleted. -5. Compass Runtime Agent Test verifies whether the Secret with certificates used for communication with Director was created. -6. Compass Runtime Agent Test verifies whether the Secret with the CA root certificate used by Istio Gateway was created. -7. Compass Runtime Agent Test verifies the content of the CompassConnection CR. - -## Building - -Pipelines build the Compass Runtime Agent test using the **release** target from the `Makefile`. - -To build **and push** the Docker images of the tests, run: - -```bash -./scripts/local-build.sh {DOCKER_TAG} {DOCKER_PUSH_REPOSITORY} -``` - -This builds the following images: -- `{DOCKER_PUSH_REPOSITORY}/compass-runtime-agent-test:{DOCKER_TAG}` - -## Running - -Tests can be run on any Kyma cluster with Compass Runtime Agent. - -Pipelines run the tests using the **test-compass-runtime-agent** target from the `Makefile`. - -### Deploy a Kyma Cluster Locally - -1. Provision a local Kubernetes cluster with k3d: - ```bash - k3d registry create kyma-registry --port 5001 - k3d cluster create kyma --kubeconfig-switch-context -p 80:80@loadbalancer -p 443:443@loadbalancer --registry-use kyma-registry - kubectl create ns kyma-system - ``` - -2. Install the minimal set of components required to run Compass Runtime Agent **for Kyma SKR (Compass mode)**: - - ```bash - kyma deploy --components-file ./resources/installation-config/mini-kyma-skr.yaml --value global.disableLegacyConnectivity=true --value compassRuntimeAgent.director.proxy.insecureSkipVerify=true - ``` - - >**TIP:** Read more about [Kyma installation](https://kyma-project.io/#/02-get-started/01-quick-install). - -### Test Setup - Compass Runtime Agent Configuration - -The [`values.yaml`](../resources/charts/compass-runtime-agent-test/values.yaml) file contains environment variables that are used in the Compass Runtime Agent tests. These values can be modified as needed. - -- **APP_DIRECTOR_URL** - Compass Director URL -- **APP_TESTING_TENANT** - Tenant used in GraphQL calls -- **APP_SKIP_DIRECTOR_CERT_VERIFICATION** - Skip certificate verification on the Director side -- **APP_OAUTH_CREDENTIALS_SECRET_NAME** - Secret name for Compass OAuth credentials -- **APP_OAUTH_CREDENTIALS_NAMESPACE** - Namespace for Compass OAuth credentials - -### Run the Tests - -1. Before running the test export the following environment variables - - **COMPASS_HOST** - host running Compass - - **COMPASS_CLIENT_ID** - client ID used for fetching authorization tokens - - **COMPASS_CLIENT_SECRET** - client Secret used for fetching authorization tokens - -2. To start the tests, run: - - ```bash - make test-compass-runtime-agent - ``` - -By default, the tests clean up after themselves, removing all the previously created resources and the `test` namespace. - -> **CAUTION:** If the names of your existing resources are the same as the names used in the tests, running this command overrides or removes the existing resources. - -## Debugging - -### Running Without Cleanup - -To run the tests without removing all the created resources afterwards, run them in the debugging mode. - -1. To start the tests in the debugging mode, run: - - ```bash - make test-compass-runtime-agent-debug - ``` - -2. Once you've finished debugging, run: - - ```bash - make clean-test-compass-runtime-agent-test - ``` - -### Debugging in the IDE - -To run the test in your IDE, perform the following steps. - -1. To prepare the cluster for debugging, run the test without cleanup: - - ```bash - make test-compass-runtime-agent-debug - ``` - -2. Before starting debugger in your IDE export the following environment variables: - - `KUBECONFIG={Your cluster kubeconfig}` - - `APP_DIRECTOR_URL=https://compass-gateway-auth-oauth.{COMPASS_HOST}/director/graphql` - - `APP_TESTING_TENANT=3e64ebae-38b5-46a0-b1ed-9ccee153a0ae` - - `APP_OAUTH_CREDENTIALS_SECRET_NAME=oauth-compass-credentials` - - `APP_OAUTH_CREDENTIALS_NAMESPACE=test` - -3. Start the debugging session. - -4. Once you've finished debugging, run: - - ```bash - make clean-test-compass-runtime-agent-test - ``` diff --git a/tests/components/application-connector/go.mod b/tests/components/application-connector/go.mod deleted file mode 100644 index 299191758b2c..000000000000 --- a/tests/components/application-connector/go.mod +++ /dev/null @@ -1,103 +0,0 @@ -module github.com/kyma-project/kyma/tests/components/application-connector - -go 1.18 - -require ( - github.com/avast/retry-go v3.0.0+incompatible - github.com/go-http-utils/logger v0.0.0-20161128092850-f3a42dcdeae6 - github.com/google/uuid v1.3.1 - github.com/gorilla/mux v1.8.0 - github.com/hashicorp/go-multierror v1.1.1 - github.com/kyma-incubator/compass/components/director v0.0.0-20240311095305-43ec866d6b0c - github.com/kyma-project/kyma/components/central-application-gateway v0.0.0-20230130154909-4c81ab2cee61 - github.com/kyma-project/kyma/components/compass-runtime-agent v0.0.0-20220927112044-a548531152a1 - github.com/matryer/is v1.4.0 - github.com/pkg/errors v0.9.1 - github.com/sirupsen/logrus v1.9.3 - github.com/stretchr/testify v1.8.4 - github.com/vrischmann/envconfig v1.3.0 - k8s.io/api v0.26.9 - k8s.io/apimachinery v0.26.9 - k8s.io/client-go v0.26.9 -) - -require ( - github.com/99designs/gqlgen v0.11.3 // indirect - github.com/Masterminds/goutils v1.1.1 // indirect - github.com/Masterminds/semver/v3 v3.2.0 // indirect - github.com/Masterminds/sprig/v3 v3.2.3 // indirect - github.com/agnivade/levenshtein v1.1.1 // indirect - github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect - github.com/davecgh/go-spew v1.1.1 // indirect - github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 // indirect - github.com/emicklei/go-restful/v3 v3.9.0 // indirect - github.com/evanphx/json-patch v4.12.0+incompatible // indirect - github.com/form3tech-oss/jwt-go v3.2.5+incompatible // indirect - github.com/go-logr/logr v1.2.3 // indirect - github.com/go-openapi/jsonpointer v0.19.5 // indirect - github.com/go-openapi/jsonreference v0.20.0 // indirect - github.com/go-openapi/swag v0.22.3 // indirect - github.com/go-ozzo/ozzo-validation/v4 v4.3.0 // indirect - github.com/goccy/go-json v0.10.2 // indirect - github.com/gogo/protobuf v1.3.2 // indirect - github.com/golang/protobuf v1.5.3 // indirect - github.com/google/gnostic v0.5.7-v3refs // indirect - github.com/google/go-cmp v0.5.9 // indirect - github.com/google/gofuzz v1.2.0 // indirect - github.com/hashicorp/errwrap v1.1.0 // indirect - github.com/huandu/xstrings v1.4.0 // indirect - github.com/imdario/mergo v0.3.14 // indirect - github.com/josharian/intern v1.0.0 // indirect - github.com/json-iterator/go v1.1.12 // indirect - github.com/kyma-incubator/compass/components/hydrator v0.0.0-20240228074947-02a81b1e3bf8 // indirect - github.com/lestrrat-go/backoff/v2 v2.0.8 // indirect - github.com/lestrrat-go/blackmagic v1.0.2 // indirect - github.com/lestrrat-go/httpcc v1.0.1 // indirect - github.com/lestrrat-go/iter v1.0.2 // indirect - github.com/lestrrat-go/jwx v1.2.28 // indirect - github.com/lestrrat-go/option v1.0.1 // indirect - github.com/mailru/easyjson v0.7.7 // indirect - github.com/mitchellh/copystructure v1.1.2 // indirect - github.com/mitchellh/reflectwalk v1.0.1 // 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/onrik/logrus v0.11.0 // indirect - github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/shopspring/decimal v1.2.0 // indirect - github.com/spf13/cast v1.5.0 // indirect - github.com/spf13/pflag v1.0.5 // indirect - github.com/stretchr/objx v0.5.0 // indirect - github.com/tidwall/gjson v1.17.0 // indirect - github.com/tidwall/match v1.1.1 // indirect - github.com/tidwall/pretty v1.2.0 // indirect - github.com/tidwall/sjson v1.2.5 // indirect - github.com/vektah/gqlparser/v2 v2.1.0 // indirect - github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect - github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect - github.com/xeipuuv/gojsonschema v1.2.0 // indirect - golang.org/x/crypto v0.17.0 // indirect - golang.org/x/net v0.17.0 // indirect - golang.org/x/oauth2 v0.11.0 // indirect - golang.org/x/sys v0.15.0 // indirect - golang.org/x/term v0.15.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.31.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.80.1 // indirect - k8s.io/kube-openapi v0.0.0-20221012153701-172d655c2280 // indirect - k8s.io/utils v0.0.0-20221128185143-99ec85e7a448 // indirect - sigs.k8s.io/json v0.0.0-20220713155537-f223a00ba0e2 // indirect - sigs.k8s.io/structured-merge-diff/v4 v4.2.3 // indirect - sigs.k8s.io/yaml v1.3.0 // indirect -) - -replace ( - golang.org/x/crypto => golang.org/x/crypto v0.0.0-20221012134737-56aed061732a - golang.org/x/net => golang.org/x/net v0.0.0-20221014081412-f15817d10f9b - golang.org/x/text => golang.org/x/text v0.3.8 -) diff --git a/tests/components/application-connector/go.sum b/tests/components/application-connector/go.sum deleted file mode 100644 index badba2239278..000000000000 --- a/tests/components/application-connector/go.sum +++ /dev/null @@ -1,364 +0,0 @@ -cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -github.com/99designs/gqlgen v0.11.3 h1:oFSxl1DFS9X///uHV3y6CEfpcXWrDUxVblR4Xib2bs4= -github.com/99designs/gqlgen v0.11.3/go.mod h1:RgX5GRRdDWNkh4pBrdzNpNPFVsdoUFY2+adM6nb1N+4= -github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI= -github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= -github.com/Masterminds/semver/v3 v3.2.0 h1:3MEsd0SM6jqZojhjLWWeBY+Kcjy9i6MQAeY7YgDP83g= -github.com/Masterminds/semver/v3 v3.2.0/go.mod h1:qvl/7zhW3nngYb5+80sSMF+FG2BjYrf8m9wsX0PNOMQ= -github.com/Masterminds/sprig/v3 v3.2.3 h1:eL2fZNezLomi0uOLqjQoN6BfsDD+fyLtgbJMAj9n6YA= -github.com/Masterminds/sprig/v3 v3.2.3/go.mod h1:rXcFaZ2zZbLRJv/xSysmlgIM1u11eBaRMhvYXJNkGuM= -github.com/agnivade/levenshtein v1.0.1/go.mod h1:CURSv5d9Uaml+FovSIICkLbAUZ9S4RqaHDIsdSBg7lM= -github.com/agnivade/levenshtein v1.0.3/go.mod h1:4SFRZbbXWLF4MU1T9Qg0pGgH3Pjs+t6ie5efyrwRJXs= -github.com/agnivade/levenshtein v1.1.1 h1:QY8M92nrzkmr798gCo3kmMyqXFzdQVpxLlGPRBij0P8= -github.com/agnivade/levenshtein v1.1.1/go.mod h1:veldBMzWxcCG2ZvUTKD2kJNRdCk5hVbJomOvKkmgYbo= -github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883 h1:bvNMNQO63//z+xNgfBlViaCIJKLlCJ6/fmUseuG0wVQ= -github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8= -github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0 h1:jfIu9sQUG6Ig+0+Ap1h4unLjW6YQJpKZVmUzxsD4E/Q= -github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0/go.mod h1:t2tdKJDJF9BV14lnkjHmOQgcvEKgtqs5a1N3LNdJhGE= -github.com/asaskevich/govalidator v0.0.0-20200108200545-475eaeb16496/go.mod h1:oGkLhpf+kjZl6xBf758TQhh5XrAeiJv/7FRz/2spLIg= -github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so= -github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= -github.com/avast/retry-go v3.0.0+incompatible h1:4SOWQ7Qs+oroOTQOYnAHqelpCO0biHSxpiH9JdtuBj0= -github.com/avast/retry-go v3.0.0+incompatible/go.mod h1:XtSnn+n/sHqQIpZ10K1qAevBhOOCWBLXXy3hyiqqBrY= -github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= -github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= -github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= -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/decred/dcrd/crypto/blake256 v1.0.1/go.mod h1:2OfgNZ5wDpcsFmHmCK5gZTPcCXqlm2ArzUIkw9czNJo= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 h1:8UrgZ3GkP4i/CLijOJx79Yu+etlyjdBU4sfcs2WYQMs= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0/go.mod h1:v57UDF4pDQJcEfFUCRop3lJL149eHGSe9Jvczhzjo/0= -github.com/dgryski/trifles v0.0.0-20190318185328-a8d75aae118c/go.mod h1:if7Fbed8SFyPtHLHbg49SI7NAdJiC5WIA09pe59rfAA= -github.com/dgryski/trifles v0.0.0-20200323201526-dd97f9abfb48 h1:fRzb/w+pyskVMQ+UbP35JkH8yB7MYb4q/qhBarqZE6g= -github.com/dgryski/trifles v0.0.0-20200323201526-dd97f9abfb48/go.mod h1:if7Fbed8SFyPtHLHbg49SI7NAdJiC5WIA09pe59rfAA= -github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815/go.mod h1:WwZ+bS3ebgob9U8Nd0kOddGdZWjyMGR8Wziv+TBNwSE= -github.com/emicklei/go-restful/v3 v3.9.0 h1:XwGDlfxEnQZzuopoqxwSEllNcCOM9DhhFyhFIIGKwxE= -github.com/emicklei/go-restful/v3 v3.9.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= -github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= -github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -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/form3tech-oss/jwt-go v3.2.5+incompatible h1:/l4kBbb4/vGSsdtB5nUe8L7B9mImVMaBPw9L/0TBHU8= -github.com/form3tech-oss/jwt-go v3.2.5+incompatible/go.mod h1:pbq4aXjuKjdthFRnoDwaVPLA+WlJuPGy+QneDUgJi2k= -github.com/frankban/quicktest v1.14.4 h1:g2rn0vABPOOXmZUj+vbmUp0lPoXEMuhTpIluN0XL9UY= -github.com/go-chi/chi v3.3.2+incompatible/go.mod h1:eB3wogJHnLi3x/kFX2A+IbTBlXxmMeXJVKy9tTv1XzQ= -github.com/go-http-utils/logger v0.0.0-20161128092850-f3a42dcdeae6 h1:R/ypabUA7vskKTRSlgP6rMUHTU6PBRgIcHVSU9qQ6qM= -github.com/go-http-utils/logger v0.0.0-20161128092850-f3a42dcdeae6/go.mod h1:CpBLxS3WrxouNECP/Y1A3i6qDnUYs8BvcXjgOW4Vqcw= -github.com/go-logr/logr v1.2.0/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.2.3 h1:2DntVwHkVopvECVRSlL5PSo9eG+cAkDCuckLubN+rq0= -github.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= -github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY= -github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= -github.com/go-openapi/jsonreference v0.20.0 h1:MYlu0sBgChmCfJxxUKZ8g1cPWFOB37YSZqewK7OKeyA= -github.com/go-openapi/jsonreference v0.20.0/go.mod h1:Ag74Ico3lPc+zR+qjn4XBUmXymS4zJbYVCZmcgkasdo= -github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= -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-ozzo/ozzo-validation/v4 v4.3.0 h1:byhDUpfEwjsVQb1vBunvIjh2BHQ9ead57VkAEY4V+Es= -github.com/go-ozzo/ozzo-validation/v4 v4.3.0/go.mod h1:2NKgrcHl3z6cJs+3Oo940FPRiTzuqKbvfrL2RxCj6Ew= -github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= -github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= -github.com/gogo/protobuf v1.0.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= -github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= -github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= -github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= -github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= -github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= -github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= -github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= -github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= -github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= -github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= -github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= -github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= -github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= -github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= -github.com/google/gnostic v0.5.7-v3refs h1:FhTMOKj2VhjpouxvWJAV1TL304uMlb9zcDqkl6cEI54= -github.com/google/gnostic v0.5.7-v3refs/go.mod h1:73MKFl6jIHelAJNaBGFzt3SPtZULs9dYrGFt8OiIsHQ= -github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= -github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= -github.com/google/go-cmp v0.5.9/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/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4= -github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/gorilla/context v0.0.0-20160226214623-1ea25387ff6f/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= -github.com/gorilla/mux v1.6.1/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= -github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= -github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= -github.com/gorilla/websocket v1.2.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= -github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= -github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= -github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= -github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= -github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= -github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= -github.com/huandu/xstrings v1.3.3/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= -github.com/huandu/xstrings v1.4.0 h1:D17IlohoQq4UcpqD7fDk80P7l+lwAmlFaBHgOipl2FU= -github.com/huandu/xstrings v1.4.0/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= -github.com/imdario/mergo v0.3.11/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= -github.com/imdario/mergo v0.3.14 h1:fOqeC1+nCuuk6PKQdg9YmosXX7Y7mHX6R/0ZldI9iHo= -github.com/imdario/mergo v0.3.14/go.mod h1:WBLT9ZmE3lPoWsEzCh9LPo3TiwVN+ZKEjmz+hD27ysY= -github.com/jmoiron/sqlx v1.3.5 h1:vFFPA71p1o5gAeqtEAwLU4dnX2napprKtHr7PYIcN3g= -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.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= -github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= -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/kyma-incubator/compass/components/director v0.0.0-20240311095305-43ec866d6b0c h1:zHZGiCf0v8P9f9ADzB+fDP5cA5KTFQuX2ZN9dPrVoqw= -github.com/kyma-incubator/compass/components/director v0.0.0-20240311095305-43ec866d6b0c/go.mod h1:m2uughFQ1t+J24NGz5N3E87n6HHmT+qzsXlpzxHnjKY= -github.com/kyma-incubator/compass/components/hydrator v0.0.0-20240228074947-02a81b1e3bf8 h1:Ig4/5zfGADb7oCL6YQ4ZkHs4WADhPDYX+NcRWBPNxL4= -github.com/kyma-incubator/compass/components/hydrator v0.0.0-20240228074947-02a81b1e3bf8/go.mod h1:E8Wf/ZyWvi48YsKZT0O9AVWLJI41Eakfk5xHz1mLeK4= -github.com/kyma-project/kyma/components/central-application-gateway v0.0.0-20230130154909-4c81ab2cee61 h1:iviPUIyUTMKA322amhFURlXbIbj9NrojpvJFDI+DtnQ= -github.com/kyma-project/kyma/components/central-application-gateway v0.0.0-20230130154909-4c81ab2cee61/go.mod h1:NL5E+cv7oyD8xJtDywLrHnkublvqifMBt5HFdw94adc= -github.com/kyma-project/kyma/components/compass-runtime-agent v0.0.0-20220927112044-a548531152a1 h1:zhIQX99vZIS5nlWIQZE6nIVB3w7W+vSgE5r9+VxLZGE= -github.com/kyma-project/kyma/components/compass-runtime-agent v0.0.0-20220927112044-a548531152a1/go.mod h1:D80/HUyVanrVfAcUOt8xRWp5oZwd1IK4SAg0A9Hlj+8= -github.com/lestrrat-go/backoff/v2 v2.0.8 h1:oNb5E5isby2kiro9AgdHLv5N5tint1AnDVVf2E2un5A= -github.com/lestrrat-go/backoff/v2 v2.0.8/go.mod h1:rHP/q/r9aT27n24JQLa7JhSQZCKBBOiM/uP402WwN8Y= -github.com/lestrrat-go/blackmagic v1.0.2 h1:Cg2gVSc9h7sz9NOByczrbUvLopQmXrfFx//N+AkAr5k= -github.com/lestrrat-go/blackmagic v1.0.2/go.mod h1:UrEqBzIR2U6CnzVyUtfM6oZNMt/7O7Vohk2J0OGSAtU= -github.com/lestrrat-go/httpcc v1.0.1 h1:ydWCStUeJLkpYyjLDHihupbn2tYmZ7m22BGkcvZZrIE= -github.com/lestrrat-go/httpcc v1.0.1/go.mod h1:qiltp3Mt56+55GPVCbTdM9MlqhvzyuL6W/NMDA8vA5E= -github.com/lestrrat-go/iter v1.0.2 h1:gMXo1q4c2pHmC3dn8LzRhJfP1ceCbgSiT9lUydIzltI= -github.com/lestrrat-go/iter v1.0.2/go.mod h1:Momfcq3AnRlRjI5b5O8/G5/BvpzrhoFTZcn06fEOPt4= -github.com/lestrrat-go/jwx v1.2.28 h1:uadI6o0WpOVrBSf498tRXZIwPpEtLnR9CvqPFXeI5sA= -github.com/lestrrat-go/jwx v1.2.28/go.mod h1:nF+91HEMh/MYFVwKPl5HHsBGMPscqbQb+8IDQdIazP8= -github.com/lestrrat-go/option v1.0.0/go.mod h1:5ZHFbivi4xwXxhxY9XHDe2FHo6/Z7WWmtT7T5nBBp3I= -github.com/lestrrat-go/option v1.0.1 h1:oAzP2fvZGQKWkvHa1/SAcFolBEca1oN+mQ7eooNBEYU= -github.com/lestrrat-go/option v1.0.1/go.mod h1:5ZHFbivi4xwXxhxY9XHDe2FHo6/Z7WWmtT7T5nBBp3I= -github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= -github.com/logrusorgru/aurora v0.0.0-20200102142835-e9ef32dff381/go.mod h1:7rIyQOR62GCctdiQpZ/zOJlFyk6y+94wXzv6RNZgaR4= -github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= -github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= -github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= -github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= -github.com/matryer/is v1.4.0 h1:sosSmIWwkYITGrxZ25ULNDeKiMNzFSr4V/eqBQP0PeE= -github.com/matryer/is v1.4.0/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU= -github.com/matryer/moq v0.0.0-20200106131100-75d0ddfc0007/go.mod h1:9ELz6aaclSIGnZBoaSLZ3NAl1VTufbOrXBPvtcy6WiQ= -github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= -github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= -github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= -github.com/mitchellh/copystructure v1.0.0/go.mod h1:SNtv71yrdKgLRyLFxmLdkAbkKEFWgYaq1OVrnRcwhnw= -github.com/mitchellh/copystructure v1.1.2 h1:Th2TIvG1+6ma3e/0/bopBKohOTY7s4dA8V2q4EUcBJ0= -github.com/mitchellh/copystructure v1.1.2/go.mod h1:EBArHfARyrSWO/+Wyr9zwEkc6XMFB9XyNgFNmRkZZU4= -github.com/mitchellh/mapstructure v0.0.0-20180203102830-a4e142e9c047/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= -github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= -github.com/mitchellh/reflectwalk v1.0.1 h1:FVzMWA5RllMAKIdUSC8mdWo3XtwoecrH79BY70sEEpE= -github.com/mitchellh/reflectwalk v1.0.1/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= -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/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= -github.com/onrik/logrus v0.11.0 h1:pu+BCaWL36t0yQaj/2UHK2erf88dwssAKOT51mxPUVs= -github.com/onrik/logrus v0.11.0/go.mod h1:fO2vlZwIdti6PidD3gV5YKt9Lq5ptpnP293RAe1ITwk= -github.com/onsi/ginkgo/v2 v2.4.0 h1:+Ig9nvqgS5OBSACXNk15PLdp0U9XPYROt9CFzVdFGIs= -github.com/onsi/gomega v1.23.0 h1:/oxKu9c2HVap+F3PfKort2Hw5DEU+HGlW8n+tguWsys= -github.com/opentracing/basictracer-go v1.0.0/go.mod h1:QfBfYuafItcjQuMwinw9GhYKwFXS9KnPs5lxoYwgW74= -github.com/opentracing/opentracing-go v1.0.2/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= -github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -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/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/rogpeppe/go-internal v1.6.1 h1:/FiVV8dS/e+YqF2JvO3yXRFbBLTIuSDkuC7aBOAvL+k= -github.com/rs/cors v1.6.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= -github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0= -github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= -github.com/shopspring/decimal v1.2.0 h1:abSATXmQEYyShuxI4/vyW3tV1MrKAJzCZ/0zLUXYbsQ= -github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= -github.com/shurcooL/httpfs v0.0.0-20171119174359-809beceb2371/go.mod h1:ZY1cvUeJuFPAdZ/B6v7RHavJWZn2YPVFQ1OSXhCGOkg= -github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= -github.com/shurcooL/vfsgen v0.0.0-20180121065927-ffb13db8def0/go.mod h1:TrYk7fJVaAttu97ZZKrO9UbRa8izdowaMIZcxYMbVaw= -github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= -github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= -github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= -github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w= -github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU= -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/stoewer/go-strcase v1.2.0/go.mod h1:IBiWB2sKIp3wVVQ3Y035++gc+knqhUQag1KpM8ahLw8= -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 h1:1zr/of2m5FGMsad5YfcqgdqdWrIhu+EBEJRhR1U7z/c= -github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= -github.com/stretchr/testify v1.2.1/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= -github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -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.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= -github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= -github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= -github.com/tidwall/gjson v1.17.0 h1:/Jocvlh98kcTfpN2+JzGQWQcqrPQwDrVEMApx/M5ZwM= -github.com/tidwall/gjson v1.17.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= -github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= -github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= -github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs= -github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= -github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY= -github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28= -github.com/urfave/cli/v2 v2.1.1/go.mod h1:SE9GqnLQmjVa0iPEY0f1w3ygNIYcIJ0OKPMoW2caLfQ= -github.com/vektah/dataloaden v0.2.1-0.20190515034641-a19b9a6e7c9e/go.mod h1:/HUdMve7rvxZma+2ZELQeNh88+003LL7Pf/CZ089j8U= -github.com/vektah/gqlparser/v2 v2.0.1/go.mod h1:SyUiHgLATUR8BiYURfTirrTcGpcE+4XkV2se04Px1Ms= -github.com/vektah/gqlparser/v2 v2.1.0 h1:uiKJ+T5HMGGQM2kRKQ8Pxw8+Zq9qhhZhz/lieYvCMns= -github.com/vektah/gqlparser/v2 v2.1.0/go.mod h1:SyUiHgLATUR8BiYURfTirrTcGpcE+4XkV2se04Px1Ms= -github.com/vrischmann/envconfig v1.3.0 h1:4XIvQTXznxmWMnjouj0ST5lFo/WAYf5Exgl3x82crEk= -github.com/vrischmann/envconfig v1.3.0/go.mod h1:bbvxFYJdRSpXrhS63mBFtKJzkDiNkyArOLXtY6q0kuI= -github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= -github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo= -github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= -github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= -github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= -github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= -github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= -github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= -golang.org/x/crypto v0.0.0-20221012134737-56aed061732a h1:NmSIgad6KjE6VvHciPZuNRTKxGhlPfD6OA87W/PLkqg= -golang.org/x/crypto v0.0.0-20221012134737-56aed061732a/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= -golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= -golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= -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/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/net v0.0.0-20221014081412-f15817d10f9b h1:tvrvnPFcdzp294diPnrdZZZ8XUt2Tyj7svb7X52iDuU= -golang.org/x/net v0.0.0-20221014081412-f15817d10f9b/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= -golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/oauth2 v0.11.0 h1:vPL4xzxBM4niKCW6g9whtaWVXTJf1U5e4aZxxFx/gbU= -golang.org/x/oauth2 v0.11.0/go.mod h1:LdF7O/8bLR/qWK9DrpXmbHLTouvRHK0SgJl0GmDBchk= -golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -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/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc= -golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.15.0 h1:y/Oo/a/q3IXu26lQgl04j/gjuBDOBlx7X6Om1j2CPW4= -golang.org/x/term v0.15.0/go.mod h1:BDl952bC7+uMoWR75FIrCDx79TPU9oHkTZ9yRbYOrX0= -golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY= -golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= -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-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190125232054-d66bd3c5d5a6/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= -golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190515012406-7d7faa4812bd/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20200114235610-7ae403b6b589/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -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.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -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.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= -google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -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/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= -google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= -google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= -google.golang.org/genproto v0.0.0-20201019141844-1ed22bb0c154/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= -google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= -google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= -google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= -google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= -google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= -google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= -google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= -google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= -google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8= -google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= -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.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.3.0/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.0-20200615113413-eeeca48fe776/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= -honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -k8s.io/api v0.26.9 h1:s8Y+G1u2JM55b90+Yo2RVb3PGT/hkWNVPN4idPERxJg= -k8s.io/api v0.26.9/go.mod h1:W/W4fEWRVzPD36820LlVUQfNBiSbiq0VPWRFJKwzmUg= -k8s.io/apimachinery v0.26.9 h1:5yAV9cFR7Z4gIorKcAjWnx4uxtxiFsERwq4Pvmx0CCg= -k8s.io/apimachinery v0.26.9/go.mod h1:qYzLkrQ9lhrZRh0jNKo2cfvf/R1/kQONnSiyB7NUJU0= -k8s.io/client-go v0.26.9 h1:TGWi/6guEjIgT0Hg871Gsmx0qFuoGyGFjlFedrk7It0= -k8s.io/client-go v0.26.9/go.mod h1:tU1FZS0bwAmAFyPYpZycUQrQnUMzQ5MHloop7EbX6ow= -k8s.io/klog/v2 v2.80.1 h1:atnLQ121W371wYYFawwYx1aEY2eUfs4l3J72wtgAwV4= -k8s.io/klog/v2 v2.80.1/go.mod h1:y1WjHnz7Dj687irZUWR/WLkLc5N1YHtjLdmgWjndZn0= -k8s.io/kube-openapi v0.0.0-20221012153701-172d655c2280 h1:+70TFaan3hfJzs+7VK2o+OGxg8HsuBr/5f6tVAjDu6E= -k8s.io/kube-openapi v0.0.0-20221012153701-172d655c2280/go.mod h1:+Axhij7bCpeqhklhUTe3xmOn6bWxolyZEeyaFpjGtl4= -k8s.io/utils v0.0.0-20221128185143-99ec85e7a448 h1:KTgPnR10d5zhztWptI952TNtt/4u5h3IzDXkdIMuo2Y= -k8s.io/utils v0.0.0-20221128185143-99ec85e7a448/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= -sigs.k8s.io/json v0.0.0-20220713155537-f223a00ba0e2 h1:iXTIw73aPyC+oRdyqqvVJuloN1p0AC/kzH07hu3NE+k= -sigs.k8s.io/json v0.0.0-20220713155537-f223a00ba0e2/go.mod h1:B8JuhiUyNFVKdsE8h686QcCxMaH6HrOAZj4vswFpcB0= -sigs.k8s.io/structured-merge-diff/v4 v4.2.3 h1:PRbqxJClWWYMNV1dhaG4NsibJbArud9kFxnAMREiWFE= -sigs.k8s.io/structured-merge-diff/v4 v4.2.3/go.mod h1:qjx8mGObPmV2aSZepjQjbmb2ihdVs8cGKBraizNC69E= -sigs.k8s.io/yaml v1.3.0 h1:a2VclLzOGrwOHDiV8EfBGhvjHvP46CtW5j6POvhYGGo= -sigs.k8s.io/yaml v1.3.0/go.mod h1:GeOyir5tyXNByN85N/dRIT9es5UQNerPYEKK56eTBm8= -sourcegraph.com/sourcegraph/appdash v0.0.0-20180110180208-2cc67fd64755/go.mod h1:hI742Nqp5OhwiqlzhgfbWU4mW4yO10fP+LoT9WOswdU= -sourcegraph.com/sourcegraph/appdash-data v0.0.0-20151005221446-73f23eafcf67/go.mod h1:L5q+DGLGOQFpo1snNEkLOJT2d1YTW66rWNzatr3He1k= diff --git a/tests/components/application-connector/hack/ci/Makefile b/tests/components/application-connector/hack/ci/Makefile deleted file mode 100644 index 585c655efdbc..000000000000 --- a/tests/components/application-connector/hack/ci/Makefile +++ /dev/null @@ -1,34 +0,0 @@ -PROJECT_ROOT ?= ../.. -KYMA_ROOT_CI ?= /home/prow/go/src/github.com/kyma-project/kyma -.PHONY: setup-environment run-gateway-tests run-validator-tests run-agent-test - -.ONESHELL: -setup-environment: - set -e - k3d registry create k3d-registry --port 5000 - k3d cluster create k3d --registry-use k3d-k3d-registry:5000 - kubectl cluster-info - CLI_VERSION=$(shell curl -s https://api.github.com/repos/kyma-project/cli/releases/latest | grep tag_name | cut -d '"' -f 4); \ - curl -Lo kyma.tar.gz https://github.com/kyma-project/cli/releases/download/$$CLI_VERSION/kyma_Linux_x86_64.tar.gz && mkdir kyma-release && tar -C kyma-release -zxvf kyma.tar.gz && chmod +x kyma-release/kyma && mv kyma-release/kyma /usr/local/bin && rm -rf kyma-release kyma.tar.gz - -k3d-gateway-tests: setup-environment - apk add openssl - kyma deploy --ci --components-file ${PROJECT_ROOT}/resources/installation-config/mini-kyma-os.yaml --source=local --workspace ${KYMA_ROOT_CI} - cd ${PROJECT_ROOT} - make -f Makefile.test-application-gateway test - k3d cluster delete - - -k3d-validator-tests: setup-environment - kyma deploy --ci --components-file ${PROJECT_ROOT}/resources/installation-config/mini-kyma-skr.yaml --value global.disableLegacyConnectivity=true --source=local --workspace ${KYMA_ROOT_CI} - cd ${PROJECT_ROOT} - make -f Makefile.test-application-conn-validator test - k3d cluster delete - -k3d-agent-tests: setup-environment - kyma deploy --ci --components-file ${PROJECT_ROOT}/resources/installation-config/mini-kyma-skr.yaml --value global.disableLegacyConnectivity=true --value compassRuntimeAgent.director.proxy.insecureSkipVerify=true --source=local --workspace ${KYMA_ROOT_CI} - kubectl apply -f ${PROJECT_ROOT}/resources/patches/coredns.yaml - kubectl -n kube-system delete pods -l k8s-app=kube-dns - cd ${PROJECT_ROOT} - make -f Makefile.test-compass-runtime-agent test - k3d cluster delete \ No newline at end of file diff --git a/tests/components/application-connector/internal/testkit/httpd/http.go b/tests/components/application-connector/internal/testkit/httpd/http.go deleted file mode 100644 index 694b03e285b5..000000000000 --- a/tests/components/application-connector/internal/testkit/httpd/http.go +++ /dev/null @@ -1,44 +0,0 @@ -package httpd - -import ( - "io" - "net/http" - "testing" -) - -type LogHttp struct { - t *testing.T - httpCli *http.Client -} - -func NewCli(t *testing.T) LogHttp { - return LogHttp{t: t, httpCli: &http.Client{}} -} - -func (c LogHttp) Get(url string) (resp *http.Response, body []byte, err error) { - c.t.Helper() - req, err := http.NewRequest(http.MethodGet, url, nil) - if err != nil { - return - } - - return c.Do(req) - -} - -func (c LogHttp) Do(req *http.Request) (res *http.Response, body []byte, err error) { - c.t.Helper() - c.t.Logf("%s %s", req.Method, req.URL) - - res, err = c.httpCli.Do(req) - if err != nil { - return - } - - body, err = io.ReadAll(res.Body) - if err == nil && len(body) > 0 { - c.t.Logf("Body: %s", body) - } - - return -} diff --git a/tests/components/application-connector/internal/testkit/test-api/apis.go b/tests/components/application-connector/internal/testkit/test-api/apis.go deleted file mode 100644 index 98c04105e831..000000000000 --- a/tests/components/application-connector/internal/testkit/test-api/apis.go +++ /dev/null @@ -1,122 +0,0 @@ -package test_api - -import ( - "fmt" - "io" - "net/http" - - "github.com/go-http-utils/logger" - "github.com/gorilla/mux" - log "github.com/sirupsen/logrus" -) - -func SetupRoutes(logOut io.Writer, basicAuthCredentials BasicAuthCredentials, oAuthCredentials OAuthCredentials, expectedRequestParameters ExpectedRequestParameters, oauthTokens map[string]OAuthToken, csrfTokens CSRFTokens) http.Handler { - router := mux.NewRouter() - - router.HandleFunc("/v1/health", alwaysOk).Methods("GET") - api := router.PathPrefix("/v1/api").Subrouter() - api.Use(Logger(logOut, logger.DevLoggerType)) - - oauth := NewOAuth(oAuthCredentials.ClientID, oAuthCredentials.ClientSecret, oauthTokens) - csrf := NewCSRF(csrfTokens) - - { - api.HandleFunc("/oauth/token", oauth.Token).Methods(http.MethodPost) - api.HandleFunc("/oauth/bad-token", oauth.BadToken).Methods(http.MethodPost) - api.HandleFunc("/csrf/token", csrf.Token).Methods(http.MethodGet) - api.HandleFunc("/csrf/bad-token", csrf.BadToken).Methods(http.MethodGet) - } - - { - r := api.PathPrefix("/unsecure").Subrouter() - r.HandleFunc("/ok", alwaysOk).Methods(http.MethodGet) - r.HandleFunc("/echo", echo).Methods(http.MethodPut, http.MethodPost, http.MethodDelete) - r.HandleFunc("/code/{code:[0-9]+}", resCode).Methods(http.MethodGet) - r.HandleFunc("/timeout", timeout).Methods(http.MethodGet) - } - { - r := api.PathPrefix("/basic").Subrouter() - r.Use(BasicAuth(basicAuthCredentials)) - r.HandleFunc("/ok", alwaysOk).Methods(http.MethodGet) - } - { - r := api.PathPrefix("/oauth").Subrouter() - r.Use(oauth.Middleware()) - r.HandleFunc("/ok", alwaysOk).Methods(http.MethodGet) - } - { - r := api.PathPrefix("/csrf-basic").Subrouter() - r.Use(csrf.Middleware()) - r.Use(BasicAuth(basicAuthCredentials)) - r.HandleFunc("/ok", alwaysOk).Methods(http.MethodGet) - } - { - r := api.PathPrefix("/csrf-oauth").Subrouter() - r.Use(csrf.Middleware()) - r.Use(oauth.Middleware()) - r.HandleFunc("/ok", alwaysOk).Methods(http.MethodGet) - } - { - r := api.PathPrefix("/request-parameters-basic").Subrouter() - r.Use(RequestParameters(expectedRequestParameters)) - r.Use(BasicAuth(basicAuthCredentials)) - r.HandleFunc("/ok", alwaysOk).Methods(http.MethodGet) - } - { - r := api.PathPrefix("/redirect").Subrouter() - - r.HandleFunc("/ok/target", alwaysOk).Methods(http.MethodGet) - - r.Handle("/ok", http.RedirectHandler("/v1/api/redirect/ok/target", http.StatusTemporaryRedirect)) - - ba := BasicAuth(basicAuthCredentials) - ok := http.HandlerFunc(alwaysOk) - r.Handle("/basic/target", ba(ok)).Methods(http.MethodGet) - r.Handle("/basic", http.RedirectHandler("/v1/api/redirect/basic/target", http.StatusTemporaryRedirect)) - - r.Handle("/external", http.RedirectHandler("http://central-application-gateway.kyma-system:8081/v1/health", http.StatusTemporaryRedirect)) - } - - return router -} - -func SetupMTLSRoutes(logOut io.Writer, oAuthCredentials OAuthCredentials, oauthTokens map[string]OAuthToken, csrfTokens CSRFTokens) http.Handler { - router := mux.NewRouter() - - router.HandleFunc("/v1/health", alwaysOk).Methods("GET") - api := router.PathPrefix("/v1/api").Subrouter() - api.Use(Logger(logOut, logger.DevLoggerType)) - - oauth := NewOAuth(oAuthCredentials.ClientID, oAuthCredentials.ClientSecret, oauthTokens) - csrf := NewCSRF(csrfTokens) - - { - r := api.PathPrefix("/mtls").Subrouter() - r.Use(oauth.Middleware()) - api.HandleFunc("/mtls-oauth/token", oauth.MTLSToken).Methods(http.MethodPost) - } - - { - r := api.PathPrefix("/mtls").Subrouter() - r.HandleFunc("/ok", alwaysOk).Methods(http.MethodGet) - } - { - r := api.PathPrefix("/csrf-mtls").Subrouter() - r.Use(csrf.Middleware()) - r.HandleFunc("/ok", alwaysOk).Methods(http.MethodGet) - } - - return router -} - -func Logger(out io.Writer, t logger.Type) mux.MiddlewareFunc { - return func(next http.Handler) http.Handler { - return logger.Handler(next, out, t) - } -} - -func handleError(w http.ResponseWriter, code int, format string, a ...interface{}) { - err := fmt.Errorf(format, a...) - log.Error(err) - w.WriteHeader(code) -} diff --git a/tests/components/application-connector/internal/testkit/test-api/basicauth.go b/tests/components/application-connector/internal/testkit/test-api/basicauth.go deleted file mode 100644 index 0307ae94540b..000000000000 --- a/tests/components/application-connector/internal/testkit/test-api/basicauth.go +++ /dev/null @@ -1,30 +0,0 @@ -package test_api - -import ( - "github.com/gorilla/mux" - "net/http" -) - -type BasicAuthCredentials struct { - User string - Password string -} - -func BasicAuth(credentials BasicAuthCredentials) mux.MiddlewareFunc { - return func(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - u, p, ok := r.BasicAuth() - if !ok { - handleError(w, http.StatusForbidden, "Basic auth header not found") - return - } - - if credentials.User != u || credentials.Password != p { - handleError(w, http.StatusForbidden, "Incorrect username or Password") - return - } - - next.ServeHTTP(w, r) - }) - } -} diff --git a/tests/components/application-connector/internal/testkit/test-api/csrf.go b/tests/components/application-connector/internal/testkit/test-api/csrf.go deleted file mode 100644 index 06f7993b4fdd..000000000000 --- a/tests/components/application-connector/internal/testkit/test-api/csrf.go +++ /dev/null @@ -1,95 +0,0 @@ -package test_api - -import ( - "github.com/google/uuid" - "github.com/gorilla/mux" - "net/http" - "sync" -) - -const ( - csrfTokenHeader = "X-csrf-token" - csrfTokenCookie = "csrftokencookie" -) - -type CSRFTokens map[string]interface{} - -type CSRFHandler struct { - mutex sync.RWMutex - tokens map[string]interface{} -} - -func NewCSRF(tokens CSRFTokens) CSRFHandler { - return CSRFHandler{ - mutex: sync.RWMutex{}, - tokens: tokens, - } -} - -func (ch *CSRFHandler) Token(w http.ResponseWriter, _ *http.Request) { - token := uuid.New().String() - - ch.mutex.Lock() - ch.tokens[token] = nil - ch.mutex.Unlock() - - w.Header().Set(csrfTokenHeader, token) - http.SetCookie(w, &http.Cookie{ - Name: csrfTokenCookie, - Value: token, - }) - - w.WriteHeader(http.StatusOK) - w.Header().Set("Content-Type", "application/json") -} - -func (ch *CSRFHandler) BadToken(w http.ResponseWriter, _ *http.Request) { - token := uuid.New().String() - - w.Header().Set(csrfTokenHeader, token) - http.SetCookie(w, &http.Cookie{ - Name: csrfTokenCookie, - Value: token, - }) - - w.WriteHeader(http.StatusOK) - w.Header().Set("Content-Type", "application/json") -} - -func (ch *CSRFHandler) Middleware() mux.MiddlewareFunc { - return func(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - headerToken := r.Header.Get(csrfTokenHeader) - if headerToken == "" { - handleError(w, http.StatusForbidden, "CSRF token header missing") - return - } - - ch.mutex.RLock() - _, found := ch.tokens[headerToken] - ch.mutex.RUnlock() - - if !found { - handleError(w, http.StatusForbidden, "Invalid CSRF token from the header") - return - } - - cookieToken, err := r.Cookie(csrfTokenCookie) - if err != nil { - handleError(w, http.StatusForbidden, "CSRF token cookie missing") - return - } - - ch.mutex.RLock() - _, found = ch.tokens[cookieToken.Value] - ch.mutex.RUnlock() - - if !found { - handleError(w, http.StatusForbidden, "Invalid CSRF token from the cookie") - return - } - - next.ServeHTTP(w, r) - }) - } -} diff --git a/tests/components/application-connector/internal/testkit/test-api/handlers.go b/tests/components/application-connector/internal/testkit/test-api/handlers.go deleted file mode 100644 index 26114863d4db..000000000000 --- a/tests/components/application-connector/internal/testkit/test-api/handlers.go +++ /dev/null @@ -1,69 +0,0 @@ -package test_api - -import ( - "encoding/json" - "io/ioutil" - "log" - "net/http" - "strconv" - "time" - - "github.com/gorilla/mux" -) - -func alwaysOk(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusOK) -} - -type EchoResponse struct { - Body []byte `json:"body"` - Headers map[string][]string `json:"headers"` - Method string `json:"method"` - Query string `json:"query"` -} - -func echo(w http.ResponseWriter, r *http.Request) { - body, err := ioutil.ReadAll(r.Body) - if err != nil { - log.Println("Couldn't read request body:", r.URL) - body = []byte("") - } - - res := EchoResponse{ - Method: r.Method, - Body: body, - Headers: r.Header, - Query: r.URL.RawQuery, - } - - w.Header().Set("Content-Type", "application/json") - err = json.NewEncoder(w).Encode(res) - - if err != nil { - log.Println("Couldn't encode the response body to JSON:", r.URL) - } -} - -// resCode should only be used in paths with `code` -// parameter, that is a valid int -func resCode(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - codeStr := vars["code"] // must exist, because path has a pattern - code, _ := strconv.Atoi(codeStr) // can't error, because path has a pattern - w.WriteHeader(code) - w.Write([]byte(codeStr)) -} - -func timeout(w http.ResponseWriter, r *http.Request) { - c := r.Context().Done() - if c == nil { - log.Println("Context has no timeout, sleeping for 2 minutes") - time.Sleep(2 * time.Minute) - return - } - log.Println("Context timeout, waiting until done") - - _ = <-c - - alwaysOk(w, r) -} diff --git a/tests/components/application-connector/internal/testkit/test-api/oauth.go b/tests/components/application-connector/internal/testkit/test-api/oauth.go deleted file mode 100644 index 2fe60ea3a8b7..000000000000 --- a/tests/components/application-connector/internal/testkit/test-api/oauth.go +++ /dev/null @@ -1,190 +0,0 @@ -package test_api - -import ( - "encoding/json" - "fmt" - "github.com/gorilla/mux" - "net/http" - "strings" - "sync" - "time" - - "github.com/google/uuid" - log "github.com/sirupsen/logrus" -) - -type OAuthCredentials struct { - ClientID string - ClientSecret string -} - -const ( - clientIDKey = "client_id" - clientSecretKey = "client_secret" - grantTypeKey = "grant_type" - tokenLifetime = "token_lifetime" - defaultTokenExpiresIn = 5 * time.Minute -) - -type OauthResponse struct { - AccessToken string `json:"access_token"` - TokenType string `json:"token_type"` - ExpiresIn int64 `json:"expires_in,omitempty"` -} - -type OAuthToken struct { - exp time.Time -} - -func (token OAuthToken) Valid() bool { - return token.exp.After(time.Now()) -} - -type OAuthHandler struct { - clientID string - clientSecret string - mutex sync.RWMutex - tokens map[string]OAuthToken -} - -func NewOAuth(clientID, clientSecret string, tokens map[string]OAuthToken) OAuthHandler { - return OAuthHandler{ - clientID: clientID, - clientSecret: clientSecret, - mutex: sync.RWMutex{}, - tokens: tokens, - } -} - -func (oh *OAuthHandler) Token(w http.ResponseWriter, r *http.Request) { - if ok, status, message := oh.isRequestValid(r); !ok { - handleError(w, status, message) - return - } - - token := uuid.New().String() - exp := defaultTokenExpiresIn - - if ttlStr := r.URL.Query().Get(tokenLifetime); ttlStr != "" { - parsedEXP, err := time.ParseDuration(ttlStr) - if err == nil { - log.Info("Received valid OAuth expiresIn:", parsedEXP) - exp = parsedEXP - } else { - log.Error("Received invalid OAuth expiresIn:", err) - } - } - - oh.storeTokenInCache(token, exp) - - response := OauthResponse{AccessToken: token, TokenType: "bearer", ExpiresIn: int64(exp.Seconds())} - oh.respondWithToken(w, response) -} - -func (oh *OAuthHandler) BadToken(w http.ResponseWriter, r *http.Request) { - if ok, status, message := oh.isRequestValid(r); !ok { - handleError(w, status, message) - return - } - - token := uuid.New().String() - response := OauthResponse{AccessToken: token, TokenType: "bearer"} - oh.respondWithToken(w, response) -} - -func (oh *OAuthHandler) MTLSToken(w http.ResponseWriter, r *http.Request) { - if ok, status, message := oh.isMTLSRequestValid(r); !ok { - handleError(w, status, message) - return - } - - token := uuid.New().String() - exp := defaultTokenExpiresIn - - oh.storeTokenInCache(token, exp) - response := OauthResponse{AccessToken: token, TokenType: "bearer", ExpiresIn: 3600} - oh.respondWithToken(w, response) -} - -func (oh *OAuthHandler) Middleware() mux.MiddlewareFunc { - return func(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - authHeader := r.Header.Get("Authorization") - if authHeader == "" { - handleError(w, http.StatusUnauthorized, "Authorization header missing") - return - } - - splitToken := strings.Split(authHeader, "Bearer") - if len(splitToken) != 2 { - handleError(w, http.StatusUnauthorized, "Bearer token missing") - return - } - - token := strings.TrimSpace(splitToken[1]) - - oh.mutex.RLock() - data, found := oh.tokens[token] - oh.mutex.RUnlock() - - if !found || !data.Valid() { - handleError(w, http.StatusUnauthorized, "Invalid token") - return - } - - next.ServeHTTP(w, r) - }) - } -} - -func (oh *OAuthHandler) isRequestValid(r *http.Request) (bool, int, string) { - err := r.ParseForm() - if err != nil { - return false, http.StatusInternalServerError, fmt.Sprintf("Failed to parse form: %v", err) - } - - clientID := r.FormValue(clientIDKey) - clientSecret := r.FormValue(clientSecretKey) - grantType := r.FormValue(grantTypeKey) - - if !oh.verifyClient(clientID, clientSecret) || grantType != "client_credentials" { - return false, http.StatusForbidden, "Client verification failed" - } - - return true, 0, "" -} - -func (oh *OAuthHandler) verifyClient(id, secret string) bool { - return id == oh.clientID && secret == oh.clientSecret -} - -func (oh *OAuthHandler) respondWithToken(w http.ResponseWriter, response OauthResponse) { - w.Header().Set("Content-Type", "application/json") - if err := json.NewEncoder(w).Encode(response); err != nil { - handleError(w, http.StatusInternalServerError, "Failed to encode token response") - return - } - w.WriteHeader(http.StatusOK) -} - -func (oh *OAuthHandler) storeTokenInCache(token string, expIn time.Duration) { - oh.mutex.Lock() - oh.tokens[token] = OAuthToken{exp: time.Now().Add(expIn)} - oh.mutex.Unlock() -} - -func (oh *OAuthHandler) isMTLSRequestValid(r *http.Request) (bool, int, string) { - err := r.ParseForm() - if err != nil { - return false, http.StatusInternalServerError, fmt.Sprintf("Failed to parse form: %v", err) - } - - clientID := r.FormValue(clientIDKey) - grantType := r.FormValue(grantTypeKey) - - if r.TLS == nil || clientID != oh.clientID || grantType != "client_credentials" { - return false, http.StatusForbidden, "Client verification failed" - } - - return true, 0, "" -} diff --git a/tests/components/application-connector/internal/testkit/test-api/requestparams.go b/tests/components/application-connector/internal/testkit/test-api/requestparams.go deleted file mode 100644 index 774ff9fae52f..000000000000 --- a/tests/components/application-connector/internal/testkit/test-api/requestparams.go +++ /dev/null @@ -1,53 +0,0 @@ -package test_api - -import ( - "github.com/gorilla/mux" - "net/http" -) - -type ExpectedRequestParameters struct { - Headers map[string][]string - QueryParameters map[string][]string -} - -func RequestParameters(expectedRequestParams ExpectedRequestParameters) mux.MiddlewareFunc { - return func(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - for key, expectedVals := range expectedRequestParams.Headers { - actualVals := r.Header.Values(key) - if !containsSubset(actualVals, expectedVals) { - handleError(w, http.StatusBadRequest, "Incorrect additional headers. Expected %s header to contain %v, but found %v", key, expectedVals, actualVals) - return - } - } - - queryParameters := r.URL.Query() - for key, expectedVals := range expectedRequestParams.QueryParameters { - actualVals := queryParameters[key] - if !containsSubset(actualVals, expectedVals) { - handleError(w, http.StatusBadRequest, "Incorrect additional query parameters. Expected %s query parameter to contain %v, but found %v", key, expectedVals, actualVals) - return - } - } - - next.ServeHTTP(w, r) - }) - } -} - -func containsSubset(set, subset []string) bool { - for _, bVal := range subset { - found := false - for _, aVal := range set { - if aVal == bVal { - found = true - break - } - } - - if !found { - return false - } - } - return true -} diff --git a/tests/components/application-connector/resources/charts/application-connectivity-validator-test/Chart.yaml b/tests/components/application-connector/resources/charts/application-connectivity-validator-test/Chart.yaml deleted file mode 100644 index 0424adb36ca8..000000000000 --- a/tests/components/application-connector/resources/charts/application-connectivity-validator-test/Chart.yaml +++ /dev/null @@ -1,23 +0,0 @@ -apiVersion: v2 -name: application-connectivity-validator-test -description: A Helm chart for Kubernetes - -# A chart can be either an 'application' or a 'library' chart. -# -# Application charts are a collection of templates that can be packaged into versioned archives -# to be deployed. -# -# Library charts provide useful utilities or functions for the chart developer. They're included as -# a dependency of application charts to inject those utilities and functions into the rendering -# pipeline. Library charts do not define any templates and therefore cannot be deployed. -type: application - -# This is the chart version. This version number should be incremented each time you make changes -# to the chart and its templates, including the app version. -# Versions are expected to follow Semantic Versioning (https://semver.org/) -version: 0.1.0 - -# This is the version number of the application being deployed. This version number should be -# incremented each time you make changes to the application. Versions are not expected to -# follow Semantic Versioning. They should reflect the version the application is using. -appVersion: 1.16.0 diff --git a/tests/components/application-connector/resources/charts/application-connectivity-validator-test/charts/echoserver/Chart.yaml b/tests/components/application-connector/resources/charts/application-connectivity-validator-test/charts/echoserver/Chart.yaml deleted file mode 100644 index 807b2174d310..000000000000 --- a/tests/components/application-connector/resources/charts/application-connectivity-validator-test/charts/echoserver/Chart.yaml +++ /dev/null @@ -1,23 +0,0 @@ -apiVersion: v2 -name: echoserver -description: A Helm chart for Kubernetes - -# A chart can be either an 'application' or a 'library' chart. -# -# Application charts are a collection of templates that can be packaged into versioned archives -# to be deployed. -# -# Library charts provide useful utilities or functions for the chart developer. They're included as -# a dependency of application charts to inject those utilities and functions into the rendering -# pipeline. Library charts do not define any templates and therefore cannot be deployed. -type: application - -# This is the chart version. This version number should be incremented each time you make changes -# to the chart and its templates, including the app version. -# Versions are expected to follow Semantic Versioning (https://semver.org/) -version: 0.1.0 - -# This is the version number of the application being deployed. This version number should be -# incremented each time you make changes to the application. Versions are not expected to -# follow Semantic Versioning. They should reflect the version the application is using. -appVersion: 1.16.0 diff --git a/tests/components/application-connector/resources/charts/application-connectivity-validator-test/charts/echoserver/templates/echoserver.yml b/tests/components/application-connector/resources/charts/application-connectivity-validator-test/charts/echoserver/templates/echoserver.yml deleted file mode 100644 index d4f83b7247e7..000000000000 --- a/tests/components/application-connector/resources/charts/application-connectivity-validator-test/charts/echoserver/templates/echoserver.yml +++ /dev/null @@ -1,41 +0,0 @@ -apiVersion: apps/v1 -kind: Deployment -metadata: - labels: - app: echosever - name: echoserver - namespace: {{ .Values.global.namespace }} -spec: - replicas: 1 - selector: - matchLabels: - app: echoserver - template: - metadata: - labels: - app: echoserver - spec: - containers: - - image: ealen/echo-server:0.7.0 - name: echoserver - ports: - - containerPort: 80 - livenessProbe: - httpGet: - path: / - port: 80 - initialDelaySeconds: 3 - periodSeconds: 3 ---- -apiVersion: v1 -kind: Service -metadata: - name: echoserver - namespace: {{ .Values.global.namespace }} -spec: - selector: - app: echoserver - ports: - - name: "http" - protocol: TCP - port: 80 diff --git a/tests/components/application-connector/resources/charts/application-connectivity-validator-test/charts/test/Chart.yaml b/tests/components/application-connector/resources/charts/application-connectivity-validator-test/charts/test/Chart.yaml deleted file mode 100644 index 6e99aa1f62d6..000000000000 --- a/tests/components/application-connector/resources/charts/application-connectivity-validator-test/charts/test/Chart.yaml +++ /dev/null @@ -1,23 +0,0 @@ -apiVersion: v2 -name: test -description: A Helm chart for Kubernetes - -# A chart can be either an 'application' or a 'library' chart. -# -# Application charts are a collection of templates that can be packaged into versioned archives -# to be deployed. -# -# Library charts provide useful utilities or functions for the chart developer. They're included as -# a dependency of application charts to inject those utilities and functions into the rendering -# pipeline. Library charts do not define any templates and therefore cannot be deployed. -type: application - -# This is the chart version. This version number should be incremented each time you make changes -# to the chart and its templates, including the app version. -# Versions are expected to follow Semantic Versioning (https://semver.org/) -version: 0.1.0 - -# This is the version number of the application being deployed. This version number should be -# incremented each time you make changes to the application. Versions are not expected to -# follow Semantic Versioning. They should reflect the version the application is using. -appVersion: 1.16.0 diff --git a/tests/components/application-connector/resources/charts/application-connectivity-validator-test/charts/test/templates/_helpers.tpl b/tests/components/application-connector/resources/charts/application-connectivity-validator-test/charts/test/templates/_helpers.tpl deleted file mode 100644 index 5acdb5e31fe7..000000000000 --- a/tests/components/application-connector/resources/charts/application-connectivity-validator-test/charts/test/templates/_helpers.tpl +++ /dev/null @@ -1,11 +0,0 @@ -{{/* -Create a URL for container images -*/}} -{{- define "imageurl" -}} -{{- $registry := default $.reg.path $.img.containerRegistryPath -}} -{{- if hasKey $.img "directory" -}} -{{- printf "%s/%s/%s:%s" $registry $.img.directory $.img.name $.img.version -}} -{{- else -}} -{{- printf "%s/%s:%s" $registry $.img.name $.img.version -}} -{{- end -}} -{{- end -}} \ No newline at end of file diff --git a/tests/components/application-connector/resources/charts/application-connectivity-validator-test/charts/test/templates/applications/event-test-compass.yml b/tests/components/application-connector/resources/charts/application-connectivity-validator-test/charts/test/templates/applications/event-test-compass.yml deleted file mode 100644 index 8e1a498e51a0..000000000000 --- a/tests/components/application-connector/resources/charts/application-connectivity-validator-test/charts/test/templates/applications/event-test-compass.yml +++ /dev/null @@ -1,12 +0,0 @@ -apiVersion: applicationconnector.kyma-project.io/v1alpha1 -kind: Application -metadata: - name: event-test-compass -spec: - compassMetadata: - applicationId: applicationId - authentication: - clientIds: ["clientId1", "clientId2"] - description: Test app-con-validator - skipVerify: true - diff --git a/tests/components/application-connector/resources/charts/application-connectivity-validator-test/charts/test/templates/applications/event-test-standalone.yml b/tests/components/application-connector/resources/charts/application-connectivity-validator-test/charts/test/templates/applications/event-test-standalone.yml deleted file mode 100644 index 424b7bd68cd9..000000000000 --- a/tests/components/application-connector/resources/charts/application-connectivity-validator-test/charts/test/templates/applications/event-test-standalone.yml +++ /dev/null @@ -1,7 +0,0 @@ -apiVersion: applicationconnector.kyma-project.io/v1alpha1 -kind: Application -metadata: - name: event-test-standalone -spec: - description: Test app-con-validator - skipVerify: true diff --git a/tests/components/application-connector/resources/charts/application-connectivity-validator-test/charts/test/templates/test.yml b/tests/components/application-connector/resources/charts/application-connectivity-validator-test/charts/test/templates/test.yml deleted file mode 100644 index 12eb1f6705a4..000000000000 --- a/tests/components/application-connector/resources/charts/application-connectivity-validator-test/charts/test/templates/test.yml +++ /dev/null @@ -1,17 +0,0 @@ -apiVersion: batch/v1 -kind: Job -metadata: - name: application-connectivity-validator-test - namespace: {{ .Values.global.namespace }} -spec: - backoffLimit: 0 - template: - metadata: - annotations: - traffic.sidecar.istio.io/excludeOutboundPorts: "8080" - spec: - containers: - - name: application-connectivity-validator-test - image: {{ include "imageurl" (dict "reg" .Values.global.containerRegistry "img" .Values.global.images.validatorTest) }} - imagePullPolicy: Always - restartPolicy: Never \ No newline at end of file diff --git a/tests/components/application-connector/resources/charts/application-connectivity-validator-test/values.yaml b/tests/components/application-connector/resources/charts/application-connectivity-validator-test/values.yaml deleted file mode 100644 index 5b84bcba6dbc..000000000000 --- a/tests/components/application-connector/resources/charts/application-connectivity-validator-test/values.yaml +++ /dev/null @@ -1,15 +0,0 @@ -# Default values for application-connectivity-validator-test. -# This is a YAML-formatted file. -# Declare variables to be passed into your templates. - -global: - containerRegistry: - path: "europe-docker.pkg.dev/kyma-project" - - images: - validatorTest: - name: "connectivity-validator-test" - version: "v20230925-75c3a9a8" - directory: "prod" - - namespace: "test" diff --git a/tests/components/application-connector/resources/charts/compass-runtime-agent-test/Chart.yaml b/tests/components/application-connector/resources/charts/compass-runtime-agent-test/Chart.yaml deleted file mode 100644 index 9b3c49e9548e..000000000000 --- a/tests/components/application-connector/resources/charts/compass-runtime-agent-test/Chart.yaml +++ /dev/null @@ -1,24 +0,0 @@ -apiVersion: v2 -name: compass-runtime-agent-test -description: A Helm chart for Kubernetes - -# A chart can be either an 'application' or a 'library' chart. -# -# Application charts are a collection of templates that can be packaged into versioned archives -# to be deployed. -# -# Library charts provide useful utilities or functions for the chart developer. They're included as -# a dependency of application charts to inject those utilities and functions into the rendering -# pipeline. Library charts do not define any templates and therefore cannot be deployed. -type: application - -# This is the chart version. This version number should be incremented each time you make changes -# to the chart and its templates, including the app version. -# Versions are expected to follow Semantic Versioning (https://semver.org/) -version: 0.1.0 - -# This is the version number of the application being deployed. This version number should be -# incremented each time you make changes to the application. Versions are not expected to -# follow Semantic Versioning. They should reflect the version the application is using. -# It is recommended to use it with quotes. -appVersion: "0.1.0" diff --git a/tests/components/application-connector/resources/charts/compass-runtime-agent-test/templates/_helpers.tpl b/tests/components/application-connector/resources/charts/compass-runtime-agent-test/templates/_helpers.tpl deleted file mode 100644 index 9cba139160b4..000000000000 --- a/tests/components/application-connector/resources/charts/compass-runtime-agent-test/templates/_helpers.tpl +++ /dev/null @@ -1,12 +0,0 @@ - -{{/* -Create a URL for container images -*/}} -{{- define "imageurl" -}} -{{- $registry := default $.reg.path $.img.containerRegistryPath -}} -{{- if hasKey $.img "directory" -}} -{{- printf "%s/%s/%s:%s" $registry $.img.directory $.img.name $.img.version -}} -{{- else -}} -{{- printf "%s/%s:%s" $registry $.img.name $.img.version -}} -{{- end -}} -{{- end -}} diff --git a/tests/components/application-connector/resources/charts/compass-runtime-agent-test/templates/applications/test-create-app.yaml b/tests/components/application-connector/resources/charts/compass-runtime-agent-test/templates/applications/test-create-app.yaml deleted file mode 100644 index e95e05cd0b3e..000000000000 --- a/tests/components/application-connector/resources/charts/compass-runtime-agent-test/templates/applications/test-create-app.yaml +++ /dev/null @@ -1,59 +0,0 @@ -apiVersion: applicationconnector.kyma-project.io/v1alpha1 -kind: Application -metadata: - labels: - applicationconnector.kyma-project.io/managed-by: compass-runtime-agent - name: app1 -spec: - description: Test Application for testing Compass Runtime Agent - displayName: "" - longDescription: "" - providerDisplayName: "" - skipVerify: false - services: - - description: Foo bar - displayName: bndl-app-1 - entries: - - centralGatewayUrl: http://central-application-gateway.kyma-system.svc.cluster.local:8082/mp-app1gkhavxduzb/bndl-app-1/comments-v1 - credentials: - secretName: "" - type: "" - gatewayUrl: "" - id: 30747de1-4a87-4b67-a75d-9fe84af6e6f9 - name: comments-v1 - targetUrl: http://mywordpress.com/comments - type: API - id: e4148ee9-79c0-4d81-863c-311f32aeed9b - identifier: "" - name: bndl-app-1-0d79e - providerDisplayName: "" ---- -apiVersion: applicationconnector.kyma-project.io/v1alpha1 -kind: Application -metadata: - labels: - applicationconnector.kyma-project.io/managed-by: compass-runtime-agent - name: app1-updated -spec: - description: "The app was updated" - displayName: "" - longDescription: "" - providerDisplayName: "" - services: - - description: Foo bar - displayName: bndl-app-1 - entries: - - centralGatewayUrl: http://central-application-gateway.kyma-system.svc.cluster.local:8082/mp-app1gkhavxduzb/bndl-app-1/comments-v1 - credentials: - secretName: "" - type: "" - gatewayUrl: "" - id: 30747de1-4a87-4b67-a75d-9fe84af6e6f9 - name: comments-v1 - targetUrl: http://mywordpress.com/comments - type: API - id: e4148ee9-79c0-4d81-863c-311f32aeed9b - identifier: "" - name: bndl-app-1-0d79e - providerDisplayName: "" - skipVerify: false diff --git a/tests/components/application-connector/resources/charts/compass-runtime-agent-test/templates/secret-compass.yaml b/tests/components/application-connector/resources/charts/compass-runtime-agent-test/templates/secret-compass.yaml deleted file mode 100644 index 8a76d2cfeee6..000000000000 --- a/tests/components/application-connector/resources/charts/compass-runtime-agent-test/templates/secret-compass.yaml +++ /dev/null @@ -1,10 +0,0 @@ -apiVersion: v1 -kind: Secret -metadata: - name: {{ .Values.oauthCredentialsSecretName }} - namespace: {{ .Values.oauthCredentialsNamespace }} -data: - client_id: {{ .Values.compassCredentials.clientID | b64enc | quote }} - client_secret: {{ .Values.compassCredentials.clientSecret | b64enc | quote }} - tokens_endpoint: {{ .Values.compassCredentials.tokensEndpoint | b64enc | quote }} -type: Opaque \ No newline at end of file diff --git a/tests/components/application-connector/resources/charts/compass-runtime-agent-test/templates/service-account.yaml b/tests/components/application-connector/resources/charts/compass-runtime-agent-test/templates/service-account.yaml deleted file mode 100644 index 92c53e1d6ad8..000000000000 --- a/tests/components/application-connector/resources/charts/compass-runtime-agent-test/templates/service-account.yaml +++ /dev/null @@ -1,59 +0,0 @@ -apiVersion: v1 -kind: ServiceAccount -metadata: - name: {{ .Values.serviceAccountName }} - namespace: {{ .Values.namespace }} ---- -apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRoleBinding -metadata: - name: {{ .Values.serviceAccountName }} - namespace: {{ .Values.namespace }} -roleRef: - apiGroup: rbac.authorization.k8s.io - kind: ClusterRole - name: {{ .Values.serviceAccountName }} -subjects: - - kind: ServiceAccount - name: {{ .Values.serviceAccountName }} - namespace: {{ .Values.namespace }} ---- -apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRole -metadata: - name: {{ .Values.serviceAccountName }} -rules: - - apiGroups: - - "" - resources: - - secrets - verbs: - - create - - get - - list - - delete - - apiGroups: - - "apps" - resources: - - deployments - verbs: - - get - - list - - update - - apiGroups: - - "applicationconnector.kyma-project.io" - resources: - - "applications" - verbs: - - get - - list - - apiGroups: - - "compass.kyma-project.io" - resources: - - "compassconnections" - verbs: - - create - - get - - delete - - update - - list \ No newline at end of file diff --git a/tests/components/application-connector/resources/charts/compass-runtime-agent-test/templates/test.yaml b/tests/components/application-connector/resources/charts/compass-runtime-agent-test/templates/test.yaml deleted file mode 100644 index 639a8b8d9d76..000000000000 --- a/tests/components/application-connector/resources/charts/compass-runtime-agent-test/templates/test.yaml +++ /dev/null @@ -1,26 +0,0 @@ -apiVersion: batch/v1 -kind: Job -metadata: - name: compass-runtime-agent-test - namespace: {{ .Values.namespace }} -spec: - template: - spec: - restartPolicy: Never - serviceAccountName: {{ .Values.serviceAccountName }} - containers: - - name: compass-runtime-agent-test - image: {{ include "imageurl" (dict "reg" .Values.containerRegistry "img" .Values.images.compassTest) }} - imagePullPolicy: Always - env: - - name: APP_DIRECTOR_URL - value: {{ .Values.directorUrl }} - - name: APP_TESTING_TENANT - value: {{ .Values.testTenant }} - - name: APP_SKIP_DIRECTOR_CERT_VERIFICATION - value: {{ .Values.skipDirectorCertVerification | quote }} - - name: APP_OAUTH_CREDENTIALS_SECRET_NAME - value: {{.Values.oauthCredentialsSecretName}} - - name: APP_OAUTH_CREDENTIALS_NAMESPACE - value: {{ .Values.oauthCredentialsNamespace }} - backoffLimit: 0 diff --git a/tests/components/application-connector/resources/charts/compass-runtime-agent-test/values.yaml b/tests/components/application-connector/resources/charts/compass-runtime-agent-test/values.yaml deleted file mode 100644 index e788e7d357d6..000000000000 --- a/tests/components/application-connector/resources/charts/compass-runtime-agent-test/values.yaml +++ /dev/null @@ -1,20 +0,0 @@ -namespace: "test" -testTenant: "3e64ebae-38b5-46a0-b1ed-9ccee153a0ae" -oauthCredentialsSecretName: "oauth-compass-credentials" -oauthCredentialsNamespace: "test" -skipDirectorCertVerification: true -serviceAccountName: "test-compass-runtime-agent" - -containerRegistry: - path: "europe-docker.pkg.dev/kyma-project" - -images: - compassTest: - name: "compass-runtime-agent-test" - version: "v20230925-75c3a9a8" - directory: "prod" - -compassCredentials: - clientID: "" - clientSecret: "" - tokensEndpoint: "" diff --git a/tests/components/application-connector/resources/charts/gateway-test/Chart.yaml b/tests/components/application-connector/resources/charts/gateway-test/Chart.yaml deleted file mode 100644 index ea515d6106cf..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/Chart.yaml +++ /dev/null @@ -1,24 +0,0 @@ -apiVersion: v2 -name: application-gateway-test -description: A Helm chart for Kubernetes - -# A chart can be either an 'application' or a 'library' chart. -# -# Application charts are a collection of templates that can be packaged into versioned archives -# to be deployed. -# -# Library charts provide useful utilities or functions for the chart developer. They're included as -# a dependency of application charts to inject those utilities and functions into the rendering -# pipeline. Library charts do not define any templates and therefore cannot be deployed. -type: application - -# This is the chart version. This version number should be incremented each time you make changes -# to the chart and its templates, including the app version. -# Versions are expected to follow Semantic Versioning (https://semver.org/) -version: 0.1.0 - -# This is the version number of the application being deployed. This version number should be -# incremented each time you make changes to the application. Versions are not expected to -# follow Semantic Versioning. They should reflect the version the application is using. -# It is recommended to use it with quotes. -appVersion: "0.1.0" diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/mock-app/Chart.yaml b/tests/components/application-connector/resources/charts/gateway-test/charts/mock-app/Chart.yaml deleted file mode 100644 index 5671f8acf6a8..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/mock-app/Chart.yaml +++ /dev/null @@ -1,24 +0,0 @@ -apiVersion: v2 -name: mock-app -description: A Helm chart for Kubernetes - -# A chart can be either an 'application' or a 'library' chart. -# -# Application charts are a collection of templates that can be packaged into versioned archives -# to be deployed. -# -# Library charts provide useful utilities or functions for the chart developer. They're included as -# a dependency of application charts to inject those utilities and functions into the rendering -# pipeline. Library charts do not define any templates and therefore cannot be deployed. -type: application - -# This is the chart version. This version number should be incremented each time you make changes -# to the chart and its templates, including the app version. -# Versions are expected to follow Semantic Versioning (https://semver.org/) -version: 0.1.0 - -# This is the version number of the application being deployed. This version number should be -# incremented each time you make changes to the application. Versions are not expected to -# follow Semantic Versioning. They should reflect the version the application is using. -# It is recommended to use it with quotes. -appVersion: "0.1.0" diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/mock-app/templates/_helpers.tpl b/tests/components/application-connector/resources/charts/gateway-test/charts/mock-app/templates/_helpers.tpl deleted file mode 100644 index 9cba139160b4..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/mock-app/templates/_helpers.tpl +++ /dev/null @@ -1,12 +0,0 @@ - -{{/* -Create a URL for container images -*/}} -{{- define "imageurl" -}} -{{- $registry := default $.reg.path $.img.containerRegistryPath -}} -{{- if hasKey $.img "directory" -}} -{{- printf "%s/%s/%s:%s" $registry $.img.directory $.img.name $.img.version -}} -{{- else -}} -{{- printf "%s/%s:%s" $registry $.img.name $.img.version -}} -{{- end -}} -{{- end -}} diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/mock-app/templates/credentials/expired-mtls-cert-secret.yaml b/tests/components/application-connector/resources/charts/gateway-test/charts/mock-app/templates/credentials/expired-mtls-cert-secret.yaml deleted file mode 100644 index 0a968871ae31..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/mock-app/templates/credentials/expired-mtls-cert-secret.yaml +++ /dev/null @@ -1,12 +0,0 @@ -apiVersion: v1 -kind: Secret -metadata: - name: expired-mtls-cert-secret - namespace: test -type: Opaque -data: - # Server certificate expired on 02.08.2022 - server.crt: bm90QmVmb3JlPUF1ZyAgMSAwMDowMDowMCAyMDIyIEdNVApub3RBZnRlcj1BdWcgIDIgMDA6MDA6MDAgMjAyMiBHTVQKLS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSURkakNDQWw2Z0F3SUJBZ0lVWnVOZ3FCQTdSUEs4bStSSnhuaXRTS21xZFdZd0RRWUpLb1pJaHZjTkFRRUwKQlFBd1dURUxNQWtHQTFVRUJoTUNVRXd4Q2pBSUJnTlZCQWdNQVVFeEREQUtCZ05WQkFvTUExTkJVREV3TUM0RwpBMVVFQXd3bmJXOWpheTFoY0hCc2FXTmhkR2x2Ymk1MFpYTjBMbk4yWXk1amJIVnpkR1Z5TG14dlkyRnNNQjRYCkRUSXlNRGd3TVRBd01EQXdNRm9YRFRJeU1EZ3dNakF3TURBd01Gb3dXVEVMTUFrR0ExVUVCaE1DVUV3eENqQUkKQmdOVkJBZ01BVUV4RERBS0JnTlZCQW9NQTFOQlVERXdNQzRHQTFVRUF3d25iVzlqYXkxaGNIQnNhV05oZEdsdgpiaTUwWlhOMExuTjJZeTVqYkhWemRHVnlMbXh2WTJGc01JSUJJakFOQmdrcWhraUc5dzBCQVFFRkFBT0NBUThBCk1JSUJDZ0tDQVFFQTQ4cTdiU21rSVZwQng5SWo3Si9qWGFJNU85dGs5dEJlTlhxcGNQM2lsTUtFMVpqTmhyb0wKRjNNV2xnWU10cCtBRlEvKzhYdjlESFVCMWtaNnU4QjZiQzFjV1NSZWMrUWY1ZThYNXZlZkFodng2ZHhCem0wbgo5MDhodTVhRFFQUXdCOHdsYSsyRHAzTjZVdTJQcW01cXk1U0xPcFZxN3hnaHBiUFBQSndoZGNIZFoxN0hvckl2CmcvdUt2M3JLdWJtY2U1MDdDaGFVWGhsWTUyeUtHelRvdXp5R3RqRjhOelRWSmQ1QmtFWGhmVW5HdWttbHBOSG8KRHNUWEJYcE9jNkdxb1VmL1FueUdQTTNtVEVkVUJEQzVEOGhtaUhSU3UyM3VHa2VLdGpWV2o1Ukdydkx2aUdRcgpoeHRhcStzNzBPTUtVbURaRDBMU3MyNXNwVzFnUWtkUzRRSURBUUFCb3pZd05EQXlCZ05WSFJFRUt6QXBnaWR0CmIyTnJMV0Z3Y0d4cFkyRjBhVzl1TG5SbGMzUXVjM1pqTG1Oc2RYTjBaWEl1Ykc5allXd3dEUVlKS29aSWh2Y04KQVFFTEJRQURnZ0VCQUMrNnM3TmJlYSs2RnRibSt1V2FUQjZSSTkzMEpIRUhEd3Y5YWQvR2VXZllZd2tBVXpQMApja1VKSzZDWHVCa2FxYzVOSkpuRmVGZGpIOXZ4MHVBSkxvNXdiZUpGTjB6SXRVdTNBMGtEMnd2U3VXTGJCbEhBCnFiTWxQMm9FMWxsU3hZZDhRMFpPaDllUld1MkMzMitjdnorRWw2RXFzbE9OVmlrZWEyNWJvYnFnelJhY2FCM0UKMG5KQUgwOUFyMys3MllzSHFNd2EyUm51bWVORDJWdGNGT3JraWt3ZkxJbml5NFJpQkdSY3RhVTF6bk9oZVpMNQoxZFJDOURhMk5nZzNrb2tDb3ZibmtHcXZsWk80ZnJJeEw1U244WjFXcEl4dXNoTzBaWjdkeWdaT0FtSEluQzd0CmJYSHJsb3VDclh4TGlHKy9qRnVvMXRZYlFHN2VUWE8rWDNBPQotLS0tLUVORCBDRVJUSUZJQ0FURS0tLS0tCg== - server.key: LS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVktLS0tLQpNSUlFcGdJQkFBS0NBUUVBNDhxN2JTbWtJVnBCeDlJajdKL2pYYUk1Tzl0azl0QmVOWHFwY1AzaWxNS0UxWmpOCmhyb0xGM01XbGdZTXRwK0FGUS8rOFh2OURIVUIxa1o2dThCNmJDMWNXU1JlYytRZjVlOFg1dmVmQWh2eDZkeEIKem0wbjkwOGh1NWFEUVBRd0I4d2xhKzJEcDNONlV1MlBxbTVxeTVTTE9wVnE3eGdocGJQUFBKd2hkY0hkWjE3SApvckl2Zy91S3Yzckt1Ym1jZTUwN0NoYVVYaGxZNTJ5S0d6VG91enlHdGpGOE56VFZKZDVCa0VYaGZVbkd1a21sCnBOSG9Ec1RYQlhwT2M2R3FvVWYvUW55R1BNM21URWRVQkRDNUQ4aG1pSFJTdTIzdUdrZUt0alZXajVSR3J2THYKaUdRcmh4dGFxK3M3ME9NS1VtRFpEMExTczI1c3BXMWdRa2RTNFFJREFRQUJBb0lCQVFEZlB1QWpZeTBsTnRURApKakxwQStZTDdTSVVoTGRWb083RGtOeWhEV0ZUazdRbHRpU3ZSb1A2VG1PelVtaUJUcDV6aGdMQTNsZ3BMajlICnBqbEE2cW5RZlVCRmFQeGNyaFdJL3FNNVRETjlHTEFsRnlVelR3MWROaU9FT2tXV2tmckVtWkdQVGU2NlhOVmsKa3NnN0t3M2xTVWFPZXNPYllkWVFGTUlrejR1SFlFZlEwbWprTUVzdWJLWDRVVmJpbzg3Q0ljbHVYTFRodnBLNwpMWGZVdjdIdXJFY0hxdkVPbDhZYXdJckdLL1VMUWJLV3ZPN0xxS2hzTzJiSmhpbWoyNjVBZGwrNjdpbXJabHRHCnExVWM3V2lVOXlkeVNycTgrbVd0elpwbVpWR1N4RFkzcXlDeEJIbmJKNDNJMFZ3SktLcURMUzVMQTkvc0ZyZUwKVUpFdWlxYmxBb0dCQVBhYU4rdmJuWGlrTEFnckhONDRjQ252QkxhUkV4YmFyVVdMT1ZHVStnWUVtenRveUdBdgpkSWdXeE1maExHL2J5Z29SWmpxenc1TTBHMGVBTTJEWUpZV1hJM1NYR3RXM3B1Vzl4b0pMS09WN2c3anorNjZJCkpSaTFqeUY0QVdOZXpZUWdUZG5ncndULys5bHhOSThMbUMxN2wrSWprNXR2Um5WVCtUQTRRSGw3QW9HQkFPeDUKQVFUZ1QxWEtiNDFGLzRFL3R2cGJBdEdneDE5VzYyb0IwcG83M2JKQjN2bUIzTzZpYzBna2VQS1dxUEFFakxINAo0MVQ0U2MxbU5qT0p2TC82Z2ZXZDRqUEllMTRFWDM5UW8xeEtPSkh0dDU4Qm5yaVZwZVBWUFprRklOYWwrRTJECk1rbzI1dzkzd3FsSDBuVEF4eHlFQ3RTNjdpS1BldVFPRXhLNlJOQlRBb0dCQU14em1jOTdHZmlPckU3dFo1YTUKMWd4K05Uc2oxbDdKV0lUaTQ5ZkdtdS9vVzhjS25hNVpTZFVXZzNsd0w4Wmh4QVZLM2FYbnFrdGVGUXZYdDBFZwpreU5KNWtSZ2p3Z0hwbUN0VVdwdTQrNDIxRVBBVExjcit3MmNZWm1QQkIrZDF1Z25YRVE2YXdETE5zUFZmb3ptClFQbmNrVlVVeCtsRGZYZ0M4Z05QYiswSEFvR0JBTnRmamlCMTcyT0pQMTl4OW94ekRVN0lLNTlKWm12OStMc0oKSWRWUGdHV2tValJwMHduV3p0ZTRiak91ck42dGVkQ0pNbXhiUWl3NGpFUFhuYkVEdHBpamRYdlFteEluUUdpZAo2RTd2MC9jYzd1R2w0UmNnVFJ0RmNiV0pXbU9HNlFrUGt4SGlTUXpDYjJZWGFSaEMxdlNQVW5UelRZUG1VMzFKCnlVdndYWEpkQW9HQkFMMC82Vlc1SGRsSkZCeHlTVGVBTVdVZ0lsVzNpSFhkeVFNRGdic3RPZHl2MittdkRJdEsKS2wzd0FPNitDZ25XNDAxek9yOFRkS2xsNC9paHdoakJaV3k4TWtXUnYrQUEyY21ZMjRRR2liY2cySjIrMkFneApRYllsbEkxWjR3dGVNVjVLTXdFS1FVaXdyTzhBVFZHZCt0QUx6MmRuZXEwNDZuRXFaa2NkZU93aQotLS0tLUVORCBSU0EgUFJJVkFURSBLRVktLS0tLQo= - # CA root certificate valid till 17.12.2049 - ca.crt: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSURrekNDQW51Z0F3SUJBZ0lVR1lXL0t2Mmo0ZTY4UkZ3S2hJTjEzYVkyRStNd0RRWUpLb1pJaHZjTkFRRUwKQlFBd1dURUxNQWtHQTFVRUJoTUNVRXd4Q2pBSUJnTlZCQWdNQVVFeEREQUtCZ05WQkFvTUExTkJVREV3TUM0RwpBMVVFQXd3bmJXOWpheTFoY0hCc2FXTmhkR2x2Ymk1MFpYTjBMbk4yWXk1amJIVnpkR1Z5TG14dlkyRnNNQjRYCkRUSXlNRGd3TVRBd01EQXdNRm9YRFRRNU1USXhOekF3TURBd01Gb3dXVEVMTUFrR0ExVUVCaE1DVUV3eENqQUkKQmdOVkJBZ01BVUV4RERBS0JnTlZCQW9NQTFOQlVERXdNQzRHQTFVRUF3d25iVzlqYXkxaGNIQnNhV05oZEdsdgpiaTUwWlhOMExuTjJZeTVqYkhWemRHVnlMbXh2WTJGc01JSUJJakFOQmdrcWhraUc5dzBCQVFFRkFBT0NBUThBCk1JSUJDZ0tDQVFFQXY5Vk4vdldzalJTZ2dsd2NBRXR2TmN5NVNiRXZkMk9aSXFMa2lVMmZQWjgvUG5QZHorNnQKZ3d6UEtzczh5bkowUEVYeEt2TDMzSWtrbFNueDFCL0lSaHNlU3VFWUxjVUZXdys2MFFpb2Q5ZlJESEFaeFhCVQpaTGlUaUJFMkFEY2lvWnQ3cjBlZGV6cHM5dEUyU3RwZ0N3dmpGeE5JZGxBUkJTN0o3eTRiOTZ3Y3lzdHFOV1luCnI2eFRCYUovTE8xM29jN1V3ZUdRa0xaSy95OG5hOWR5cTlGVDdFbFZVbFEyT0ptYXErdENiK2NLK2hOcWhMaEoKcmpXemJjVHdTRmtNQWt3eDVHUGp2RHRJak5seEpFY1BsWlA2M0tSZEhyWnZWeXEyQllxUkhCb0VHT3F0ZmpYQgpTZkV4bFNLMXVZQ1NkU2oyMFQ4YUJ5Q1dqTEhiL3hrZFRRSURBUUFCbzFNd1VUQWRCZ05WSFE0RUZnUVVqTjRiCnVaRWg3SkFBaG9pdDE4ZXJXM2RlVFBnd0h3WURWUjBqQkJnd0ZvQVVqTjRidVpFaDdKQUFob2l0MThlclczZGUKVFBnd0R3WURWUjBUQVFIL0JBVXdBd0VCL3pBTkJna3Foa2lHOXcwQkFRc0ZBQU9DQVFFQWtSRGhlbHYvT3IvbwpQRzB1S3hReVVvMXJvRlhFNmRnN2tSd1FsYjhNbnlVQmZZWkZrWHFSU04yRGZKaFZ1OTVoWnR4RXVobTBKbjRSCmNKUzV5NUZHNmF5WmZJN3krN0Yvdk9pb0RZYUNWWXluWkRZRlluOENsZld1aWplbW1JSStUTEZIUnFiOEJQUDIKSVRtUGl1VkhEeWMrbUdmMU95WmVONnc5bTZRL0FmdEJ1d3R6Qmt3MGlQUFlHVHZFSFdiNkRWWGIyUjBFYnBJUApPYWsveUtUZ2VOR1htemY2ZUhqZnkxaVVla0VXV1N3YWhkSlo1WFYzbGRUY3Q4bmRwM0NRdHZ1Z3YzQzl6T3A5CkxnMUlGR1JhVElIU2NvOWhheWQ2eEtlL0kvTXY1OStHeTlITDhqeGJxMWpMbzFneEN0Mi9KUWZZRmxpb3RkVGMKQ0VJVjVNNGt2dz09Ci0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0K diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/mock-app/templates/credentials/mtls-cert-secret.yml b/tests/components/application-connector/resources/charts/gateway-test/charts/mock-app/templates/credentials/mtls-cert-secret.yml deleted file mode 100644 index aa8e6027372a..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/mock-app/templates/credentials/mtls-cert-secret.yml +++ /dev/null @@ -1,13 +0,0 @@ -apiVersion: v1 -kind: Secret -metadata: - name: mtls-cert-secret - namespace: test -type: Opaque -data: - {{- $files := .Files }} - {{- range tuple "ca.crt" "server.crt" "server.key" }} - {{- $path := printf "certs/positive/%s" . }} - {{ . }}: >- - {{ $files.Get $path | b64enc }} - {{- end }} diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/mock-app/templates/mock-app.yml b/tests/components/application-connector/resources/charts/gateway-test/charts/mock-app/templates/mock-app.yml deleted file mode 100644 index a57dfb873653..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/mock-app/templates/mock-app.yml +++ /dev/null @@ -1,65 +0,0 @@ -apiVersion: apps/v1 -kind: Deployment -metadata: - labels: - app: {{ .Values.global.mockServiceName}} - name: {{ .Values.global.mockServiceName}} - namespace: {{.Values.global.namespace}} -spec: - replicas: 1 - selector: - matchLabels: - app: {{ .Values.global.mockServiceName}} - template: - metadata: - annotations: - traffic.sidecar.istio.io/includeInboundPorts: "*" - traffic.sidecar.istio.io/excludeInboundPorts: "8090,8091" - labels: - app: {{ .Values.global.mockServiceName}} - spec: - containers: - - image: {{ include "imageurl" (dict "reg" .Values.global.containerRegistry "img" .Values.global.images.mockApplication) }} - name: {{ .Values.global.mockServiceName}} - ports: - - containerPort: 8080 - - containerPort: 8090 - - containerPort: 8091 - imagePullPolicy: Always - volumeMounts: - - name: certs-secret-volume - mountPath: /etc/secret-volume - - name: expired-certs-secret-volume - mountPath: /etc/expired-server-cert-volume - livenessProbe: - httpGet: - path: /v1/health - port: 8080 - initialDelaySeconds: 3 - periodSeconds: 3 - volumes: - - name: certs-secret-volume - secret: - secretName: mtls-cert-secret - - name: expired-certs-secret-volume - secret: - secretName: expired-mtls-cert-secret ---- -apiVersion: v1 -kind: Service -metadata: - name: {{ .Values.global.mockServiceName}} - namespace: {{ .Values.global.namespace }} -spec: - selector: - app: {{ .Values.global.mockServiceName}} - ports: - - name: "http" - protocol: TCP - port: 8080 - - name: "https" - protocol: TCP - port: 8090 - - name: "httpsexp" - protocol: TCP - port: 8091 \ No newline at end of file diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/test/Chart.yaml b/tests/components/application-connector/resources/charts/gateway-test/charts/test/Chart.yaml deleted file mode 100644 index ecec00c5639f..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/test/Chart.yaml +++ /dev/null @@ -1,24 +0,0 @@ -apiVersion: v2 -name: test -description: A Helm chart for Kubernetes - -# A chart can be either an 'application' or a 'library' chart. -# -# Application charts are a collection of templates that can be packaged into versioned archives -# to be deployed. -# -# Library charts provide useful utilities or functions for the chart developer. They're included as -# a dependency of application charts to inject those utilities and functions into the rendering -# pipeline. Library charts do not define any templates and therefore cannot be deployed. -type: application - -# This is the chart version. This version number should be incremented each time you make changes -# to the chart and its templates, including the app version. -# Versions are expected to follow Semantic Versioning (https://semver.org/) -version: 0.1.0 - -# This is the version number of the application being deployed. This version number should be -# incremented each time you make changes to the application. Versions are not expected to -# follow Semantic Versioning. They should reflect the version the application is using. -# It is recommended to use it with quotes. -appVersion: "0.1.0" diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/_helpers.tpl b/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/_helpers.tpl deleted file mode 100644 index 9cba139160b4..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/_helpers.tpl +++ /dev/null @@ -1,12 +0,0 @@ - -{{/* -Create a URL for container images -*/}} -{{- define "imageurl" -}} -{{- $registry := default $.reg.path $.img.containerRegistryPath -}} -{{- if hasKey $.img "directory" -}} -{{- printf "%s/%s/%s:%s" $registry $.img.directory $.img.name $.img.version -}} -{{- else -}} -{{- printf "%s/%s:%s" $registry $.img.name $.img.version -}} -{{- end -}} -{{- end -}} diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/code-rewriting.yaml b/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/code-rewriting.yaml deleted file mode 100644 index 19977c60832e..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/code-rewriting.yaml +++ /dev/null @@ -1,47 +0,0 @@ -apiVersion: applicationconnector.kyma-project.io/v1alpha1 -kind: Application -metadata: - name: code-rewriting - namespace: "{{ .Values.global.namespace }}" -spec: - description: Code Rewriting - skipVerify: true - labels: - app: code-rewriting - services: - - displayName: code 500 - name: code 500 - providerDisplayName: code 500 - description: Should return 502 given 500 - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/unsecure/code/500" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/code-rewriting/code-500" - - displayName: code 503 - name: code 503 - providerDisplayName: code 503 - description: Should return 502 given 503 - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/unsecure/code/503" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/code-rewriting/code-503" - - displayName: code 502 - name: code 502 - providerDisplayName: code 502 - description: Should return 502 given 502 - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/unsecure/code/502" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/code-rewriting/code-502" - - displayName: code 123 - name: code 123 - providerDisplayName: code 123 - description: Should return 200 given 123 - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/unsecure/code/123" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/code-rewriting/code-123" diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/basic-auth-negative.yaml b/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/basic-auth-negative.yaml deleted file mode 100644 index 1507127e5dd6..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/basic-auth-negative.yaml +++ /dev/null @@ -1,10 +0,0 @@ -apiVersion: v1 -kind: Secret -metadata: - name: basic-test-negative-case - namespace: kyma-system -type: Opaque -data: - password: {{ "passwd" | b64enc }} - username: {{ "user" | b64enc }} - diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/basic-auth-positive.yaml b/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/basic-auth-positive.yaml deleted file mode 100644 index 311f41fb694e..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/basic-auth-positive.yaml +++ /dev/null @@ -1,9 +0,0 @@ -apiVersion: v1 -kind: Secret -metadata: - name: basic-test - namespace: kyma-system -type: Opaque -data: - password: {{ "passwd" | b64enc }} - username: {{ "user" | b64enc }} diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/mtls-negative-case.yaml b/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/mtls-negative-case.yaml deleted file mode 100644 index f2025ecbcb4f..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/mtls-negative-case.yaml +++ /dev/null @@ -1,10 +0,0 @@ -apiVersion: v1 -kind: Secret -metadata: - name: mtls-negative-case - namespace: kyma-system -type: Opaque -data: - {{- $files := .Files }} - crt: {{ $files.Get "certs/positive/client.crt" | b64enc }} - key: {{ $files.Get "certs/positive/client.key" | b64enc }} \ No newline at end of file diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/mtls-negative-expired-client-cert.yaml b/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/mtls-negative-expired-client-cert.yaml deleted file mode 100644 index b8e71c3bc540..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/mtls-negative-expired-client-cert.yaml +++ /dev/null @@ -1,10 +0,0 @@ -apiVersion: v1 -kind: Secret -metadata: - name: mtls-negative-expired-client-cert - namespace: kyma-system -type: Opaque -data: - # Client certificate expired on 02.08.2022 - crt: bm90QmVmb3JlPUF1ZyAgMSAwMDowMDowMCAyMDIyIEdNVApub3RBZnRlcj1BdWcgIDIgMDA6MDA6MDAgMjAyMiBHTVQKLS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSURkakNDQWw2Z0F3SUJBZ0lVZldyTzlHRG1rR0FCRktMdzYvL0tVcDdYMnE0d0RRWUpLb1pJaHZjTkFRRUwKQlFBd1dURUxNQWtHQTFVRUJoTUNVRXd4Q2pBSUJnTlZCQWdNQVVFeEREQUtCZ05WQkFvTUExTkJVREV3TUM0RwpBMVVFQXd3bmJXOWpheTFoY0hCc2FXTmhkR2x2Ymk1MFpYTjBMbk4yWXk1amJIVnpkR1Z5TG14dlkyRnNNQjRYCkRUSXlNRGd3TVRBd01EQXdNRm9YRFRJeU1EZ3dNakF3TURBd01Gb3dXVEVMTUFrR0ExVUVCaE1DVUV3eENqQUkKQmdOVkJBZ01BVUV4RERBS0JnTlZCQW9NQTFOQlVERXdNQzRHQTFVRUF3d25iVzlqYXkxaGNIQnNhV05oZEdsdgpiaTUwWlhOMExuTjJZeTVqYkhWemRHVnlMbXh2WTJGc01JSUJJakFOQmdrcWhraUc5dzBCQVFFRkFBT0NBUThBCk1JSUJDZ0tDQVFFQTZSMU1VeVRTT2FyNGtPTUdMV1BWZUU4WXkwRTRlcGV3NS9aL2ZZNlQ5d1BWYUdSTE9RSEYKLzhCVjVEeHhGLzN0K0Y0S21tSHJ6TjlyUDN5T3VnVnY4bEhlek9VeFhmZWFrN0hMR2VGV3k5TGxmc3BtODhJMwpxR3BHM2FaUUhZS0VGRk1IUDREcGdkM3JUUVlhNVFnMDRNZDZuZjk1SFY1YzJtTlErb2pqUWt0cWROSUpPb2p5Clk4WjdlaWMyRURtMWxqYkdCTFZESEY1aUY3QjQ1bXp0OTgzZElaeC81TW9OMnpjdlF5OU9GMlkvcm1EL284QkQKd3llR2xvejVqTHNGRUJqbWdBSWFrSXBiVkZqekk4Tlp3cW0wOTZSM2JuZCtJdml3eS96YkRxYlNxQ2Qvdi9qRApIT0x2M0pIRXNLL0VxNng0VGZhL1lqTFozbjRrNmhCVHVRSURBUUFCb3pZd05EQXlCZ05WSFJFRUt6QXBnaWR0CmIyTnJMV0Z3Y0d4cFkyRjBhVzl1TG5SbGMzUXVjM1pqTG1Oc2RYTjBaWEl1Ykc5allXd3dEUVlKS29aSWh2Y04KQVFFTEJRQURnZ0VCQUxpMVI2MjhpOXZXWkkrNnJKZHN4MEhtZUZLUGNVenV3R1ptU2t2TC9rTHliOUE3b2V6SQpPbkRLL0EzOFpGcmpzTE9YQWRJZkxXS0laMkh5b21FNG9HMldNL3phN1BCWDc4dXpycWw5bFR2eWtQOFRkdm5qCkpTN2l4cWZucW1UNDdLVHFOSjRleXMzd2NOU29kTHlydWNDUWlLeUllMEFUQ3RUSUY2WnNGR3Q2WkN0WS84czYKQTJ0Rk92dmhTWm01UytsZGVEQ3FMajJMOW1oZEY0RzlMRmJ5Q2pTbVNDWEFSbDVpanBjb2pEWEVDRTdobTk5YwpnbU1scjE2Uzh1Nm5mWEVRdXFwTys4MU4xTEVpTzVyUzRwUGxBdGgyVk5YOXc0WHBmbEM1VDA0bzA5S21HYzhLCjhVTjB1YXJpRGx2NW93SEZlWVRsZkZ6eGhUUDJBOWFPL3U4PQotLS0tLUVORCBDRVJUSUZJQ0FURS0tLS0tCg== - key: LS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVktLS0tLQpNSUlFcEFJQkFBS0NBUUVBNlIxTVV5VFNPYXI0a09NR0xXUFZlRThZeTBFNGVwZXc1L1ovZlk2VDl3UFZhR1JMCk9RSEYvOEJWNUR4eEYvM3QrRjRLbW1IcnpOOXJQM3lPdWdWdjhsSGV6T1V4WGZlYWs3SExHZUZXeTlMbGZzcG0KODhJM3FHcEczYVpRSFlLRUZGTUhQNERwZ2QzclRRWWE1UWcwNE1kNm5mOTVIVjVjMm1OUStvampRa3RxZE5JSgpPb2p5WThaN2VpYzJFRG0xbGpiR0JMVkRIRjVpRjdCNDVtenQ5ODNkSVp4LzVNb04yemN2UXk5T0YyWS9ybUQvCm84QkR3eWVHbG96NWpMc0ZFQmptZ0FJYWtJcGJWRmp6SThOWndxbTA5NlIzYm5kK0l2aXd5L3piRHFiU3FDZC8Kdi9qREhPTHYzSkhFc0svRXE2eDRUZmEvWWpMWjNuNGs2aEJUdVFJREFRQUJBb0lCQUhWalJZNFEyclFqZm13bgpobkxROVN4U1dGL3lCZWpsL2pXeEVWNCtzQkFScENPZmJhblZWTW1ISnpsNW5sSEFrMWNndENJdDhUb0h2OUFHCmZ6RDVqL2ZzZGsramtvcUpKeFA4MGhQRVA1c0FKb1VFazNkb2MvS2hJZkozejV3c255cEU3VDl6UVNNZWgyRVEKRS9jRmZPczhTR2pMdjBla3Z3bFNQZk1MZjdWZm9vK2h6K2krUW5jMXFRR2lPVW90Tk11WmoxcU85Mm5Ib2toMApxcWRRWlFOa1pUQm1sd2Y0bGNpeVJsTVUwRHJJNmd1bDNRazNpd2hueU1Kb2h4dVJxT3RSNzJjTS9SVFpsMHdWClh4WmJ5VkM1R2dhRUR0aUtFaE9xdmpPN2N4WU9BU3U3aGVDbWRnRFdMMGFSVjE1ai9Sb0twRUtkeWt0SHFrRjQKcWVLZndBa0NnWUVBL2pKaHBqSWh5N09Vajh1cW1scHE4L0tyRG5zUG1FK0VqbzFxOWdiTDByRVZSaktMNHpLaAp2SDdrdHJjQUkrMkpaS0hlSDVmVUJSMVYxK3R5WXM5OHUwOFpHSmQ0TFdjNjFFUTQvbEtFVUhaUU41TnpJOHprCmhWbjBhNWZOQjlLMDQ4aU1XQTh6ZlgyQ2JvWWltT0V3ZC9BZUtwdzZjN0E0UXU5RVRGckNhMGNDZ1lFQTZzU2gKb2V4U0pxbE9RMjk1VjlVWWtNTkkrNkR1ZGNoSUZkamY2bUp2NEo1aGhQSmJDY1doZkZjdnZmNkQ0SzBDei8rVwpybmhreWNlU1dDRHNuN3laN1VBbHAwVXp2bk1IYXBqUXUwN3JpcGI0UGExdlE2MkxRYWhTWnFJZmkxeFVqQ1NmCm1GcDJZSXVRV2FWOWFlYUdmSnY0anRnZUJ6VUxFYngwMGdpb3lQOENnWUVBOUR5Q09JWm9sR2xxYjdOWHExRCsKL0grSVBiU2Q2bEZVNHdjYjQySHFTdmtjb01NR1Iza3BqNHc0d3hvWUIyMC9Hckt3VXBpMS9XZ1BTQlFRWnNKSApiVTExcG53NjJ4MFptRVFvb3F1ME4vOUYyZkJScSs4OURxZTh3ZmdyNXIxY1VwUXB6SjVtY2NlN0graS9xemFMCk5HSkJDZDNzQjZZa21LTitjd0t0VlJjQ2dZQkRKaFM1RkxmMm1PeHF1Mkt3cmFIR0hpVXMyNzM0OEYwMTZuODUKTWdpZjdZMGxFcERaZmE2UHV2eEwwcFZ6Mk9oNkI3ZllsVlQycGQrRTEzMzJ2bUlraXZsNkc0QU9WQ1psNWVtbAorWS9EWnlUL3R6Q2c0ZTEzelNZc2R1aWcycnJRRHRXYkpSekF4b3AyS2JCeWJ0NCttL24vR1crVlRpV3BZQWJsCjRGWXVqd0tCZ1FDT3VUenVZS1QrVHZuU3hDVWdZbUN3SWs5MlVxUHJCS3J5UE1sekxMdFBaMlF3UjNpRGlWTzEKUlpxNGtkc1NzU05SNUJKUzlrVW92dUpubG1hb0ZBM2NLZXhRdk9mcmFVdXNGcXVHb3NWR3hrSGo3S24ydnFadQppK0NDNTZPNHRRMnNhOXZ6MFNpTWZoMzdFRlh6eUFVODNpWGY2aTB0MGlzb0cvYmFpTlNDZ2c9PQotLS0tLUVORCBSU0EgUFJJVkFURSBLRVktLS0tLQo= \ No newline at end of file diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/mtls-negative-expired-server-cert.yaml b/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/mtls-negative-expired-server-cert.yaml deleted file mode 100644 index e96af97d018a..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/mtls-negative-expired-server-cert.yaml +++ /dev/null @@ -1,10 +0,0 @@ -apiVersion: v1 -kind: Secret -metadata: - name: mtls-negative-expired-server-cert - namespace: kyma-system -type: Opaque -data: - # Valid client certificate expiring on 17.12.2049 - crt: bm90QmVmb3JlPUF1ZyAgMSAwMDowMDowMCAyMDIyIEdNVApub3RBZnRlcj1EZWMgMTcgMDA6MDA6MDAgMjA0OSBHTVQKLS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSURkakNDQWw2Z0F3SUJBZ0lVWnVOZ3FCQTdSUEs4bStSSnhuaXRTS21xZFdjd0RRWUpLb1pJaHZjTkFRRUwKQlFBd1dURUxNQWtHQTFVRUJoTUNVRXd4Q2pBSUJnTlZCQWdNQVVFeEREQUtCZ05WQkFvTUExTkJVREV3TUM0RwpBMVVFQXd3bmJXOWpheTFoY0hCc2FXTmhkR2x2Ymk1MFpYTjBMbk4yWXk1amJIVnpkR1Z5TG14dlkyRnNNQjRYCkRUSXlNRGd3TVRBd01EQXdNRm9YRFRRNU1USXhOekF3TURBd01Gb3dXVEVMTUFrR0ExVUVCaE1DVUV3eENqQUkKQmdOVkJBZ01BVUV4RERBS0JnTlZCQW9NQTFOQlVERXdNQzRHQTFVRUF3d25iVzlqYXkxaGNIQnNhV05oZEdsdgpiaTUwWlhOMExuTjJZeTVqYkhWemRHVnlMbXh2WTJGc01JSUJJakFOQmdrcWhraUc5dzBCQVFFRkFBT0NBUThBCk1JSUJDZ0tDQVFFQTRpZHp6dFhjZG9Dd21YNm9HeSt5elFjYW5iZVpmZ2xBTFlrVktUUVhrYXoyWW8wWXV3cGQKS1VhSjZEbkVUTVVneGYwb3RUWENBSU9HM1cySTZyRzc1UXBsVWZTNDVzNWQ4MVE5WGhMRm9Oa0o1ZWlzUW1paQpCSURQOC9qQ2RHSk04Z2hpa1A1bk1xQ0hRdGk1bkR3MmtINCtiZDNIVzgyWTFWWkg5Y3ArdUpDa251clMvbDArCnFSUkxndWZUY0c0VU5iaGEwWnZaNUcwMStTdnJxVXBudmVaQUdlcTlOaWlhUXhmSkFkcTdISHMrMnFDOGtEczQKUllOVFJNTUMrYXVueDV3M1g4eEUyR0oxRkdjSjNmRkszTFhsNnRXaWFBajVHNjloSnpoNG5HMzdEVy9aMEF0UgovM3B2UnB2K0k1WCtTUWZUVHBqQzBGbld6Z1JrZ2hucWV3SURBUUFCb3pZd05EQXlCZ05WSFJFRUt6QXBnaWR0CmIyTnJMV0Z3Y0d4cFkyRjBhVzl1TG5SbGMzUXVjM1pqTG1Oc2RYTjBaWEl1Ykc5allXd3dEUVlKS29aSWh2Y04KQVFFTEJRQURnZ0VCQUxQSmVJNGtGRlV4YlNVN2NtcHFjaFpWWUx0dmhYRkU4Y0YrUUZTRzhTOXZIOUVxdnlYNApNNW8wSkQzeDU3T0dnK0liVHJRQXRXVG5zbnNBbGk4d3FMQTJVYlZZTThOM0JRSFBSNHZUMkZjRndHQmpQR3hGCmlGcDZlUGxvbTJ0bTBEVjNXbzkzdG0wWnhmRXpQYXlHOHJhc0puc3psT0hVOEtqT2ppOUtjN0F4WXBhODh4MDIKdTN4RjNUMkhZMkExeS9NdmJpeFpwNG12YWZiTFJOOUFqUWY3QXJxNEQ5cThlS0ZhY3EwYndFaVlTK3daZG9kNQp0RDM5MktweVNPZDBFMld4dHozNTRsZmI0cEIzK2k5Z21Ma3lUbUhHZWJzMWdBUmV1TENQTW5OQThTZTdHVGNkCjA0ZlltR3pmNjVySDNqM1d2MzQ0dy81M2dtRWdrOXg0TGswPQotLS0tLUVORCBDRVJUSUZJQ0FURS0tLS0tCg== - key: LS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVktLS0tLQpNSUlFcFFJQkFBS0NBUUVBNGlkenp0WGNkb0N3bVg2b0d5K3l6UWNhbmJlWmZnbEFMWWtWS1RRWGthejJZbzBZCnV3cGRLVWFKNkRuRVRNVWd4ZjBvdFRYQ0FJT0czVzJJNnJHNzVRcGxVZlM0NXM1ZDgxUTlYaExGb05rSjVlaXMKUW1paUJJRFA4L2pDZEdKTThnaGlrUDVuTXFDSFF0aTVuRHcya0g0K2JkM0hXODJZMVZaSDljcCt1SkNrbnVyUwovbDArcVJSTGd1ZlRjRzRVTmJoYTBadlo1RzAxK1N2cnFVcG52ZVpBR2VxOU5paWFReGZKQWRxN0hIcysycUM4CmtEczRSWU5UUk1NQythdW54NXczWDh4RTJHSjFGR2NKM2ZGSzNMWGw2dFdpYUFqNUc2OWhKemg0bkczN0RXL1oKMEF0Ui8zcHZScHYrSTVYK1NRZlRUcGpDMEZuV3pnUmtnaG5xZXdJREFRQUJBb0lCQVFDWUFySzUzVkFocXlDSgpHL1E4eWRQaU1oczIxZGpyT2FhVXRPYXZXbDlaUUt3ZjAvMUNnNVhaRDV2VXB6ZUY3cDYzMWhGTnRFT2hlc2JsCkFTSWR0cmU0SFVPN1VjWVRCYlZxd0QyN2hOeW40QnJpR1lIbjVWSzV1aWVOTXJEcDc4VU9qb3BLTVdZR1JwYUUKWFE1dHNKOXdnaHJPV0ZzUEh1UFN5ZnIyZ0ZTckV2TEdYRUQxUVBFdUhqcllZeDBMcVJDVSt4NUhvajBkLzZyYgpOMEJjako5SHVwMDZLejN4QlBxemgyeHp1Q2kyYjdGc01vQndkTGcyNGM3bHJsZCtLb09ZdFczLzJSZUJPdXpHCk1HWjFPZlJJcERjdk9xNXlBWXZuYjcya0xJV3E2ZUxCVkx2ekFJZnBLRFBtbmVkd0p2dXVpcUZldktzQVY5eXAKSlo1NjdXeXBBb0dCQVBPbHZvT3pxRUwrN0c4RUM5TW9Vc0lOWVRMMXdYU3VUTzVvczlpc0doRzJHNlprajRWWgpPNlY4Qm1ET2tYT0NtRzNpTWY4M0NSVGs3Um5MVExiRVJJRkxzNFpnend0N2trVHVXSnlzTkRUeGZuMmFVeUlwCm9iNWFvWVozcHNiTXBIbmxNSGN2R1l4SXFVK0JzQVpnbGtOYTdSQVVwTnN5bkJWYzNpZEV5R0hmQW9HQkFPMmUKcWx1dlI4b096VC9jbzVCS1pWS05jQ2V2bHhJNmVXd1NrRDJaaGNuZU1aWFcyY3Z5NERzUWFHQWNKelJsaWpvNAo0RXFsN2VQM0VYbVZYNEtQWXlkSFpZWGZubEkwWVdrSHloR015anBueWFYUWZ2c3AyU1BpM0lKQTZCZ2htbThKCkxyMWFTcmtLaXE3bis3dmtVYitESktBSk0wZXoyc1dzTkNMMC9XTGxBb0dCQUpkcU1YTjNldUhudXRkakZGWXQKZ1FESGY5aERrZTRKUkJZRlMzOGp0Uys4bElKYmpEVzZ0cTZvM08zY2NkZnZHUHR3enRGa1NtaUp2QytEZ0RFMAoxNzNpWmJibEFzYUlET1o1bU9nRXZJMEtaeWwzZHFLTWJNLzNVdHBXRVhjS1JremFlYndYc1REVkZ5TXAzVktaClE4aW9BUnMxT1I1ZjNWQUpYcVhZd1E3UkFvR0Fid0ZvWkZ5R0ZRYkZLOGhQUU9FQVpJaGVsS3VhejVFeG1DTXoKN3hNQlJVVGZ0VGdobHYxbmN6QS9FbWNVaVkzRi9WMEVxdHJKUDIzMFkvQThKaW9HRUJ0eWVnLzFUa0hhSDg3Ygp2MGNlVWhxYVFUUWRuZ2Yyd0tVQ2puYno5aEg4cTFLRzJ6NkxHZGFxNHZyTXh3SHFqcVVkUHdZTlJybm13ZUdvCm1Zd0pzMkVDZ1lFQXROSHI2TEx6VkVIaWU3MzhZV0doYnRSUGRPWGdFMStqVTdhZGZ4RXJtckVLL0ZZdkl5dmoKVWZ1WHlrZ3ZBeWF1Q2tiS2RsRFZkd1d5K2NuTXNCSkFSbFY5a1BGK2xwaTVweUpBL2J6blF4VVJHYmZ1UHNkUQpHZmRjUUhyMjVjR0xxN3E2Z0xaRUJxS0JpMmFZc3BkcmtNQTFIY0txNDhmVUNtNmZyMGVyelVzPQotLS0tLUVORCBSU0EgUFJJVkFURSBLRVktLS0tLQo= \ No newline at end of file diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/mtls-negative-other-ca.yaml b/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/mtls-negative-other-ca.yaml deleted file mode 100644 index 6ae6ceac03fd..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/mtls-negative-other-ca.yaml +++ /dev/null @@ -1,10 +0,0 @@ -apiVersion: v1 -kind: Secret -metadata: - name: mtls-negative-other-ca - namespace: kyma-system -type: Opaque -data: - {{- $files := .Files }} - crt: {{ $files.Get "certs/negative/client.crt" | b64enc }} - key: {{ $files.Get "certs/negative/client.key" | b64enc }} diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/mtls-oauth-nagative-incorrect-clientid.yaml b/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/mtls-oauth-nagative-incorrect-clientid.yaml deleted file mode 100644 index cce16c4f38a5..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/mtls-oauth-nagative-incorrect-clientid.yaml +++ /dev/null @@ -1,11 +0,0 @@ -apiVersion: v1 -kind: Secret -metadata: - name: mtls-oauth-negative-incorrect-clientid - namespace: kyma-system -type: Opaque -data: - {{- $files := .Files }} - crt: {{ $files.Get "certs/positive/client.crt" | b64enc }} - key: {{ $files.Get "certs/positive/client.key" | b64enc }} - clientId: {{ "incorrect" | b64enc }} diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/mtls-oauth-nagative-other-ca.yaml b/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/mtls-oauth-nagative-other-ca.yaml deleted file mode 100644 index 3bbb0851b0b7..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/mtls-oauth-nagative-other-ca.yaml +++ /dev/null @@ -1,11 +0,0 @@ -apiVersion: v1 -kind: Secret -metadata: - name: mtls-oauth-negative-other-ca - namespace: kyma-system -type: Opaque -data: - {{- $files := .Files }} - crt: {{ $files.Get "certs/invalid-ca/client.crt" | b64enc }} - key: {{ $files.Get "certs/invalid-ca/client.key" | b64enc }} - clientId: {{ "clientID" | b64enc }} diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/mtls-oauth-negative-case.yaml b/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/mtls-oauth-negative-case.yaml deleted file mode 100644 index 02377d6e5b11..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/mtls-oauth-negative-case.yaml +++ /dev/null @@ -1,11 +0,0 @@ -apiVersion: v1 -kind: Secret -metadata: - name: mtls-oauth-negative-case - namespace: kyma-system -type: Opaque -data: - {{- $files := .Files }} - crt: {{ $files.Get "certs/positive/client.crt" | b64enc }} - key: {{ $files.Get "certs/positive/client.key" | b64enc }} - clientId: {{ "clientID" | b64enc }} \ No newline at end of file diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/mtls-oauth-negative-expired-client-cert.yaml b/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/mtls-oauth-negative-expired-client-cert.yaml deleted file mode 100644 index 743fd94117ff..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/mtls-oauth-negative-expired-client-cert.yaml +++ /dev/null @@ -1,10 +0,0 @@ -apiVersion: v1 -kind: Secret -metadata: - name: mtls-oauth-negative-expired-client-cert - namespace: kyma-system -type: Opaque -data: - crt: bm90QmVmb3JlPUF1ZyAgMSAwMDowMDowMCAyMDIyIEdNVApub3RBZnRlcj1BdWcgIDIgMDA6MDA6MDAgMjAyMiBHTVQKLS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSURkakNDQWw2Z0F3SUJBZ0lVZldyTzlHRG1rR0FCRktMdzYvL0tVcDdYMnE0d0RRWUpLb1pJaHZjTkFRRUwKQlFBd1dURUxNQWtHQTFVRUJoTUNVRXd4Q2pBSUJnTlZCQWdNQVVFeEREQUtCZ05WQkFvTUExTkJVREV3TUM0RwpBMVVFQXd3bmJXOWpheTFoY0hCc2FXTmhkR2x2Ymk1MFpYTjBMbk4yWXk1amJIVnpkR1Z5TG14dlkyRnNNQjRYCkRUSXlNRGd3TVRBd01EQXdNRm9YRFRJeU1EZ3dNakF3TURBd01Gb3dXVEVMTUFrR0ExVUVCaE1DVUV3eENqQUkKQmdOVkJBZ01BVUV4RERBS0JnTlZCQW9NQTFOQlVERXdNQzRHQTFVRUF3d25iVzlqYXkxaGNIQnNhV05oZEdsdgpiaTUwWlhOMExuTjJZeTVqYkhWemRHVnlMbXh2WTJGc01JSUJJakFOQmdrcWhraUc5dzBCQVFFRkFBT0NBUThBCk1JSUJDZ0tDQVFFQTZSMU1VeVRTT2FyNGtPTUdMV1BWZUU4WXkwRTRlcGV3NS9aL2ZZNlQ5d1BWYUdSTE9RSEYKLzhCVjVEeHhGLzN0K0Y0S21tSHJ6TjlyUDN5T3VnVnY4bEhlek9VeFhmZWFrN0hMR2VGV3k5TGxmc3BtODhJMwpxR3BHM2FaUUhZS0VGRk1IUDREcGdkM3JUUVlhNVFnMDRNZDZuZjk1SFY1YzJtTlErb2pqUWt0cWROSUpPb2p5Clk4WjdlaWMyRURtMWxqYkdCTFZESEY1aUY3QjQ1bXp0OTgzZElaeC81TW9OMnpjdlF5OU9GMlkvcm1EL284QkQKd3llR2xvejVqTHNGRUJqbWdBSWFrSXBiVkZqekk4Tlp3cW0wOTZSM2JuZCtJdml3eS96YkRxYlNxQ2Qvdi9qRApIT0x2M0pIRXNLL0VxNng0VGZhL1lqTFozbjRrNmhCVHVRSURBUUFCb3pZd05EQXlCZ05WSFJFRUt6QXBnaWR0CmIyTnJMV0Z3Y0d4cFkyRjBhVzl1TG5SbGMzUXVjM1pqTG1Oc2RYTjBaWEl1Ykc5allXd3dEUVlKS29aSWh2Y04KQVFFTEJRQURnZ0VCQUxpMVI2MjhpOXZXWkkrNnJKZHN4MEhtZUZLUGNVenV3R1ptU2t2TC9rTHliOUE3b2V6SQpPbkRLL0EzOFpGcmpzTE9YQWRJZkxXS0laMkh5b21FNG9HMldNL3phN1BCWDc4dXpycWw5bFR2eWtQOFRkdm5qCkpTN2l4cWZucW1UNDdLVHFOSjRleXMzd2NOU29kTHlydWNDUWlLeUllMEFUQ3RUSUY2WnNGR3Q2WkN0WS84czYKQTJ0Rk92dmhTWm01UytsZGVEQ3FMajJMOW1oZEY0RzlMRmJ5Q2pTbVNDWEFSbDVpanBjb2pEWEVDRTdobTk5YwpnbU1scjE2Uzh1Nm5mWEVRdXFwTys4MU4xTEVpTzVyUzRwUGxBdGgyVk5YOXc0WHBmbEM1VDA0bzA5S21HYzhLCjhVTjB1YXJpRGx2NW93SEZlWVRsZkZ6eGhUUDJBOWFPL3U4PQotLS0tLUVORCBDRVJUSUZJQ0FURS0tLS0tCg== - key: LS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVktLS0tLQpNSUlFcEFJQkFBS0NBUUVBNlIxTVV5VFNPYXI0a09NR0xXUFZlRThZeTBFNGVwZXc1L1ovZlk2VDl3UFZhR1JMCk9RSEYvOEJWNUR4eEYvM3QrRjRLbW1IcnpOOXJQM3lPdWdWdjhsSGV6T1V4WGZlYWs3SExHZUZXeTlMbGZzcG0KODhJM3FHcEczYVpRSFlLRUZGTUhQNERwZ2QzclRRWWE1UWcwNE1kNm5mOTVIVjVjMm1OUStvampRa3RxZE5JSgpPb2p5WThaN2VpYzJFRG0xbGpiR0JMVkRIRjVpRjdCNDVtenQ5ODNkSVp4LzVNb04yemN2UXk5T0YyWS9ybUQvCm84QkR3eWVHbG96NWpMc0ZFQmptZ0FJYWtJcGJWRmp6SThOWndxbTA5NlIzYm5kK0l2aXd5L3piRHFiU3FDZC8Kdi9qREhPTHYzSkhFc0svRXE2eDRUZmEvWWpMWjNuNGs2aEJUdVFJREFRQUJBb0lCQUhWalJZNFEyclFqZm13bgpobkxROVN4U1dGL3lCZWpsL2pXeEVWNCtzQkFScENPZmJhblZWTW1ISnpsNW5sSEFrMWNndENJdDhUb0h2OUFHCmZ6RDVqL2ZzZGsramtvcUpKeFA4MGhQRVA1c0FKb1VFazNkb2MvS2hJZkozejV3c255cEU3VDl6UVNNZWgyRVEKRS9jRmZPczhTR2pMdjBla3Z3bFNQZk1MZjdWZm9vK2h6K2krUW5jMXFRR2lPVW90Tk11WmoxcU85Mm5Ib2toMApxcWRRWlFOa1pUQm1sd2Y0bGNpeVJsTVUwRHJJNmd1bDNRazNpd2hueU1Kb2h4dVJxT3RSNzJjTS9SVFpsMHdWClh4WmJ5VkM1R2dhRUR0aUtFaE9xdmpPN2N4WU9BU3U3aGVDbWRnRFdMMGFSVjE1ai9Sb0twRUtkeWt0SHFrRjQKcWVLZndBa0NnWUVBL2pKaHBqSWh5N09Vajh1cW1scHE4L0tyRG5zUG1FK0VqbzFxOWdiTDByRVZSaktMNHpLaAp2SDdrdHJjQUkrMkpaS0hlSDVmVUJSMVYxK3R5WXM5OHUwOFpHSmQ0TFdjNjFFUTQvbEtFVUhaUU41TnpJOHprCmhWbjBhNWZOQjlLMDQ4aU1XQTh6ZlgyQ2JvWWltT0V3ZC9BZUtwdzZjN0E0UXU5RVRGckNhMGNDZ1lFQTZzU2gKb2V4U0pxbE9RMjk1VjlVWWtNTkkrNkR1ZGNoSUZkamY2bUp2NEo1aGhQSmJDY1doZkZjdnZmNkQ0SzBDei8rVwpybmhreWNlU1dDRHNuN3laN1VBbHAwVXp2bk1IYXBqUXUwN3JpcGI0UGExdlE2MkxRYWhTWnFJZmkxeFVqQ1NmCm1GcDJZSXVRV2FWOWFlYUdmSnY0anRnZUJ6VUxFYngwMGdpb3lQOENnWUVBOUR5Q09JWm9sR2xxYjdOWHExRCsKL0grSVBiU2Q2bEZVNHdjYjQySHFTdmtjb01NR1Iza3BqNHc0d3hvWUIyMC9Hckt3VXBpMS9XZ1BTQlFRWnNKSApiVTExcG53NjJ4MFptRVFvb3F1ME4vOUYyZkJScSs4OURxZTh3ZmdyNXIxY1VwUXB6SjVtY2NlN0graS9xemFMCk5HSkJDZDNzQjZZa21LTitjd0t0VlJjQ2dZQkRKaFM1RkxmMm1PeHF1Mkt3cmFIR0hpVXMyNzM0OEYwMTZuODUKTWdpZjdZMGxFcERaZmE2UHV2eEwwcFZ6Mk9oNkI3ZllsVlQycGQrRTEzMzJ2bUlraXZsNkc0QU9WQ1psNWVtbAorWS9EWnlUL3R6Q2c0ZTEzelNZc2R1aWcycnJRRHRXYkpSekF4b3AyS2JCeWJ0NCttL24vR1crVlRpV3BZQWJsCjRGWXVqd0tCZ1FDT3VUenVZS1QrVHZuU3hDVWdZbUN3SWs5MlVxUHJCS3J5UE1sekxMdFBaMlF3UjNpRGlWTzEKUlpxNGtkc1NzU05SNUJKUzlrVW92dUpubG1hb0ZBM2NLZXhRdk9mcmFVdXNGcXVHb3NWR3hrSGo3S24ydnFadQppK0NDNTZPNHRRMnNhOXZ6MFNpTWZoMzdFRlh6eUFVODNpWGY2aTB0MGlzb0cvYmFpTlNDZ2c9PQotLS0tLUVORCBSU0EgUFJJVkFURSBLRVktLS0tLQo= - clientId: {{ "clientID" | b64enc }} \ No newline at end of file diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/mtls-oauth-negative-expired-server-cert.yaml b/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/mtls-oauth-negative-expired-server-cert.yaml deleted file mode 100644 index 2a536df03d0a..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/mtls-oauth-negative-expired-server-cert.yaml +++ /dev/null @@ -1,10 +0,0 @@ -apiVersion: v1 -kind: Secret -metadata: - name: mtls-oauth-negative-expired-server-cert - namespace: kyma-system -type: Opaque -data: - crt: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUQwRENDQXJpZ0F3SUJBZ0lVSkV2L3RtUndLOXRzdWhpQVlaT2Q4NjN1UHlBd0RRWUpLb1pJaHZjTkFRRUwKQlFBd1pqRUxNQWtHQTFVRUJoTUNVRXd4Q2pBSUJnTlZCQWdNQVVFeEREQUtCZ05WQkFvTUExTkJVREU5TURzRwpBMVVFQXd3MGJXOWpheTFoY0hCc2FXTmhkR2x2Ymk1MFpYTjBMbk4yWXk1amJIVnpkR1Z5TG14dlkyRnNkR1Z6CmRDMXZkR2hsY2kxallUQWVGdzB5TWpBeE1ERXdPVEV3TVRCYUZ3MHlNakF4TURJd09URXdNVEJhTUdZeEN6QUoKQmdOVkJBWVRBbEJNTVFvd0NBWURWUVFJREFGQk1Rd3dDZ1lEVlFRS0RBTlRRVkF4UFRBN0JnTlZCQU1NTkcxdgpZMnN0WVhCd2JHbGpZWFJwYjI0dWRHVnpkQzV6ZG1NdVkyeDFjM1JsY2k1c2IyTmhiSFJsYzNRdGIzUm9aWEl0ClkyRXdnZ0VpTUEwR0NTcUdTSWIzRFFFQkFRVUFBNElCRHdBd2dnRUtBb0lCQVFERzFDaHE2WmI3eUdaS0ZwUmgKV01sUDh6L0NtZEFZbktpRkxKNVhpMFlXakpZZXlUSUdXRWM4bm5SK1VOalZKejZjN0w5cCs4bFEvK1ZGZUpmRwpmYTM4WnhHQVZxNitpcXdJOVpwSTd2SlVZRnd0SDJLQXA5cDdZRHdOVllUbXZEb3lyTFh3L1c3c1p1Q2c3QWVBCkh5MGlBcGtBQkk1Tmg4dWFMNkk3eE8xK0dCSVhNYVkzNlFDZXpvejdvbkoyUURBVjlybVEzQndpZUtwMkNUV1QKS3ZHaVBac04rTlVLbndjdVoxbThpUHQxYmozaGsvS3p1MGxvR2RVaXJiOFFUNkFzRnJ2ZzdGNFBYVmFsb1FSNwpJMy9paWpxZFBERmlEOHVwOXltdE9ja2tjQlorSmhqVDI4OTZxcFIzQVJVaGl0dXhreENpMUZHeEd1YlJNREFpCitmcExBZ01CQUFHamRqQjBNRElHQTFVZEVRUXJNQ21DSjIxdlkyc3RZWEJ3YkdsallYUnBiMjR1ZEdWemRDNXoKZG1NdVkyeDFjM1JsY2k1c2IyTmhiREFkQmdOVkhRNEVGZ1FVY25wWGg2b2xoei9tV01LTE1sVTR1Z0gxRUpNdwpId1lEVlIwakJCZ3dGb0FVMzRJa3V5V2NoVlN2ZXlNQXZmdDZOdE1JZkdVd0RRWUpLb1pJaHZjTkFRRUxCUUFECmdnRUJBQmNvYmVNSmkrQVZ1MGZtY0szYzM1RXhQU0pZTWlOYms1VXU0QmgzUlloY0tJeFFyUjY4T1FYT3ZzMEkKVVNaYmRkRjhrQU1KOFpwTGJWQmJnZ2NmUktrVUxPYko3TklyTEF2UmR6cVVzeThMc0VMZUM5cVlVM0E0TUFEWApHWU8zZjlWbnFIelpmRFNMTjFzOGoyK1JQU0hGL3lZbGxETWhCbkVJa1NwdXdWbXprMGFoZEtXRmthcG1xbEZMCkRSZ2JsTThMMVZTbGpXb3hGYUdLNUZFQ2dGZzJIcHJDc2o3SHl0TFR0KzEwc1F5ZU9vVktUVU9lNjhWeFlzR2kKbXd3bnhzTGtHdkdGWTNaVU9JQk5BY0ovdlJLSER4R1pPS29QblIrRmlodkJvZkR1RlBzbnRSTnBIRncrNVJsUQpjL1lUdThmQ1U4QnRpeGwvYkRxdTZUWmtyazg9Ci0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0= - key: LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCk1JSUV2Z0lCQURBTkJna3Foa2lHOXcwQkFRRUZBQVNDQktnd2dnU2tBZ0VBQW9JQkFRREcxQ2hxNlpiN3lHWksKRnBSaFdNbFA4ei9DbWRBWW5LaUZMSjVYaTBZV2pKWWV5VElHV0VjOG5uUitVTmpWSno2YzdMOXArOGxRLytWRgplSmZHZmEzOFp4R0FWcTYraXF3STlacEk3dkpVWUZ3dEgyS0FwOXA3WUR3TlZZVG12RG95ckxYdy9XN3NadUNnCjdBZUFIeTBpQXBrQUJJNU5oOHVhTDZJN3hPMStHQklYTWFZMzZRQ2V6b3o3b25KMlFEQVY5cm1RM0J3aWVLcDIKQ1RXVEt2R2lQWnNOK05VS253Y3VaMW04aVB0MWJqM2hrL0t6dTBsb0dkVWlyYjhRVDZBc0Zydmc3RjRQWFZhbApvUVI3STMvaWlqcWRQREZpRDh1cDl5bXRPY2trY0JaK0poalQyODk2cXBSM0FSVWhpdHV4a3hDaTFGR3hHdWJSCk1EQWkrZnBMQWdNQkFBRUNnZ0VBQlgrem1IVmFZQjlFT1BOVDZqZE81ZitudVVXUXZFV0U0WjRBeVJJSWY3SW0KcXJaTXhHRW5velVNcXJ1b3E0aDQwbFUzM0FJREtOTFM3KzlzWHloMXFkL2QyNHRLTE9uZjVTV0p2VStpY3hQeApLS3hRQ0pmYjBvS3dWbndSZjJJZ1IrdC80cWpYcXdFVFlFLzJ5eVBSbHptMEtveDF0UTQyNHM1RGNkeTU1cjFPCklNbEhPcXhFcE84YWtiY2ZacHE4cVdqMUFkU2VCRk5WdXJQaUxmQjMxN2pQd25RSkp2MU9NWWxsQXJWa1NDcisKNDlMcmk1QjRBL0UrQkh6SnhCQ1lyaC9IRCtCVlhxY3JDSDBKNEQ3TWEwVWJWMER5Vml5UWtwK2c5MGhoQ21HMwpnYVpKUmdkczJnQzI2cGRlR0E1and2Tjd3ZUYveUtsRVEwZXRib0NHS1FLQmdRREtJYUN3czVHbVZUYlRlaDJ0CnRFWmY1MWZwNVdRL1R2V1VJaWtsdHBXU1RRUHQwQWVtZFJxL1FQak5OS3YycnR0dDZIT0RHcW9iSnFVTENjaGYKbEU1cmc0N09EYnV5OHVPWmtVOEYyMTRjZDlSbnU3alNzcFd3ZkEwakpndFhiblZ2aVlXeUtjam90QVQwTXhQcgpON1VqV2dva20yQWg3amRMU2hvMFF4bkkwd0tCZ1FENzBUVzNCa2llYUdzN3IzY3hhUytvd1VoaUdMTnEyajN4Ckd2QmtXVmx5TzM5aHlCcm5aUk92ak9HRFE4eCtxSmRTN2V6Q2xGVmpsanc2V2dra1V6U1ZQSHkrb094RjE5T3UKM00xalhCZC9PMUh6VU1WUkcvYmJxaTJZeThhb0gyRWplbzE4VE9XbWhYUnFNb045TDV4Q3RkbDRnMGxMNnBJZgpPb3FlanltZHFRS0JnUURCZjZPbXhLQS96UCtwUHhPK1AvL0d1MTZycUU5cFU1dEFiZHRhSVFuYWZpT3V1eUUzCnRvOGVXNEpTWDRQbnFNaWkxSTRRQ2F5aVJVSmw2TDJLMGh5b1M4NmZid0lxY3Q1ekdtbTl2NXkrUC9CMFJYN1AKSk9xcmduWEpHaGh0WUc3SGthME5PM2I3WGFvSVpBVkRmWmJIK3VBTzN6Y09CRSttb1krb1REd1l4UUtCZ1FEcgo4TWpRZFEzRGhuaTYwcHZ1YXV6aHhEK3EwaFFCa1B5cWxLQWFsZkVON0J0ZEpkMjNZMmcvZXRPdFp2QUsyTEg0ClhMOFNUV040VE1LZnRjNk0vM3pzTzJGeVIxczUwWkFnYmZmdkdkRldQK0Y0QmZ6ckV6V0grZnFCQ0tWWXp4WDMKNVJMK0hScXJuSzFIOTQ1bDFCOG9EalQyQ3FTNWdjNXBmak4xZnhQeUNRS0JnQzVJR2FnbldPSG9XVEpnUG95YQptY1QrMk1NUGdJMzhaL2xzM0lmd1dIc2hUbE5sQ2k2RklnMkQrUUYrZk80ZGdYZS85K0dESERvM3J5MDU2Z2VhCng4T1FYZ2dxa0lJdkxDUnZGVlVId0M3Z0MyekpHakJ1V2dYUDhsYjRDNG4yemlQd1c5M1c2RkpXMnpwMzRacSsKU29JaUNXUEh6RXF3WjgxbEJwZ1VkVTZYCi0tLS0tRU5EIFBSSVZBVEUgS0VZLS0tLS0K - clientId: {{ "clientID" | b64enc }} \ No newline at end of file diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/mtls-oauth-positive.yaml b/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/mtls-oauth-positive.yaml deleted file mode 100644 index 1d83b2b2bfca..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/mtls-oauth-positive.yaml +++ /dev/null @@ -1,12 +0,0 @@ -apiVersion: v1 -kind: Secret -metadata: - name: mtls-oauth-positive - namespace: kyma-system -type: Opaque -data: - {{- $files := .Files }} - crt: {{ $files.Get "certs/positive/client.crt" | b64enc }} - key: {{ $files.Get "certs/positive/client.key" | b64enc }} - clientId: {{ "clientID" | b64enc }} - diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/mtls-positive.yaml b/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/mtls-positive.yaml deleted file mode 100644 index f5540a3e9380..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/mtls-positive.yaml +++ /dev/null @@ -1,10 +0,0 @@ -apiVersion: v1 -kind: Secret -metadata: - name: mtls-positive - namespace: kyma-system -type: Opaque -data: - {{- $files := .Files }} - crt: {{ $files.Get "certs/positive/client.crt" | b64enc }} - key: {{ $files.Get "certs/positive/client.key" | b64enc }} diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/oauth-negative-incorrect-id.yaml b/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/oauth-negative-incorrect-id.yaml deleted file mode 100644 index 94ffed2132dc..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/oauth-negative-incorrect-id.yaml +++ /dev/null @@ -1,9 +0,0 @@ -apiVersion: v1 -kind: Secret -metadata: - name: wrong-oauth-test - namespace: kyma-system -type: Opaque -data: - clientId: {{ "bad id" | b64enc }} - clientSecret: {{ "bad secret" | b64enc }} diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/oauth-negative-invalid-token.yaml b/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/oauth-negative-invalid-token.yaml deleted file mode 100644 index 13d0df23fae8..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/oauth-negative-invalid-token.yaml +++ /dev/null @@ -1,9 +0,0 @@ -apiVersion: v1 -kind: Secret -metadata: - name: oauth-test-negative-case - namespace: kyma-system -type: Opaque -data: - clientId: {{ "clientID" | b64enc }} - clientSecret: {{ "clientSecret" | b64enc }} diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/oauth-positive.yaml b/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/oauth-positive.yaml deleted file mode 100644 index af54df50e439..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/oauth-positive.yaml +++ /dev/null @@ -1,9 +0,0 @@ -apiVersion: v1 -kind: Secret -metadata: - name: oauth-test - namespace: kyma-system -type: Opaque -data: - clientId: {{ "clientID" | b64enc }} - clientSecret: {{ "clientSecret" | b64enc }} diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/redirect-basic-auth.yml b/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/redirect-basic-auth.yml deleted file mode 100644 index e6405b0d4e54..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/redirect-basic-auth.yml +++ /dev/null @@ -1,9 +0,0 @@ -apiVersion: v1 -kind: Secret -metadata: - name: redirect-basic - namespace: kyma-system -type: Opaque -data: - password: {{ "passwd" | b64enc }} - username: {{ "user" | b64enc }} diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/request-parameters-negative.yaml b/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/request-parameters-negative.yaml deleted file mode 100644 index f62520b2e9ad..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/request-parameters-negative.yaml +++ /dev/null @@ -1,11 +0,0 @@ -apiVersion: v1 -kind: Secret -metadata: - name: wrong-request-parameters-test - namespace: kyma-system -type: Opaque -stringData: - headers: |- - {"Hkey1":["Wrong-value"],"Wrong-key":["Hval22"]} - queryParameters: |- - {"Wrong-key":["Qval1"],"Qkey2":["Qval21","Qval22","Additional-value"]} \ No newline at end of file diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/request-parameters.yaml b/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/request-parameters.yaml deleted file mode 100644 index 847ac1eed988..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/credentials/request-parameters.yaml +++ /dev/null @@ -1,11 +0,0 @@ -apiVersion: v1 -kind: Secret -metadata: - name: request-parameters-test - namespace: kyma-system -type: Opaque -stringData: - headers: |- - {"Hkey1":["Hval1"],"Hkey2":["Hval21","Hval22"]} - queryParameters: |- - {"Qkey1":["Qval1"],"Qkey2":["Qval21","Qval22"]} \ No newline at end of file diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/manual.yml b/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/manual.yml deleted file mode 100644 index 8a17420326b2..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/manual.yml +++ /dev/null @@ -1,23 +0,0 @@ -apiVersion: applicationconnector.kyma-project.io/v1alpha1 -kind: Application -metadata: - name: complex-cases - namespace: "{{ .Values.global.namespace }}" -spec: - description: Endpoints for complex tests - skipVerify: true - labels: - app: complex-cases - services: - - displayName: oauth-expired-token-renewal - name: oauth-expired-token-renewal - providerDisplayName: Kyma - description: Should renew the OAuth token after the expiration time - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/oauth/ok" - credentials: - secretName: oauth-test - authenticationUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/oauth/token?token_lifetime=5s" - type: OAuth diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/methods-with-body.yml b/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/methods-with-body.yml deleted file mode 100644 index 1c8a72652a54..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/methods-with-body.yml +++ /dev/null @@ -1,40 +0,0 @@ -apiVersion: applicationconnector.kyma-project.io/v1alpha1 -kind: Application -metadata: - name: methods-with-body - namespace: "{{ .Values.global.namespace }}" -spec: - description: |- - Verify if methods, specified by `descritpion`, - are correctly forwarded, including their body - skipVerify: true - labels: - app: methods-with-body - services: - - displayName: post - name: post - providerDisplayName: post - description: POST - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/unsecure/echo" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/methods-with-body/post" - - displayName: delete - name: delete - providerDisplayName: delete - description: DELETE - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/unsecure/echo" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/methods-with-body/delete" - - displayName: put - name: put - providerDisplayName: put - description: PUT - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/unsecure/echo" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/methods-with-body/put" diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/missing-resources-error-handling.yml b/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/missing-resources-error-handling.yml deleted file mode 100644 index 0b87dc656a8f..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/missing-resources-error-handling.yml +++ /dev/null @@ -1,101 +0,0 @@ -apiVersion: applicationconnector.kyma-project.io/v1alpha1 -kind: Application -metadata: - name: missing-resources-error-handling - namespace: "{{ .Values.global.namespace }}" -spec: - description: Missing resources - skipVerify: true - labels: - app: missing-resources-error-handling - services: - - displayName: application-doesnt-exist - name: application-doesnt-exist - providerDisplayName: Kyma - description: Should return 404 when application doesn't exist - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/unsecure/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/where-is-app/idk" - - displayName: service-doesnt-exist - name: service-doesnt-exist - providerDisplayName: Kyma - description: Should return 404 when service doesn't exist - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/unsecure/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/missing-resources-error-handling/where-is-service" - - displayName: missing-secret-oauth - name: missing-secret-oauth - providerDisplayName: Kyma - description: Should return 500 when secret containing OAuth credentials is missing in the cluster - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/oauth/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/missing-resources-error-handling/missing-secret-oauth" - credentials: - secretName: where-is-the-secret - authenticationUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/server/oauth/token?client_secret=clientSecret" - type: OAuth - - displayName: missing-secret-basic-auth - name: missing-secret-basic-auth - providerDisplayName: Kyma - description: Should return 500 when secret containing Basic Auth credentials is missing in the cluster - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/basic/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/missing-resources-error-handling/missing-secret-basic-auth" - credentials: - secretName: where-is-the-secret - type: Basic - - displayName: missing-secret-oauth-mtls - name: missing-secret-oauth-mtls - providerDisplayName: Kyma - description: Should return 500 when secret containing OAuth mTLS credentials is missing in the cluster - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/basic/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/missing-resources-error-handling/missing-secret-oauth-mtls" - credentials: - secretName: where-is-the-secret - authenticationUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/server/oauth/token?client_secret=clientSecret" - type: OAuthWithCert - - displayName: missing-secret-certgen-mtls - name: missing-secret-certgen-mtls - providerDisplayName: Kyma - description: Should return 500 when secret containing Cert Gen mTLS credentials is missing in the cluster - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/basic/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/missing-resources-error-handling/missing-secret-certgen-mtls" - credentials: - secretName: where-is-the-secret - type: CertificateGen - - displayName: missing-request-parameters-header - name: missing-request-parameters-header - providerDisplayName: Kyma - description: Should return 500 when secret and request parameters credentials is missing in the cluster - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/basic/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/missing-resources-error-handling/missing-request-parameters-header" - requestParametersSecretName: where-are-the-paramterers - credentials: - secretName: basic-test - type: Basic - - displayName: non-existing-target-url - name: non-existing-target-url - providerDisplayName: Kyma - description: Should return 502 when target url is not resolvable - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://bad.bad.svc.cluster.local:8080/v1/api/unsecure/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/missing-resources-error-handling/non-existing-target-url" diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/negative-authorisation.yml b/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/negative-authorisation.yml deleted file mode 100644 index 7932928916d7..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/negative-authorisation.yml +++ /dev/null @@ -1,254 +0,0 @@ -apiVersion: applicationconnector.kyma-project.io/v1alpha1 -kind: Application -metadata: - name: negative-authorisation - namespace: {{ .Values.global.namespace }} -spec: - description: Negative authorisation - skipVerify: true - labels: - app: negative-authorisation - services: - - displayName: bad oauth token - name: bad-oauth-token - providerDisplayName: OAuth - description: Should return 401 for OAuth with a wrong token - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/oauth/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/negative-authorisation/bad-oauth-token" - credentials: - secretName: oauth-test-negative-case - authenticationUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/oauth/bad-token" - type: OAuth - - displayName: wrong oauth secret - name: wrong-oauth-secret - providerDisplayName: OAuth - description: Should return 502 for OAuth with a wrong secret - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/oauth/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/negative-authorisation/wrong-oauth-secret" - credentials: - secretName: wrong-oauth-test - authenticationUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/oauth/token" - type: OAuth - - displayName: mtls-oauth-other-ca - name: mtls-oauth-other-ca - providerDisplayName: mTLS-OAuth - description: Should return 500 for mTLS Oauth with client certificate generated from other CA - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/oauth/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/negative-authorisation/mtls-oauth-other-ca" - credentials: - secretName: mtls-oauth-negative-other-ca - authenticationUrl: "https://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8090/v1/api/mtls-oauth/token" - type: OAuthWithCert - - displayName: mtls-oauth-incorrect-clientid - name: mtls-oauth-incorrect-clientid - providerDisplayName: mTLS-OAuth - description: Should return 500 for mTLS Oauth with valid certificate but invalid client id - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/oauth/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/negative-authorisation/mtls-oauth-incorrect-clientid" - credentials: - secretName: mtls-oauth-negative-incorrect-clientid - authenticationUrl: "https://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8090/v1/api/mtls-oauth/token" - type: OAuthWithCert - - displayName: mtls-oauth-negative-expired-client-cert - name: mtls-oauth-negative-expired-client-cert - providerDisplayName: mTLS-OAuth - description: Should return 500 for mTLS Oauth with expired client certificate - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/oauth/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/negative-authorisation/mtls-oauth-negative-expired-client-cert" - credentials: - secretName: mtls-oauth-negative-expired-client-cert - authenticationUrl: "https://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8090/v1/api/mtls-oauth/token" - type: OAuthWithCert - - displayName: mtls-oauth-negative-expired-server-cert - name: mtls-oauth-negative-expired-server-cert - providerDisplayName: mTLS-OAuth - description: Should return 500 for mTLS Oauth with expired server certificate - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/oauth/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/negative-authorisation/mtls-oauth-negative-expired-server-cert" - credentials: - secretName: mtls-oauth-negative-expired-server-cert - authenticationUrl: "https://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8091/v1/api/mtls-oauth/token" - type: OAuthWithCert - - displayName: mtls-negative-other-ca - name: mtls-negative-other-ca - providerDisplayName: mTLS - description: Should return 502 for mTLS with client certificate generated from other CA - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "https://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8090/v1/api/mtls/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/negative-authorisation/mtls-negative-other-ca" - credentials: - secretName: mtls-negative-other-ca - type: CertificateGen - - displayName: mtls-negative-expired-client-cert - name: mtls-negative-expired-client-cert - providerDisplayName: mTLS - description: Should return 502 for mTLS with expired client certificate - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "https://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8090/v1/api/mtls/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/negative-authorisation/mtls-negative-expired-client-cert" - credentials: - secretName: mtls-negative-expired-client-cert - type: CertificateGen - - displayName: mtls-negative-expired-server-cert - name: mtls-negative-expired-server-cert - providerDisplayName: mTLS - description: Should return 502 for mTLS with expired server certificate - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "https://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8091/v1/api/mtls/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/negative-authorisation/mtls-negative-expired-server-cert" - credentials: - secretName: mtls-negative-expired-client-cert - type: CertificateGen - - displayName: bad csrf token basic - name: bad-csrf-token-basic - providerDisplayName: Basic with CSRF - description: Should return 403 for Basic Auth with a bad CSRF token - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/csrf-basic/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/negative-authorisation/bad-csrf-token-basic" - credentials: - secretName: basic-test-negative-case - type: Basic - csrfInfo: - tokenEndpointURL: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/csrf/bad-token" - - displayName: bad csrf endpoint basic - name: bad-csrf-endpoint-basic - providerDisplayName: Basic with CSRF - description: Should return 502 for Basic Auth with a bad CSRF token endpoint - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/csrf-basic/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/negative-authorisation/bad-csrf-endpoint-basic" - credentials: - secretName: basic-test-negative-case - type: Basic - csrfInfo: - tokenEndpointURL: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/csrf/nonexistingpath" - - displayName: bad csrf token oauth - name: bad-csrf-token-oauth - providerDisplayName: OAuth with CSRF - description: Should return 403 for OAuth with a bad CSRF token - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/csrf-oauth/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/negative-authorisation/bad-csrf-token-oauth" - credentials: - secretName: oauth-test-negative-case - authenticationUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/oauth/token" - type: OAuth - csrfInfo: - tokenEndpointURL: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/csrf/bad-token" - - displayName: bad csrf endpoint oauth - name: bad-csrf-endpoint-oauth - providerDisplayName: OAuth with CSRF - description: Should return 502 for OAuth with a bad CSRF token endpoint - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/csrf-oauth/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/negative-authorisation/bad-csrf-endpoint-oauth" - credentials: - secretName: oauth-test-negative-case - authenticationUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/oauth/token" - type: OAuth - csrfInfo: - tokenEndpointURL: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/csrf/nonexistingpath" - - displayName: bad csrf token mtls oauth - name: bad-csrf-token-mtls-oauth - providerDisplayName: mTLS-OAuth with CSRF - description: Should return 403 for mTLS OAuth with a bad CSRF token - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/csrf-oauth/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/negative-authorisation/bad-csrf-token-mtls-oauth" - credentials: - secretName: mtls-oauth-negative-case - authenticationUrl: "https://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8090/v1/api/mtls-oauth/token" - type: OAuthWithCert - csrfInfo: - tokenEndpointURL: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/csrf/bad-token" - - displayName: bad csrf endpoint mtls oauth - name: bad-csrf-endpoint-mtls-oauth - providerDisplayName: mTLS-OAuth with CSRF - description: Should return 502 for mTLS OAuth with a bad CSRF token endpoint - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/csrf-oauth/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/negative-authorisation/bad-csrf-endpoint-mtls-oauth" - credentials: - secretName: mtls-oauth-negative-case - authenticationUrl: "https://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8090/v1/api/mtls-oauth/token" - type: OAuthWithCert - csrfInfo: - tokenEndpointURL: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/csrf/nonexistingpath" - - displayName: bad csrf token mtls - name: bad-csrf-token-mtls - providerDisplayName: mTLS with CSRF - description: Should return 403 for mTLS with a bad CSRF token - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "https://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8090/v1/api/csrf-mtls/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/negative-authorisation/bad-csrf-token-mtls" - credentials: - secretName: mtls-negative-case - type: CertificateGen - csrfInfo: - tokenEndpointURL: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/csrf/bad-token" - - displayName: bad csrf endpoint mtls - name: bad-csrf-endpoint-mtls - providerDisplayName: mTLS with CSRF - description: Should return 502 for mTLS with a bad CSRF token endpoint - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "https://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8090/v1/api/csrf-mtls/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/negative-authorisation/bad-csrf-endpoint-mtls" - credentials: - secretName: mtls-negative-case - type: CertificateGen - csrfInfo: - tokenEndpointURL: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/csrf/nonexistingpath" - - displayName: basic-auth-with-wrong-request-parameters - name: basic-auth-with-wrong-request-parameters - providerDisplayName: Basic - description: Should return 400 when calling endpoint protected with Basic Auth with wrong additional request parameters - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/request-parameters-basic/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/negative-authorisation/basic-auth-with-wrong-request-parameters" - requestParametersSecretName: wrong-request-parameters-test - credentials: - secretName: basic-test - type: Basic diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/path-related-error-handling.yml b/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/path-related-error-handling.yml deleted file mode 100644 index acdcca708a1c..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/path-related-error-handling.yml +++ /dev/null @@ -1,29 +0,0 @@ -apiVersion: applicationconnector.kyma-project.io/v1alpha1 -kind: Application -metadata: - name: path-related-error-handling - namespace: "{{ .Values.global.namespace }}" -spec: - description: Path handling - skipVerify: true - labels: - app: path-related-error-handling - services: - - displayName: missing-srv-app - name: missing-srv-app - providerDisplayName: Kyma - description: Should return 400 when service and application are missing in the path - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/unsecure/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080" - - displayName: missing-srv - name: missing-srv - providerDisplayName: Kyma - description: Should return 400 when service is missing in the path - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/unsecure/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/path-related-error-handling" \ No newline at end of file diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/positive-authorisation.yml b/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/positive-authorisation.yml deleted file mode 100644 index e22ca8547cef..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/positive-authorisation.yml +++ /dev/null @@ -1,141 +0,0 @@ -apiVersion: applicationconnector.kyma-project.io/v1alpha1 -kind: Application -metadata: - name: positive-authorisation - namespace: {{ .Values.global.namespace }} -spec: - description: Authorisation - skipVerify: true - labels: - app: positive-authorisation - services: - - displayName: unsecure-always-ok - name: unsecure-always-ok - providerDisplayName: AlwaysOK - description: Should return 200 when calling unprotected endpoint - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/unsecure/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/positive-authorisation/unsecure-always-ok" - - displayName: basic-auth-ok - name: basic-auth-ok - providerDisplayName: Basic - description: Should return 200 when calling endpoint protected with Basic Auth - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/basic/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/positive-authorisation/basic-auth-ok" - credentials: - secretName: basic-test - type: Basic - - displayName: oauth - name: oauth - providerDisplayName: OAuth - description: Should return 200 when calling endpoint protected with OAuth - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/oauth/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/positive-authorisation/oauth" - credentials: - secretName: oauth-test - authenticationUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/oauth/token" - type: OAuth - - displayName: mtls-oauth - name: mtls-oauth - providerDisplayName: mTLS-OAuth - description: Should return 200 when calling endpoint protected with mTLS OAuth - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/oauth/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/positive-authorisation/mtls-oauth" - credentials: - secretName: mtls-oauth-positive - authenticationUrl: "https://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8090/v1/api/mtls-oauth/token" - type: OAuthWithCert - - displayName: mtls - name: mtls - providerDisplayName: mTLS - description: Should return 200 when calling endpoint protected with mTLS - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "https://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8090/v1/api/mtls/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/positive-authorisation/mtls" - credentials: - secretName: mtls-positive - type: CertificateGen - - displayName: csrf basic - name: csrf-basic - providerDisplayName: Basic with CSRF - description: Should return 200 for Basic Auth with CSRF optimistic scenario - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/csrf-basic/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/positive-authorisation/csrf-basic" - credentials: - secretName: basic-test - type: Basic - csrfInfo: - tokenEndpointURL: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/csrf/token" - - displayName: csrf-oauth - name: csrf-oauth - providerDisplayName: OAuth with CSRF - description: Should return 200 when calling endpoint protected with OAuth with CSRF - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/csrf-oauth/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/positive-authorisation/csrf-oauth" - credentials: - secretName: oauth-test - authenticationUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/oauth/token" - type: OAuth - csrfInfo: - tokenEndpointURL: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/csrf/token" - - displayName: csrf-mtls-oauth - name: csrf-mtls-oauth - providerDisplayName: mTLS-OAuth with CSRF - description: Should return 200 when calling endpoint protected with mTLS OAuth with CSRF - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/csrf-oauth/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/positive-authorisation/csrf-mtls-oauth" - credentials: - secretName: mtls-oauth-positive - authenticationUrl: "https://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8090/v1/api/mtls-oauth/token" - type: OAuthWithCert - csrfInfo: - tokenEndpointURL: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/csrf/token" - - displayName: csrf-mtls - name: csrf-mtls - providerDisplayName: mTLS with CSRF - description: Should return 200 when calling endpoint protected with mTLS with CSRF - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "https://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8090/v1/api/csrf-mtls/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/positive-authorisation/csrf-mtls" - credentials: - secretName: mtls-positive - type: CertificateGen - csrfInfo: - tokenEndpointURL: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/csrf/token" - - displayName: basic-auth-with-request-parameters - name: basic-auth-with-request-parameters - providerDisplayName: Basic - description: Should return 200 when calling endpoint protected with Basic Auth with additional request parameters - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/request-parameters-basic/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/positive-authorisation/basic-auth-with-request-parameters" - requestParametersSecretName: request-parameters-test - credentials: - secretName: basic-test - type: Basic diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/proxy-cases.yml b/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/proxy-cases.yml deleted file mode 100644 index 54b558e145c6..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/proxy-cases.yml +++ /dev/null @@ -1,38 +0,0 @@ -apiVersion: applicationconnector.kyma-project.io/v1alpha1 -kind: Application -metadata: - name: proxy-cases - namespace: "{{ .Values.global.namespace }}" -spec: - description: Proxying - skipVerify: true - labels: - app: proxy-cases - services: - - displayName: code 451 - name: code 451 - providerDisplayName: code 451 - description: Should return 451 forwarded from target endpoint - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/unsecure/code/451" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/proxy-cases/code-451" - - displayName: code 307 - name: code 307 - providerDisplayName: code 307 - description: Should return 307 forwarded from target endpoint - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/unsecure/code/307" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/proxy-cases/code-307" - - displayName: code 203 - name: code 203 - providerDisplayName: code 203 - description: Should return 203 forwarded from target endpoint - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/unsecure/code/203" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/proxy-cases/code-203" diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/proxy-errors.yml b/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/proxy-errors.yml deleted file mode 100644 index c0b46d34e11e..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/proxy-errors.yml +++ /dev/null @@ -1,20 +0,0 @@ -apiVersion: applicationconnector.kyma-project.io/v1alpha1 -kind: Application -metadata: - name: proxy-errors - namespace: "{{ .Values.global.namespace }}" -spec: - description: Proxying edge cases - skipVerify: true - labels: - app: proxy-errors - services: - - displayName: timeout - name: timeout - providerDisplayName: timeout - description: Should return 504 when target times out - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.global.mockServiceName }}.{{ .Values.global.namespace }}.svc.cluster.local:8080/v1/api/unsecure/timeout" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/proxy-errors/timeout" diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/redirect.yml b/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/redirect.yml deleted file mode 100644 index 40d5137d0b36..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/applications/redirect.yml +++ /dev/null @@ -1,41 +0,0 @@ -apiVersion: applicationconnector.kyma-project.io/v1alpha1 -kind: Application -metadata: - name: redirects - namespace: "{{ .Values.global.namespace }}" -spec: - description: Endpoints for redirect cases - skipVerify: true - labels: - app: redirect-cases - services: - - displayName: unsecured - name: unsecured - providerDisplayName: unsecured - description: Should return 200 when redirected to unsecured endpoint - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.mockServiceName }}.{{ .Values.namespace }}.svc.cluster.local:8080/v1/api/redirect/ok" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/redirects/unsecured" - - displayName: basic - name: basic - providerDisplayName: basic - description: Should return 200 when redirected to basic-auth endpoint - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.mockServiceName }}.{{ .Values.namespace }}.svc.cluster.local:8080/v1/api/redirect/basic" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/redirects/basic" - credentials: - secretName: redirect-basic - type: Basic - - displayName: external - name: external - providerDisplayName: external - description: Should return 200 when redirected to external service - id: "{{ uuidv4 }}" - entries: - - type: API - targetUrl: "http://{{ .Values.mockServiceName }}.{{ .Values.namespace }}.svc.cluster.local:8080/v1/api/redirect/external" - centralGatewayUrl: "http://central-application-gateway.kyma-system:8080/redirects/external" diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/service-account.yml b/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/service-account.yml deleted file mode 100644 index 80fd71f16787..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/service-account.yml +++ /dev/null @@ -1,33 +0,0 @@ -apiVersion: v1 -kind: ServiceAccount -metadata: - name: {{ .Values.global.serviceAccountName }} - namespace: {{ .Values.global.namespace }} -automountServiceAccountToken: true ---- -apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRoleBinding -metadata: - name: {{ .Values.global.serviceAccountName }} -subjects: - - kind: ServiceAccount - name: {{ .Values.global.serviceAccountName }} - namespace: {{ .Values.global.namespace }} -roleRef: - apiGroup: rbac.authorization.k8s.io - kind: ClusterRole - name: {{ .Values.global.serviceAccountName }} ---- -apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRole -metadata: - name: {{ .Values.global.serviceAccountName }} -rules: - - verbs: - - get - - list - apiGroups: - - "" - - applicationconnector.kyma-project.io - resources: - - "*" diff --git a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/test.yml b/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/test.yml deleted file mode 100644 index b31e011558bc..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/charts/test/templates/test.yml +++ /dev/null @@ -1,15 +0,0 @@ -apiVersion: batch/v1 -kind: Job -metadata: - name: application-gateway-test - namespace: {{ .Values.global.namespace }} -spec: - template: - spec: - containers: - - name: application-gateway-test - image: {{ include "imageurl" (dict "reg" .Values.global.containerRegistry "img" .Values.global.images.gatewayTest) }} - imagePullPolicy: Always - restartPolicy: Never - serviceAccountName: {{ .Values.global.serviceAccountName }} - backoffLimit: 0 \ No newline at end of file diff --git a/tests/components/application-connector/resources/charts/gateway-test/values.yaml b/tests/components/application-connector/resources/charts/gateway-test/values.yaml deleted file mode 100644 index 63ec00cb3d3e..000000000000 --- a/tests/components/application-connector/resources/charts/gateway-test/values.yaml +++ /dev/null @@ -1,19 +0,0 @@ -global: - containerRegistry: - path: "europe-docker.pkg.dev/kyma-project" - - images: - gatewayTest: - name: "gateway-test" - version: "v20230925-75c3a9a8" - directory: "prod" - mockApplication: - name: "mock-app" - version: "v20230925-75c3a9a8" - directory: "prod" - - serviceAccountName: "test-account" - namespace: "test" - - mockServiceName: "mock-application" - diff --git a/tests/components/application-connector/resources/installation-config/mini-kyma-os.yaml b/tests/components/application-connector/resources/installation-config/mini-kyma-os.yaml deleted file mode 100644 index 63eb2f7c8dc0..000000000000 --- a/tests/components/application-connector/resources/installation-config/mini-kyma-os.yaml +++ /dev/null @@ -1,9 +0,0 @@ ---- -defaultNamespace: kyma-system -prerequisites: - - name: "istio" - namespace: "istio-system" - - name: "certificates" - namespace: "istio-system" -components: - - name: "application-connector" \ No newline at end of file diff --git a/tests/components/application-connector/resources/installation-config/mini-kyma-skr.yaml b/tests/components/application-connector/resources/installation-config/mini-kyma-skr.yaml deleted file mode 100644 index d1a6e71718a3..000000000000 --- a/tests/components/application-connector/resources/installation-config/mini-kyma-skr.yaml +++ /dev/null @@ -1,10 +0,0 @@ ---- -defaultNamespace: kyma-system -prerequisites: - - name: "istio" - namespace: "istio-system" - - name: "certificates" - namespace: "istio-system" -components: - - name: "application-connector" - - name: "compass-runtime-agent" \ No newline at end of file diff --git a/tests/components/application-connector/resources/patches/central-application-connectivity-validator.json b/tests/components/application-connector/resources/patches/central-application-connectivity-validator.json deleted file mode 100644 index b676d8dd54dd..000000000000 --- a/tests/components/application-connector/resources/patches/central-application-connectivity-validator.json +++ /dev/null @@ -1,24 +0,0 @@ -[ - { - "op": "replace", - "path": "/spec/template/spec/containers/0/args", - "value": [ - "/app/centralapplicationconnectivityvalidator", - "--proxyPort=8080", - "--externalAPIPort=8081", - "--eventingPathPrefixV1=/%%APP_NAME%%/v1/events", - "--eventingPathPrefixV2=/%%APP_NAME%%/v2/events", - "--eventingPublisherHost=echoserver.test.svc.cluster.local", - "--eventingDestinationPath=/anything/rewrite", - "--eventingPathPrefixEvents=/%%APP_NAME%%/events", - "--appNamePlaceholder=%%APP_NAME%%", - ] - }, - { - "op": "add", - "path": "/spec/template/metadata/annotations", - "value": { - "traffic.sidecar.istio.io/excludeInboundPorts": "8080" - } - } -] diff --git a/tests/components/application-connector/resources/patches/coredns.yaml b/tests/components/application-connector/resources/patches/coredns.yaml deleted file mode 100644 index 1a7c466f7621..000000000000 --- a/tests/components/application-connector/resources/patches/coredns.yaml +++ /dev/null @@ -1,40 +0,0 @@ -apiVersion: v1 -data: - Corefile: |2 - - .:53 { - errors - health - rewrite name regex (.*)\.local\.kyma\.dev istio-ingressgateway.istio-system.svc.cluster.local - ready - kubernetes cluster.local in-addr.arpa ip6.arpa { - pods insecure - fallthrough in-addr.arpa ip6.arpa - } - hosts /etc/coredns/NodeHosts { - reload 1s - fallthrough - } - prometheus :9153 - forward . tls://1.1.1.1 tls://1.0.0.1 { - tls_servername cloudflare-dns.com - health_check 5s - } - cache 30 - loop - reload - loadbalance - } - - NodeHosts: | - 172.18.0.3 k3d-kyma-server-0 - 172.18.0.2 k3d-kyma-registry - 172.18.0.4 k3d-kyma-agent-0 -kind: ConfigMap -metadata: - annotations: - objectset.rio.cattle.io/owner-gvk: k3s.cattle.io/v1, Kind=Addon - objectset.rio.cattle.io/owner-name: coredns - objectset.rio.cattle.io/owner-namespace: kube-system - name: coredns - namespace: kube-system diff --git a/tests/components/application-connector/scripts/check-pod-logs.sh b/tests/components/application-connector/scripts/check-pod-logs.sh deleted file mode 100755 index acba6d06144a..000000000000 --- a/tests/components/application-connector/scripts/check-pod-logs.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash -NAMESPACE=test -GOPATH=$(go env GOPATH) -JOB_NAME=$1 - -if [ $# -ne 1 ]; then - echo "Usage: check-pod-logs.sh " - exit 1 -fi - - -time_so_far=0 # we've already waited that many seconds -sleep_sec=5 # wait between checks -wait_timeout=900 # 15min -> 900sec -retval_complete=1 -retval_failed=1 -while [[ $retval_complete -ne 0 ]] && [[ $retval_failed -ne 0 ]] && [[ $time_so_far -le $wait_timeout ]]; do - sleep $sleep_sec - time_so_far=$((time_so_far+sleep_sec)) - - output=$(kubectl wait --for=condition=failed -n $NAMESPACE job/$JOB_NAME --timeout=0 2>&1) - retval_failed=$? - output=$(kubectl wait --for=condition=complete -n $NAMESPACE job/$JOB_NAME --timeout=0 2>&1) - retval_complete=$? -done - -if ([[ ${EXPORT_RESULT} == true ]]); then - kubectl -n $NAMESPACE logs -f job/$JOB_NAME | tee /dev/stderr | $GOPATH/bin/go-junit-report -subtest-mode exclude-parents -set-exit-code > junit-report.xml -else - kubectl -n $NAMESPACE logs -f job/$JOB_NAME -fi - -if [ $retval_failed -eq 0 ]; then - echo "Job failed. Please check logs." - exit 1 -fi diff --git a/tests/components/application-connector/scripts/generate-self-signed-certs.sh b/tests/components/application-connector/scripts/generate-self-signed-certs.sh deleted file mode 100755 index 9cd6422e60d9..000000000000 --- a/tests/components/application-connector/scripts/generate-self-signed-certs.sh +++ /dev/null @@ -1,47 +0,0 @@ -#!/usr/bin/env bash - -if [ $# -ne 2 ]; then - echo "Usage: generate-self-signed-certs.sh " - exit 1 -fi - -export APP_URL=$1 -export GATEWAY_TEST_CERTS_DIR=$2 -export SUBJECT="/C=PL/ST=A/O=SAP/CN=$APP_URL" - -mkdir -p "$GATEWAY_TEST_CERTS_DIR" - -echo "Generating certificate for domain: $APP_URL" -openssl version -openssl req -newkey rsa:2048 -nodes -x509 -days 365 -out "$GATEWAY_TEST_CERTS_DIR/ca.crt" -keyout "$GATEWAY_TEST_CERTS_DIR/ca.key" -subj $SUBJECT - -openssl genrsa -out "$GATEWAY_TEST_CERTS_DIR/server.key" 2048 -openssl genrsa -out "$GATEWAY_TEST_CERTS_DIR"/client.key 2048 - -openssl req -new \ - -key "$GATEWAY_TEST_CERTS_DIR/server.key" \ - -subj "$SUBJECT" \ - -reqexts SAN \ - -config <(cat /etc/ssl/openssl.cnf \ - <(printf "\n[SAN]\nsubjectAltName=DNS:%s" "$APP_URL")) \ - -out "$GATEWAY_TEST_CERTS_DIR/server.csr" - -openssl x509 -req -sha256 -days 365 -CA "$GATEWAY_TEST_CERTS_DIR/ca.crt" -CAkey "$GATEWAY_TEST_CERTS_DIR/ca.key" -CAcreateserial \ - -extensions SAN \ - -extfile <(cat /etc/ssl/openssl.cnf \ - <(printf "\n[SAN]\nsubjectAltName=DNS:%s" "$APP_URL" )) \ - -in "$GATEWAY_TEST_CERTS_DIR/server.csr" -out "$GATEWAY_TEST_CERTS_DIR/server.crt" - -openssl req -new \ - -key "$GATEWAY_TEST_CERTS_DIR/client.key" \ - -subj "$SUBJECT" \ - -reqexts SAN \ - -config <(cat /etc/ssl/openssl.cnf \ - <(printf "\n[SAN]\nsubjectAltName=DNS:%s" "$APP_URL")) \ - -out "$GATEWAY_TEST_CERTS_DIR/client.csr" - -openssl x509 -req -sha256 -days 365 -CA "$GATEWAY_TEST_CERTS_DIR/ca.crt" -CAkey "$GATEWAY_TEST_CERTS_DIR/ca.key" -CAcreateserial \ - -extensions SAN \ - -extfile <(cat /etc/ssl/openssl.cnf \ - <(printf "\n[SAN]\nsubjectAltName=DNS:%s" "$APP_URL")) \ - -in "$GATEWAY_TEST_CERTS_DIR/client.csr" -out "$GATEWAY_TEST_CERTS_DIR/client.crt" \ No newline at end of file diff --git a/tests/components/application-connector/scripts/jobguard.sh b/tests/components/application-connector/scripts/jobguard.sh deleted file mode 100755 index f92a9653ed56..000000000000 --- a/tests/components/application-connector/scripts/jobguard.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/bin/bash -export GO111MODULE=on - -ROOT_PATH=$(dirname "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)") - -KYMA_PROJECT_DIR=${KYMA_PROJECT_DIR:-"/home/prow/go/src/github.com/kyma-project"} -JOB_NAME_PATTERN=${JOB_NAME_PATTERN:-"(pre-main-kyma-components-.*)|(pre-main-kyma-tests-.*)|(pre-kyma-components-.*)|(pre-kyma-tests-.*)|(pull-.*-build)"} -TIMEOUT=${JOBGUARD_TIMEOUT:-"15m"} - -export TEST_INFRA_SOURCES_DIR="${KYMA_PROJECT_DIR}/test-infra" - -if [ -z "$PULL_PULL_SHA" ]; then - echo "WORKAROUND: skip jobguard execution - not on PR commit" - exit 0 -fi - -args=( - "-github-endpoint=http://ghproxy" - "-github-endpoint=https://api.github.com" - "-github-token-path=/etc/github/token" - "-fail-on-no-contexts=false" - "-timeout=$TIMEOUT" - "-org=$REPO_OWNER" - "-repo=$REPO_NAME" - "-base-ref=$PULL_PULL_SHA" - "-expected-contexts-regexp=$JOB_NAME_PATTERN" -) - -if [ -x "/prow-tools/jobguard" ]; then - /prow-tools/jobguard "${args[@]}" -else - cd "${ROOT_PATH}/cmd/jobguard" || exit 1 - go run main.go "${args[@]}" -fi diff --git a/tests/components/application-connector/scripts/local-build.sh b/tests/components/application-connector/scripts/local-build.sh deleted file mode 100755 index bb2306656e4f..000000000000 --- a/tests/components/application-connector/scripts/local-build.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env bash - -if [ $# -ne 2 ]; then - echo "Usage: local_build.sh " - exit 1 -fi - -export DOCKER_TAG=$1 -export DOCKER_PUSH_REPOSITORY=$2 -make release diff --git a/tests/components/application-connector/scripts/test-cra.sh b/tests/components/application-connector/scripts/test-cra.sh deleted file mode 100755 index 2b84c945eafc..000000000000 --- a/tests/components/application-connector/scripts/test-cra.sh +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env bash - -./tests/components/application-connector/scripts/jobguard.sh - -service docker start -curl -s https://raw.githubusercontent.com/k3d-io/k3d/main/install.sh | bash -curl -Lo kyma.tar.gz "https://github.com/kyma-project/cli/releases/download/$(curl -s https://api.github.com/repos/kyma-project/cli/releases/latest | grep tag_name | cut -d '"' -f 4)/kyma_Linux_x86_64.tar.gz" && mkdir kyma-release && tar -C kyma-release -zxvf kyma.tar.gz && chmod +x kyma-release/kyma && rm -rf kyma.tar.gz -k3d registry create kyma-registry --port 5001 -k3d cluster create kyma --kubeconfig-switch-context -p 80:80@loadbalancer -p 443:443@loadbalancer --registry-use kyma-registry -kubectl create ns kyma-system -kubectl cluster-info -kyma-release/kyma deploy --ci --components-file tests/components/application-connector/resources/installation-config/mini-kyma-skr.yaml --source local --workspace $PWD -cd tests/components/application-connector - -# reconfigure DNS -kubectl apply -f resources/patches/coredns.yaml -kubectl -n kube-system delete pods -l k8s-app=kube-dns - -make -f Makefile.test-compass-runtime-agent test-compass-runtime-agent -failed=$? - -k3d cluster delete kyma -exit $failed diff --git a/tests/components/application-connector/test/application-connectivity-validator/suite_test.go b/tests/components/application-connector/test/application-connectivity-validator/suite_test.go deleted file mode 100644 index b08c4fde96e4..000000000000 --- a/tests/components/application-connector/test/application-connectivity-validator/suite_test.go +++ /dev/null @@ -1,136 +0,0 @@ -package application_connectivity_validator - -import ( - "fmt" - "net/http" - "testing" - - "github.com/stretchr/testify/suite" - - "github.com/kyma-project/kyma/tests/components/application-connector/internal/testkit/httpd" -) - -const v1EventsFormat = "http://central-application-connectivity-validator.kyma-system:8080/%s/v1/events" -const v2EventsFormat = "http://central-application-connectivity-validator.kyma-system:8080/%s/v2/events" -const publishRoutedFormat = "http://central-application-connectivity-validator.kyma-system:8080/%s/events" - -const XForwardedClientCertFormat = "Hash=hash1;Cert=\"cert\";Subject=\"O=client organization,CN=%s\";URI=,By=spiffe://cluster.local/ns/default/sa/echoserver;Hash=hash;Subject=\"\";URI=spiffe://cluster.local/ns/istio-system/sa/istio-ingressgateway-service-account" - -const standaloneAppName = "event-test-standalone" -const compassAppName = "event-test-compass" - -type ValidatorSuite struct { - suite.Suite -} - -func (vs *ValidatorSuite) SetupSuite() { -} - -func (vs *ValidatorSuite) TearDownSuite() { - _, err := http.Post("http://localhost:15000/quitquitquit", "", nil) - vs.Nil(err) - _, err = http.Post("http://localhost:15020/quitquitquit", "", nil) - vs.Nil(err) -} - -func TestValidatorSuite(t *testing.T) { - suite.Run(t, new(ValidatorSuite)) -} - -func (vs *ValidatorSuite) TestGoodCert() { - cli := httpd.NewCli(vs.T()) - - for _, testCase := range []struct { - appName string - expectedCName string - }{{ - appName: standaloneAppName, - expectedCName: standaloneAppName, - }, { - appName: compassAppName, - expectedCName: "clientId1", - }} { - v1Events := fmt.Sprintf(v1EventsFormat, testCase.appName) - v2Events := fmt.Sprintf(v2EventsFormat, testCase.appName) - routedEvents := fmt.Sprintf(publishRoutedFormat, testCase.appName) - endpoints := []string{v1Events, v2Events, routedEvents} - - for _, url := range endpoints { - vs.Run(fmt.Sprintf("Send request to %s URL", url), func() { - req, err := http.NewRequest(http.MethodGet, url, nil) - vs.Nil(err) - - req.Header.Add("X-Forwarded-Client-Cert", certFields(testCase.expectedCName)) - - res, _, err := cli.Do(req) - vs.Require().Nil(err) - vs.Equal(http.StatusOK, res.StatusCode) - }) - } - } -} - -func (vs *ValidatorSuite) TestBadCert() { - cli := httpd.NewCli(vs.T()) - - appNames := []string{standaloneAppName, compassAppName} - - for _, appName := range appNames { - v1Events := fmt.Sprintf(v1EventsFormat, appName) - v2Events := fmt.Sprintf(v2EventsFormat, appName) - routedEvents := fmt.Sprintf(publishRoutedFormat, appName) - endpoints := []string{v1Events, v2Events, routedEvents} - - for _, url := range endpoints { - vs.Run(fmt.Sprintf("Send request to %s URL with incorrect cname in header", url), func() { - req, err := http.NewRequest(http.MethodGet, url, nil) - vs.Nil(err) - - req.Header.Add("X-Forwarded-Client-Cert", certFields("nonexistant")) - - res, _, err := cli.Do(req) - vs.Require().Nil(err) - vs.Equal(http.StatusForbidden, res.StatusCode) - }) - - vs.Run(fmt.Sprintf("Send request to %s URL without subject in header", url), func() { - req, err := http.NewRequest(http.MethodGet, url, nil) - vs.Nil(err) - - req.Header.Add("X-Forwarded-Client-Cert", "Hash=hash1;Cert=\"cert\"") - - res, _, err := cli.Do(req) - vs.Require().Nil(err) - vs.Equal(http.StatusForbidden, res.StatusCode) - }) - - vs.Run(fmt.Sprintf("Send request to %s URL without header", url), func() { - req, err := http.NewRequest(http.MethodGet, url, nil) - vs.Nil(err) - - res, _, err := cli.Do(req) - vs.Require().Nil(err) - vs.Equal(http.StatusInternalServerError, res.StatusCode) - }) - } - } -} - -func (vs *ValidatorSuite) TestInvalidPathPrefix() { - const v3vents = "http://central-application-connectivity-validator.kyma-system:8080/event-test-compass/v3/events" - - cli := httpd.NewCli(vs.T()) - - req, err := http.NewRequest(http.MethodGet, v3vents, nil) - vs.Nil(err) - - req.Header.Add("X-Forwarded-Client-Cert", certFields("clientId1")) - - res, _, err := cli.Do(req) - vs.Require().Nil(err) - vs.Equal(http.StatusNotFound, res.StatusCode) -} - -func certFields(cname string) string { - return fmt.Sprintf(XForwardedClientCertFormat, cname) -} diff --git a/tests/components/application-connector/test/application-connectivity-validator/tools.go b/tests/components/application-connector/test/application-connectivity-validator/tools.go deleted file mode 100644 index 0d136f35da76..000000000000 --- a/tests/components/application-connector/test/application-connectivity-validator/tools.go +++ /dev/null @@ -1,5 +0,0 @@ -package application_connectivity_validator - -func validatorURL(app, path string) string { - return "http://central-application-connectivity-validator.kyma-system:8080/" + app + "/" + path -} diff --git a/tests/components/application-connector/test/application-gateway/complex_test.go b/tests/components/application-connector/test/application-gateway/complex_test.go deleted file mode 100644 index 7d94b0a49ef6..000000000000 --- a/tests/components/application-connector/test/application-gateway/complex_test.go +++ /dev/null @@ -1,28 +0,0 @@ -package application_gateway - -import ( - "time" - - "github.com/kyma-project/kyma/tests/components/application-connector/internal/testkit/httpd" -) - -func (gs *GatewaySuite) TestComplex() { - gs.Run("OAuth token renewal", func() { - http := httpd.NewCli(gs.T()) - - url := gatewayURL("complex-cases", "oauth-expired-token-renewal") - gs.T().Log("Url:", url) - - // Authorize, then call endpoint - res, _, err := http.Get(url) - gs.Nil(err, "First request failed") - gs.Equal(200, res.StatusCode, "First request failed") - - time.Sleep(10 * time.Second) // wait for token to expire - - // Call endpoint, requiring token renewall - res, _, err = http.Get(url) - gs.Nil(err, "Second request failed") - gs.Equal(200, res.StatusCode, "Second request failed") - }) -} diff --git a/tests/components/application-connector/test/application-gateway/runner_test.go b/tests/components/application-connector/test/application-gateway/runner_test.go deleted file mode 100644 index 76e4860ca14c..000000000000 --- a/tests/components/application-connector/test/application-gateway/runner_test.go +++ /dev/null @@ -1,109 +0,0 @@ -package application_gateway - -import ( - "context" - "net/http" - "strconv" - "strings" - - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - "github.com/kyma-project/kyma/tests/components/application-connector/internal/testkit/httpd" -) - -var applications = []string{"positive-authorisation", "negative-authorisation", "path-related-error-handling", "missing-resources-error-handling", "proxy-cases", "proxy-errors", "redirects", "code-rewriting"} - -func (gs *GatewaySuite) TestGetRequest() { - - for _, app := range applications { - app, err := gs.cli.ApplicationconnectorV1alpha1().Applications().Get(context.Background(), app, v1.GetOptions{}) - gs.Nil(err) - - gs.Run(app.Spec.Description, func() { - for _, service := range app.Spec.Services { - gs.Run(service.Description, func() { - http := httpd.NewCli(gs.T()) - - for _, entry := range service.Entries { - if entry.Type != "API" { - gs.T().Log("Skipping event entry") - continue - } - - expectedCode, err := getExpectedHTTPCode(service) - if err != nil { - gs.T().Log("Error during getting the error code from description -> applicationCRD") - gs.T().Fail() - } - - res, _, err := http.Get(entry.CentralGatewayUrl) - gs.Nil(err, "Request failed") - gs.Equal(expectedCode, res.StatusCode, "Incorrect response code") - } - }) - } - }) - } -} - -func (gs *GatewaySuite) TestResponseBody() { - app, err := gs.cli.ApplicationconnectorV1alpha1().Applications().Get(context.Background(), "proxy-cases", v1.GetOptions{}) - gs.Nil(err) - for _, service := range app.Spec.Services { - gs.Run(service.Description, func() { - http := httpd.NewCli(gs.T()) - - for _, entry := range service.Entries { - if entry.Type != "API" { - gs.T().Log("Skipping event entry") - continue - } - - expectedCode, err := getExpectedHTTPCode(service) - if err != nil { - gs.T().Log("Error during getting the error code from description -> applicationCRD") - gs.T().Fail() - } - - _, body, err := http.Get(entry.CentralGatewayUrl) - gs.Nil(err, "Request failed") - - codeStr := strconv.Itoa(expectedCode) - - gs.Equal(codeStr, string(body), "Incorrect body") - } - }) - } -} - -func (gs *GatewaySuite) TestBodyPerMethod() { - app, err := gs.cli.ApplicationconnectorV1alpha1().Applications().Get(context.Background(), "methods-with-body", v1.GetOptions{}) - gs.Nil(err) - for _, service := range app.Spec.Services { - gs.Run(service.Description, func() { - httpCli := httpd.NewCli(gs.T()) - - for _, entry := range service.Entries { - if entry.Type != "API" { - gs.T().Log("Skipping event entry") - continue - } - - method := service.Description - bodyBuf := strings.NewReader(service.Description) - - req, err := http.NewRequest(method, entry.CentralGatewayUrl, bodyBuf) - gs.Nil(err, "Preparing request failed") - - _, body, err := httpCli.Do(req) - gs.Nil(err, "Request failed") - - res, err := unmarshalBody(body) - gs.Nil(err, "Response body wasn't correctly forwarded") - - gs.Equal(service.Description, string(res.Body), "Request body doesn't match") - gs.Equal(service.Description, res.Method, "Request method doesn't match") - } - }) - } -} diff --git a/tests/components/application-connector/test/application-gateway/suite_test.go b/tests/components/application-connector/test/application-gateway/suite_test.go deleted file mode 100644 index 764ebabf17ca..000000000000 --- a/tests/components/application-connector/test/application-gateway/suite_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package application_gateway - -import ( - "net/http" - "testing" - - cli "github.com/kyma-project/kyma/components/central-application-gateway/pkg/client/clientset/versioned" - "github.com/stretchr/testify/suite" - "k8s.io/client-go/rest" -) - -type GatewaySuite struct { - suite.Suite - cli *cli.Clientset -} - -func (gs *GatewaySuite) SetupSuite() { - cfg, err := rest.InClusterConfig() - gs.Require().Nil(err) - - gs.cli, err = cli.NewForConfig(cfg) - gs.Require().Nil(err) -} - -func (gs *GatewaySuite) TearDownSuite() { - _, err := http.Post("http://localhost:15000/quitquitquit", "", nil) - gs.Nil(err) - _, err = http.Post("http://localhost:15020/quitquitquit", "", nil) - gs.Nil(err) -} - -func TestGatewaySuite(t *testing.T) { - suite.Run(t, new(GatewaySuite)) -} diff --git a/tests/components/application-connector/test/application-gateway/tools.go b/tests/components/application-connector/test/application-gateway/tools.go deleted file mode 100644 index 135c49c6e987..000000000000 --- a/tests/components/application-connector/test/application-gateway/tools.go +++ /dev/null @@ -1,30 +0,0 @@ -package application_gateway - -import ( - "encoding/json" - "regexp" - "strconv" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" - "github.com/pkg/errors" - - test_api "github.com/kyma-project/kyma/tests/components/application-connector/internal/testkit/test-api" -) - -func getExpectedHTTPCode(service v1alpha1.Service) (int, error) { - re := regexp.MustCompile(`\d+`) - if codeStr := re.FindString(service.Description); len(codeStr) > 0 { - return strconv.Atoi(codeStr) - } - return 0, errors.New("Bad configuration") -} - -func gatewayURL(app, service string) string { - return "http://central-application-gateway.kyma-system:8080/" + app + "/" + service -} - -func unmarshalBody(body []byte) (test_api.EchoResponse, error) { - res := test_api.EchoResponse{} - err := json.Unmarshal(body, &res) - return res, err -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/config.go b/tests/components/application-connector/test/compass-runtime-agent/config.go deleted file mode 100644 index c004c3987acf..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/config.go +++ /dev/null @@ -1,19 +0,0 @@ -package compass_runtime_agent - -import "fmt" - -type config struct { - DirectorURL string `envconfig:"default=http://compass-director.compass-system.svc.cluster.local:3000/graphql"` - SkipDirectorCertVerification bool `envconfig:"default=false"` - OAuthCredentialsNamespace string `envconfig:"default=test"` - SystemNamespace string `envconfig:"default=kyma-system"` - CompassRuntimeAgentDeploymentName string `envconfig:"default=compass-runtime-agent"` - CompassNamespace string `envconfig:"default=kyma-system"` - OAuthCredentialsSecretName string `envconfig:"default=oauth-compass-credentials"` - TestingTenant string `envconfig:"default=tenant"` -} - -func (c *config) String() string { - return fmt.Sprintf("DirectorURL: %s, SkipDirectorCertVerification: %v, OAuthCredentialsNamespace: %s, IntegrationNamespace: %s, CompassNamespace: %s, OAuthCredentialsSecretName: %s, TestingTenant %s", - c.DirectorURL, c.SkipDirectorCertVerification, c.OAuthCredentialsNamespace, c.SystemNamespace, c.CompassNamespace, c.OAuthCredentialsSecretName, c.TestingTenant) -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/suite_test.go b/tests/components/application-connector/test/compass-runtime-agent/suite_test.go deleted file mode 100644 index c3e62ea213d0..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/suite_test.go +++ /dev/null @@ -1,166 +0,0 @@ -package compass_runtime_agent - -import ( - "crypto/tls" - "fmt" - "net/http" - "os" - "testing" - "time" - - cli "github.com/kyma-project/kyma/components/central-application-gateway/pkg/client/clientset/versioned" - ccclientset "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/client/clientset/versioned" - "github.com/pkg/errors" - "github.com/stretchr/testify/suite" - "github.com/vrischmann/envconfig" - "k8s.io/client-go/kubernetes" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/clientcmd" - - "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/applications" - "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/director" - "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/graphql" - initcra "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/init" - compassruntimeagentinittypes "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types" - "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/oauth" - "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/random" -) - -type CompassRuntimeAgentSuite struct { - suite.Suite - applicationsClientSet *cli.Clientset - compassConnectionClientSet *ccclientset.Clientset - coreClientSet *kubernetes.Clientset - compassRuntimeAgentConfigurator initcra.CompassRuntimeAgentConfigurator - directorClient director.Client - appComparator applications.Comparator - testConfig config - rollbackTestFunc compassruntimeagentinittypes.RollbackFunc - formationName string -} - -func (cs *CompassRuntimeAgentSuite) SetupSuite() { - - err := envconfig.InitWithPrefix(&cs.testConfig, "APP") - cs.Require().Nil(err) - - cs.T().Logf("Config: %s", cs.testConfig.String()) - - cs.T().Logf("Init Kubernetes APIs") - cs.initKubernetesApis() - - cs.T().Logf("Configure Compass Runtime Agent for test") - cs.initCompassRuntimeAgentConfigurator() - cs.initComparators() - cs.configureRuntimeAgent() -} - -func (cs *CompassRuntimeAgentSuite) initKubernetesApis() { - var cfg *rest.Config - var err error - - cs.T().Logf("Initializing with in cluster config") - cfg, err = rest.InClusterConfig() - cs.Assert().NoError(err) - - if err != nil { - cs.T().Logf("Initializing kubeconfig") - kubeconfig, ok := os.LookupEnv("KUBECONFIG") - cs.Require().True(ok) - - cfg, err = clientcmd.BuildConfigFromFlags("", kubeconfig) - cs.Require().NoError(err) - } - - cs.applicationsClientSet, err = cli.NewForConfig(cfg) - cs.Require().NoError(err) - - cs.compassConnectionClientSet, err = ccclientset.NewForConfig(cfg) - cs.Require().NoError(err) - - cs.coreClientSet, err = kubernetes.NewForConfig(cfg) - cs.Require().NoError(err) -} - -func (cs *CompassRuntimeAgentSuite) initComparators() { - secretComparator, err := applications.NewSecretComparator(cs.coreClientSet, cs.testConfig.OAuthCredentialsNamespace, cs.testConfig.SystemNamespace) - cs.Require().NoError(err) - - applicationGetter := cs.applicationsClientSet.ApplicationconnectorV1alpha1().Applications() - cs.appComparator, err = applications.NewComparator(secretComparator, applicationGetter, "kyma-system", "kyma-system") -} - -func (cs *CompassRuntimeAgentSuite) configureRuntimeAgent() { - cs.T().Helper() - - var err error - runtimeName := "cratest" - cs.formationName = "cratest" + random.RandomString(5) - - cs.rollbackTestFunc, err = cs.compassRuntimeAgentConfigurator.Do(runtimeName, cs.formationName) - cs.Require().NoError(err) -} - -func (cs *CompassRuntimeAgentSuite) initCompassRuntimeAgentConfigurator() { - var err error - cs.directorClient, err = cs.makeCompassDirectorClient() - cs.Require().NoError(err) - - cs.compassRuntimeAgentConfigurator = initcra.NewCompassRuntimeAgentConfigurator( - initcra.NewCompassConfigurator(cs.directorClient, cs.testConfig.TestingTenant), - initcra.NewCertificateSecretConfigurator(cs.coreClientSet), - initcra.NewConfigurationSecretConfigurator(cs.coreClientSet), - initcra.NewCompassConnectionCRConfiguration(cs.compassConnectionClientSet.CompassV1alpha1().CompassConnections()), - initcra.NewDeploymentConfiguration(cs.coreClientSet, "compass-runtime-agent", cs.testConfig.CompassNamespace), - cs.testConfig.OAuthCredentialsNamespace) -} - -func (cs *CompassRuntimeAgentSuite) TearDownSuite() { - if cs.rollbackTestFunc != nil { - cs.T().Logf("Restore Compass Runtime Agent configuration") - err := cs.rollbackTestFunc() - - if err != nil { - cs.T().Logf("Failed to rollback test configuration: %v", err) - } - } - _, err := http.Post("http://localhost:15000/quitquitquit", "", nil) - if err != nil { - cs.T().Logf("Failed to quit sidecar: %v", err) - } - _, err = http.Post("http://localhost:15020/quitquitquit", "", nil) - if err != nil { - cs.T().Logf("Failed to quit sidecar: %v", err) - } -} - -func TestCompassRuntimeAgentSuite(t *testing.T) { - suite.Run(t, new(CompassRuntimeAgentSuite)) -} - -func (cs *CompassRuntimeAgentSuite) makeCompassDirectorClient() (director.Client, error) { - - secretsRepo := cs.coreClientSet.CoreV1().Secrets(cs.testConfig.OAuthCredentialsNamespace) - - if secretsRepo == nil { - return nil, fmt.Errorf("could not access secrets in %s namespace", cs.testConfig.OAuthCredentialsNamespace) - } - client := &http.Client{ - Transport: &http.Transport{ - TLSClientConfig: &tls.Config{InsecureSkipVerify: cs.testConfig.SkipDirectorCertVerification}, - }, - Timeout: 10 * time.Second, - } - - gqlClient := graphql.NewGraphQLClient(cs.testConfig.DirectorURL, true, cs.testConfig.SkipDirectorCertVerification) - if gqlClient == nil { - return nil, fmt.Errorf("could not create GraphQLClient for endpoint %s", cs.testConfig.DirectorURL) - } - - oauthClient, err := oauth.NewOauthClient(client, secretsRepo, cs.testConfig.OAuthCredentialsSecretName) - if err != nil { - return nil, errors.Wrap(err, "Could not create OAuthClient client") - } - - return director.NewDirectorClient(gqlClient, oauthClient, cs.testConfig.TestingTenant), nil -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/synchronisation_test.go b/tests/components/application-connector/test/compass-runtime-agent/synchronisation_test.go deleted file mode 100644 index ac19f018cb51..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/synchronisation_test.go +++ /dev/null @@ -1,157 +0,0 @@ -package compass_runtime_agent - -import ( - "context" - "fmt" - "time" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" - "k8s.io/apimachinery/pkg/api/errors" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/executor" - "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/random" -) - -const checkAppExistsPeriod = 10 * time.Second -const appCreationTimeout = 2 * time.Minute -const appUpdateTimeout = 2 * time.Minute - -const updatedDescription = "The app was updated" - -type ApplicationReader interface { - Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.Application, error) -} - -func (cs *CompassRuntimeAgentSuite) TestApplication() { - expectedAppName := "app1" - updatedAppName := "app1-updated" - - compassAppName := expectedAppName + random.RandomString(10) - - correctState := false - //Create Application in Director - applicationID, err := cs.directorClient.RegisterApplication(compassAppName, "Test Application for testing Compass Runtime Agent") - cs.Require().NoError(err) - - synchronizedCompassAppName := fmt.Sprintf("mp-%s", compassAppName) - - applicationInterface := cs.applicationsClientSet.ApplicationconnectorV1alpha1().Applications() - err = cs.assignApplicationToFormationAndWaitForSync(applicationInterface, synchronizedCompassAppName, applicationID) - cs.NoError(err) - - // Compare Application created by Compass Runtime Agent with expected result - - cs.Run("Compass Runtime Agent should create Application", func() { - err = cs.appComparator.Compare(cs.T(), expectedAppName, synchronizedCompassAppName) - cs.NoError(err) - - correctState = err == nil - }) - - cs.Run("Update app", func() { - if !correctState { - cs.T().Skip("App not in correct state") - } - - _ = cs.updateAndWait(applicationInterface, synchronizedCompassAppName, applicationID) - - err = cs.appComparator.Compare(cs.T(), updatedAppName, synchronizedCompassAppName) - cs.NoError(err) - - correctState = err == nil - }) - - // Clean up - cs.Run("Compass Runtime Agent should remove Application", func() { - err = cs.removeApplicationAndWaitForSync(applicationInterface, synchronizedCompassAppName, applicationID) - cs.NoError(err) - }) -} - -func (cs *CompassRuntimeAgentSuite) updateAndWait(appReader ApplicationReader, compassAppName, applicationID string) error { - t := cs.T() - t.Helper() - - exec := func() error { - _, err := cs.directorClient.UpdateApplication(applicationID, updatedDescription) - return err - } - - verify := func() bool { - app, err := appReader.Get(context.Background(), compassAppName, v1.GetOptions{}) - if err != nil { - t.Logf("Couldn't get updated: %v", err) - } - - return err == nil && app.Spec.Description == updatedDescription - } - - return executor.ExecuteAndWaitForCondition{ - RetryableExecuteFunc: exec, - ConditionMetFunc: verify, - Tick: checkAppExistsPeriod, - Timeout: appUpdateTimeout, - }.Do() -} - -func (cs *CompassRuntimeAgentSuite) assignApplicationToFormationAndWaitForSync(appReader ApplicationReader, compassAppName, applicationID string) error { - t := cs.T() - t.Helper() - - exec := func() error { - return cs.directorClient.AssignApplicationToFormation(applicationID, cs.formationName) - } - - verify := func() bool { - _, err := appReader.Get(context.Background(), compassAppName, v1.GetOptions{}) - if err != nil { - t.Logf("Failed to get app: %v", err) - } - - return err == nil - } - - return executor.ExecuteAndWaitForCondition{ - RetryableExecuteFunc: exec, - ConditionMetFunc: verify, - Tick: checkAppExistsPeriod, - Timeout: appCreationTimeout, - }.Do() -} - -func (cs *CompassRuntimeAgentSuite) removeApplicationAndWaitForSync(appReader ApplicationReader, compassAppName, applicationID string) error { - t := cs.T() - t.Helper() - - exec := func() error { - err := cs.directorClient.UnassignApplication(applicationID, cs.formationName) - if err != nil { - return err - } - - err = cs.directorClient.UnregisterApplication(applicationID) - return err - } - - verify := func() bool { - _, err := appReader.Get(context.Background(), compassAppName, v1.GetOptions{}) - if errors.IsNotFound(err) { - t.Logf("Application was successfully removed by Compass Runtime Agent: %v", err) - return true - } - - if err != nil { - t.Logf("Failed to check whether Application was removed by Compass Runtime Agent: %v", err) - } - - return false - } - - return executor.ExecuteAndWaitForCondition{ - RetryableExecuteFunc: exec, - ConditionMetFunc: verify, - Tick: checkAppExistsPeriod, - Timeout: appCreationTimeout, - }.Do() -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/applications/comparator.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/applications/comparator.go deleted file mode 100644 index 1a9ab03c34c2..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/applications/comparator.go +++ /dev/null @@ -1,125 +0,0 @@ -package applications - -import ( - "context" - "errors" - "testing" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" - "github.com/stretchr/testify/assert" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -//go:generate mockery --name=ApplicationGetter -type ApplicationGetter interface { - Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.Application, error) -} - -func NewComparator(secretComparer Comparator, applicationGetter ApplicationGetter, expectedNamespace, actualNamespace string) (Comparator, error) { - return &comparator{ - secretComparer: secretComparer, - applicationGetter: applicationGetter, - expectedNamespace: expectedNamespace, - actualNamespace: actualNamespace, - }, nil -} - -type comparator struct { - secretComparer Comparator - applicationGetter ApplicationGetter - expectedNamespace string - actualNamespace string -} - -func (c comparator) Compare(t *testing.T, expected, actual string) error { - t.Helper() - - if actual == "" || expected == "" { - return errors.New("empty actual or expected application name") - } - - actualApp, err := c.applicationGetter.Get(context.Background(), actual, v1.GetOptions{}) - if err != nil { - return err - } - - expectedApp, err := c.applicationGetter.Get(context.Background(), expected, v1.GetOptions{}) - if err != nil { - return err - } - - c.compareSpec(t, expectedApp, actualApp) - return nil -} - -func (c comparator) compareSpec(t *testing.T, expected, actual *v1alpha1.Application) { - t.Helper() - a := assert.New(t) - - a.Equal(expected.Spec.Description, actual.Spec.Description, "Description is incorrect") - a.Equal(expected.Spec.SkipInstallation, actual.Spec.SkipInstallation, "SkipInstallation is incorrect") - - c.compareServices(t, expected.Spec.Services, actual.Spec.Services) - - a.NotNil(actual.Spec.Labels) - a.Equal(actual.Name, actual.Spec.Labels["connected-app"]) - - a.Equal(expected.Spec.Tenant, actual.Spec.Tenant, "Tenant is incorrect") - a.Equal(expected.Spec.Group, actual.Spec.Group, "Group is incorrect") - - a.Equal(expected.Spec.Tags, actual.Spec.Tags, "Tags is incorrect") - a.Equal(expected.Spec.DisplayName, actual.Spec.DisplayName, "DisplayName is incorrect") - a.Equal(expected.Spec.ProviderDisplayName, actual.Spec.ProviderDisplayName, "ProviderDisplayName is incorrect") - a.Equal(expected.Spec.LongDescription, actual.Spec.LongDescription, "LongDescription is incorrect") - a.Equal(expected.Spec.SkipVerify, actual.Spec.SkipVerify, "SkipVerify is incorrect") -} - -func (c comparator) compareServices(t *testing.T, expected, actual []v1alpha1.Service) { - t.Helper() - a := assert.New(t) - - a.Equal(len(expected), len(actual)) - - for i := 0; i < len(actual); i++ { - a.Equal(expected[i].Identifier, actual[i].Identifier) - a.Equal(expected[i].DisplayName, actual[i].DisplayName) - a.Equal(expected[i].Description, actual[i].Description) - - c.compareEntries(t, expected[i].Entries, actual[i].Entries) - - a.Equal(expected[i].AuthCreateParameterSchema, actual[i].AuthCreateParameterSchema) - } -} - -func (c comparator) compareEntries(t *testing.T, expected, actual []v1alpha1.Entry) { - t.Helper() - a := assert.New(t) - - a.Equal(len(expected), len(actual)) - - for i := 0; i < len(actual); i++ { - a.Equal(expected[i].Type, actual[i].Type) - a.Equal(expected[i].TargetUrl, actual[i].TargetUrl) - a.Equal(expected[i].SpecificationUrl, actual[i].SpecificationUrl) - a.Equal(expected[i].ApiType, actual[i].ApiType) - - c.compareCredentials(t, expected[i].Credentials, actual[i].Credentials) - - a.Equal(expected[i].RequestParametersSecretName, actual[i].RequestParametersSecretName) - a.Equal(expected[i].Name, actual[i].Name) - } -} - -func (c comparator) compareCredentials(t *testing.T, expected, actual v1alpha1.Credentials) { - t.Helper() - a := assert.New(t) - - a.Equal(expected.Type, actual.Type) - - err := c.secretComparer.Compare(t, expected.SecretName, actual.SecretName) - a.NoError(err) - - a.Equal(expected.AuthenticationUrl, actual.AuthenticationUrl) - - a.Equal(expected.CSRFInfo, actual.CSRFInfo) -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/applications/comparator_test.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/applications/comparator_test.go deleted file mode 100644 index 5583b2915d41..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/applications/comparator_test.go +++ /dev/null @@ -1,195 +0,0 @@ -package applications - -import ( - "errors" - "testing" - - "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/applications/mocks" -) - -func TestApplicationCrdCompare(t *testing.T) { - - t.Run("should compare applications", func(t *testing.T) { - secretComparatorMock := &mocks.Comparator{} - applicationGetterMock := &mocks.ApplicationGetter{} - actualApp := getTestApp("actual", "actualNamespace", "actualSecret") - expectedApp := getTestApp("expected", "expectedNamespace", "expectedSecret") - - secretComparatorMock.On("Compare", mock.Anything, "expectedSecret", "actualSecret").Return(nil) - applicationGetterMock.On("Get", mock.Anything, "actual", v1.GetOptions{}).Return(actualApp, nil).Once() - applicationGetterMock.On("Get", mock.Anything, "expected", v1.GetOptions{}).Return(expectedApp, nil).Once() - - //when - applicationComparator, err := NewComparator(secretComparatorMock, applicationGetterMock, "expectedNamespace", "actualNamespace") - err = applicationComparator.Compare(t, "expected", "actual") - - //then - require.NoError(t, err) - secretComparatorMock.AssertExpectations(t) - applicationGetterMock.AssertExpectations(t) - }) - - t.Run("should return error when expected or actual application name is empty", func(t *testing.T) { - //given - secretComparatorMock := &mocks.Comparator{} - applicationGetterMock := &mocks.ApplicationGetter{} - - { - //when - applicationComparator, err := NewComparator(secretComparatorMock, applicationGetterMock, "expected", "actual") - err = applicationComparator.Compare(t, "expected", "") - - //then - require.Error(t, err) - } - - { - //when - applicationComparator, err := NewComparator(secretComparatorMock, applicationGetterMock, "expected", "actual") - err = applicationComparator.Compare(t, "", "actual") - - //then - require.Error(t, err) - } - - }) - - t.Run("should return error when failed to get actual application", func(t *testing.T) { - //given - secretComparatorMock := &mocks.Comparator{} - applicationGetterMock := &mocks.ApplicationGetter{} - actualApp := v1alpha1.Application{} - - applicationGetterMock.On("Get", mock.Anything, "actual", v1.GetOptions{}).Return(&actualApp, errors.New("failed to get actual app")).Once() - - //when - applicationComparator, err := NewComparator(secretComparatorMock, applicationGetterMock, "expected", "actual") - err = applicationComparator.Compare(t, "expected", "actual") - - //then - require.Error(t, err) - secretComparatorMock.AssertExpectations(t) - applicationGetterMock.AssertExpectations(t) - }) - - t.Run("should return error when failed to get expected application", func(t *testing.T) { - //given - secretComparatorMock := &mocks.Comparator{} - applicationGetterMock := &mocks.ApplicationGetter{} - expectedApp := v1alpha1.Application{} - actualApp := v1alpha1.Application{} - - applicationGetterMock.On("Get", mock.Anything, "actual", v1.GetOptions{}).Return(&actualApp, nil).Once() - applicationGetterMock.On("Get", mock.Anything, "expected", v1.GetOptions{}).Return(&expectedApp, errors.New("failed to get expected app")).Once() - - //when - applicationComparator, err := NewComparator(secretComparatorMock, applicationGetterMock, "expected", "actual") - err = applicationComparator.Compare(t, "expected", "actual") - - //then - require.Error(t, err) - secretComparatorMock.AssertExpectations(t) - applicationGetterMock.AssertExpectations(t) - }) -} - -func getTestApp(name, namespace, secretName string) *v1alpha1.Application { - //given - services := make([]v1alpha1.Service, 0, 0) - entries := make([]v1alpha1.Entry, 0, 0) - - credentials := v1alpha1.Credentials{ - Type: "OAuth", - SecretName: secretName, - AuthenticationUrl: "authURL", - CSRFInfo: &v1alpha1.CSRFInfo{TokenEndpointURL: "csrfTokenURL"}, - } - - entries = append(entries, v1alpha1.Entry{ - Type: "api", - TargetUrl: "targetURL", - SpecificationUrl: "specURL", - ApiType: "v1", - Credentials: credentials, - RequestParametersSecretName: "paramSecret", - Name: "test2", - ID: "t2", - CentralGatewayUrl: "centralURL", - AccessLabel: "", //ignore for now - GatewayUrl: "", - }) - - entries = append(entries, v1alpha1.Entry{ - Type: "api", - TargetUrl: "targetURL", - SpecificationUrl: "specURL", - ApiType: "v1", - Credentials: credentials, - RequestParametersSecretName: "paramSecret", - Name: "test1", - ID: "t1", - CentralGatewayUrl: "centralURL", - AccessLabel: "", - GatewayUrl: "", - }) - - services = append(services, v1alpha1.Service{ - ID: "serviceTest", - Identifier: "st1", - Name: "srvTest1", - DisplayName: "srvTest1", - Description: "srvTest1", - Entries: entries, - AuthCreateParameterSchema: nil, - Labels: nil, - LongDescription: "", - ProviderDisplayName: "", - Tags: nil, - }) - - services = append(services, v1alpha1.Service{ - ID: "serviceTest2", - Identifier: "st2", - Name: "srvTest2", - DisplayName: "srvTest2", - Description: "srvTest2", - Entries: entries, - AuthCreateParameterSchema: nil, - Labels: nil, - LongDescription: "", - ProviderDisplayName: "", - Tags: nil, - }) - - return &v1alpha1.Application{ - TypeMeta: v1.TypeMeta{}, - ObjectMeta: v1.ObjectMeta{ - Name: name, - Namespace: namespace, - }, - Spec: v1alpha1.ApplicationSpec{ - Description: "testapp", - SkipInstallation: false, - Services: services, - Labels: map[string]string{"connected-app": name}, - - Tenant: "test", - Group: "test", - CompassMetadata: &v1alpha1.CompassMetadata{ - ApplicationID: "compassID1", - Authentication: v1alpha1.Authentication{ClientIds: []string{"11", "22"}}, - }, - Tags: []string{"tag1", "tag2"}, - DisplayName: "applicationOneDisplay", - ProviderDisplayName: "applicationOneDisplay", - LongDescription: "applicationOne Test", - SkipVerify: true, - }, - } - -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/applications/mocks/ApplicationGetter.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/applications/mocks/ApplicationGetter.go deleted file mode 100644 index 82933f9afc46..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/applications/mocks/ApplicationGetter.go +++ /dev/null @@ -1,55 +0,0 @@ -// Code generated by mockery v2.15.0. DO NOT EDIT. - -package mocks - -import ( - context "context" - - mock "github.com/stretchr/testify/mock" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - v1alpha1 "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" -) - -// ApplicationGetter is an autogenerated mock type for the ApplicationGetter type -type ApplicationGetter struct { - mock.Mock -} - -// Get provides a mock function with given fields: ctx, name, opts -func (_m *ApplicationGetter) Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.Application, error) { - ret := _m.Called(ctx, name, opts) - - var r0 *v1alpha1.Application - if rf, ok := ret.Get(0).(func(context.Context, string, v1.GetOptions) *v1alpha1.Application); ok { - r0 = rf(ctx, name, opts) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*v1alpha1.Application) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(context.Context, string, v1.GetOptions) error); ok { - r1 = rf(ctx, name, opts) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -type mockConstructorTestingTNewApplicationGetter interface { - mock.TestingT - Cleanup(func()) -} - -// NewApplicationGetter creates a new instance of ApplicationGetter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewApplicationGetter(t mockConstructorTestingTNewApplicationGetter) *ApplicationGetter { - mock := &ApplicationGetter{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/applications/mocks/Comparator.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/applications/mocks/Comparator.go deleted file mode 100644 index abccb412f069..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/applications/mocks/Comparator.go +++ /dev/null @@ -1,43 +0,0 @@ -// Code generated by mockery v2.15.0. DO NOT EDIT. - -package mocks - -import ( - testing "testing" - - mock "github.com/stretchr/testify/mock" -) - -// Comparator is an autogenerated mock type for the Comparator type -type Comparator struct { - mock.Mock -} - -// Compare provides a mock function with given fields: test, expected, actual -func (_m *Comparator) Compare(test *testing.T, expected string, actual string) error { - ret := _m.Called(test, expected, actual) - - var r0 error - if rf, ok := ret.Get(0).(func(*testing.T, string, string) error); ok { - r0 = rf(test, expected, actual) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -type mockConstructorTestingTNewComparator interface { - mock.TestingT - Cleanup(func()) -} - -// NewComparator creates a new instance of Comparator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewComparator(t mockConstructorTestingTNewComparator) *Comparator { - mock := &Comparator{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/applications/secretcomparator.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/applications/secretcomparator.go deleted file mode 100644 index 5573754d02bf..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/applications/secretcomparator.go +++ /dev/null @@ -1,59 +0,0 @@ -package applications - -import ( - "context" - "errors" - "testing" - - "github.com/stretchr/testify/require" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/client-go/kubernetes" -) - -//go:generate mockery --name=Comparator -type Comparator interface { - Compare(test *testing.T, expected, actual string) error -} - -func NewSecretComparator(coreClientSet kubernetes.Interface, expectedNamespace, actualNamespace string) (Comparator, error) { - return &secretComparator{ - coreClientSet: coreClientSet, - expectedNamespace: expectedNamespace, - actualNamespace: actualNamespace, - }, nil -} - -type secretComparator struct { - coreClientSet kubernetes.Interface - expectedNamespace string - actualNamespace string -} - -func (c secretComparator) Compare(t *testing.T, expected, actual string) error { - t.Helper() - - if actual == "" && expected == "" { - return nil - } - - if actual == "" || expected == "" { - return errors.New("empty actual or expected secret name") - } - - expectedSecretRepo := c.coreClientSet.CoreV1().Secrets(c.expectedNamespace) - actualSecretRepo := c.coreClientSet.CoreV1().Secrets(c.actualNamespace) - - expectedSecret, err := expectedSecretRepo.Get(context.Background(), expected, metav1.GetOptions{}) - if err != nil { - return err - } - - actualSecret, err := actualSecretRepo.Get(context.Background(), actual, metav1.GetOptions{}) - if err != nil { - return err - } - - require.Equal(t, expectedSecret.Data, actualSecret.Data) - - return nil -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/applications/secretcomparator_test.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/applications/secretcomparator_test.go deleted file mode 100644 index 1241a785f36d..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/applications/secretcomparator_test.go +++ /dev/null @@ -1,117 +0,0 @@ -package applications - -import ( - "context" - "testing" - - "github.com/stretchr/testify/require" - v1 "k8s.io/api/core/v1" - meta "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/client-go/kubernetes/fake" - core "k8s.io/client-go/kubernetes/typed/core/v1" -) - -func TestCompare(t *testing.T) { - - t.Run("should return true if secrets are equal", func(t *testing.T) { - //given - coreV1 := fake.NewSimpleClientset() - secretComparator, err := NewSecretComparator(coreV1, "test", "kyma-system") - require.NoError(t, err) - createFakeCredentialsSecret(t, coreV1.CoreV1().Secrets("test"), "expected", "test") - createFakeCredentialsSecret(t, coreV1.CoreV1().Secrets("kyma-system"), "actual", "kyma-system") - - //when - err = secretComparator.Compare(t, "expected", "actual") - - // then - require.NoError(t, err) - }) - - t.Run("should return error if failed to read actual secret", func(t *testing.T) { - //given - coreV1 := fake.NewSimpleClientset() - secretComparator, err := NewSecretComparator(coreV1, "test", "kyma-system") - require.NoError(t, err) - createFakeCredentialsSecret(t, coreV1.CoreV1().Secrets("test"), "expected", "test") - - //when - err = secretComparator.Compare(t, "actual", "expected") - - // then - require.Error(t, err) - }) - - t.Run("should return error if failed to read expected secret", func(t *testing.T) { - //given - coreV1 := fake.NewSimpleClientset() - secretComparator, err := NewSecretComparator(coreV1, "test", "kyma-system") - require.NoError(t, err) - createFakeCredentialsSecret(t, coreV1.CoreV1().Secrets("kyma-system"), "actual", "kyma-system") - - //when - err = secretComparator.Compare(t, "actual", "expected") - - // then - require.Error(t, err) - }) - - t.Run("should return error if expected secret name is empty", func(t *testing.T) { - //given - secretComparator, err := NewSecretComparator(nil, "test", "kyma-system") - require.NoError(t, err) - - //when - err = secretComparator.Compare(t, "actual", "") - - // then - require.Error(t, err) - }) - - t.Run("should return error if actual secret name is empty", func(t *testing.T) { - //given - secretComparator, err := NewSecretComparator(nil, "test", "kyma-system") - require.NoError(t, err) - - //when - err = secretComparator.Compare(t, "", "expected") - - // then - require.Error(t, err) - }) - - t.Run("should return no error if actual and expected secret name is empty", func(t *testing.T) { - //given - secretComparator, err := NewSecretComparator(nil, "test", "kyma-system") - require.NoError(t, err) - - //when - err = secretComparator.Compare(t, "", "") - - // then - require.NoError(t, err) - }) -} - -func createFakeCredentialsSecret(t *testing.T, secrets core.SecretInterface, secretName, namespace string) { - - secret := &v1.Secret{ - ObjectMeta: meta.ObjectMeta{ - Name: secretName, - Namespace: namespace, - }, - TypeMeta: meta.TypeMeta{ - Kind: "Secret", - APIVersion: "v1", - }, - Data: map[string][]byte{ - "key1": []byte("val1"), - "key2": []byte("val2"), - "key3": []byte("val3"), - }, - } - - _, err := secrets.Create(context.Background(), secret, meta.CreateOptions{}) - - require.NoError(t, err) -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/director/directorclient.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/director/directorclient.go deleted file mode 100644 index 6aa3336345ae..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/director/directorclient.go +++ /dev/null @@ -1,320 +0,0 @@ -package director - -import ( - "fmt" - - "github.com/kyma-incubator/compass/components/director/pkg/graphql" - "github.com/kyma-incubator/compass/components/director/pkg/graphql/graphqlizer" - "github.com/pkg/errors" - log "github.com/sirupsen/logrus" - - gql "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/graphql" - "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/oauth" - gcli "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/third_party/machinebox/graphql" -) - -const ( - AuthorizationHeader = "Authorization" - TenantHeader = "Tenant" -) - -//go:generate mockery --name=Client -type Client interface { - RegisterApplication(appName, displayName string) (string, error) - UnregisterApplication(id string) error - AssignApplicationToFormation(appId, formationName string) error - UnassignApplication(appId, formationName string) error - RegisterRuntime(runtimeName string) (string, error) - UnregisterRuntime(id string) error - RegisterFormation(formationName string) error - UnregisterFormation(formationName string) error - AssignRuntimeToFormation(runtimeId, formationName string) error - GetConnectionToken(runtimeID string) (string, string, error) - UpdateApplication(id, newDesc string) (string, error) -} - -type directorClient struct { - gqlClient gql.Client - queryProvider queryProvider - graphqlizer graphqlizer.Graphqlizer - token oauth.Token - oauthClient oauth.Client - tenant string -} - -func NewDirectorClient(gqlClient gql.Client, oauthClient oauth.Client, tenant string) Client { - - return &directorClient{ - gqlClient: gqlClient, - oauthClient: oauthClient, - queryProvider: queryProvider{}, - graphqlizer: graphqlizer.Graphqlizer{}, - token: oauth.Token{}, - tenant: tenant, - } -} - -func (cc *directorClient) getToken() error { - token, err := cc.oauthClient.GetAuthorizationToken() - if err != nil { - return err - } - - if token.EmptyOrExpired() { - return errors.New("Obtained empty or expired token") - } - - cc.token = token - return nil -} - -func (cc *directorClient) RegisterFormation(formationName string) error { - log.Infof("Registering Formation") - - queryFunc := func() string { return cc.queryProvider.createFormation(formationName) } - execFunc := getExecGraphQLFunc[graphql.Formation](cc) - operationDescription := "register Formation" - successfulLogMessage := fmt.Sprintf("Successfully registered Formation %s in Director for tenant %s", formationName, cc.tenant) - - return executeQuerySkipResponse(queryFunc, execFunc, operationDescription, successfulLogMessage) -} - -func (cc *directorClient) UnregisterFormation(formationName string) error { - log.Infof("Unregistering Formation") - queryFunc := func() string { return cc.queryProvider.deleteFormation(formationName) } - execFunc := getExecGraphQLFunc[graphql.Formation](cc) - operationDescription := "unregister Formation" - successfulLogMessage := fmt.Sprintf("Successfully unregistered Formation %s in Director for tenant %s", formationName, cc.tenant) - - return executeQuerySkipResponse(queryFunc, execFunc, operationDescription, successfulLogMessage) -} - -func (cc *directorClient) RegisterRuntime(runtimeName string) (string, error) { - log.Infof("Registering Runtime") - queryFunc := func() string { return cc.queryProvider.registerRuntimeMutation(runtimeName) } - execFunc := getExecGraphQLFunc[graphql.Runtime](cc) - operationDescription := "register Runtime" - successfulLogMessage := fmt.Sprintf("Successfully registered Runtime %s in Director for tenant %s", runtimeName, cc.tenant) - - response, err := executeQuery(queryFunc, execFunc, operationDescription, successfulLogMessage) - if err != nil { - return "", err - } - - return response.Result.ID, nil -} - -func (cc *directorClient) UnregisterRuntime(id string) error { - log.Infof("Unregistering Runtime") - - queryFunc := func() string { return cc.queryProvider.deleteRuntimeMutation(id) } - execFunc := getExecGraphQLFunc[graphql.Runtime](cc) - operationDescription := "unregister Runtime" - successfulLogMessage := fmt.Sprintf("Successfully unregistered Runtime %s in Director for tenant %s", id, cc.tenant) - - response, err := executeQuery(queryFunc, execFunc, operationDescription, successfulLogMessage) - if err != nil { - return err - } - - if response.Result.ID != id { - return fmt.Errorf("Failed to unregister runtime %s in Director: received unexpected RuntimeID.", id) - } - - return nil -} - -func (cc *directorClient) GetConnectionToken(runtimeId string) (string, string, error) { - log.Infof("Requesting one time token for Runtime from Director service") - - queryFunc := func() string { return cc.queryProvider.requestOneTimeTokenMutation(runtimeId) } - execFunc := getExecGraphQLFunc[graphql.OneTimeTokenForRuntimeExt](cc) - operationDescription := "register application" - successfulLogMessage := fmt.Sprintf("Received OneTimeToken for Runtime %s in Director for tenant %s", runtimeId, cc.tenant) - - response, err := executeQuery(queryFunc, execFunc, operationDescription, successfulLogMessage) - if err != nil { - return "", "", err - } - return response.Result.Token, response.Result.ConnectorURL, nil -} - -func (cc *directorClient) RegisterApplication(appName, displayName string) (string, error) { - log.Infof("Registering Application") - - queryFunc := func() string { return cc.queryProvider.registerApplicationFromTemplateMutation(appName, displayName) } - execFunc := getExecGraphQLFunc[graphql.Application](cc) - operationDescription := "register application" - successfulLogMessage := fmt.Sprintf("Successfully registered application %s in Director for tenant %s", appName, cc.tenant) - - result, err := executeQuery(queryFunc, execFunc, operationDescription, successfulLogMessage) - if err != nil { - return "", err - } - - id := result.Result.ID - _, err = cc.AddBundle(id) - return id, err -} - -func (cc *directorClient) AddBundle(appID string) (string, error) { - log.Infof("Adding Bundle to Application") - - queryFunc := func() string { return cc.queryProvider.addBundleMutation(appID) } - execFunc := getExecGraphQLFunc[graphql.Application](cc) - operationDescription := "add bundle" - successfulLogMessage := fmt.Sprintf("Successfully added bundle to application with ID %s in Director for tenant %s", appID, cc.tenant) - - result, err := executeQuery(queryFunc, execFunc, operationDescription, successfulLogMessage) - if err != nil { - return "", err - } - return result.Result.ID, err -} - -func (cc *directorClient) UpdateApplication(id, newDesc string) (string, error) { - log.Infof("Updating Application %s", id) - - queryFunc := func() string { - return cc.queryProvider. - updateApplicationMutation(id, newDesc) - } - execFunc := getExecGraphQLFunc[graphql.Application](cc) - operationDescription := "update application" - successfulLogMessage := fmt.Sprintf("Successfully updated application %s in Director for tenant %s", id, cc.tenant) - - result, err := executeQuery(queryFunc, execFunc, operationDescription, successfulLogMessage) - if err != nil { - return "", err - } - return result.Result.ID, err -} - -func (cc *directorClient) AssignApplicationToFormation(appId, formationName string) error { - log.Infof("Assigning Application to Formation") - - queryFunc := func() string { return cc.queryProvider.assignFormationForAppMutation(appId, formationName) } - execFunc := getExecGraphQLFunc[graphql.Formation](cc) - operationDescription := "assign Application to Formation" - successfulLogMessage := fmt.Sprintf("Successfully assigned application %s to Formation %s in Director for tenant %s", appId, formationName, cc.tenant) - - return executeQuerySkipResponse(queryFunc, execFunc, operationDescription, successfulLogMessage) -} - -func (cc *directorClient) UnassignApplication(appId, formationName string) error { - log.Infof("Unregistering Application from Formation") - - queryFunc := func() string { return cc.queryProvider.unassignFormation(appId, formationName) } - execFunc := getExecGraphQLFunc[graphql.Formation](cc) - operationDescription := "unregister formation" - successfulLogMessage := fmt.Sprintf("Successfully unassigned application %s from Formation %s in Director for tenant %s", appId, formationName, cc.tenant) - - return executeQuerySkipResponse(queryFunc, execFunc, operationDescription, successfulLogMessage) -} - -func (cc *directorClient) AssignRuntimeToFormation(runtimeId, formationName string) error { - log.Infof("Assigning Runtime to Formation") - - queryFunc := func() string { return cc.queryProvider.assignFormationForRuntimeMutation(runtimeId, formationName) } - execFunc := getExecGraphQLFunc[graphql.Formation](cc) - operationDescription := "assign Runtime to Formation" - successfulLogMessage := fmt.Sprintf("Successfully assigned runtime %s to Formation %s in Director for tenant %s", runtimeId, formationName, cc.tenant) - - return executeQuerySkipResponse(queryFunc, execFunc, operationDescription, successfulLogMessage) -} - -func (cc *directorClient) UnregisterApplication(appID string) error { - log.Infof("Unregistering Application") - - queryFunc := func() string { return cc.queryProvider.unregisterApplicationMutation(appID) } - execFunc := getExecGraphQLFunc[graphql.Application](cc) - operationDescription := "Unregistering Application" - successfulLogMessage := fmt.Sprintf("Successfully unregister application %s in Director for tenant %s", appID, cc.tenant) - - response, err := executeQuery(queryFunc, execFunc, operationDescription, successfulLogMessage) - if err != nil { - return err - } - - if response.Result.ID != appID { - return fmt.Errorf("Failed to unregister Application %s in Director: received unexpected applicationID.", appID) - } - - return nil -} - -func (cc *directorClient) executeDirectorGraphQLCall(directorQuery string, tenant string, response interface{}) error { - if cc.token.EmptyOrExpired() { - log.Infof("Refreshing token to access Director Service") - if err := cc.getToken(); err != nil { - return err - } - } - - req := gcli.NewRequest(directorQuery) - req.Header.Set(AuthorizationHeader, fmt.Sprintf("Bearer %s", cc.token.AccessToken)) - req.Header.Set(TenantHeader, tenant) - - if err := cc.gqlClient.Do(req, response); err != nil { - if egErr, ok := err.(gcli.ExtendedError); ok { - return errors.Wrap(egErr, "Failed to execute GraphQL request to Director") - } - return fmt.Errorf("Failed to execute GraphQL request to Director: %v", err) - } - - return nil -} - -type Response[T any] struct { - Result *T -} - -func executeQuerySkipResponse[T any](getQueryFunc func() string, executeQueryFunc func(string, *Response[T]) error, operationDescription, successfulLogMessage string) error { - _, err := executeQuery(getQueryFunc, executeQueryFunc, operationDescription, successfulLogMessage) - - return err -} - -func executeQuery[T any](getQueryFunc func() string, executeQueryFunc func(string, *Response[T]) error, operationDescription, successfulLogMessage string) (Response[T], error) { - query := getQueryFunc() - - var response Response[T] - err := executeQueryFunc(query, &response) - - if err != nil { - return Response[T]{}, errors.Wrap(err, fmt.Sprintf("Failed to %s in Director. Request failed", operationDescription)) - } - - // Nil check is necessary due to GraphQL client not checking response code - if response.Result == nil { - return Response[T]{}, errors.New(fmt.Sprintf("Failed to %s in Director: Received nil response.", operationDescription)) - } - - log.Infof(successfulLogMessage) - - return response, nil -} - -func getExecGraphQLFunc[T any](cc *directorClient) func(string, *Response[T]) error { - return func(query string, result *Response[T]) error { - if cc.token.EmptyOrExpired() { - log.Infof("Refreshing token to access Director Service") - if err := cc.getToken(); err != nil { - return err - } - } - - req := gcli.NewRequest(query) - req.Header.Set(AuthorizationHeader, fmt.Sprintf("Bearer %s", cc.token.AccessToken)) - req.Header.Set(TenantHeader, cc.tenant) - - if err := cc.gqlClient.Do(req, result); err != nil { - if egErr, ok := err.(gcli.ExtendedError); ok { - return errors.Wrap(egErr, "Failed to execute GraphQL request to Director") - } - return fmt.Errorf("Failed to execute GraphQL request to Director: %v", err) - } - - return nil - } -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/director/directorclient_test.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/director/directorclient_test.go deleted file mode 100644 index baa5480c2e63..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/director/directorclient_test.go +++ /dev/null @@ -1,1142 +0,0 @@ -package director - -import ( - "errors" - "fmt" - "github.com/kyma-incubator/compass/components/director/pkg/graphql" - "testing" - "time" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - gcli "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/third_party/machinebox/graphql" - - gql "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/graphql" - "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/oauth" - oauthmocks "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/oauth/mocks" -) - -const ( - runtimeTestingID = "test-runtime-ID-12345" - runtimeTestingName = "Runtime Test name" - testAppName = "Test-application-123" - applicationTestingID = "test-application-ID-12345" - testAppScenario = "Testing-scenario" - testAppDisplayName = "Testing-app-display-name" - validTokenValue = "12345" - tenantValue = "3e64ebae-38b5-46a0-b1ed-9ccee153a0ae" - oneTimeToken = "54321" - connectorURL = "https://kyma.cx/connector/graphql" - - expectedRegisterApplicationQuery = `mutation { - result: registerApplicationFromTemplate(in: { - templateName: "SAP Commerce Cloud" - values: [ - { placeholder: "name", value: "Test-application-123" } - { placeholder: "display-name", value: "Testing-app-display-name" } - ] - }) { id } }` - - expectedAssignAppToFormationQuery = `mutation { - result: assignFormation( - objectID: "test-application-ID-12345" - objectType: APPLICATION - formation: { name: "Testing-scenario" } - ) { id } }` - - expectedAssignRuntimeToFormationQuery = `mutation { - result: assignFormation( - objectID: "test-runtime-ID-12345" - objectType: RUNTIME - formation: { name: "Testing-scenario" } - ) { id } }` - - expectedDeleteApplicationQuery = `mutation { - result: unregisterApplication(id: "test-application-ID-12345") { - id - } }` - - expectedRegisterRuntimeQuery = `mutation { - result: registerRuntime(in: { - name: "Runtime Test name" - }) { id } }` - - expectedDeleteRuntimeQuery = `mutation { - result: unregisterRuntime(id: "test-runtime-ID-12345") { - id - }}` - - expectedOneTimeTokenQuery = `mutation { - result: requestOneTimeTokenForRuntime(id: "test-runtime-ID-12345") { - token connectorURL - }}` - - expectedRegisterFormationQuery = `mutation { - result: createFormation(formation: { - name: "Testing-scenario" - }) { id } }` - - expectedDeleteFormationQuery = `mutation { - result: deleteFormation(formation: { - name: "Testing-scenario" - }) { id } }` -) - -var ( - futureExpirationTime = time.Now().Add(time.Duration(60) * time.Minute).Unix() - passedExpirationTime = time.Now().Add(time.Duration(60) * time.Minute * -1).Unix() -) - -func TestDirectorClient_RuntimeRegistering(t *testing.T) { - expectedRequest := gcli.NewRequest(expectedRegisterRuntimeQuery) - expectedRequest.Header.Set(AuthorizationHeader, fmt.Sprintf("Bearer %s", validTokenValue)) - expectedRequest.Header.Set(TenantHeader, tenantValue) - - t.Run("Should register runtime and return new runtime ID when the Director access token is valid", func(t *testing.T) { - // given - responseDescription := "runtime description" - expectedResponse := &graphql.Runtime{ - ID: runtimeTestingID, - Name: runtimeTestingName, - Description: &responseDescription, - } - - expectedID := runtimeTestingID - - gqlClient := newQueryAssertClient(t, expectedRequest, expectedResponse) - token := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(token, nil) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient, tenantValue) - - // when - receivedRuntimeID, err := configClient.RegisterRuntime(runtimeTestingName) - - // then - assert.NoError(t, err) - assert.Equal(t, expectedID, receivedRuntimeID) - }) - - t.Run("Should not register runtime and return an error when the Director access token is empty", func(t *testing.T) { - // given - token := oauth.Token{ - AccessToken: "", - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(token, nil) - - configClient := NewDirectorClient(nil, mockedOAuthClient, tenantValue) - - // when - receivedRuntimeID, err := configClient.RegisterRuntime(runtimeTestingName) - - // then - assert.Error(t, err) - assert.Empty(t, receivedRuntimeID) - }) - - t.Run("Should not register runtime and return an error when the Director access token is expired", func(t *testing.T) { - // given - expiredToken := oauth.Token{ - AccessToken: validTokenValue, - Expiration: passedExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(expiredToken, nil) - - configClient := NewDirectorClient(nil, mockedOAuthClient, tenantValue) - - // when - receivedRuntimeID, err := configClient.RegisterRuntime(runtimeTestingName) - - // then - assert.Error(t, err) - assert.Empty(t, receivedRuntimeID) - }) - - t.Run("Should not register Runtime and return error when the client fails to get an access token for Director", func(t *testing.T) { - // given - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(oauth.Token{}, errors.New("Failed token error")) - - configClient := NewDirectorClient(nil, mockedOAuthClient, tenantValue) - - // when - receivedRuntimeID, err := configClient.RegisterRuntime(runtimeTestingName) - - // then - assert.Error(t, err) - assert.Empty(t, receivedRuntimeID) - }) - - t.Run("Should return error when the result of the call to Director service is nil", func(t *testing.T) { - // given - validToken := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(validToken, nil) - - gqlClient := newFailingQueryAssertClient[graphql.Runtime](t, expectedRequest) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient, tenantValue) - - // when - receivedRuntimeID, err := configClient.RegisterRuntime(runtimeTestingName) - - // then - assert.Error(t, err) - assert.Empty(t, receivedRuntimeID) - }) - - t.Run("Should return error when Director fails to register Runtime ", func(t *testing.T) { - // given - validToken := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(validToken, nil) - - gqlClient := newFailingQueryAssertClient[graphql.Runtime](t, expectedRequest) - configClient := NewDirectorClient(gqlClient, mockedOAuthClient, tenantValue) - - // when - receivedRuntimeID, err := configClient.RegisterRuntime(runtimeTestingName) - - // then - assert.Error(t, err) - assert.Empty(t, receivedRuntimeID) - }) -} - -func TestDirectorClient_RuntimeUnregistering(t *testing.T) { - expectedRequest := gcli.NewRequest(expectedDeleteRuntimeQuery) - expectedRequest.Header.Set(AuthorizationHeader, fmt.Sprintf("Bearer %s", validTokenValue)) - expectedRequest.Header.Set(TenantHeader, tenantValue) - - t.Run("Should unregister runtime of given ID and return no error when the Director access token is valid", func(t *testing.T) { - // given - responseDescription := "runtime description" - expectedResponse := &graphql.Runtime{ - ID: runtimeTestingID, - Name: runtimeTestingName, - Description: &responseDescription, - } - - gqlClient := newQueryAssertClient(t, expectedRequest, expectedResponse) - validToken := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(validToken, nil) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient, tenantValue) - - // when - err := configClient.UnregisterRuntime(runtimeTestingID) - - // then - assert.NoError(t, err) - }) - - t.Run("Should not unregister runtime and return an error when the Director access token is empty", func(t *testing.T) { - // given - emptyToken := oauth.Token{ - AccessToken: "", - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(emptyToken, nil) - - configClient := NewDirectorClient(nil, mockedOAuthClient, tenantValue) - - // when - err := configClient.UnregisterRuntime(runtimeTestingID) - - // then - assert.Error(t, err) - }) - - t.Run("Should not unregister register runtime and return an error when the Director access token is expired", func(t *testing.T) { - // given - expiredToken := oauth.Token{ - AccessToken: validTokenValue, - Expiration: passedExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(expiredToken, nil) - - configClient := NewDirectorClient(nil, mockedOAuthClient, tenantValue) - - // when - err := configClient.UnregisterRuntime(runtimeTestingID) - - // then - assert.Error(t, err) - }) - - t.Run("Should not unregister Runtime and return error when the client fails to get an access token for Director", func(t *testing.T) { - // given - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(oauth.Token{}, errors.New("Failed token error")) - - configClient := NewDirectorClient(nil, mockedOAuthClient, tenantValue) - - // when - err := configClient.UnregisterRuntime(runtimeTestingID) - - // then - assert.Error(t, err) - }) - - t.Run("Should return error when the result of the call to Director service is nil", func(t *testing.T) { - // given - validToken := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(validToken, nil) - - // given - gqlClient := newFailingQueryAssertClient[graphql.Runtime](t, expectedRequest) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient, tenantValue) - - // when - err := configClient.UnregisterRuntime(runtimeTestingID) - - // then - assert.Error(t, err) - }) - - t.Run("Should return error when Director fails to delete Runtime", func(t *testing.T) { - // given - gqlClient := newFailingQueryAssertClient[graphql.Runtime](t, expectedRequest) - - validToken := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(validToken, nil) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient, tenantValue) - - // when - err := configClient.UnregisterRuntime(runtimeTestingID) - - // then - assert.Error(t, err) - }) - - // unusual and strange case - t.Run("Should return error when Director returns bad ID after Deleting", func(t *testing.T) { - // given - responseDescription := "runtime description" - expectedResponse := &graphql.Runtime{ - ID: "BadId", - Name: runtimeTestingName, - Description: &responseDescription, - } - - gqlClient := newQueryAssertClient(t, expectedRequest, expectedResponse) - - validToken := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(validToken, nil) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient, tenantValue) - - // when - err := configClient.UnregisterRuntime(runtimeTestingID) - - // then - assert.Error(t, err) - }) -} - -func TestDirectorClient_FormationRegistering(t *testing.T) { - expectedRequest := gcli.NewRequest(expectedRegisterFormationQuery) - expectedRequest.Header.Set(AuthorizationHeader, fmt.Sprintf("Bearer %s", validTokenValue)) - expectedRequest.Header.Set(TenantHeader, tenantValue) - - t.Run("Should register Formation and return no error when the Director access token is valid", func(t *testing.T) { - // given - expectedResponse := &graphql.Formation{ - Name: testAppScenario, - } - - gqlClient := newQueryAssertClient(t, expectedRequest, expectedResponse) - - token := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(token, nil) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient, tenantValue) - - // when - err := configClient.RegisterFormation(testAppScenario) - - // then - assert.NoError(t, err) - }) - - t.Run("Should not register Formation and return an error when the Director access token is empty", func(t *testing.T) { - // given - token := oauth.Token{ - AccessToken: "", - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(token, nil) - - configClient := NewDirectorClient(nil, mockedOAuthClient, tenantValue) - - // when - err := configClient.RegisterFormation(testAppScenario) - - // then - assert.Error(t, err) - }) - - t.Run("Should not register Formation and return an error when the Director access token is expired", func(t *testing.T) { - // given - expiredToken := oauth.Token{ - AccessToken: validTokenValue, - Expiration: passedExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(expiredToken, nil) - - configClient := NewDirectorClient(nil, mockedOAuthClient, tenantValue) - - // when - err := configClient.RegisterFormation(testAppScenario) - - // then - assert.Error(t, err) - }) - - t.Run("Should not register Formation and return error when the client fails to get an access token for Director", func(t *testing.T) { - // given - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(oauth.Token{}, errors.New("Failed token error")) - - configClient := NewDirectorClient(nil, mockedOAuthClient, tenantValue) - - // when - err := configClient.RegisterFormation(testAppScenario) - - // then - assert.Error(t, err) - }) - - t.Run("Should return error when the result of the call to Director service is nil", func(t *testing.T) { - // given - validToken := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(validToken, nil) - - gqlClient := gql.NewQueryAssertClient(t, nil, []*gcli.Request{expectedRequest}, func(t *testing.T, r interface{}) { - cfg, ok := r.(*Response[graphql.Formation]) - require.True(t, ok) - assert.Empty(t, cfg.Result) - cfg.Result = nil - }) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient, tenantValue) - - // when - err := configClient.RegisterFormation(testAppScenario) - - // then - assert.Error(t, err) - }) - - t.Run("Should return error when Director fails to register Formation ", func(t *testing.T) { - // given - validToken := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(validToken, nil) - - gqlClient := newFailingQueryAssertClient[graphql.Formation](t, expectedRequest) - configClient := NewDirectorClient(gqlClient, mockedOAuthClient, tenantValue) - - // when - err := configClient.RegisterFormation(testAppScenario) - - // then - assert.Error(t, err) - }) -} - -func TestDirectorClient_FormationUnregistering(t *testing.T) { - expectedRequest := gcli.NewRequest(expectedDeleteFormationQuery) - expectedRequest.Header.Set(AuthorizationHeader, fmt.Sprintf("Bearer %s", validTokenValue)) - expectedRequest.Header.Set(TenantHeader, tenantValue) - - t.Run("Should unregister Formation of given name and return no error when the Director access token is valid", func(t *testing.T) { - // given - expectedResponse := &graphql.Formation{ - Name: testAppScenario, - } - - gqlClient := newQueryAssertClient(t, expectedRequest, expectedResponse) - - validToken := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(validToken, nil) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient, tenantValue) - - // when - err := configClient.UnregisterFormation(testAppScenario) - - // then - assert.NoError(t, err) - }) - - t.Run("Should not unregister Formation and return an error when the Director access token is empty", func(t *testing.T) { - // given - emptyToken := oauth.Token{ - AccessToken: "", - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(emptyToken, nil) - - configClient := NewDirectorClient(nil, mockedOAuthClient, tenantValue) - - // when - err := configClient.UnregisterFormation(testAppScenario) - - // then - assert.Error(t, err) - }) - - t.Run("Should not unregister register Formation and return an error when the Director access token is expired", func(t *testing.T) { - // given - expiredToken := oauth.Token{ - AccessToken: validTokenValue, - Expiration: passedExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(expiredToken, nil) - - configClient := NewDirectorClient(nil, mockedOAuthClient, tenantValue) - - // when - err := configClient.UnregisterFormation(testAppScenario) - - // then - assert.Error(t, err) - }) - - t.Run("Should not unregister Formation and return error when the client fails to get an access token for Director", func(t *testing.T) { - // given - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(oauth.Token{}, errors.New("Failed token error")) - - configClient := NewDirectorClient(nil, mockedOAuthClient, tenantValue) - - // when - err := configClient.UnregisterFormation(testAppScenario) - - // then - assert.Error(t, err) - }) - - t.Run("Should return error when the result of the call to Director service is nil", func(t *testing.T) { - // given - validToken := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(validToken, nil) - - // given - gqlClient := newFailingQueryAssertClient[graphql.Formation](t, expectedRequest) - configClient := NewDirectorClient(gqlClient, mockedOAuthClient, tenantValue) - - // when - err := configClient.UnregisterFormation(testAppScenario) - // then - assert.Error(t, err) - }) - - t.Run("Should return error when Director fails to delete Formation", func(t *testing.T) { - // given - gqlClient := newFailingQueryAssertClient[graphql.Formation](t, expectedRequest) - - validToken := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(validToken, nil) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient, tenantValue) - - // when - err := configClient.UnregisterFormation(testAppScenario) - - // then - assert.Error(t, err) - }) -} - -func TestDirectorClient_ApplicationRegistering(t *testing.T) { - expectedRequest := gcli.NewRequest(expectedRegisterApplicationQuery) - expectedRequest.Header.Set(AuthorizationHeader, fmt.Sprintf("Bearer %s", validTokenValue)) - expectedRequest.Header.Set(TenantHeader, tenantValue) - - t.Run("Should register application and return new application ID when the Director access token is valid", func(t *testing.T) { - // given - expectedResponse := &graphql.Application{ - Name: testAppName, - BaseEntity: &graphql.BaseEntity{ - ID: applicationTestingID, - }, - } - expectedID := applicationTestingID - gqlClient := newQueryAssertClient(t, expectedRequest, expectedResponse) - - token := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(token, nil) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient, tenantValue) - - // when - receivedApplicationID, err := configClient.RegisterApplication(testAppName, testAppDisplayName) - - // then - assert.NoError(t, err) - assert.Equal(t, expectedID, receivedApplicationID) - }) - - t.Run("Should not register application and return an error when the Director access token is empty", func(t *testing.T) { - // given - token := oauth.Token{ - AccessToken: "", - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(token, nil) - - configClient := NewDirectorClient(nil, mockedOAuthClient, tenantValue) - - // when - receivedApplicationID, err := configClient.RegisterApplication(testAppName, testAppDisplayName) - - // then - assert.Error(t, err) - assert.Empty(t, receivedApplicationID) - }) - - t.Run("Should not register Application and return an error when the Director access token is expired", func(t *testing.T) { - // given - expiredToken := oauth.Token{ - AccessToken: validTokenValue, - Expiration: passedExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(expiredToken, nil) - - configClient := NewDirectorClient(nil, mockedOAuthClient, tenantValue) - - // when - receivedApplicationID, err := configClient.RegisterApplication(testAppName, testAppDisplayName) - - // then - assert.Error(t, err) - assert.Empty(t, receivedApplicationID) - }) - - t.Run("Should not register Application and return error when the client fails to get an access token for Director", func(t *testing.T) { - // given - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(oauth.Token{}, errors.New("Failed token error")) - - configClient := NewDirectorClient(nil, mockedOAuthClient, tenantValue) - - // when - receivedApplicationID, err := configClient.RegisterApplication(testAppName, testAppDisplayName) - - // then - assert.Error(t, err) - assert.Empty(t, receivedApplicationID) - }) - - t.Run("Should return error when the result of the call to Director service is nil", func(t *testing.T) { - // given - validToken := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(validToken, nil) - - gqlClient := newFailingQueryAssertClient[graphql.Application](t, expectedRequest) - configClient := NewDirectorClient(gqlClient, mockedOAuthClient, tenantValue) - - // when - receivedApplicationID, err := configClient.RegisterApplication(testAppName, testAppDisplayName) - - // then - assert.Error(t, err) - assert.Empty(t, receivedApplicationID) - }) - - t.Run("Should return error when Director fails to register Runtime ", func(t *testing.T) { - // given - validToken := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(validToken, nil) - - gqlClient := newFailingQueryAssertClient[graphql.Application](t, expectedRequest) - configClient := NewDirectorClient(gqlClient, mockedOAuthClient, tenantValue) - - // when - receivedRuntimeID, err := configClient.RegisterApplication(testAppName, testAppDisplayName) - - // then - assert.Error(t, err) - assert.Empty(t, receivedRuntimeID) - }) -} - -func TestDirectorClient_ApplicationAssignToFormation(t *testing.T) { - expectedRequest := gcli.NewRequest(expectedAssignAppToFormationQuery) - expectedRequest.Header.Set(AuthorizationHeader, fmt.Sprintf("Bearer %s", validTokenValue)) - expectedRequest.Header.Set(TenantHeader, tenantValue) - - t.Run("Should assign application to formation and return new application ID when the Director access token is valid", func(t *testing.T) { - // given - expectedResponse := &graphql.Formation{ - Name: testAppScenario, - } - - gqlClient := newQueryAssertClient(t, expectedRequest, expectedResponse) - token := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(token, nil) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient, tenantValue) - - // when - err := configClient.AssignApplicationToFormation(applicationTestingID, testAppScenario) - - // then - assert.NoError(t, err) - }) - - t.Run("Should not assign application to formation and return an error when the Director access token is empty", func(t *testing.T) { - // given - token := oauth.Token{ - AccessToken: "", - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(token, nil) - - configClient := NewDirectorClient(nil, mockedOAuthClient, tenantValue) - - // when - err := configClient.AssignApplicationToFormation(applicationTestingID, testAppScenario) - // then - assert.Error(t, err) - }) -} - -func TestDirectorClient_RuntimeAssignToFormation(t *testing.T) { - expectedRequest := gcli.NewRequest(expectedAssignRuntimeToFormationQuery) - expectedRequest.Header.Set(AuthorizationHeader, fmt.Sprintf("Bearer %s", validTokenValue)) - expectedRequest.Header.Set(TenantHeader, tenantValue) - - t.Run("Should assign application to formation and return new application ID when the Director access token is valid", func(t *testing.T) { - // given - expectedResponse := &graphql.Formation{ - Name: testAppScenario, - } - - gqlClient := newQueryAssertClient(t, expectedRequest, expectedResponse) - token := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(token, nil) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient, tenantValue) - - // when - err := configClient.AssignRuntimeToFormation(runtimeTestingID, testAppScenario) - - // then - assert.NoError(t, err) - }) - - t.Run("Should not assign application to formation and return an error when the Director access token is empty", func(t *testing.T) { - // given - token := oauth.Token{ - AccessToken: "", - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(token, nil) - - configClient := NewDirectorClient(nil, mockedOAuthClient, tenantValue) - - // when - err := configClient.AssignRuntimeToFormation(runtimeTestingID, testAppScenario) - // then - assert.Error(t, err) - }) -} - -func TestDirectorClient_ApplicationUnregistering(t *testing.T) { - expectedRequest := gcli.NewRequest(expectedDeleteApplicationQuery) - expectedRequest.Header.Set(AuthorizationHeader, fmt.Sprintf("Bearer %s", validTokenValue)) - expectedRequest.Header.Set(TenantHeader, tenantValue) - - t.Run("Should unregister runtime of given ID and return no error when the Director access token is valid", func(t *testing.T) { - // given - expectedResponse := &graphql.Application{ - Name: testAppName, - BaseEntity: &graphql.BaseEntity{ - ID: applicationTestingID, - }, - } - - gqlClient := newQueryAssertClient(t, expectedRequest, expectedResponse) - validToken := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(validToken, nil) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient, tenantValue) - - // when - err := configClient.UnregisterApplication(applicationTestingID) - - // then - assert.NoError(t, err) - }) - - t.Run("Should not unregister runtime and return an error when the Director access token is empty", func(t *testing.T) { - // given - emptyToken := oauth.Token{ - AccessToken: "", - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(emptyToken, nil) - - configClient := NewDirectorClient(nil, mockedOAuthClient, tenantValue) - - // when - err := configClient.UnregisterApplication(applicationTestingID) - - // then - assert.Error(t, err) - }) - - t.Run("Should not unregister register runtime and return an error when the Director access token is expired", func(t *testing.T) { - // given - expiredToken := oauth.Token{ - AccessToken: validTokenValue, - Expiration: passedExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(expiredToken, nil) - - configClient := NewDirectorClient(nil, mockedOAuthClient, tenantValue) - - // when - err := configClient.UnregisterApplication(applicationTestingID) - - // then - assert.Error(t, err) - }) - - t.Run("Should not unregister Runtime and return error when the client fails to get an access token for Director", func(t *testing.T) { - // given - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(oauth.Token{}, errors.New("Failed token error")) - - configClient := NewDirectorClient(nil, mockedOAuthClient, tenantValue) - - // when - err := configClient.UnregisterApplication(applicationTestingID) - - // then - assert.Error(t, err) - }) - - t.Run("Should return error when the result of the call to Director service is nil", func(t *testing.T) { - // given - validToken := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(validToken, nil) - - // given - gqlClient := newFailingQueryAssertClient[graphql.Application](t, expectedRequest) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient, tenantValue) - - // when - err := configClient.UnregisterApplication(applicationTestingID) - - // then - assert.Error(t, err) - }) - - t.Run("Should return error when Director fails to delete Runtime", func(t *testing.T) { - // given - gqlClient := newFailingQueryAssertClient[graphql.Application](t, expectedRequest) - - validToken := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(validToken, nil) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient, tenantValue) - - // when - err := configClient.UnregisterApplication(applicationTestingID) - - // then - assert.Error(t, err) - }) - - // unusual and strange case - t.Run("Should return error when Director returns bad ID after Deleting", func(t *testing.T) { - // given - expectedResponse := &graphql.Application{ - Name: testAppName, - BaseEntity: &graphql.BaseEntity{ - ID: "badID", - }, - } - - gqlClient := newQueryAssertClient(t, expectedRequest, expectedResponse) - - validToken := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(validToken, nil) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient, tenantValue) - - // when - err := configClient.UnregisterApplication(applicationTestingID) - - // then - assert.Error(t, err) - }) -} - -func TestDirectorClient_GetConnectionToken(t *testing.T) { - expectedRequest := gcli.NewRequest(expectedOneTimeTokenQuery) - expectedRequest.Header.Set(AuthorizationHeader, fmt.Sprintf("Bearer %s", validTokenValue)) - expectedRequest.Header.Set(TenantHeader, tenantValue) - - t.Run("Should return OneTimeToken when Oauth Token is valid", func(t *testing.T) { - // given - expectedResponse := &graphql.OneTimeTokenForRuntimeExt{ - OneTimeTokenForRuntime: graphql.OneTimeTokenForRuntime{ - TokenWithURL: graphql.TokenWithURL{ - Token: oneTimeToken, - ConnectorURL: connectorURL, - }, - }, - } - - gqlClient := newQueryAssertClient(t, expectedRequest, expectedResponse) - token := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(token, nil) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient, tenantValue) - - // when - receivedOneTimeToken, receivedConnectorURL, err := configClient.GetConnectionToken(runtimeTestingID) - - // then - require.NoError(t, err) - require.NotEmpty(t, receivedOneTimeToken) - assert.Equal(t, oneTimeToken, receivedOneTimeToken) - assert.Equal(t, connectorURL, receivedConnectorURL) - }) - - t.Run("Should return error when Oauth Token is empty", func(t *testing.T) { - // given - token := oauth.Token{ - AccessToken: "", - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(token, nil) - - configClient := NewDirectorClient(nil, mockedOAuthClient, tenantValue) - - // when - receivedOneTimeToken, receivedConnectorURL, err := configClient.GetConnectionToken(runtimeTestingID) - - // then - require.Error(t, err) - require.Empty(t, receivedConnectorURL) - require.Empty(t, receivedOneTimeToken) - }) - - t.Run("Should return error when Oauth Token is expired", func(t *testing.T) { - // given - token := oauth.Token{ - AccessToken: validTokenValue, - Expiration: passedExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(token, nil) - - configClient := NewDirectorClient(nil, mockedOAuthClient, tenantValue) - - // when - receivedOneTimeToken, receivedConnectorURL, err := configClient.GetConnectionToken(runtimeTestingID) - - // then - require.Error(t, err) - require.Empty(t, receivedConnectorURL) - require.Empty(t, receivedOneTimeToken) - }) - - t.Run("Should return error when Director call returns nil response", func(t *testing.T) { - // given - gqlClient := newQueryAssertClient[graphql.OneTimeTokenForRuntimeExt](t, expectedRequest, nil) - - token := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(token, nil) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient, tenantValue) - - // when - receivedOneTimeToken, receivedConnectorURL, err := configClient.GetConnectionToken(runtimeTestingID) - - // then - require.Error(t, err) - require.Empty(t, receivedConnectorURL) - require.Empty(t, receivedOneTimeToken) - }) -} - -func newQueryAssertClient[T any](t *testing.T, expectedRequest *gcli.Request, expectedResponse *T) gql.Client { - return gql.NewQueryAssertClient(t, nil, []*gcli.Request{expectedRequest}, func(t *testing.T, r interface{}) { - cfg, ok := r.(*Response[T]) - require.True(t, ok) - assert.Empty(t, cfg.Result) - - if expectedResponse != nil { - cfg.Result = expectedResponse - } - }) -} - -func newFailingQueryAssertClient[T any](t *testing.T, expectedRequest *gcli.Request) gql.Client { - return gql.NewQueryAssertClient(t, nil, []*gcli.Request{expectedRequest}, func(t *testing.T, r interface{}) { - cfg, ok := r.(*Response[T]) - require.True(t, ok) - assert.Empty(t, cfg.Result) - cfg.Result = nil - }) -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/director/mocks/Client.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/director/mocks/Client.go deleted file mode 100644 index ccfa1a77af57..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/director/mocks/Client.go +++ /dev/null @@ -1,193 +0,0 @@ -// Code generated by mockery v2.15.0. DO NOT EDIT. - -package mocks - -import mock "github.com/stretchr/testify/mock" - -// Client is an autogenerated mock type for the Client type -type Client struct { - mock.Mock -} - -// AssignApplicationToFormation provides a mock function with given fields: appId, formationName -func (_m *Client) AssignApplicationToFormation(appId string, formationName string) error { - ret := _m.Called(appId, formationName) - - var r0 error - if rf, ok := ret.Get(0).(func(string, string) error); ok { - r0 = rf(appId, formationName) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// AssignRuntimeToFormation provides a mock function with given fields: runtimeId, formationName -func (_m *Client) AssignRuntimeToFormation(runtimeId string, formationName string) error { - ret := _m.Called(runtimeId, formationName) - - var r0 error - if rf, ok := ret.Get(0).(func(string, string) error); ok { - r0 = rf(runtimeId, formationName) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// GetConnectionToken provides a mock function with given fields: runtimeID -func (_m *Client) GetConnectionToken(runtimeID string) (string, string, error) { - ret := _m.Called(runtimeID) - - var r0 string - if rf, ok := ret.Get(0).(func(string) string); ok { - r0 = rf(runtimeID) - } else { - r0 = ret.Get(0).(string) - } - - var r1 string - if rf, ok := ret.Get(1).(func(string) string); ok { - r1 = rf(runtimeID) - } else { - r1 = ret.Get(1).(string) - } - - var r2 error - if rf, ok := ret.Get(2).(func(string) error); ok { - r2 = rf(runtimeID) - } else { - r2 = ret.Error(2) - } - - return r0, r1, r2 -} - -// RegisterApplication provides a mock function with given fields: appName, displayName -func (_m *Client) RegisterApplication(appName string, displayName string) (string, error) { - ret := _m.Called(appName, displayName) - - var r0 string - if rf, ok := ret.Get(0).(func(string, string) string); ok { - r0 = rf(appName, displayName) - } else { - r0 = ret.Get(0).(string) - } - - var r1 error - if rf, ok := ret.Get(1).(func(string, string) error); ok { - r1 = rf(appName, displayName) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// RegisterFormation provides a mock function with given fields: formationName -func (_m *Client) RegisterFormation(formationName string) error { - ret := _m.Called(formationName) - - var r0 error - if rf, ok := ret.Get(0).(func(string) error); ok { - r0 = rf(formationName) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// RegisterRuntime provides a mock function with given fields: runtimeName -func (_m *Client) RegisterRuntime(runtimeName string) (string, error) { - ret := _m.Called(runtimeName) - - var r0 string - if rf, ok := ret.Get(0).(func(string) string); ok { - r0 = rf(runtimeName) - } else { - r0 = ret.Get(0).(string) - } - - var r1 error - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(runtimeName) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// UnassignApplication provides a mock function with given fields: appId, formationName -func (_m *Client) UnassignApplication(appId string, formationName string) error { - ret := _m.Called(appId, formationName) - - var r0 error - if rf, ok := ret.Get(0).(func(string, string) error); ok { - r0 = rf(appId, formationName) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// UnregisterApplication provides a mock function with given fields: id -func (_m *Client) UnregisterApplication(id string) error { - ret := _m.Called(id) - - var r0 error - if rf, ok := ret.Get(0).(func(string) error); ok { - r0 = rf(id) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// UnregisterFormation provides a mock function with given fields: formationName -func (_m *Client) UnregisterFormation(formationName string) error { - ret := _m.Called(formationName) - - var r0 error - if rf, ok := ret.Get(0).(func(string) error); ok { - r0 = rf(formationName) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// UnregisterRuntime provides a mock function with given fields: id -func (_m *Client) UnregisterRuntime(id string) error { - ret := _m.Called(id) - - var r0 error - if rf, ok := ret.Get(0).(func(string) error); ok { - r0 = rf(id) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -type mockConstructorTestingTNewClient interface { - mock.TestingT - Cleanup(func()) -} - -// NewClient creates a new instance of Client. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewClient(t mockConstructorTestingTNewClient) *Client { - mock := &Client{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/director/mocks/DirectorClient.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/director/mocks/DirectorClient.go deleted file mode 100644 index ee496d09f90c..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/director/mocks/DirectorClient.go +++ /dev/null @@ -1,60 +0,0 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. - -package mocks - -import mock "github.com/stretchr/testify/mock" - -// DirectorClient is an autogenerated mock type for the DirectorClient type -type DirectorClient struct { - mock.Mock -} - -// RegisterApplication provides a mock function with given fields: appName, scenario, tenant -func (_m *DirectorClient) RegisterApplication(appName string, scenario string, tenant string) (string, error) { - ret := _m.Called(appName, scenario, tenant) - - var r0 string - if rf, ok := ret.Get(0).(func(string, string, string) string); ok { - r0 = rf(appName, scenario, tenant) - } else { - r0 = ret.Get(0).(string) - } - - var r1 error - if rf, ok := ret.Get(1).(func(string, string, string) error); ok { - r1 = rf(appName, scenario, tenant) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// UnregisterApplication provides a mock function with given fields: id, tenant -func (_m *DirectorClient) UnregisterApplication(id string, tenant string) error { - ret := _m.Called(id, tenant) - - var r0 error - if rf, ok := ret.Get(0).(func(string, string) error); ok { - r0 = rf(id, tenant) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -type mockConstructorTestingTNewDirectorClient interface { - mock.TestingT - Cleanup(func()) -} - -// NewDirectorClient creates a new instance of DirectorClient. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewDirectorClient(t mockConstructorTestingTNewDirectorClient) *DirectorClient { - mock := &DirectorClient{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/director/queryprovider.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/director/queryprovider.go deleted file mode 100644 index c7cec324761e..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/director/queryprovider.go +++ /dev/null @@ -1,127 +0,0 @@ -package director - -import "fmt" - -type queryProvider struct{} - -func (qp queryProvider) createFormation(formationName string) string { - return fmt.Sprintf(`mutation { - result: createFormation(formation: { - name: "%s" - }) { id } }`, formationName) -} - -func (qp queryProvider) deleteFormation(formationName string) string { - return fmt.Sprintf(`mutation { - result: deleteFormation(formation: { - name: "%s" - }) { id } }`, formationName) -} - -func (qp queryProvider) registerApplicationFromTemplateMutation(appName, displayName string) string { - return fmt.Sprintf(`mutation { - result: registerApplicationFromTemplate(in: { - templateName: "SAP Commerce Cloud" - values: [ - { placeholder: "name", value: "%s" } - { placeholder: "display-name", value: "%s" } - ] - }) { id } }`, appName, displayName) -} - -func (qp queryProvider) addBundleMutation(appID string) string { - return fmt.Sprintf(`mutation { - result: addBundle( - applicationID: "%s" - in: { - name: "bndl-app-1" - description: "Foo bar" - apiDefinitions: [ - { - name: "comments-v1" - description: "api for adding comments" - targetURL: "http://mywordpress.com/comments" - group: "comments" - spec: { - data: "{\"openapi\":\"3.0.2\"}" - type: OPEN_API - format: YAML - } - version: { - value: "1.0.0" - deprecated: true - deprecatedSince: "v5" - forRemoval: false - } - } - ] - } - ) { id } }`, appID) -} - -func (qp queryProvider) updateApplicationMutation(id, description string) string { - return fmt.Sprintf(`mutation { - result: updateApplication( - id: "%s" - in: {description: "%s" - }) { id } }`, - id, description) -} - -func (qp queryProvider) assignFormationForAppMutation(applicationId, formationName string) string { - return fmt.Sprintf(`mutation { - result: assignFormation( - objectID: "%s" - objectType: APPLICATION - formation: { name: "%s" } - ) { id } }`, applicationId, formationName) -} - -func (qp queryProvider) unassignFormation(applicationId, formationName string) string { - return fmt.Sprintf(`mutation { - result: unassignFormation( - objectID: "%s" - objectType: APPLICATION - formation: { name: "%s" } - ) { - name - } -}`, applicationId, formationName) -} - -func (qp queryProvider) assignFormationForRuntimeMutation(runtimeId, formationName string) string { - return fmt.Sprintf(`mutation { - result: assignFormation( - objectID: "%s" - objectType: RUNTIME - formation: { name: "%s" } - ) { id } }`, runtimeId, formationName) -} - -func (qp queryProvider) unregisterApplicationMutation(applicationID string) string { - return fmt.Sprintf(`mutation { - result: unregisterApplication(id: "%s") { - id - } }`, applicationID) -} - -func (qp queryProvider) deleteRuntimeMutation(runtimeID string) string { - return fmt.Sprintf(`mutation { - result: unregisterRuntime(id: "%s") { - id - }}`, runtimeID) -} - -func (qp queryProvider) registerRuntimeMutation(runtimeName string) string { - return fmt.Sprintf(`mutation { - result: registerRuntime(in: { - name: "%s" - }) { id } }`, runtimeName) -} - -func (qp queryProvider) requestOneTimeTokenMutation(runtimeID string) string { - return fmt.Sprintf(`mutation { - result: requestOneTimeTokenForRuntime(id: "%s") { - token connectorURL - }}`, runtimeID) -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/executor/toolkit.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/executor/toolkit.go deleted file mode 100644 index f132c9b56aa2..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/executor/toolkit.go +++ /dev/null @@ -1,53 +0,0 @@ -package executor - -import ( - "context" - "github.com/avast/retry-go" - "github.com/pkg/errors" - "time" -) - -type RetryableExecuteFunc func() error -type ConditionMet func() bool - -type ExecuteAndWaitForCondition struct { - RetryableExecuteFunc RetryableExecuteFunc - ConditionMetFunc ConditionMet - Tick time.Duration - Timeout time.Duration -} - -func (e ExecuteAndWaitForCondition) Do() error { - - err := retry.Do(func() error { - return e.RetryableExecuteFunc() - }) - - if err != nil { - return err - } - ctx, cancel := context.WithTimeout(context.Background(), e.Timeout) - defer cancel() - - ticker := time.NewTicker(e.Tick) - - for { - select { - case <-ticker.C: - { - res := e.ConditionMetFunc() - - if res { - ticker.Stop() - return nil - } - - } - case <-ctx.Done(): - { - ticker.Stop() - return errors.New("Condition not met") - } - } - } -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/executor/toolkit_test.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/executor/toolkit_test.go deleted file mode 100644 index 8a6342763bab..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/executor/toolkit_test.go +++ /dev/null @@ -1,101 +0,0 @@ -package executor - -import ( - "github.com/pkg/errors" - "github.com/stretchr/testify/require" - "testing" - "time" -) - -func TestToolkit(t *testing.T) { - t.Run("Should return no error when verify function returns true", func(t *testing.T) { - // given - executeAndWait := ExecuteAndWaitForCondition{ - RetryableExecuteFunc: func() error { - return nil - }, - ConditionMetFunc: func() bool { - return true - }, - Tick: 10 * time.Second, - Timeout: 1 * time.Minute, - } - - // when - err := executeAndWait.Do() - - //then - require.NoError(t, err) - }) - - t.Run("Retry when exec function fails", func(t *testing.T) { - // given - counter := 1 - - executeAndWait := ExecuteAndWaitForCondition{ - - RetryableExecuteFunc: func() error { - if counter < 3 { - counter++ - return errors.New("failed") - } - - return nil - }, - ConditionMetFunc: func() bool { - return true - }, - Tick: 10 * time.Second, - Timeout: 1 * time.Minute, - } - - // when - err := executeAndWait.Do() - - //then - require.NoError(t, err) - require.Greater(t, counter, 2) - }) - - t.Run("Return error when exec function constantly fails", func(t *testing.T) { - // given - executeAndWait := ExecuteAndWaitForCondition{ - - RetryableExecuteFunc: func() error { - return errors.New("call failed") - }, - ConditionMetFunc: func() bool { - return true - }, - Tick: 10 * time.Second, - Timeout: 1 * time.Minute, - } - - // when - err := executeAndWait.Do() - - //then - require.Error(t, err) - }) - - t.Run("Return error when verify function constantly returns false", func(t *testing.T) { - // given - executeAndWait := ExecuteAndWaitForCondition{ - - RetryableExecuteFunc: func() error { - return nil - }, - ConditionMetFunc: func() bool { - return false - }, - Tick: 10 * time.Second, - Timeout: 1 * time.Minute, - } - - // when - err := executeAndWait.Do() - - //then - require.Error(t, err) - }) -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/graphql/client.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/graphql/client.go deleted file mode 100644 index 888094abc2a4..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/graphql/client.go +++ /dev/null @@ -1,76 +0,0 @@ -package graphql - -import ( - "context" - "crypto/tls" - "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/third_party/machinebox/graphql" - "net/http" - "time" - - "github.com/sirupsen/logrus" -) - -const ( - timeout = 30 * time.Second -) - -type ClientConstructor func(certificate *tls.Certificate, graphqlEndpoint string, enableLogging bool, insecureConfigFetch bool) (Client, error) - -//go:generate mockery --name=Client -type Client interface { - Do(req *graphql.Request, res interface{}) error -} - -type client struct { - gqlClient *graphql.Client - logs []string - logging bool -} - -func NewGraphQLClient(graphqlEndpoint string, enableLogging bool, insecureSkipVerify bool) Client { - httpClient := &http.Client{ - Transport: &http.Transport{ - TLSClientConfig: &tls.Config{InsecureSkipVerify: insecureSkipVerify}, - }, - } - - gqlClient := graphql.NewClient(graphqlEndpoint, graphql.WithHTTPClient(httpClient)) - - client := &client{ - gqlClient: gqlClient, - logging: enableLogging, - logs: []string{}, - } - - client.gqlClient.Log = client.addLog - - return client -} - -func (c *client) Do(req *graphql.Request, res interface{}) error { - ctx, cancel := context.WithTimeout(context.Background(), timeout) - defer cancel() - - c.clearLogs() - err := c.gqlClient.Run(ctx, req, res) - if err != nil { - for _, l := range c.logs { - if l != "" { - logrus.Info(l) - } - } - } - return err -} - -func (c *client) addLog(log string) { - if !c.logging { - return - } - - c.logs = append(c.logs, log) -} - -func (c *client) clearLogs() { - c.logs = []string{} -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/graphql/gql_client_testkit.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/graphql/gql_client_testkit.go deleted file mode 100644 index 1bfe2a779052..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/graphql/gql_client_testkit.go +++ /dev/null @@ -1,47 +0,0 @@ -package graphql - -import ( - "errors" - "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/third_party/machinebox/graphql" - "testing" - - "github.com/stretchr/testify/assert" -) - -type QueryAssertClient struct { - t *testing.T - expectedRequests []*graphql.Request - err error - modifyResponseFunc ModifyResponseFunc -} - -type ModifyResponseFunc []func(t *testing.T, r interface{}) - -func (c *QueryAssertClient) Do(req *graphql.Request, res interface{}) error { - if len(c.expectedRequests) == 0 { - return errors.New("no more requests were expected") - } - - assert.Equal(c.t, c.expectedRequests[0], req) - if len(c.expectedRequests) > 1 { - c.expectedRequests = c.expectedRequests[1:] - } - - if len(c.modifyResponseFunc) > 0 { - c.modifyResponseFunc[0](c.t, res) - if len(c.modifyResponseFunc) > 1 { - c.modifyResponseFunc = c.modifyResponseFunc[1:] - } - } - - return c.err -} - -func NewQueryAssertClient(t *testing.T, err error, expectedReq []*graphql.Request, modifyResponseFunc ...func(t *testing.T, r interface{})) Client { - return &QueryAssertClient{ - t: t, - expectedRequests: expectedReq, - err: err, - modifyResponseFunc: modifyResponseFunc, - } -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/graphql/mocks/Client.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/graphql/mocks/Client.go deleted file mode 100644 index e6a42c6cfa39..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/graphql/mocks/Client.go +++ /dev/null @@ -1,42 +0,0 @@ -// Code generated by mockery v2.15.0. DO NOT EDIT. - -package mocks - -import ( - graphql "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/third_party/machinebox/graphql" - mock "github.com/stretchr/testify/mock" -) - -// Client is an autogenerated mock type for the Client type -type Client struct { - mock.Mock -} - -// Do provides a mock function with given fields: req, res -func (_m *Client) Do(req *graphql.Request, res interface{}) error { - ret := _m.Called(req, res) - - var r0 error - if rf, ok := ret.Get(0).(func(*graphql.Request, interface{}) error); ok { - r0 = rf(req, res) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -type mockConstructorTestingTNewClient interface { - mock.TestingT - Cleanup(func()) -} - -// NewClient creates a new instance of Client. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewClient(t mockConstructorTestingTNewClient) *Client { - mock := &Client{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/certificatesecrets_test.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/init/certificatesecrets_test.go deleted file mode 100644 index 530e11af323c..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/certificatesecrets_test.go +++ /dev/null @@ -1,78 +0,0 @@ -package init - -import ( - "context" - "github.com/stretchr/testify/require" - v1 "k8s.io/api/core/v1" - k8serrors "k8s.io/apimachinery/pkg/api/errors" - meta "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/client-go/kubernetes/fake" - "testing" -) - -func TestCertificateSecrets(t *testing.T) { - t.Run("should return rollback function that will remove secrets", func(t *testing.T) { - // given - fakeKubernetesInterface := fake.NewSimpleClientset() - - // when - configurator := NewCertificateSecretConfigurator(fakeKubernetesInterface) - rollbackFunc, err := configurator.Do("newCaSecret", "newClientSetSecret") - - // then - require.NoError(t, err) - - // given - caCertSecret := createSecret("newCaSecret", IstioSystemNamespace) - clientCertSecret := createSecret("newClientSetSecret", CompassSystemNamespace) - - _, err = fakeKubernetesInterface.CoreV1().Secrets(IstioSystemNamespace).Create(context.TODO(), caCertSecret, meta.CreateOptions{}) - require.NoError(t, err) - - _, err = fakeKubernetesInterface.CoreV1().Secrets(CompassSystemNamespace).Create(context.TODO(), clientCertSecret, meta.CreateOptions{}) - require.NoError(t, err) - - // when - err = rollbackFunc() - require.NoError(t, err) - - // then - _, err = fakeKubernetesInterface.CoreV1().Secrets("test").Get(context.TODO(), "newCaSecret", meta.GetOptions{}) - require.Error(t, err) - require.True(t, k8serrors.IsNotFound(err)) - - _, err = fakeKubernetesInterface.CoreV1().Secrets("test").Get(context.TODO(), "newClientSetSecret", meta.GetOptions{}) - require.Error(t, err) - require.True(t, k8serrors.IsNotFound(err)) - }) - - t.Run("should not return error when rollback function tries to delete non-existent secrets", func(t *testing.T) { - // given - fakeKubernetesInterface := fake.NewSimpleClientset() - - // when - configurator := NewCertificateSecretConfigurator(fakeKubernetesInterface) - rollbackFunc, err := configurator.Do("newCaSecret", "newClientSetSecret") - - // then - require.NoError(t, err) - - // when - err = rollbackFunc() - require.NoError(t, err) - }) - // TODO: consider a case when rollback function fails -} - -func createSecret(name, namespace string) *v1.Secret { - return &v1.Secret{ - ObjectMeta: meta.ObjectMeta{ - Name: name, - Namespace: namespace, - }, - TypeMeta: meta.TypeMeta{ - Kind: "Secret", - APIVersion: "v1", - }, - } -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/certificatessecrets.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/init/certificatessecrets.go deleted file mode 100644 index 3141ca9c4028..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/certificatessecrets.go +++ /dev/null @@ -1,41 +0,0 @@ -package init - -import ( - "github.com/hashicorp/go-multierror" - "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types" - "k8s.io/client-go/kubernetes" -) - -type certificatesSecretsConfigurator struct { - kubernetesInterface kubernetes.Interface -} - -func NewCertificateSecretConfigurator(kubernetesInterface kubernetes.Interface) certificatesSecretsConfigurator { - return certificatesSecretsConfigurator{ - kubernetesInterface: kubernetesInterface, - } -} - -func (csc certificatesSecretsConfigurator) Do(newCASecretName, newClusterCertSecretName string) (types.RollbackFunc, error) { - // Original secrets created by Compass Runtime Agent are left intact so that they can be restored after the test. - // As part of the test preparation new secret names are passed to the Compass Runtime Agent Deployment. Rollback function needs to delete those. - return csc.getRollbackFunction(newCASecretName, newClusterCertSecretName), nil -} - -func (csc certificatesSecretsConfigurator) getRollbackFunction(caSecretName, clusterCertSecretName string) types.RollbackFunc { - return func() error { - var result *multierror.Error - - err := deleteSecretWithRetry(csc.kubernetesInterface, caSecretName, IstioSystemNamespace) - if err != nil { - multierror.Append(result, err) - } - - err = deleteSecretWithRetry(csc.kubernetesInterface, clusterCertSecretName, CompassSystemNamespace) - if err != nil { - multierror.Append(result, err) - } - - return result.ErrorOrNil() - } -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/compass.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/init/compass.go deleted file mode 100644 index 454b85bc4226..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/compass.go +++ /dev/null @@ -1,53 +0,0 @@ -package init - -import ( - "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types" -) - -type compassconfigurator struct { - directorClient types.DirectorClient - tenant string -} - -func NewCompassConfigurator(directorClient types.DirectorClient, tenant string) compassconfigurator { - return compassconfigurator{ - directorClient: directorClient, - tenant: tenant, - } -} - -func (cc compassconfigurator) Do(runtimeName, formationName string) (types.CompassRuntimeAgentConfig, types.RollbackFunc, error) { - runtimeID, err := cc.directorClient.RegisterRuntime(runtimeName) - if err != nil { - return types.CompassRuntimeAgentConfig{}, nil, err - } - - unregisterRuntimeRollbackFunc := func() error { return cc.directorClient.UnregisterRuntime(runtimeID) } - - err = cc.directorClient.RegisterFormation(formationName) - if err != nil { - return types.CompassRuntimeAgentConfig{}, unregisterRuntimeRollbackFunc, err - } - - unregisterFormationRollbackFunc := func() error { return cc.directorClient.UnregisterFormation(formationName) } - rollBackFunc := newRollbackFunc(unregisterRuntimeRollbackFunc, unregisterFormationRollbackFunc) - - err = cc.directorClient.AssignRuntimeToFormation(runtimeID, formationName) - if err != nil { - return types.CompassRuntimeAgentConfig{}, rollBackFunc, err - } - - token, compassConnectorUrl, err := cc.directorClient.GetConnectionToken(runtimeID) - if err != nil { - return types.CompassRuntimeAgentConfig{}, rollBackFunc, err - } - - config := types.CompassRuntimeAgentConfig{ - ConnectorUrl: compassConnectorUrl, - RuntimeID: runtimeID, - Token: token, - Tenant: cc.tenant, - } - - return config, rollBackFunc, nil -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/compass_test.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/init/compass_test.go deleted file mode 100644 index d47ca08d2727..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/compass_test.go +++ /dev/null @@ -1,159 +0,0 @@ -package init - -import ( - "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types" - "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types/mocks" - "github.com/pkg/errors" - "github.com/stretchr/testify/require" - "testing" -) - -func TestCompassConfigurator(t *testing.T) { - runtimeName := "runtime" - runtimeID := "runtimeID" - formationName := "formation" - connectionToken := "token" - connectorURL := "connector.com" - tenant := "tenant" - - t.Run("should register Runtime, Formation and get connection token", func(t *testing.T) { - // given - directorClientMock := &mocks.DirectorClient{} - directorClientMock.On("RegisterRuntime", runtimeName).Return(runtimeID, nil) - directorClientMock.On("RegisterFormation", formationName).Return(nil) - - directorClientMock.On("UnregisterRuntime", runtimeID).Return(nil) - directorClientMock.On("UnregisterFormation", formationName).Return(nil) - - directorClientMock.On("GetConnectionToken", runtimeID).Return(connectionToken, connectorURL, nil) - directorClientMock.On("AssignRuntimeToFormation", runtimeID, formationName).Return(nil) - - // when - compassConfigurator := NewCompassConfigurator(directorClientMock, tenant) - require.NotNil(t, compassConfigurator) - - compassRuntimeAgentConfig, rollbackFunc, err := compassConfigurator.Do(runtimeName, formationName) - - // then - require.NotNil(t, rollbackFunc) - require.NoError(t, err) - require.Equal(t, runtimeID, compassRuntimeAgentConfig.RuntimeID) - require.Equal(t, tenant, compassRuntimeAgentConfig.Tenant) - require.Equal(t, connectionToken, compassRuntimeAgentConfig.Token) - require.Equal(t, connectorURL, compassRuntimeAgentConfig.ConnectorUrl) - - // when - err = rollbackFunc() - - // then - require.NoError(t, err) - directorClientMock.AssertExpectations(t) - }) - - t.Run("should fail when failed to register Runtime", func(t *testing.T) { - // given - directorClientMock := &mocks.DirectorClient{} - directorClientMock.On("RegisterRuntime", runtimeName).Return(runtimeID, errors.New("some error")) - - // when - compassConfigurator := NewCompassConfigurator(directorClientMock, tenant) - require.NotNil(t, compassConfigurator) - - compassRuntimeAgentConfig, rollbackFunc, err := compassConfigurator.Do(runtimeName, formationName) - - // then - require.Equal(t, types.CompassRuntimeAgentConfig{}, compassRuntimeAgentConfig) - require.Nil(t, rollbackFunc) - require.Error(t, err) - directorClientMock.AssertExpectations(t) - }) - - t.Run("should fail when failed to register Formation", func(t *testing.T) { - // given - directorClientMock := &mocks.DirectorClient{} - directorClientMock.On("RegisterRuntime", runtimeName).Return(runtimeID, nil) - directorClientMock.On("RegisterFormation", formationName).Return(errors.New("some error")) - directorClientMock.On("UnregisterRuntime", runtimeID).Return(nil) - - // when - compassConfigurator := NewCompassConfigurator(directorClientMock, tenant) - require.NotNil(t, compassConfigurator) - - compassRuntimeAgentConfig, rollbackFunc, err := compassConfigurator.Do(runtimeName, formationName) - - // then - require.Equal(t, types.CompassRuntimeAgentConfig{}, compassRuntimeAgentConfig) - require.NotNil(t, rollbackFunc) - require.Error(t, err) - - // when - err = rollbackFunc() - - // then - require.NoError(t, err) - directorClientMock.AssertExpectations(t) - }) - - t.Run("should fail when failed to assign Runtime to Formation", func(t *testing.T) { - // given - directorClientMock := &mocks.DirectorClient{} - directorClientMock.On("RegisterRuntime", runtimeName).Return(runtimeID, nil) - directorClientMock.On("RegisterFormation", formationName).Return(nil) - - directorClientMock.On("UnregisterRuntime", runtimeID).Return(nil) - directorClientMock.On("UnregisterFormation", formationName).Return(nil) - - directorClientMock.On("AssignRuntimeToFormation", runtimeID, formationName).Return(errors.New("some error")) - - // when - compassConfigurator := NewCompassConfigurator(directorClientMock, tenant) - require.NotNil(t, compassConfigurator) - - compassRuntimeAgentConfig, rollbackFunc, err := compassConfigurator.Do(runtimeName, formationName) - - // then - require.NotNil(t, compassConfigurator) - require.Equal(t, types.CompassRuntimeAgentConfig{}, compassRuntimeAgentConfig) - require.NotNil(t, rollbackFunc) - require.Error(t, err) - - // when - err = rollbackFunc() - - // then - require.NoError(t, err) - directorClientMock.AssertExpectations(t) - }) - - t.Run("should fail when failed to get connection token", func(t *testing.T) { - // given - directorClientMock := &mocks.DirectorClient{} - directorClientMock.On("RegisterRuntime", runtimeName).Return(runtimeID, nil) - directorClientMock.On("RegisterFormation", formationName).Return(nil) - - directorClientMock.On("UnregisterRuntime", runtimeID).Return(nil) - directorClientMock.On("UnregisterFormation", formationName).Return(nil) - - directorClientMock.On("AssignRuntimeToFormation", runtimeID, formationName).Return(nil) - directorClientMock.On("GetConnectionToken", runtimeID).Return("", "", errors.New("some error")) - - // when - compassConfigurator := NewCompassConfigurator(directorClientMock, tenant) - require.NotNil(t, compassConfigurator) - - compassRuntimeAgentConfig, rollbackFunc, err := compassConfigurator.Do(runtimeName, formationName) - - // then - require.NotNil(t, compassConfigurator) - require.Equal(t, types.CompassRuntimeAgentConfig{}, compassRuntimeAgentConfig) - require.NotNil(t, rollbackFunc) - require.Error(t, err) - - // when - err = rollbackFunc() - - // then - require.NoError(t, err) - directorClientMock.AssertExpectations(t) - }) -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/compassconnection.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/init/compassconnection.go deleted file mode 100644 index 41d2885ea407..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/compassconnection.go +++ /dev/null @@ -1,114 +0,0 @@ -package init - -import ( - "context" - "github.com/avast/retry-go" - "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/apis/compass/v1alpha1" - "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types" - "github.com/pkg/errors" - k8serrors "k8s.io/apimachinery/pkg/api/errors" - meta "k8s.io/apimachinery/pkg/apis/meta/v1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -type compassConnectionCRConfiguration struct { - compassConnectionInterface CompassConnectionInterface -} - -const ( - ConnectionCRName = "compass-connection" - ConnectionBackupCRName = "compass-connection-backup" -) - -//go:generate mockery --name=CompassConnectionInterface -type CompassConnectionInterface interface { - Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.CompassConnection, error) - Create(ctx context.Context, compassConnection *v1alpha1.CompassConnection, opts v1.CreateOptions) (*v1alpha1.CompassConnection, error) - Update(ctx context.Context, compassConnection *v1alpha1.CompassConnection, opts v1.UpdateOptions) (*v1alpha1.CompassConnection, error) - Delete(ctx context.Context, name string, opts v1.DeleteOptions) error -} - -func NewCompassConnectionCRConfiguration(compassConnectionInterface CompassConnectionInterface) compassConnectionCRConfiguration { - return compassConnectionCRConfiguration{ - compassConnectionInterface: compassConnectionInterface, - } -} - -func (cc compassConnectionCRConfiguration) Do() (types.RollbackFunc, error) { - - backupRollbackFunc, err := cc.backup() - if err != nil { - return nil, err - } - - deleteRollbackFunc, err := cc.delete() - if err != nil { - return backupRollbackFunc, err - } - - return newRollbackFunc(deleteRollbackFunc, backupRollbackFunc), nil -} -func (cc compassConnectionCRConfiguration) backup() (types.RollbackFunc, error) { - compassConnectionCR, err := cc.compassConnectionInterface.Get(context.TODO(), ConnectionCRName, meta.GetOptions{}) - if err != nil { - return nil, errors.Wrap(err, "failed to get Compass Connection CR") - } - - compassConnectionCR.ResourceVersion = "" - - compassConnectionCRBackup := compassConnectionCR.DeepCopy() - compassConnectionCRBackup.ObjectMeta.Name = "compass-connection-backup" - _, err = cc.compassConnectionInterface.Create(context.TODO(), compassConnectionCRBackup, meta.CreateOptions{}) - if err != nil { - return nil, errors.Wrap(err, "failed to create Compass Connection CR") - } - - rollbackFunc := func() error { - return retry.Do(func() error { - err = cc.compassConnectionInterface.Delete(context.TODO(), "compass-connection-backup", meta.DeleteOptions{}) - if err != nil { - if k8serrors.IsNotFound(err) { - return nil - } - return errors.Wrap(err, "failed to delete Compass Connection CR") - } - - return nil - }) - } - - return rollbackFunc, nil -} - -func (cc compassConnectionCRConfiguration) delete() (types.RollbackFunc, error) { - err := cc.compassConnectionInterface.Delete(context.TODO(), ConnectionCRName, meta.DeleteOptions{}) - - if err != nil { - return nil, errors.Wrap(err, "failed to delete Compass Connection CR") - } - - rollbackFunc := func() error { - return retry.Do(func() error { - restoredCompassConnection, err := cc.compassConnectionInterface.Get(context.TODO(), ConnectionCRName, meta.GetOptions{}) - if err != nil { - return err - } - - compassConnectionCRBackup, err := cc.compassConnectionInterface.Get(context.TODO(), ConnectionBackupCRName, meta.GetOptions{}) - if err != nil { - return err - } - - restoredCompassConnection.Spec = compassConnectionCRBackup.Spec - restoredCompassConnection.Status = compassConnectionCRBackup.Status - - _, err = cc.compassConnectionInterface.Update(context.TODO(), restoredCompassConnection, meta.UpdateOptions{}) - if err != nil { - return errors.Wrap(err, "failed to update Compass Connection CR") - } - return err - }) - } - - return rollbackFunc, nil -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/compassconnection_test.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/init/compassconnection_test.go deleted file mode 100644 index 36ec6ee1fc9b..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/compassconnection_test.go +++ /dev/null @@ -1,139 +0,0 @@ -package init - -import ( - "context" - "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/apis/compass/v1alpha1" - "github.com/kyma-project/kyma/components/compass-runtime-agent/pkg/client/clientset/versioned/fake" - "github.com/stretchr/testify/require" - k8serrors "k8s.io/apimachinery/pkg/api/errors" - meta "k8s.io/apimachinery/pkg/apis/meta/v1" - "testing" -) - -func TestCompassConnectionConfigurator(t *testing.T) { - t.Run("should delete CompassConnection CR and restore it when RollbackFunction is called", func(t *testing.T) { - // given - compassConnectionCRFake := fake.NewSimpleClientset().CompassV1alpha1().CompassConnections() - compassConnection := &v1alpha1.CompassConnection{ - ObjectMeta: meta.ObjectMeta{ - Name: ConnectionCRName, - }, - TypeMeta: meta.TypeMeta{ - Kind: "CompassConnection", - APIVersion: "v1alpha", - }, - } - - _, err := compassConnectionCRFake.Create(context.TODO(), compassConnection, meta.CreateOptions{}) - require.NoError(t, err) - - // when - configurator := NewCompassConnectionCRConfiguration(compassConnectionCRFake) - rollbackFunc, err := configurator.Do() - - // then - require.NoError(t, err) - _, err = compassConnectionCRFake.Get(context.TODO(), "compass-connection", meta.GetOptions{}) - require.Error(t, err) - require.True(t, k8serrors.IsNotFound(err)) - - _, err = compassConnectionCRFake.Get(context.TODO(), "compass-connection-backup", meta.GetOptions{}) - require.NoError(t, err) - - _, err = compassConnectionCRFake.Create(context.TODO(), compassConnection, meta.CreateOptions{}) - require.NoError(t, err) - // when - err = rollbackFunc() - - // then - require.NoError(t, err) - _, err = compassConnectionCRFake.Get(context.TODO(), "compass-connection", meta.GetOptions{}) - require.NoError(t, err) - }) - - t.Run("should fail when CompassConnection CR doesn't exist", func(t *testing.T) { - // given - compassConnectionCRFake := fake.NewSimpleClientset().CompassV1alpha1().CompassConnections() - - // when - configurator := NewCompassConnectionCRConfiguration(compassConnectionCRFake) - _, err := configurator.Do() - - // then - require.Error(t, err) - }) - - t.Run("should fail when CompassConnection CR backup already exist", func(t *testing.T) { - // given - compassConnectionCRFake := fake.NewSimpleClientset().CompassV1alpha1().CompassConnections() - compassConnection := &v1alpha1.CompassConnection{ - ObjectMeta: meta.ObjectMeta{ - Name: ConnectionCRName, - }, - TypeMeta: meta.TypeMeta{ - Kind: "CompassConnection", - APIVersion: "v1alpha", - }, - } - - compassConnectionBackup := &v1alpha1.CompassConnection{ - ObjectMeta: meta.ObjectMeta{ - Name: ConnectionBackupCRName, - }, - TypeMeta: meta.TypeMeta{ - Kind: "CompassConnection", - APIVersion: "v1alpha", - }, - } - - _, err := compassConnectionCRFake.Create(context.TODO(), compassConnection, meta.CreateOptions{}) - require.NoError(t, err) - - _, err = compassConnectionCRFake.Create(context.TODO(), compassConnectionBackup, meta.CreateOptions{}) - require.NoError(t, err) - - // when - configurator := NewCompassConnectionCRConfiguration(compassConnectionCRFake) - rollbackFunc, err := configurator.Do() - - // then - require.Nil(t, rollbackFunc) - require.Error(t, err) - }) - - t.Run("rollback function should fail when CompassConnection CR backup doesn't exist", func(t *testing.T) { - // given - compassConnectionCRFake := fake.NewSimpleClientset().CompassV1alpha1().CompassConnections() - compassConnection := &v1alpha1.CompassConnection{ - ObjectMeta: meta.ObjectMeta{ - Name: ConnectionCRName, - }, - TypeMeta: meta.TypeMeta{ - Kind: "CompassConnection", - APIVersion: "v1alpha", - }, - } - - _, err := compassConnectionCRFake.Create(context.TODO(), compassConnection, meta.CreateOptions{}) - require.NoError(t, err) - - // when - configurator := NewCompassConnectionCRConfiguration(compassConnectionCRFake) - rollbackFunc, err := configurator.Do() - - // then - require.NoError(t, err) - - // when - _, err = compassConnectionCRFake.Create(context.TODO(), compassConnection, meta.CreateOptions{}) - require.NoError(t, err) - - err = compassConnectionCRFake.Delete(context.TODO(), ConnectionBackupCRName, meta.DeleteOptions{}) - require.NoError(t, err) - - err = rollbackFunc() - - // then - require.Error(t, err) - }) -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/configurationsecret.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/init/configurationsecret.go deleted file mode 100644 index eaa6b04a520c..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/configurationsecret.go +++ /dev/null @@ -1,83 +0,0 @@ -package init - -import ( - "context" - "github.com/avast/retry-go" - "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types" - "github.com/pkg/errors" - v1 "k8s.io/api/core/v1" - k8serrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/client-go/kubernetes" - "time" -) - -const ( - connectorURLConfigKey = "CONNECTOR_URL" - tokenConfigKey = "TOKEN" - runtimeIdConfigKey = "RUNTIME_ID" - tenantConfigKey = "TENANT" -) - -type configurationSecretConfigurator struct { - kubernetesInterface kubernetes.Interface -} - -func NewConfigurationSecretConfigurator(kubernetesInterface kubernetes.Interface) configurationSecretConfigurator { - return configurationSecretConfigurator{ - kubernetesInterface: kubernetesInterface, - } -} - -func (s configurationSecretConfigurator) Do(newConfigSecretName string, config types.CompassRuntimeAgentConfig) (types.RollbackFunc, error) { - - secret := v1.Secret{ - ObjectMeta: metav1.ObjectMeta{ - Name: newConfigSecretName, - Namespace: CompassSystemNamespace, - }, - Data: map[string][]byte{ - connectorURLConfigKey: []byte(config.ConnectorUrl), - tokenConfigKey: []byte(config.Token), - runtimeIdConfigKey: []byte(config.RuntimeID), - tenantConfigKey: []byte(config.Tenant), - }, - } - - err := retry.Do(func() error { - _, err := s.kubernetesInterface.CoreV1().Secrets(CompassSystemNamespace).Create(context.Background(), &secret, metav1.CreateOptions{}) - if err != nil { - if k8serrors.IsAlreadyExists(err) { - return retry.Unrecoverable(err) - } - return errors.Wrap(err, "failed to create configuration secret") - } - - return nil - }, retry.Attempts(RetryAttempts), retry.Delay(RetrySeconds*time.Second)) - - if err != nil { - return nil, err - } - - return s.newRollbackSecretFunc(newConfigSecretName, CompassSystemNamespace), nil -} - -func (s configurationSecretConfigurator) newRollbackSecretFunc(name, namespace string) types.RollbackFunc { - return func() error { - return deleteSecretWithRetry(s.kubernetesInterface, name, namespace) - } -} - -func deleteSecretWithRetry(kubernetesInterface kubernetes.Interface, name, namespace string) error { - return retry.Do(func() error { - err := kubernetesInterface.CoreV1().Secrets(namespace).Delete(context.Background(), name, metav1.DeleteOptions{}) - if err != nil { - if k8serrors.IsNotFound(err) { - return nil - } - } - - return errors.Wrap(err, "failed to delete secret") - }, retry.Attempts(RetryAttempts), retry.Delay(RetrySeconds*time.Second)) -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/configurationsecret_test.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/init/configurationsecret_test.go deleted file mode 100644 index b3fd06fb0572..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/configurationsecret_test.go +++ /dev/null @@ -1,73 +0,0 @@ -package init - -import ( - "context" - "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types" - "github.com/stretchr/testify/require" - k8serrors "k8s.io/apimachinery/pkg/api/errors" - meta "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/client-go/kubernetes/fake" - "testing" -) - -func TestConfigurationSecret(t *testing.T) { - t.Run("should create configuration secret", func(t *testing.T) { - // given - fakeKubernetesInterface := fake.NewSimpleClientset() - secretConfigurator := NewConfigurationSecretConfigurator(fakeKubernetesInterface) - connectorURL := "www.example.com" - runtimeID := "runtimeID" - token := "token" - tenant := "tenant" - - config := types.CompassRuntimeAgentConfig{ - ConnectorUrl: connectorURL, - RuntimeID: runtimeID, - Token: token, - Tenant: tenant, - } - secretName := "config" - - // when - rollbackFunc, err := secretConfigurator.Do(secretName, config) - require.NotNil(t, rollbackFunc) - require.NoError(t, err) - - // then - secret, err := fakeKubernetesInterface.CoreV1().Secrets(CompassSystemNamespace).Get(context.TODO(), secretName, meta.GetOptions{}) - require.NoError(t, err) - - require.Equal(t, connectorURL, string(secret.Data[connectorURLConfigKey])) - require.Equal(t, token, string(secret.Data[tokenConfigKey])) - require.Equal(t, runtimeID, string(secret.Data[runtimeIdConfigKey])) - require.Equal(t, tenant, string(secret.Data[tenantConfigKey])) - - // when - err = rollbackFunc() - require.NoError(t, err) - - _, err = fakeKubernetesInterface.CoreV1().Secrets(CompassSystemNamespace).Get(context.TODO(), secretName, meta.GetOptions{}) - require.Error(t, err) - require.True(t, k8serrors.IsNotFound(err)) - }) - - t.Run("should return error when failed to create secret", func(t *testing.T) { - // given - fakeKubernetesInterface := fake.NewSimpleClientset() - secretConfigurator := NewConfigurationSecretConfigurator(fakeKubernetesInterface) - - config := types.CompassRuntimeAgentConfig{} - secretName := "config" - - // when - secret := createSecret(secretName, CompassSystemNamespace) - _, err := fakeKubernetesInterface.CoreV1().Secrets(CompassSystemNamespace).Create(context.Background(), secret, meta.CreateOptions{}) - require.NoError(t, err) - - rollbackFunc, err := secretConfigurator.Do(secretName, config) - - // then - require.Nil(t, rollbackFunc) - require.Error(t, err) - }) -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/deployment.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/init/deployment.go deleted file mode 100644 index ffe11af04805..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/deployment.go +++ /dev/null @@ -1,160 +0,0 @@ -package init - -import ( - "context" - "fmt" - "github.com/avast/retry-go" - "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types" - "github.com/pkg/errors" - v12 "k8s.io/api/apps/v1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/client-go/kubernetes" - v13 "k8s.io/client-go/kubernetes/typed/apps/v1" - "time" -) - -const ( - CRAContainerNumber = 0 - ConfigurationSecretEnvName = "APP_AGENT_CONFIGURATION_SECRET" - CASecretEnvName = "APP_CA_CERTIFICATES_SECRET" - ClusterCertSecretEnvName = "APP_CLUSTER_CERTIFICATES_SECRET" - ControllerSyncPeriodEnvTime = "APP_CONTROLLER_SYNC_PERIOD" -) - -type deploymentConfiguration struct { - kubernetesInterface kubernetes.Interface - deploymentName string - namespaceName string -} - -func NewDeploymentConfiguration(kubernetesInterface kubernetes.Interface, deploymentName, namespaceName string) deploymentConfiguration { - return deploymentConfiguration{ - kubernetesInterface: kubernetesInterface, - deploymentName: deploymentName, - namespaceName: namespaceName, - } -} - -func (dc deploymentConfiguration) Do(newCANamespacedSecretName, newClusterNamespacedCertSecretName, newConfigNamespacedSecretName, newControllerSyncPeriodTime string) (types.RollbackFunc, error) { - deploymentInterface := dc.kubernetesInterface.AppsV1().Deployments(dc.namespaceName) - - deployment, err := retryGetDeployment(dc.deploymentName, deploymentInterface) - if err != nil { - return nil, err - } - - if len(deployment.Spec.Template.Spec.Containers) < 1 { - return nil, fmt.Errorf("no containers found in %s/%s deployment", "kyma-system", dc.deploymentName) - } - - previousConfigSecretNamespacedName, found := replaceEnvValue(deployment, ConfigurationSecretEnvName, newConfigNamespacedSecretName) - if !found { - return nil, fmt.Errorf("environment variable '%s' not found in %s deployment", ConfigurationSecretEnvName, dc.deploymentName) - } - - previousCASecretNamespacedName, found := replaceEnvValue(deployment, CASecretEnvName, newCANamespacedSecretName) - if !found { - return nil, fmt.Errorf("environment variable '%s' not found in %s deployment", CASecretEnvName, dc.deploymentName) - } - - previousCertSecretNamespacedName, found := replaceEnvValue(deployment, ClusterCertSecretEnvName, newClusterNamespacedCertSecretName) - if !found { - return nil, fmt.Errorf("environment variable '%s' not found in %s deployment", ClusterCertSecretEnvName, dc.deploymentName) - } - - previousControllerSyncPeriodTime, found := replaceEnvValue(deployment, ControllerSyncPeriodEnvTime, newControllerSyncPeriodTime) - if !found { - return nil, fmt.Errorf("environment variable '%s' not found in %s deployment", ControllerSyncPeriodEnvTime, dc.deploymentName) - } - - err = retryUpdateDeployment(deployment, deploymentInterface) - if err != nil { - return nil, err - } - rollbackDeploymentFunc := newRollbackDeploymentFunc(dc.deploymentName, previousConfigSecretNamespacedName, previousCASecretNamespacedName, previousCertSecretNamespacedName, previousControllerSyncPeriodTime, deploymentInterface) - - err = waitForRollout(dc.deploymentName, deploymentInterface) - - return rollbackDeploymentFunc, err -} - -func newRollbackDeploymentFunc(name, previousConfigSecretNamespacedName, previousCASecretNamespacedName, previousCertSecretNamespacedName, previousControllerSyncPeriodTime string, deploymentInterface v13.DeploymentInterface) types.RollbackFunc { - return func() error { - deployment, err := retryGetDeployment(name, deploymentInterface) - if err != nil { - return err - } - - _, found := replaceEnvValue(deployment, ConfigurationSecretEnvName, previousConfigSecretNamespacedName) - if !found { - return fmt.Errorf("environment variable '%s' not found in %s deployment", ConfigurationSecretEnvName, name) - } - - _, found = replaceEnvValue(deployment, CASecretEnvName, previousCASecretNamespacedName) - if !found { - return fmt.Errorf("environment variable '%s' not found in %s deployment", CASecretEnvName, name) - } - - _, found = replaceEnvValue(deployment, ClusterCertSecretEnvName, previousCertSecretNamespacedName) - if !found { - return fmt.Errorf("environment variable '%s' not found in %s deployment", ClusterCertSecretEnvName, name) - } - - _, found = replaceEnvValue(deployment, ControllerSyncPeriodEnvTime, previousControllerSyncPeriodTime) - if !found { - return fmt.Errorf("environment variable '%s' not found in %s deployment", ControllerSyncPeriodEnvTime, name) - } - - return retryUpdateDeployment(deployment, deploymentInterface) - } -} - -func replaceEnvValue(deployment *v12.Deployment, name, newValue string) (string, bool) { - envs := deployment.Spec.Template.Spec.Containers[CRAContainerNumber].Env - for i := range envs { - if envs[i].Name == name { - previousValue := envs[i].Value - envs[i].Value = newValue - deployment.Spec.Template.Spec.Containers[CRAContainerNumber].Env = envs - - return previousValue, true - } - } - - return "", false -} - -func retryGetDeployment(name string, deploymentInterface v13.DeploymentInterface) (*v12.Deployment, error) { - var deployment *v12.Deployment - - err := retry.Do(func() error { - var err error - deployment, err = deploymentInterface.Get(context.TODO(), name, v1.GetOptions{}) - if err != nil { - return errors.Wrap(err, "failed to get Compass Runtime Agent deployment") - } - return nil - }, retry.Attempts(RetryAttempts), retry.Delay(RetrySeconds*time.Second)) - - return deployment, err -} - -func retryUpdateDeployment(deployment *v12.Deployment, deploymentInterface v13.DeploymentInterface) error { - return retry.Do(func() error { - _, err := deploymentInterface.Update(context.TODO(), deployment, v1.UpdateOptions{}) - return errors.Wrap(err, "failed to update Compass Runtime Agent deployment") - }, retry.Attempts(RetryAttempts), retry.Delay(RetrySeconds*time.Second)) -} - -func waitForRollout(name string, deploymentInterface v13.DeploymentInterface) error { - return retry.Do(func() error { - deployment, err := deploymentInterface.Get(context.TODO(), name, v1.GetOptions{}) - if err != nil { - return errors.Wrap(err, "failed to get Compass Runtime Agent deployment") - } - if deployment.Status.AvailableReplicas == 0 || deployment.Status.UnavailableReplicas != 0 { - return fmt.Errorf("deployment %s is not yet ready", name) - } - return nil - }, retry.Attempts(RetryAttempts), retry.Delay(RetrySeconds*time.Second)) -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/init.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/init/init.go deleted file mode 100644 index 68b397c8c3f9..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/init.go +++ /dev/null @@ -1,140 +0,0 @@ -package init - -import ( - "fmt" - "github.com/hashicorp/go-multierror" - "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types" - log "github.com/sirupsen/logrus" -) - -const ( - CompassSystemNamespace = "kyma-system" - IstioSystemNamespace = "istio-system" - CompassRuntimeAgentDeployment = "compass-runtime-agent" - NewCompassRuntimeConfigName = "test-compass-runtime-agent-config" - NewCACertSecretName = "ca-cert-test" - NewClientCertSecretName = "client-cert-test" - NewControllerSyncPeriodTime = "15s" - RetryAttempts = 6 - RetrySeconds = 5 -) - -type CompassRuntimeAgentConfigurator interface { - Do(runtimeName, formationName string) (types.RollbackFunc, error) -} - -type Configurator interface { - Configure(runtimeName, formationName string) (types.RollbackFunc, error) -} - -type compassRuntimeAgentConfigurator struct { - compassConfigurator types.CompassConfigurator - certificateSecretConfigurator types.CertificateSecretConfigurator - configurationSecretConfigurator types.ConfigurationSecretConfigurator - compassConnectionConfigurator types.CompassConnectionConfigurator - deploymentConfigurator types.DeploymentConfigurator - testNamespace string -} - -func NewCompassRuntimeAgentConfigurator(compassConfigurator types.CompassConfigurator, - certificateSecretConfigurator types.CertificateSecretConfigurator, - configurationSecretConfigurator types.ConfigurationSecretConfigurator, - compassConnectionConfigurator types.CompassConnectionConfigurator, - deploymentConfigurator types.DeploymentConfigurator, - testNamespace string) CompassRuntimeAgentConfigurator { - return compassRuntimeAgentConfigurator{ - compassConfigurator: compassConfigurator, - certificateSecretConfigurator: certificateSecretConfigurator, - configurationSecretConfigurator: configurationSecretConfigurator, - compassConnectionConfigurator: compassConnectionConfigurator, - deploymentConfigurator: deploymentConfigurator, - testNamespace: testNamespace, - } -} - -func (crc compassRuntimeAgentConfigurator) Do(runtimeName, formationName string) (types.RollbackFunc, error) { - log.Info("Configuring Compass") - compassRuntimeAgentConfig, compassConfiguratorRollbackFunc, err := crc.compassConfigurator.Do(runtimeName, formationName) - if err != nil { - return nil, crc.rollbackOnError(err, - compassConfiguratorRollbackFunc) - } - - log.Info("Configuring certificate secrets") - certificateSecretsRollbackFunc, err := crc.certificateSecretConfigurator.Do(NewCACertSecretName, NewClientCertSecretName) - if err != nil { - return nil, crc.rollbackOnError(err, - compassConfiguratorRollbackFunc, - certificateSecretsRollbackFunc) - } - - log.Info("Preparing Compass Runtime Agent configuration secret") - configurationSecretRollbackFunc, err := crc.configurationSecretConfigurator.Do(NewCompassRuntimeConfigName, compassRuntimeAgentConfig) - if err != nil { - return nil, crc.rollbackOnError(err, - compassConfiguratorRollbackFunc, - certificateSecretsRollbackFunc, - configurationSecretRollbackFunc) - } - - newCACertNamespacedSecretName := fmt.Sprintf("%s/%s", IstioSystemNamespace, NewCACertSecretName) - newClientCertNamespacedSecretName := fmt.Sprintf("%s/%s", CompassSystemNamespace, NewClientCertSecretName) - newCompassRuntimeNamespacedSecretConfigName := fmt.Sprintf("%s/%s", CompassSystemNamespace, NewCompassRuntimeConfigName) - newControllerSyncPeriodTime := fmt.Sprintf("%s", NewControllerSyncPeriodTime) - - log.Info("Preparing Compass Runtime Agent configuration secret") - deploymentRollbackFunc, err := crc.deploymentConfigurator.Do(newCACertNamespacedSecretName, - newClientCertNamespacedSecretName, - newCompassRuntimeNamespacedSecretConfigName, newControllerSyncPeriodTime) - if err != nil { - return nil, crc.rollbackOnError(err, - compassConfiguratorRollbackFunc, - certificateSecretsRollbackFunc, - configurationSecretRollbackFunc, - deploymentRollbackFunc) - } - - compassConnectionRollbackFunc, err := crc.compassConnectionConfigurator.Do() - if err != nil { - return nil, crc.rollbackOnError(err, - compassConfiguratorRollbackFunc, - certificateSecretsRollbackFunc, - configurationSecretRollbackFunc, - deploymentRollbackFunc, - compassConnectionRollbackFunc) - } - - return newRollbackFunc(compassConfiguratorRollbackFunc, - certificateSecretsRollbackFunc, - configurationSecretRollbackFunc, - deploymentRollbackFunc, - compassConnectionRollbackFunc), nil -} - -func (crc compassRuntimeAgentConfigurator) rollbackOnError(initialErr error, rollbackFunctions ...types.RollbackFunc) error { - var result *multierror.Error - result = multierror.Append(result, initialErr) - - err := newRollbackFunc(rollbackFunctions...)() - if err != nil { - result = multierror.Append(result, err) - } - - return result.ErrorOrNil() -} - -func newRollbackFunc(rollbackFunctions ...types.RollbackFunc) types.RollbackFunc { - var result *multierror.Error - - return func() error { - for _, f := range rollbackFunctions { - if f != nil { - if err := f(); err != nil { - result = multierror.Append(result, err) - } - } - } - - return result.ErrorOrNil() - } -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/init_test.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/init/init_test.go deleted file mode 100644 index 9078c01e7a1c..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/init_test.go +++ /dev/null @@ -1,232 +0,0 @@ -package init - -import ( - "fmt" - "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types" - "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types/mocks" - "github.com/pkg/errors" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "testing" -) - -func TestCompassRuntimeAgentInit(t *testing.T) { - runtimeName := "newRuntime" - runtimeID := "runtimeID" - token := "token" - connectorURL := "www.someurl.com" - tenant := "tenant" - formationName := "newFormation" - - t.Run("should succeed and return rollback function", func(t *testing.T) { - // given - compassConfiguratorMock := &mocks.CompassConfigurator{} - certificateSecretConfiguratorMock := &mocks.CertificateSecretConfigurator{} - configurationSecretConfiguratorMock := &mocks.ConfigurationSecretConfigurator{} - compassConnectionConfiguratorMock := &mocks.CompassConnectionConfigurator{} - deploymentConfiguratorMock := &mocks.DeploymentConfigurator{} - - compassConfiguratorRollbackFunc := RollbackFuncTest{} - certificateSecretsRollbackFunc := RollbackFuncTest{} - configurationSecretRollbackFunc := RollbackFuncTest{} - compassConnectionRollbackFunc := RollbackFuncTest{} - deploymentRollbackFunc := RollbackFuncTest{} - - config := types.CompassRuntimeAgentConfig{ - ConnectorUrl: connectorURL, - RuntimeID: runtimeID, - Token: token, - Tenant: tenant, - } - - compassConfiguratorMock.On("Do", runtimeName, formationName).Return(config, compassConfiguratorRollbackFunc.Func(), nil) - certificateSecretConfiguratorMock.On("Do", NewCACertSecretName, NewClientCertSecretName).Return(certificateSecretsRollbackFunc.Func(), nil) - configurationSecretConfiguratorMock.On("Do", NewCompassRuntimeConfigName, config).Return(configurationSecretRollbackFunc.Func(), nil) - compassConnectionConfiguratorMock.On("Do").Return(compassConnectionRollbackFunc.Func(), nil) - deploymentConfiguratorMock.On("Do", - fmt.Sprintf("%s/%s", IstioSystemNamespace, NewCACertSecretName), - fmt.Sprintf("%s/%s", CompassSystemNamespace, NewClientCertSecretName), - fmt.Sprintf("%s/%s", CompassSystemNamespace, NewCompassRuntimeConfigName), - fmt.Sprintf("%s", NewControllerSyncPeriodTime)). - Return(deploymentRollbackFunc.Func(), nil) - - configurator := NewCompassRuntimeAgentConfigurator(compassConfiguratorMock, certificateSecretConfiguratorMock, configurationSecretConfiguratorMock, compassConnectionConfiguratorMock, deploymentConfiguratorMock, "tenant") - - // when - rollbackFunc, err := configurator.Do(runtimeName, formationName) - - // then - require.NoError(t, err) - certificateSecretConfiguratorMock.AssertExpectations(t) - compassConnectionConfiguratorMock.AssertExpectations(t) - deploymentConfiguratorMock.AssertExpectations(t) - - //when - err = rollbackFunc() - - // then - require.NoError(t, err) - require.True(t, compassConfiguratorRollbackFunc.invoked) - require.True(t, certificateSecretsRollbackFunc.invoked) - require.True(t, configurationSecretRollbackFunc.invoked) - require.True(t, compassConnectionRollbackFunc.invoked) - require.True(t, deploymentRollbackFunc.invoked) - }) - - t.Run("should fail if failed to register runtime", func(t *testing.T) { - // given - compassConfiguratorMock := &mocks.CompassConfigurator{} - compassConfiguratorRollbackFunc := RollbackFuncTest{} - - compassConfiguratorMock.On("Do", runtimeName, formationName).Return(types.CompassRuntimeAgentConfig{}, compassConfiguratorRollbackFunc.Func(), errors.New("some error")) - - configurator := NewCompassRuntimeAgentConfigurator(compassConfiguratorMock, nil, nil, nil, nil, "tenant") - - // when - rollbackFunc, err := configurator.Do(runtimeName, formationName) - - // then - require.Error(t, err) - require.Nil(t, rollbackFunc) - assert.True(t, compassConfiguratorRollbackFunc.invoked) - }) - - t.Run("should fail if failed to create configuration secret", func(t *testing.T) { - // given - compassConfiguratorMock := &mocks.CompassConfigurator{} - certificateSecretConfiguratorMock := &mocks.CertificateSecretConfigurator{} - configurationSecretConfiguratorMock := &mocks.ConfigurationSecretConfigurator{} - - compassConfiguratorRollbackFunc := RollbackFuncTest{} - certificateSecretsRollbackFunc := RollbackFuncTest{} - - config := types.CompassRuntimeAgentConfig{ - ConnectorUrl: connectorURL, - RuntimeID: runtimeID, - Token: token, - Tenant: tenant, - } - - compassConfiguratorMock.On("Do", runtimeName, formationName).Return(config, compassConfiguratorRollbackFunc.Func(), nil) - certificateSecretConfiguratorMock.On("Do", NewCACertSecretName, NewClientCertSecretName).Return(certificateSecretsRollbackFunc.Func(), nil) - configurationSecretConfiguratorMock.On("Do", NewCompassRuntimeConfigName, config).Return(nil, errors.New("some error")) - - configurator := NewCompassRuntimeAgentConfigurator(compassConfiguratorMock, certificateSecretConfiguratorMock, configurationSecretConfiguratorMock, nil, nil, "tenant") - - // when - rollbackFunc, err := configurator.Do(runtimeName, formationName) - - // then - require.Error(t, err) - require.Nil(t, rollbackFunc) - compassConfiguratorMock.AssertExpectations(t) - certificateSecretConfiguratorMock.AssertExpectations(t) - certificateSecretConfiguratorMock.AssertExpectations(t) - require.True(t, compassConfiguratorRollbackFunc.invoked) - require.True(t, certificateSecretsRollbackFunc.invoked) - }) - - t.Run("should fail if failed to modify deployment", func(t *testing.T) { - // given - compassConfiguratorMock := &mocks.CompassConfigurator{} - certificateSecretConfiguratorMock := &mocks.CertificateSecretConfigurator{} - configurationSecretConfiguratorMock := &mocks.ConfigurationSecretConfigurator{} - deploymentConfiguratorMock := &mocks.DeploymentConfigurator{} - - compassConfiguratorRollbackFunc := RollbackFuncTest{} - certificateSecretsRollbackFunc := RollbackFuncTest{} - configurationSecretRollbackFunc := RollbackFuncTest{} - - config := types.CompassRuntimeAgentConfig{ - ConnectorUrl: connectorURL, - RuntimeID: runtimeID, - Token: token, - Tenant: tenant, - } - - compassConfiguratorMock.On("Do", runtimeName, formationName).Return(config, compassConfiguratorRollbackFunc.Func(), nil) - certificateSecretConfiguratorMock.On("Do", NewCACertSecretName, NewClientCertSecretName).Return(certificateSecretsRollbackFunc.Func(), nil) - configurationSecretConfiguratorMock.On("Do", NewCompassRuntimeConfigName, config).Return(configurationSecretRollbackFunc.Func(), nil) - deploymentConfiguratorMock.On("Do", - fmt.Sprintf("%s/%s", IstioSystemNamespace, NewCACertSecretName), - fmt.Sprintf("%s/%s", CompassSystemNamespace, NewClientCertSecretName), - fmt.Sprintf("%s/%s", CompassSystemNamespace, NewCompassRuntimeConfigName), - fmt.Sprintf("%s", NewControllerSyncPeriodTime)). - Return(nil, errors.New("some error")) - - configurator := NewCompassRuntimeAgentConfigurator(compassConfiguratorMock, certificateSecretConfiguratorMock, configurationSecretConfiguratorMock, nil, deploymentConfiguratorMock, "tenant") - - // when - rollbackFunc, err := configurator.Do(runtimeName, formationName) - - // then - require.Error(t, err) - require.Nil(t, rollbackFunc) - certificateSecretConfiguratorMock.AssertExpectations(t) - deploymentConfiguratorMock.AssertExpectations(t) - require.True(t, compassConfiguratorRollbackFunc.invoked) - require.True(t, certificateSecretsRollbackFunc.invoked) - require.True(t, configurationSecretRollbackFunc.invoked) - }) - - t.Run("should fail if failed to configure Compass Connection CR", func(t *testing.T) { - // given - compassConfiguratorMock := &mocks.CompassConfigurator{} - certificateSecretConfiguratorMock := &mocks.CertificateSecretConfigurator{} - configurationSecretConfiguratorMock := &mocks.ConfigurationSecretConfigurator{} - compassConnectionConfiguratorMock := &mocks.CompassConnectionConfigurator{} - deploymentConfiguratorMock := &mocks.DeploymentConfigurator{} - - compassConfiguratorRollbackFunc := RollbackFuncTest{} - certificateSecretsRollbackFunc := RollbackFuncTest{} - configurationSecretRollbackFunc := RollbackFuncTest{} - compassConnectionRollbackFunc := RollbackFuncTest{} - deploymentRollbackFunc := RollbackFuncTest{} - - config := types.CompassRuntimeAgentConfig{ - ConnectorUrl: connectorURL, - RuntimeID: runtimeID, - Token: token, - Tenant: tenant, - } - - compassConfiguratorMock.On("Do", runtimeName, formationName).Return(config, compassConfiguratorRollbackFunc.Func(), nil) - certificateSecretConfiguratorMock.On("Do", NewCACertSecretName, NewClientCertSecretName).Return(certificateSecretsRollbackFunc.Func(), nil) - configurationSecretConfiguratorMock.On("Do", NewCompassRuntimeConfigName, config).Return(configurationSecretRollbackFunc.Func(), nil) - compassConnectionConfiguratorMock.On("Do").Return(compassConnectionRollbackFunc.Func(), errors.New("some error")) - deploymentConfiguratorMock.On("Do", - fmt.Sprintf("%s/%s", IstioSystemNamespace, NewCACertSecretName), - fmt.Sprintf("%s/%s", CompassSystemNamespace, NewClientCertSecretName), - fmt.Sprintf("%s/%s", CompassSystemNamespace, NewCompassRuntimeConfigName), - fmt.Sprintf("%s", NewControllerSyncPeriodTime)). - Return(deploymentRollbackFunc.Func(), nil) - - configurator := NewCompassRuntimeAgentConfigurator(compassConfiguratorMock, certificateSecretConfiguratorMock, configurationSecretConfiguratorMock, compassConnectionConfiguratorMock, deploymentConfiguratorMock, "tenant") - - // when - rollbackFunc, err := configurator.Do(runtimeName, formationName) - - // then - require.Error(t, err) - require.Nil(t, rollbackFunc) - certificateSecretConfiguratorMock.AssertExpectations(t) - compassConnectionConfiguratorMock.AssertExpectations(t) - deploymentConfiguratorMock.AssertExpectations(t) - require.True(t, compassConfiguratorRollbackFunc.invoked) - require.True(t, certificateSecretsRollbackFunc.invoked) - require.True(t, configurationSecretRollbackFunc.invoked) - //require.True(t, compassConnectionRollbackFunc.invoked) - require.True(t, deploymentRollbackFunc.invoked) - }) -} - -type RollbackFuncTest struct { - invoked bool -} - -func (rfc *RollbackFuncTest) Func() types.RollbackFunc { - return func() error { - rfc.invoked = true - return nil - } -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types/mocks/CertificateSecretConfigurator.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types/mocks/CertificateSecretConfigurator.go deleted file mode 100644 index 3130678bf447..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types/mocks/CertificateSecretConfigurator.go +++ /dev/null @@ -1,51 +0,0 @@ -// Code generated by mockery v2.15.0. DO NOT EDIT. - -package mocks - -import ( - types "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types" - mock "github.com/stretchr/testify/mock" -) - -// CertificateSecretConfigurator is an autogenerated mock type for the CertificateSecretConfigurator type -type CertificateSecretConfigurator struct { - mock.Mock -} - -// Do provides a mock function with given fields: caSecretName, clusterCertSecretName -func (_m *CertificateSecretConfigurator) Do(caSecretName string, clusterCertSecretName string) (types.RollbackFunc, error) { - ret := _m.Called(caSecretName, clusterCertSecretName) - - var r0 types.RollbackFunc - if rf, ok := ret.Get(0).(func(string, string) types.RollbackFunc); ok { - r0 = rf(caSecretName, clusterCertSecretName) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(types.RollbackFunc) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(string, string) error); ok { - r1 = rf(caSecretName, clusterCertSecretName) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -type mockConstructorTestingTNewCertificateSecretConfigurator interface { - mock.TestingT - Cleanup(func()) -} - -// NewCertificateSecretConfigurator creates a new instance of CertificateSecretConfigurator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewCertificateSecretConfigurator(t mockConstructorTestingTNewCertificateSecretConfigurator) *CertificateSecretConfigurator { - mock := &CertificateSecretConfigurator{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types/mocks/CompassConfigurator.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types/mocks/CompassConfigurator.go deleted file mode 100644 index aa11389aa32b..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types/mocks/CompassConfigurator.go +++ /dev/null @@ -1,58 +0,0 @@ -// Code generated by mockery v2.15.0. DO NOT EDIT. - -package mocks - -import ( - types "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types" - mock "github.com/stretchr/testify/mock" -) - -// CompassConfigurator is an autogenerated mock type for the CompassConfigurator type -type CompassConfigurator struct { - mock.Mock -} - -// Do provides a mock function with given fields: runtimeName, formationName -func (_m *CompassConfigurator) Do(runtimeName string, formationName string) (types.CompassRuntimeAgentConfig, types.RollbackFunc, error) { - ret := _m.Called(runtimeName, formationName) - - var r0 types.CompassRuntimeAgentConfig - if rf, ok := ret.Get(0).(func(string, string) types.CompassRuntimeAgentConfig); ok { - r0 = rf(runtimeName, formationName) - } else { - r0 = ret.Get(0).(types.CompassRuntimeAgentConfig) - } - - var r1 types.RollbackFunc - if rf, ok := ret.Get(1).(func(string, string) types.RollbackFunc); ok { - r1 = rf(runtimeName, formationName) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(types.RollbackFunc) - } - } - - var r2 error - if rf, ok := ret.Get(2).(func(string, string) error); ok { - r2 = rf(runtimeName, formationName) - } else { - r2 = ret.Error(2) - } - - return r0, r1, r2 -} - -type mockConstructorTestingTNewCompassConfigurator interface { - mock.TestingT - Cleanup(func()) -} - -// NewCompassConfigurator creates a new instance of CompassConfigurator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewCompassConfigurator(t mockConstructorTestingTNewCompassConfigurator) *CompassConfigurator { - mock := &CompassConfigurator{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types/mocks/CompassConnectionConfigurator.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types/mocks/CompassConnectionConfigurator.go deleted file mode 100644 index cea552f18088..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types/mocks/CompassConnectionConfigurator.go +++ /dev/null @@ -1,51 +0,0 @@ -// Code generated by mockery v2.15.0. DO NOT EDIT. - -package mocks - -import ( - types "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types" - mock "github.com/stretchr/testify/mock" -) - -// CompassConnectionConfigurator is an autogenerated mock type for the CompassConnectionConfigurator type -type CompassConnectionConfigurator struct { - mock.Mock -} - -// Do provides a mock function with given fields: -func (_m *CompassConnectionConfigurator) Do() (types.RollbackFunc, error) { - ret := _m.Called() - - var r0 types.RollbackFunc - if rf, ok := ret.Get(0).(func() types.RollbackFunc); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(types.RollbackFunc) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -type mockConstructorTestingTNewCompassConnectionConfigurator interface { - mock.TestingT - Cleanup(func()) -} - -// NewCompassConnectionConfigurator creates a new instance of CompassConnectionConfigurator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewCompassConnectionConfigurator(t mockConstructorTestingTNewCompassConnectionConfigurator) *CompassConnectionConfigurator { - mock := &CompassConnectionConfigurator{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types/mocks/ConfigurationSecretConfigurator.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types/mocks/ConfigurationSecretConfigurator.go deleted file mode 100644 index 33ae8a419aed..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types/mocks/ConfigurationSecretConfigurator.go +++ /dev/null @@ -1,51 +0,0 @@ -// Code generated by mockery v2.15.0. DO NOT EDIT. - -package mocks - -import ( - types "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types" - mock "github.com/stretchr/testify/mock" -) - -// ConfigurationSecretConfigurator is an autogenerated mock type for the ConfigurationSecretConfigurator type -type ConfigurationSecretConfigurator struct { - mock.Mock -} - -// Do provides a mock function with given fields: configurationSecretName, config -func (_m *ConfigurationSecretConfigurator) Do(configurationSecretName string, config types.CompassRuntimeAgentConfig) (types.RollbackFunc, error) { - ret := _m.Called(configurationSecretName, config) - - var r0 types.RollbackFunc - if rf, ok := ret.Get(0).(func(string, types.CompassRuntimeAgentConfig) types.RollbackFunc); ok { - r0 = rf(configurationSecretName, config) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(types.RollbackFunc) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(string, types.CompassRuntimeAgentConfig) error); ok { - r1 = rf(configurationSecretName, config) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -type mockConstructorTestingTNewConfigurationSecretConfigurator interface { - mock.TestingT - Cleanup(func()) -} - -// NewConfigurationSecretConfigurator creates a new instance of ConfigurationSecretConfigurator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewConfigurationSecretConfigurator(t mockConstructorTestingTNewConfigurationSecretConfigurator) *ConfigurationSecretConfigurator { - mock := &ConfigurationSecretConfigurator{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types/mocks/DeploymentConfigurator.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types/mocks/DeploymentConfigurator.go deleted file mode 100644 index f49a52b21854..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types/mocks/DeploymentConfigurator.go +++ /dev/null @@ -1,54 +0,0 @@ -// Code generated by mockery v2.22.1. DO NOT EDIT. - -package mocks - -import ( - types "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types" - mock "github.com/stretchr/testify/mock" -) - -// DeploymentConfigurator is an autogenerated mock type for the DeploymentConfigurator type -type DeploymentConfigurator struct { - mock.Mock -} - -// Do provides a mock function with given fields: caSecretName, clusterCertSecretName, runtimeAgentConfigSecretName, controllerSyncPeriodTime -func (_m *DeploymentConfigurator) Do(caSecretName string, clusterCertSecretName string, runtimeAgentConfigSecretName string, controllerSyncPeriodTime string) (types.RollbackFunc, error) { - ret := _m.Called(caSecretName, clusterCertSecretName, runtimeAgentConfigSecretName, controllerSyncPeriodTime) - - var r0 types.RollbackFunc - var r1 error - if rf, ok := ret.Get(0).(func(string, string, string, string) (types.RollbackFunc, error)); ok { - return rf(caSecretName, clusterCertSecretName, runtimeAgentConfigSecretName, controllerSyncPeriodTime) - } - if rf, ok := ret.Get(0).(func(string, string, string, string) types.RollbackFunc); ok { - r0 = rf(caSecretName, clusterCertSecretName, runtimeAgentConfigSecretName, controllerSyncPeriodTime) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(types.RollbackFunc) - } - } - - if rf, ok := ret.Get(1).(func(string, string, string, string) error); ok { - r1 = rf(caSecretName, clusterCertSecretName, runtimeAgentConfigSecretName, controllerSyncPeriodTime) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -type mockConstructorTestingTNewDeploymentConfigurator interface { - mock.TestingT - Cleanup(func()) -} - -// NewDeploymentConfigurator creates a new instance of DeploymentConfigurator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewDeploymentConfigurator(t mockConstructorTestingTNewDeploymentConfigurator) *DeploymentConfigurator { - mock := &DeploymentConfigurator{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types/mocks/DirectorClient.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types/mocks/DirectorClient.go deleted file mode 100644 index da03b2b68c30..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types/mocks/DirectorClient.go +++ /dev/null @@ -1,130 +0,0 @@ -// Code generated by mockery v2.15.0. DO NOT EDIT. - -package mocks - -import mock "github.com/stretchr/testify/mock" - -// DirectorClient is an autogenerated mock type for the DirectorClient type -type DirectorClient struct { - mock.Mock -} - -// AssignRuntimeToFormation provides a mock function with given fields: runtimeId, formationName -func (_m *DirectorClient) AssignRuntimeToFormation(runtimeId string, formationName string) error { - ret := _m.Called(runtimeId, formationName) - - var r0 error - if rf, ok := ret.Get(0).(func(string, string) error); ok { - r0 = rf(runtimeId, formationName) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// GetConnectionToken provides a mock function with given fields: runtimeID -func (_m *DirectorClient) GetConnectionToken(runtimeID string) (string, string, error) { - ret := _m.Called(runtimeID) - - var r0 string - if rf, ok := ret.Get(0).(func(string) string); ok { - r0 = rf(runtimeID) - } else { - r0 = ret.Get(0).(string) - } - - var r1 string - if rf, ok := ret.Get(1).(func(string) string); ok { - r1 = rf(runtimeID) - } else { - r1 = ret.Get(1).(string) - } - - var r2 error - if rf, ok := ret.Get(2).(func(string) error); ok { - r2 = rf(runtimeID) - } else { - r2 = ret.Error(2) - } - - return r0, r1, r2 -} - -// RegisterFormation provides a mock function with given fields: formationName -func (_m *DirectorClient) RegisterFormation(formationName string) error { - ret := _m.Called(formationName) - - var r0 error - if rf, ok := ret.Get(0).(func(string) error); ok { - r0 = rf(formationName) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// RegisterRuntime provides a mock function with given fields: runtimeName -func (_m *DirectorClient) RegisterRuntime(runtimeName string) (string, error) { - ret := _m.Called(runtimeName) - - var r0 string - if rf, ok := ret.Get(0).(func(string) string); ok { - r0 = rf(runtimeName) - } else { - r0 = ret.Get(0).(string) - } - - var r1 error - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(runtimeName) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// UnregisterFormation provides a mock function with given fields: formationName -func (_m *DirectorClient) UnregisterFormation(formationName string) error { - ret := _m.Called(formationName) - - var r0 error - if rf, ok := ret.Get(0).(func(string) error); ok { - r0 = rf(formationName) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// UnregisterRuntime provides a mock function with given fields: id -func (_m *DirectorClient) UnregisterRuntime(id string) error { - ret := _m.Called(id) - - var r0 error - if rf, ok := ret.Get(0).(func(string) error); ok { - r0 = rf(id) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -type mockConstructorTestingTNewDirectorClient interface { - mock.TestingT - Cleanup(func()) -} - -// NewDirectorClient creates a new instance of DirectorClient. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewDirectorClient(t mockConstructorTestingTNewDirectorClient) *DirectorClient { - mock := &DirectorClient{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types/types.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types/types.go deleted file mode 100644 index c657ad619a0d..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/init/types/types.go +++ /dev/null @@ -1,45 +0,0 @@ -package types - -type CompassRuntimeAgentConfig struct { - ConnectorUrl string - RuntimeID string - Token string - Tenant string -} - -type RollbackFunc func() error - -//go:generate mockery --name=DirectorClient -type DirectorClient interface { - RegisterRuntime(runtimeName string) (string, error) - RegisterFormation(formationName string) error - AssignRuntimeToFormation(runtimeId, formationName string) error - UnregisterRuntime(id string) error - UnregisterFormation(formationName string) error - GetConnectionToken(runtimeID string) (string, string, error) -} - -//go:generate mockery --name=CompassConfigurator -type CompassConfigurator interface { - Do(runtimeName, formationName string) (CompassRuntimeAgentConfig, RollbackFunc, error) -} - -//go:generate mockery --name=DeploymentConfigurator -type DeploymentConfigurator interface { - Do(caSecretName, clusterCertSecretName, runtimeAgentConfigSecretName, controllerSyncPeriodTime string) (RollbackFunc, error) -} - -//go:generate mockery --name=CertificateSecretConfigurator -type CertificateSecretConfigurator interface { - Do(caSecretName, clusterCertSecretName string) (RollbackFunc, error) -} - -//go:generate mockery --name=ConfigurationSecretConfigurator -type ConfigurationSecretConfigurator interface { - Do(configurationSecretName string, config CompassRuntimeAgentConfig) (RollbackFunc, error) -} - -//go:generate mockery --name=CompassConnectionConfigurator -type CompassConnectionConfigurator interface { - Do() (RollbackFunc, error) -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/oauth/client.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/oauth/client.go deleted file mode 100644 index 51d0e8f39d7d..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/oauth/client.go +++ /dev/null @@ -1,119 +0,0 @@ -package oauth - -import ( - "context" - "encoding/json" - "fmt" - "github.com/pkg/errors" - log "github.com/sirupsen/logrus" - "io/ioutil" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - v1 "k8s.io/client-go/kubernetes/typed/core/v1" - "net/http" - "net/http/httputil" - "net/url" - "strings" - "time" -) - -//go:generate mockery --name=Client -type Client interface { - GetAuthorizationToken() (Token, error) -} - -type oauthClient struct { - httpClient *http.Client - secretsClient v1.SecretInterface - secretName string -} - -func NewOauthClient(client *http.Client, secrets v1.SecretInterface, secretName string) (Client, error) { - - _, err := secrets.Get(context.Background(), secretName, metav1.GetOptions{}) - - if err != nil { - return nil, fmt.Errorf("Cound not access oauthCredential secret %s", secretName) - } - - return &oauthClient{ - httpClient: client, - secretsClient: secrets, - secretName: secretName, - }, nil -} - -func (c *oauthClient) GetAuthorizationToken() (Token, error) { - credentials, err := c.getCredentials() - - if err != nil { - return Token{}, err - } - - return c.getAuthorizationToken(credentials) -} - -func (c *oauthClient) getCredentials() (credentials, error) { - secret, err := c.secretsClient.Get(context.Background(), c.secretName, metav1.GetOptions{}) - - if err != nil { - return credentials{}, err - } - - return credentials{ - clientID: string(secret.Data[clientIDKey]), - clientSecret: string(secret.Data[clientSecretKey]), - tokensEndpoint: string(secret.Data[tokensEndpointKey]), - }, nil -} - -func (c *oauthClient) getAuthorizationToken(credentials credentials) (Token, error) { - log.Infof("Getting authorisation token for credentials to access Director from endpoint: %s", credentials.tokensEndpoint) - - form := url.Values{} - form.Add(grantTypeFieldName, credentialsGrantType) - form.Add(scopeFieldName, scopes) - - request, err := http.NewRequest(http.MethodPost, credentials.tokensEndpoint, strings.NewReader(form.Encode())) - if err != nil { - log.Errorf("Failed to create authorisation token request") - return Token{}, errors.Wrap(err, "Failed to create authorisation token request") - } - - now := time.Now().Unix() - - request.SetBasicAuth(credentials.clientID, credentials.clientSecret) - request.Header.Set(contentTypeHeader, contentTypeApplicationURLEncoded) - - response, err := c.httpClient.Do(request) - if err != nil { - return Token{}, errors.Wrap(err, "Failed to execute http call") - } - - defer response.Body.Close() - - if response.StatusCode != http.StatusOK { - dump, err := httputil.DumpResponse(response, true) - if err != nil { - dump = []byte("failed to dump response body") - } - return Token{}, fmt.Errorf("Get token call returned unexpected status: %s. Response dump: %s", response.Status, string(dump)) - } - - body, err := ioutil.ReadAll(response.Body) - if err != nil { - return Token{}, fmt.Errorf("Failed to read token response body from '%s': %s", credentials.tokensEndpoint, err.Error()) - } - - tokenResponse := Token{} - - err = json.Unmarshal(body, &tokenResponse) - if err != nil { - return Token{}, fmt.Errorf("failed to unmarshal token response body: %s", err.Error()) - } - - log.Infof("Successfully unmarshal response oauth token for accessing Director") - - tokenResponse.Expiration += now - - return tokenResponse, nil -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/oauth/client_test.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/oauth/client_test.go deleted file mode 100644 index 5bfdb5f29de9..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/oauth/client_test.go +++ /dev/null @@ -1,109 +0,0 @@ -package oauth - -import ( - "bytes" - "context" - "encoding/json" - "io/ioutil" - "net/http" - "testing" - "time" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - v1 "k8s.io/api/core/v1" - meta "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/client-go/kubernetes/fake" - core "k8s.io/client-go/kubernetes/typed/core/v1" -) - -const ( - namespace = "test" - secretName = "oauth-compass-credentials" -) - -func TestOauthClient_GetAuthorizationToken(t *testing.T) { - t.Run("Should return oauth token", func(t *testing.T) { - //given - credentials := credentials{ - clientID: "12345", - clientSecret: "some dark and scary secret", - tokensEndpoint: "http://hydra:4445", - } - - token := Token{ - AccessToken: "12345", - Expiration: 1234, - } - - client := NewTestClient(func(req *http.Request) *http.Response { - username, secret, ok := req.BasicAuth() - - if ok && username == credentials.clientID && secret == credentials.clientSecret { - jsonToken, err := json.Marshal(&token) - - require.NoError(t, err) - - return &http.Response{ - StatusCode: http.StatusOK, - Body: ioutil.NopCloser(bytes.NewReader(jsonToken)), - } - } - return &http.Response{ - StatusCode: http.StatusForbidden, - } - }) - - coreV1 := fake.NewSimpleClientset() - secrets := coreV1.CoreV1().Secrets(namespace) - - createFakeCredentialsSecret(t, secrets, credentials) - - oauthClient, err := NewOauthClient(client, secrets, secretName) - require.NoError(t, err) - - //when - responseToken, err := oauthClient.GetAuthorizationToken() - require.NoError(t, err) - token.Expiration += time.Now().Unix() - - //then - assert.Equal(t, token.AccessToken, responseToken.AccessToken) - assert.Equal(t, token.Expiration, responseToken.Expiration) - }) -} - -func NewTestClient(fn RoundTripFunc) *http.Client { - return &http.Client{ - Transport: fn, - } -} - -type RoundTripFunc func(req *http.Request) *http.Response - -func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { - return f(req), nil -} - -func createFakeCredentialsSecret(t *testing.T, secrets core.SecretInterface, credentials credentials) { - - secret := &v1.Secret{ - ObjectMeta: meta.ObjectMeta{ - Name: secretName, - Namespace: namespace, - }, - TypeMeta: meta.TypeMeta{ - Kind: "Secret", - APIVersion: "v1", - }, - Data: map[string][]byte{ - clientIDKey: []byte(credentials.clientID), - clientSecretKey: []byte(credentials.clientSecret), - tokensEndpointKey: []byte(credentials.tokensEndpoint), - }, - } - - _, err := secrets.Create(context.Background(), secret, meta.CreateOptions{}) - - require.NoError(t, err) -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/oauth/mocks/Client.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/oauth/mocks/Client.go deleted file mode 100644 index 3a3579034e05..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/oauth/mocks/Client.go +++ /dev/null @@ -1,49 +0,0 @@ -// Code generated by mockery v2.15.0. DO NOT EDIT. - -package mocks - -import ( - oauth "github.com/kyma-project/kyma/tests/components/application-connector/test/compass-runtime-agent/testkit/oauth" - mock "github.com/stretchr/testify/mock" -) - -// Client is an autogenerated mock type for the Client type -type Client struct { - mock.Mock -} - -// GetAuthorizationToken provides a mock function with given fields: -func (_m *Client) GetAuthorizationToken() (oauth.Token, error) { - ret := _m.Called() - - var r0 oauth.Token - if rf, ok := ret.Get(0).(func() oauth.Token); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(oauth.Token) - } - - var r1 error - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -type mockConstructorTestingTNewClient interface { - mock.TestingT - Cleanup(func()) -} - -// NewClient creates a new instance of Client. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewClient(t mockConstructorTestingTNewClient) *Client { - mock := &Client{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/oauth/types.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/oauth/types.go deleted file mode 100644 index 86fc07c2cc28..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/oauth/types.go +++ /dev/null @@ -1,38 +0,0 @@ -package oauth - -import "time" - -const ( - contentTypeHeader = "Content-Type" - contentTypeApplicationURLEncoded = "application/x-www-form-urlencoded" - - grantTypeFieldName = "grant_type" - credentialsGrantType = "client_credentials" - - scopeFieldName = "scope" - scopes = "application:read application:write formation:write runtime:read runtime:write" - - clientIDKey = "client_id" - clientSecretKey = "client_secret" - tokensEndpointKey = "tokens_endpoint" -) - -type Token struct { - AccessToken string `json:"access_token"` - Expiration int64 `json:"expires_in"` -} - -type credentials struct { - clientID string - clientSecret string - tokensEndpoint string -} - -func (token Token) EmptyOrExpired() bool { - if token.AccessToken == "" { - return true - } - - expiration := time.Unix(token.Expiration, 0) - return time.Now().After(expiration) -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/oauth/types_test.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/oauth/types_test.go deleted file mode 100644 index e1f8b0f76aeb..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/oauth/types_test.go +++ /dev/null @@ -1,53 +0,0 @@ -package oauth - -import ( - "testing" - "time" - - "github.com/stretchr/testify/assert" -) - -func TestToken_EmptyOrExpired(t *testing.T) { - t.Run("Should return true when token is empty", func(t *testing.T) { - //given - token := Token{} - - //when - empty := token.EmptyOrExpired() - - //then - assert.True(t, empty) - }) - - t.Run("Should return true when expired", func(t *testing.T) { - //given - time2000 := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC).Unix() - - token := Token{ - AccessToken: "token", - Expiration: time2000, - } - - //when - expired := token.EmptyOrExpired() - - //then - assert.True(t, expired) - }) - - t.Run("Should return false when not empty or expired", func(t *testing.T) { - //given - time3000 := time.Date(3000, 1, 1, 0, 0, 0, 0, time.UTC).Unix() - - token := Token{ - AccessToken: "token", - Expiration: time3000, - } - - //when - notExpired := token.EmptyOrExpired() - - //then - assert.False(t, notExpired) - }) -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/random/randomstring.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/random/randomstring.go deleted file mode 100644 index 7fbb0075bf81..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/random/randomstring.go +++ /dev/null @@ -1,25 +0,0 @@ -package random - -import ( - "math/rand" - "strings" - "time" -) - -const charset = "abcdefghijklmnopqrstuvwxyz" + - "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" - -var seededRand *rand.Rand = rand.New( - rand.NewSource(time.Now().UnixNano())) - -func StringWithCharset(length int, charset string) string { - b := make([]byte, length) - for i := range b { - b[i] = charset[seededRand.Intn(len(charset))] - } - return string(b) -} - -func RandomString(length int) string { - return strings.ToLower(StringWithCharset(length, charset)) -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/third_party/machinebox/graphql/LICENSE b/tests/components/application-connector/test/compass-runtime-agent/testkit/third_party/machinebox/graphql/LICENSE deleted file mode 100644 index 9b0dfaa85e35..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/third_party/machinebox/graphql/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright 2017 Machine Box, Ltd. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/third_party/machinebox/graphql/README.md b/tests/components/application-connector/test/compass-runtime-agent/testkit/third_party/machinebox/graphql/README.md deleted file mode 100644 index fabd7c8ec2f5..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/third_party/machinebox/graphql/README.md +++ /dev/null @@ -1,67 +0,0 @@ -# graphql [![GoDoc](https://godoc.org/github.com/machinebox/graphql?status.png)](http://godoc.org/github.com/machinebox/graphql) [![Build Status](https://travis-ci.org/machinebox/graphql.svg?branch=master)](https://travis-ci.org/machinebox/graphql) [![Go Report Card](https://goreportcard.com/badge/github.com/machinebox/graphql)](https://goreportcard.com/report/github.com/machinebox/graphql) - -Low-level GraphQL client for Go. - -* Simple, familiar API -* Respects `context.Context` timeouts and cancellation -* Build and execute any kind of GraphQL request -* Use strong Go types for response data -* Use variables and upload files -* Simple error handling - -## Installation -Make sure you have a working Go environment. To install graphql, simply run: - -``` -$ go get github.com/machinebox/graphql -``` - -## Usage - -```go -import "context" - -// create a client (safe to share across requests) -client := graphql.NewClient("https://machinebox.io/graphql") - -// make a request -req := graphql.NewRequest(` - query ($key: String!) { - items (id:$key) { - field1 - field2 - field3 - } - } -`) - -// set any variables -req.Var("key", "value") - -// set header fields -req.Header.Set("Cache-Control", "no-cache") - -// define a Context for the request -ctx := context.Background() - -// run it and capture the response -var respData ResponseStruct -if err := client.Run(ctx, req, &respData); err != nil { - log.Fatal(err) -} -``` - -### File Support via Multipart Form Data - -By default, the package will send a JSON body. To enable the sending of files, you can opt to -use multipart form data instead using the `UseMultipartForm` option when you create your `Client`: - -``` -client := graphql.NewClient("https://machinebox.io/graphql", graphql.UseMultipartForm()) -``` - -For more information, [read the godoc package documentation](http://godoc.org/github.com/machinebox/graphql). - -## Thanks - -Thanks to [Chris Broadfoot](https://github.com/broady) for design help. diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/third_party/machinebox/graphql/graphql.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/third_party/machinebox/graphql/graphql.go deleted file mode 100644 index dc005dad5a19..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/third_party/machinebox/graphql/graphql.go +++ /dev/null @@ -1,354 +0,0 @@ -// Package graphql provides a low level GraphQL client. -// -// // create a client (safe to share across requests) -// client := graphql.NewClient("https://machinebox.io/graphql") -// -// // make a request -// req := graphql.NewRequest(` -// query ($key: String!) { -// items (id:$key) { -// field1 -// field2 -// field3 -// } -// } -// `) -// -// // set any variables -// req.Var("key", "value") -// -// // run it and capture the response -// var respData ResponseStruct -// if err := client.Run(ctx, req, &respData); err != nil { -// log.Fatal(err) -// } -// -// Specify client -// -// To specify your own http.Client, use the WithHTTPClient option: -// httpclient := &http.Client{} -// client := graphql.NewClient("https://machinebox.io/graphql", graphql.WithHTTPClient(httpclient)) -package graphql - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "mime/multipart" - "net/http" - "strings" - "unicode/utf8" - - "github.com/pkg/errors" -) - -// Client is a client for interacting with a GraphQL API. -type Client struct { - endpoint string - httpClient *http.Client - useMultipartForm bool - - // closeReq will close the request body immediately allowing for reuse of client - closeReq bool - - // Log is called with various debug information. - // To log to standard out, use: - // client.Log = func(s string) { log.Println(s) } - Log func(s string) -} - -// NewClient makes a new Client capable of making GraphQL requests. -func NewClient(endpoint string, opts ...ClientOption) *Client { - c := &Client{ - endpoint: endpoint, - Log: func(string) {}, - } - for _, optionFunc := range opts { - optionFunc(c) - } - if c.httpClient == nil { - c.httpClient = http.DefaultClient - } - return c -} - -func (c *Client) logf(format string, args ...interface{}) { - c.Log(fmt.Sprintf(format, args...)) -} - -// Run executes the query and unmarshals the response from the data field -// into the response object. -// Pass in a nil response object to skip response parsing. -// If the request fails or the server returns an error, the first error -// will be returned. -func (c *Client) Run(ctx context.Context, req *Request, resp interface{}) error { - select { - case <-ctx.Done(): - return ctx.Err() - default: - } - if len(req.files) > 0 && !c.useMultipartForm { - return errors.New("cannot send files with PostFields option") - } - if c.useMultipartForm { - return c.runWithPostFields(ctx, req, resp) - } - return c.runWithJSON(ctx, req, resp) -} - -func (c *Client) runWithJSON(ctx context.Context, req *Request, resp interface{}) error { - var requestBody bytes.Buffer - requestBodyObj := struct { - Query string `json:"query"` - Variables map[string]interface{} `json:"variables"` - }{ - Query: req.q, - Variables: req.vars, - } - if err := json.NewEncoder(&requestBody).Encode(requestBodyObj); err != nil { - return errors.Wrap(err, "encode body") - } - c.logf(">> variables: %v", req.vars) - c.logf(">> query: %s", req.q) - gr := &graphResponse{ - Data: resp, - } - r, err := http.NewRequest(http.MethodPost, c.endpoint, &requestBody) - if err != nil { - return err - } - r.Close = c.closeReq - r.Header.Set("Content-Type", "application/json; charset=utf-8") - r.Header.Set("Accept", "application/json; charset=utf-8") - for key, values := range req.Header { - for _, value := range values { - r.Header.Add(key, value) - } - } - c.logf(">> headers: %v", hideHeaders(r.Header)) - r = r.WithContext(ctx) - res, err := c.httpClient.Do(r) - if err != nil { - return err - } - defer res.Body.Close() - var buf bytes.Buffer - if _, err := io.Copy(&buf, res.Body); err != nil { - return errors.Wrap(err, "reading body") - } - c.logf("<< %s", buf.String()) - if err := json.NewDecoder(&buf).Decode(&gr); err != nil { - if res.StatusCode != http.StatusOK { - return fmt.Errorf("graphql: server returned a non-200 status code: %v", res.StatusCode) - } - return errors.Wrap(err, "decoding response") - } - if len(gr.Errors) > 0 { - // return first error - return gr.Errors[0] - } - return nil -} - -func (c *Client) runWithPostFields(ctx context.Context, req *Request, resp interface{}) error { - var requestBody bytes.Buffer - writer := multipart.NewWriter(&requestBody) - if err := writer.WriteField("query", req.q); err != nil { - return errors.Wrap(err, "write query field") - } - var variablesBuf bytes.Buffer - if len(req.vars) > 0 { - variablesField, err := writer.CreateFormField("variables") - if err != nil { - return errors.Wrap(err, "create variables field") - } - if err := json.NewEncoder(io.MultiWriter(variablesField, &variablesBuf)).Encode(req.vars); err != nil { - return errors.Wrap(err, "encode variables") - } - } - for i := range req.files { - part, err := writer.CreateFormFile(req.files[i].Field, req.files[i].Name) - if err != nil { - return errors.Wrap(err, "create form file") - } - if _, err := io.Copy(part, req.files[i].R); err != nil { - return errors.Wrap(err, "preparing file") - } - } - if err := writer.Close(); err != nil { - return errors.Wrap(err, "close writer") - } - c.logf(">> variables: %s", variablesBuf.String()) - c.logf(">> files: %d", len(req.files)) - c.logf(">> query: %s", req.q) - gr := &graphResponse{ - Data: resp, - } - r, err := http.NewRequest(http.MethodPost, c.endpoint, &requestBody) - if err != nil { - return err - } - r.Close = c.closeReq - r.Header.Set("Content-Type", writer.FormDataContentType()) - r.Header.Set("Accept", "application/json; charset=utf-8") - for key, values := range req.Header { - for _, value := range values { - r.Header.Add(key, value) - } - } - c.logf(">> headers: %v", hideHeaders(r.Header)) - r = r.WithContext(ctx) - res, err := c.httpClient.Do(r) - if err != nil { - return err - } - defer res.Body.Close() - var buf bytes.Buffer - if _, err := io.Copy(&buf, res.Body); err != nil { - return errors.Wrap(err, "reading body") - } - c.logf("<< %s", buf.String()) - if err := json.NewDecoder(&buf).Decode(&gr); err != nil { - if res.StatusCode != http.StatusOK { - return fmt.Errorf("graphql: server returned a non-200 status code: %v", res.StatusCode) - } - return errors.Wrap(err, "decoding response") - } - if len(gr.Errors) > 0 { - // return first error - return gr.Errors[0] - } - return nil -} - -// WithHTTPClient specifies the underlying http.Client to use when -// making requests. -// NewClient(endpoint, WithHTTPClient(specificHTTPClient)) -func WithHTTPClient(httpclient *http.Client) ClientOption { - return func(client *Client) { - client.httpClient = httpclient - } -} - -// UseMultipartForm uses multipart/form-data and activates support for -// files. -func UseMultipartForm() ClientOption { - return func(client *Client) { - client.useMultipartForm = true - } -} - -// ImmediatelyCloseReqBody will close the req body immediately after each request body is ready -func ImmediatelyCloseReqBody() ClientOption { - return func(client *Client) { - client.closeReq = true - } -} - -// ClientOption are functions that are passed into NewClient to -// modify the behaviour of the Client. -type ClientOption func(*Client) - -type ExtendedError interface { - Error() string - Extensions() map[string]interface{} -} - -type graphErr struct { - Message string `json:"message,omitempty"` - ErrorExtensions map[string]interface{} `json:"extensions,omitempty"` -} - -func (e graphErr) Error() string { - return "graphql: " + e.Message -} - -func (e graphErr) Extensions() map[string]interface{} { - return e.ErrorExtensions -} - -type graphResponse struct { - Data interface{} - Errors []graphErr -} - -// Request is a GraphQL request. -type Request struct { - q string - vars map[string]interface{} - files []File - - // Header represent any request headers that will be set - // when the request is made. - Header http.Header -} - -// NewRequest makes a new Request with the specified string. -func NewRequest(q string) *Request { - req := &Request{ - q: q, - Header: make(map[string][]string), - } - return req -} - -// Var sets a variable. -func (req *Request) Var(key string, value interface{}) { - if req.vars == nil { - req.vars = make(map[string]interface{}) - } - req.vars[key] = value -} - -// Vars gets the variables for this Request. -func (req *Request) Vars() map[string]interface{} { - return req.vars -} - -// Files gets the files in this request. -func (req *Request) Files() []File { - return req.files -} - -// Query gets the query string of this request. -func (req *Request) Query() string { - return req.q -} - -// File sets a file to upload. -// Files are only supported with a Client that was created with -// the UseMultipartForm option. -func (req *Request) File(fieldname, filename string, r io.Reader) { - req.files = append(req.files, File{ - Field: fieldname, - Name: filename, - R: r, - }) -} - -// File represents a file to upload. -type File struct { - Field string - Name string - R io.Reader -} - -// hideHeaders creates a copy of headers -// with specified fields censored (eg 'password' -> '********') -// Additionally by default censors: -// - Authorization -func hideHeaders(headers http.Header, toHide ...string) http.Header { - toHide = append(toHide, "Authorization") - hs := headers.Clone() - for _, h := range toHide { - v, ok := hs[h] - if ok { - for i := range v { - hs[h][i] = strings.Repeat("*", utf8.RuneCountInString(v[i])) - } - } - } - return hs -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/third_party/machinebox/graphql/graphql_json_test.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/third_party/machinebox/graphql/graphql_json_test.go deleted file mode 100644 index f2a9b23e9ad3..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/third_party/machinebox/graphql/graphql_json_test.go +++ /dev/null @@ -1,233 +0,0 @@ -package graphql - -import ( - "bytes" - "context" - "io" - "io/ioutil" - "net/http" - "net/http/httptest" - "strings" - "testing" - "time" - - "github.com/matryer/is" -) - -func TestDoJSON(t *testing.T) { - is := is.New(t) - var calls int - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - calls++ - is.Equal(r.Method, http.MethodPost) - b, err := ioutil.ReadAll(r.Body) - is.NoErr(err) - is.Equal(string(b), `{"query":"query {}","variables":null}`+"\n") - io.WriteString(w, `{ - "data": { - "something": "yes" - } - }`) - })) - defer srv.Close() - - ctx := context.Background() - client := NewClient(srv.URL) - - ctx, cancel := context.WithTimeout(ctx, 1*time.Second) - defer cancel() - var responseData map[string]interface{} - err := client.Run(ctx, &Request{q: "query {}"}, &responseData) - is.NoErr(err) - is.Equal(calls, 1) // calls - is.Equal(responseData["something"], "yes") -} - -func TestDoJSONServerError(t *testing.T) { - is := is.New(t) - var calls int - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - calls++ - is.Equal(r.Method, http.MethodPost) - b, err := ioutil.ReadAll(r.Body) - is.NoErr(err) - is.Equal(string(b), `{"query":"query {}","variables":null}`+"\n") - w.WriteHeader(http.StatusInternalServerError) - io.WriteString(w, `Internal Server Error`) - })) - defer srv.Close() - - ctx := context.Background() - client := NewClient(srv.URL) - - ctx, cancel := context.WithTimeout(ctx, 1*time.Second) - defer cancel() - var responseData map[string]interface{} - err := client.Run(ctx, &Request{q: "query {}"}, &responseData) - is.Equal(calls, 1) // calls - is.Equal(err.Error(), "graphql: server returned a non-200 status code: 500") -} - -func TestDoJSONBadRequestErr(t *testing.T) { - is := is.New(t) - var calls int - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - calls++ - is.Equal(r.Method, http.MethodPost) - b, err := ioutil.ReadAll(r.Body) - is.NoErr(err) - is.Equal(string(b), `{"query":"query {}","variables":null}`+"\n") - w.WriteHeader(http.StatusBadRequest) - io.WriteString(w, `{ - "errors": [{ - "message": "miscellaneous message as to why the the request was bad" - }] - }`) - })) - defer srv.Close() - - ctx := context.Background() - client := NewClient(srv.URL) - - ctx, cancel := context.WithTimeout(ctx, 1*time.Second) - defer cancel() - var responseData map[string]interface{} - err := client.Run(ctx, &Request{q: "query {}"}, &responseData) - is.Equal(calls, 1) // calls - is.Equal(err.Error(), "graphql: miscellaneous message as to why the the request was bad") -} - -func TestDoJSONErrWithExtensions(t *testing.T) { - is := is.New(t) - var calls int - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - calls++ - is.Equal(r.Method, http.MethodPost) - b, err := ioutil.ReadAll(r.Body) - is.NoErr(err) - is.Equal(string(b), `{"query":"query {}","variables":null}`+"\n") - w.WriteHeader(http.StatusOK) - io.WriteString(w, `{ - "errors": [{ - "message": "miscellaneous message as to why the the request was bad", - "extensions": { - "code": "400" - } - }] - }`) - })) - defer srv.Close() - - ctx := context.Background() - client := NewClient(srv.URL) - - ctx, cancel := context.WithTimeout(ctx, 1*time.Second) - defer cancel() - var responseData map[string]interface{} - err := client.Run(ctx, &Request{q: "query {}"}, &responseData) - is.Equal(calls, 1) // calls - is.Equal(err.Error(), "graphql: miscellaneous message as to why the the request was bad") - is.Equal(err.(ExtendedError).Extensions()["code"], "400") -} - -func TestQueryJSON(t *testing.T) { - is := is.New(t) - - var calls int - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - calls++ - b, err := ioutil.ReadAll(r.Body) - is.NoErr(err) - is.Equal(string(b), `{"query":"query {}","variables":{"username":"matryer"}}`+"\n") - _, err = io.WriteString(w, `{"data":{"value":"some data"}}`) - is.NoErr(err) - })) - defer srv.Close() - ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) - defer cancel() - - client := NewClient(srv.URL) - - req := NewRequest("query {}") - req.Var("username", "matryer") - - // check variables - is.True(req != nil) - is.Equal(req.vars["username"], "matryer") - - var resp struct { - Value string - } - err := client.Run(ctx, req, &resp) - is.NoErr(err) - is.Equal(calls, 1) - - is.Equal(resp.Value, "some data") -} - -func TestHeader(t *testing.T) { - is := is.New(t) - - var calls int - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - calls++ - is.Equal(r.Header.Get("X-Custom-Header"), "123") - - _, err := io.WriteString(w, `{"data":{"value":"some data"}}`) - is.NoErr(err) - })) - defer srv.Close() - ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) - defer cancel() - - client := NewClient(srv.URL) - - req := NewRequest("query {}") - req.Header.Set("X-Custom-Header", "123") - - var resp struct { - Value string - } - err := client.Run(ctx, req, &resp) - is.NoErr(err) - is.Equal(calls, 1) - - is.Equal(resp.Value, "some data") -} - -func TestHideAuthInJSON(t *testing.T) { - is := is.New(t) - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, `{ - "data": { - "something": "yes" - } - }`) - })) - defer srv.Close() - - ctx := context.Background() - client := NewClient(srv.URL) - - var cout bytes.Buffer - client.Log = func(s string) { - _, err := cout.WriteString(s) - is.NoErr(err) - } - - ctx, cancel := context.WithTimeout(ctx, 1*time.Second) - defer cancel() - var responseData map[string]interface{} - - header := make(http.Header) - header["Authorization"] = []string{"some secret key", "another secret key"} - req := Request{ - q: "query {}", - Header: header, - } - - err := client.Run(ctx, &req, &responseData) - is.NoErr(err) - is.Equal(responseData["something"], "yes") - is.True(!strings.Contains(cout.String(), "secret key")) -} diff --git a/tests/components/application-connector/test/compass-runtime-agent/testkit/third_party/machinebox/graphql/graphql_multipart_test.go b/tests/components/application-connector/test/compass-runtime-agent/testkit/third_party/machinebox/graphql/graphql_multipart_test.go deleted file mode 100644 index 4bf3fb8ced67..000000000000 --- a/tests/components/application-connector/test/compass-runtime-agent/testkit/third_party/machinebox/graphql/graphql_multipart_test.go +++ /dev/null @@ -1,302 +0,0 @@ -package graphql - -import ( - "bytes" - "context" - "io" - "io/ioutil" - "net/http" - "net/http/httptest" - "strings" - "testing" - "time" - - "github.com/matryer/is" -) - -func TestWithClient(t *testing.T) { - is := is.New(t) - var calls int - testClient := &http.Client{ - Transport: roundTripperFunc(func(req *http.Request) (*http.Response, error) { - calls++ - resp := &http.Response{ - Body: ioutil.NopCloser(strings.NewReader(`{"data":{"key":"value"}}`)), - } - return resp, nil - }), - } - - ctx := context.Background() - client := NewClient("", WithHTTPClient(testClient), UseMultipartForm()) - - req := NewRequest(``) - client.Run(ctx, req, nil) - - is.Equal(calls, 1) // calls -} - -func TestDoUseMultipartForm(t *testing.T) { - is := is.New(t) - var calls int - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - calls++ - is.Equal(r.Method, http.MethodPost) - query := r.FormValue("query") - is.Equal(query, `query {}`) - io.WriteString(w, `{ - "data": { - "something": "yes" - } - }`) - })) - defer srv.Close() - - ctx := context.Background() - client := NewClient(srv.URL, UseMultipartForm()) - - ctx, cancel := context.WithTimeout(ctx, 1*time.Second) - defer cancel() - var responseData map[string]interface{} - err := client.Run(ctx, &Request{q: "query {}"}, &responseData) - is.NoErr(err) - is.Equal(calls, 1) // calls - is.Equal(responseData["something"], "yes") -} - -func TestImmediatelyCloseReqBody(t *testing.T) { - is := is.New(t) - var calls int - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - calls++ - is.Equal(r.Method, http.MethodPost) - query := r.FormValue("query") - is.Equal(query, `query {}`) - io.WriteString(w, `{ - "data": { - "something": "yes" - } - }`) - })) - defer srv.Close() - - ctx := context.Background() - client := NewClient(srv.URL, ImmediatelyCloseReqBody(), UseMultipartForm()) - - ctx, cancel := context.WithTimeout(ctx, 1*time.Second) - defer cancel() - var responseData map[string]interface{} - err := client.Run(ctx, &Request{q: "query {}"}, &responseData) - is.NoErr(err) - is.Equal(calls, 1) // calls - is.Equal(responseData["something"], "yes") -} - -func TestDoErr(t *testing.T) { - is := is.New(t) - var calls int - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - calls++ - is.Equal(r.Method, http.MethodPost) - query := r.FormValue("query") - is.Equal(query, `query {}`) - io.WriteString(w, `{ - "errors": [{ - "message": "Something went wrong" - }] - }`) - })) - defer srv.Close() - - ctx := context.Background() - client := NewClient(srv.URL, UseMultipartForm()) - - ctx, cancel := context.WithTimeout(ctx, 1*time.Second) - defer cancel() - var responseData map[string]interface{} - err := client.Run(ctx, &Request{q: "query {}"}, &responseData) - is.True(err != nil) - is.Equal(err.Error(), "graphql: Something went wrong") -} - -func TestDoServerErr(t *testing.T) { - is := is.New(t) - var calls int - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - calls++ - is.Equal(r.Method, http.MethodPost) - query := r.FormValue("query") - is.Equal(query, `query {}`) - w.WriteHeader(http.StatusInternalServerError) - io.WriteString(w, `Internal Server Error`) - })) - defer srv.Close() - - ctx := context.Background() - client := NewClient(srv.URL, UseMultipartForm()) - - ctx, cancel := context.WithTimeout(ctx, 1*time.Second) - defer cancel() - var responseData map[string]interface{} - err := client.Run(ctx, &Request{q: "query {}"}, &responseData) - is.Equal(err.Error(), "graphql: server returned a non-200 status code: 500") -} - -func TestDoBadRequestErr(t *testing.T) { - is := is.New(t) - var calls int - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - calls++ - is.Equal(r.Method, http.MethodPost) - query := r.FormValue("query") - is.Equal(query, `query {}`) - w.WriteHeader(http.StatusBadRequest) - io.WriteString(w, `{ - "errors": [{ - "message": "miscellaneous message as to why the the request was bad" - }] - }`) - })) - defer srv.Close() - - ctx := context.Background() - client := NewClient(srv.URL, UseMultipartForm()) - - ctx, cancel := context.WithTimeout(ctx, 1*time.Second) - defer cancel() - var responseData map[string]interface{} - err := client.Run(ctx, &Request{q: "query {}"}, &responseData) - is.Equal(err.Error(), "graphql: miscellaneous message as to why the the request was bad") -} - -func TestDoNoResponse(t *testing.T) { - is := is.New(t) - var calls int - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - calls++ - is.Equal(r.Method, http.MethodPost) - query := r.FormValue("query") - is.Equal(query, `query {}`) - io.WriteString(w, `{ - "data": { - "something": "yes" - } - }`) - })) - defer srv.Close() - - ctx := context.Background() - client := NewClient(srv.URL, UseMultipartForm()) - - ctx, cancel := context.WithTimeout(ctx, 1*time.Second) - defer cancel() - err := client.Run(ctx, &Request{q: "query {}"}, nil) - is.NoErr(err) - is.Equal(calls, 1) // calls -} - -func TestQuery(t *testing.T) { - is := is.New(t) - - var calls int - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - calls++ - query := r.FormValue("query") - is.Equal(query, "query {}") - is.Equal(r.FormValue("variables"), `{"username":"matryer"}`+"\n") - _, err := io.WriteString(w, `{"data":{"value":"some data"}}`) - is.NoErr(err) - })) - defer srv.Close() - ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) - defer cancel() - - client := NewClient(srv.URL, UseMultipartForm()) - - req := NewRequest("query {}") - req.Var("username", "matryer") - - // check variables - is.True(req != nil) - is.Equal(req.vars["username"], "matryer") - - var resp struct { - Value string - } - err := client.Run(ctx, req, &resp) - is.NoErr(err) - is.Equal(calls, 1) - - is.Equal(resp.Value, "some data") -} - -func TestFile(t *testing.T) { - is := is.New(t) - - var calls int - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - calls++ - file, header, err := r.FormFile("file") - is.NoErr(err) - defer file.Close() - is.Equal(header.Filename, "filename.txt") - - b, err := ioutil.ReadAll(file) - is.NoErr(err) - is.Equal(string(b), `This is a file`) - - _, err = io.WriteString(w, `{"data":{"value":"some data"}}`) - is.NoErr(err) - })) - defer srv.Close() - ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) - defer cancel() - client := NewClient(srv.URL, UseMultipartForm()) - f := strings.NewReader(`This is a file`) - req := NewRequest("query {}") - req.File("file", "filename.txt", f) - err := client.Run(ctx, req, nil) - is.NoErr(err) -} - -type roundTripperFunc func(req *http.Request) (*http.Response, error) - -func (fn roundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) { - return fn(req) -} - -func TestHideAuthInMultipartForm(t *testing.T) { - is := is.New(t) - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, `{ - "data": { - "something": "yes" - } - }`) - })) - defer srv.Close() - - ctx := context.Background() - client := NewClient(srv.URL, UseMultipartForm()) - - var cout bytes.Buffer - client.Log = func(s string) { - _, err := cout.WriteString(s) - is.NoErr(err) - } - - header := make(http.Header) - header["Authorization"] = []string{"some secret key", "another secret key"} - req := Request{ - q: "query {}", - Header: header, - } - - ctx, cancel := context.WithTimeout(ctx, 1*time.Second) - defer cancel() - var responseData map[string]interface{} - err := client.Run(ctx, &req, &responseData) - is.NoErr(err) - is.Equal(responseData["something"], "yes") - is.True(!strings.Contains(cout.String(), "secret key")) -} diff --git a/tests/components/application-connector/tools/external-api-mock-app/config.go b/tests/components/application-connector/tools/external-api-mock-app/config.go deleted file mode 100644 index 19927178c612..000000000000 --- a/tests/components/application-connector/tools/external-api-mock-app/config.go +++ /dev/null @@ -1,54 +0,0 @@ -package main - -import ( - "fmt" -) - -type mTLS struct { - caCertPath string - serverCertPath string - serverKeyPath string - port int -} - -type Config struct { - LogLevel string - Port int - BasicAuthUser string - BasicAuthPassword string - OAuthClientID string - OAuthClientSecret string - RequestHeaders map[string][]string - RequestQueryParameters map[string][]string - mTLS mTLS - mTLSExpiredCerts mTLS -} - -func NewConfig() *Config { - return &Config{ - LogLevel: "info", - Port: 8080, - BasicAuthUser: "user", - BasicAuthPassword: "passwd", - OAuthClientID: "clientID", - OAuthClientSecret: "clientSecret", - RequestHeaders: map[string][]string{"Hkey1": {"Hval1"}, "Hkey2": {"Hval21", "Hval22"}}, - RequestQueryParameters: map[string][]string{"Qkey1": {"Qval1"}, "Qkey2": {"Qval21", "Qval22"}}, - mTLS: mTLS{ - port: 8090, - caCertPath: "/etc/secret-volume/ca.crt", - serverCertPath: "/etc/secret-volume/server.crt", - serverKeyPath: "/etc/secret-volume/server.key", - }, - mTLSExpiredCerts: mTLS{ - port: 8091, - caCertPath: "/etc/expired-server-cert-volume/ca.crt", - serverCertPath: "/etc/expired-server-cert-volume/server.crt", - serverKeyPath: "/etc/expired-server-cert-volume/server.key", - }, - } -} - -func (c *Config) String() string { - return fmt.Sprintf("LogLevel: %s", c.LogLevel) -} diff --git a/tests/components/application-connector/tools/external-api-mock-app/server.go b/tests/components/application-connector/tools/external-api-mock-app/server.go deleted file mode 100644 index b469380a8af4..000000000000 --- a/tests/components/application-connector/tools/external-api-mock-app/server.go +++ /dev/null @@ -1,79 +0,0 @@ -package main - -import ( - "crypto/tls" - "crypto/x509" - "fmt" - "github.com/kyma-project/kyma/tests/components/application-connector/internal/testkit/test-api" - log "github.com/sirupsen/logrus" - "io/ioutil" - "net/http" - "os" - "sync" -) - -func main() { - cfg := NewConfig() - logLevel, err := log.ParseLevel(cfg.LogLevel) - if err != nil { - log.Warnf("Invalid log level: '%s', defaulting to 'info'", cfg.LogLevel) - logLevel = log.InfoLevel - } - log.SetLevel(logLevel) - - log.Infof("Starting mock application") - log.Infof("Config: %s", cfg.String()) - - wg := sync.WaitGroup{} - wg.Add(3) - - basicAuthCredentials := test_api.BasicAuthCredentials{User: cfg.BasicAuthUser, Password: cfg.BasicAuthPassword} - oAuthCredentials := test_api.OAuthCredentials{ClientID: cfg.OAuthClientID, ClientSecret: cfg.OAuthClientSecret} - expectedRequestParameters := test_api.ExpectedRequestParameters{Headers: cfg.RequestHeaders, QueryParameters: cfg.RequestQueryParameters} - oauthTokens := make(map[string]test_api.OAuthToken) - csrfTokens := make(test_api.CSRFTokens) - - go func() { - address := fmt.Sprintf(":%d", cfg.Port) - router := test_api.SetupRoutes(os.Stdout, basicAuthCredentials, oAuthCredentials, expectedRequestParameters, oauthTokens, csrfTokens) - log.Fatal(http.ListenAndServe(address, router)) - }() - - go func() { - address := fmt.Sprintf(":%d", cfg.mTLS.port) - router := test_api.SetupMTLSRoutes(os.Stdout, oAuthCredentials, oauthTokens, csrfTokens) - mtlsServer := newMTLSServer(cfg.mTLS.caCertPath, address, router) - log.Fatal(mtlsServer.ListenAndServeTLS(cfg.mTLS.serverCertPath, cfg.mTLS.serverKeyPath)) - }() - - go func() { - address := fmt.Sprintf(":%d", cfg.mTLSExpiredCerts.port) - router := test_api.SetupMTLSRoutes(os.Stdout, oAuthCredentials, oauthTokens, csrfTokens) - mtlsServer := newMTLSServer(cfg.mTLSExpiredCerts.caCertPath, address, router) - log.Fatal(mtlsServer.ListenAndServeTLS(cfg.mTLSExpiredCerts.serverCertPath, cfg.mTLSExpiredCerts.serverKeyPath)) - }() - - wg.Wait() -} - -func newMTLSServer(caCertPath, address string, handler http.Handler) *http.Server { - // Create a CA certificate pool and add cert.pem to it - caCert, err := ioutil.ReadFile(caCertPath) - if err != nil { - log.Fatal(err) - } - caCertPool := x509.NewCertPool() - caCertPool.AppendCertsFromPEM(caCert) - - // Create the TLS Config with the CA pool and enable Client certificate validation - tlsConfig := &tls.Config{ - ClientCAs: caCertPool, - ClientAuth: tls.RequireAndVerifyClientCert, - } - - return &http.Server{ - Addr: address, - Handler: handler, - TLSConfig: tlsConfig, - } -}