From 1dcc14011e8729075436d718f69dfc857659100f Mon Sep 17 00:00:00 2001 From: Austin Abro <37223396+AustinAbro321@users.noreply.github.com> Date: Thu, 23 May 2024 18:53:16 -0400 Subject: [PATCH] test: argo agent unit tests (#2536) ## Description Relates to #2512 ## Checklist before merging - [ ] Test, docs, adr added or updated as needed - [ ] [Contributor Guide Steps](https://github.com/defenseunicorns/zarf/blob/main/.github/CONTRIBUTING.md#developer-workflow) followed --------- Co-authored-by: Lucas Rodriguez Co-authored-by: razzle Co-authored-by: schristoff <167717759+schristoff-du@users.noreply.github.com> --- packages/zarf-agent/manifests/deployment.yaml | 6 - .../agent/hooks/argocd-application.go | 102 ++++++++------- .../agent/hooks/argocd-application_test.go | 95 ++++++++++++++ src/internal/agent/hooks/argocd-repository.go | 92 +++++++------- .../agent/hooks/argocd-repository_test.go | 119 ++++++++++++++++++ src/internal/agent/http/proxy.go | 28 +++-- src/internal/agent/http/server.go | 4 +- src/internal/agent/state/state.go | 26 ---- 8 files changed, 338 insertions(+), 134 deletions(-) create mode 100644 src/internal/agent/hooks/argocd-application_test.go create mode 100644 src/internal/agent/hooks/argocd-repository_test.go delete mode 100644 src/internal/agent/state/state.go diff --git a/packages/zarf-agent/manifests/deployment.yaml b/packages/zarf-agent/manifests/deployment.yaml index a4113812f9..a8e481845f 100644 --- a/packages/zarf-agent/manifests/deployment.yaml +++ b/packages/zarf-agent/manifests/deployment.yaml @@ -43,9 +43,6 @@ spec: - name: tls-certs mountPath: /etc/certs readOnly: true - - name: zarf-state - mountPath: /etc/zarf-state - readOnly: true # Required for OpenShift to mount k9s vendored directories - name: config mountPath: /.config @@ -55,9 +52,6 @@ spec: - name: tls-certs secret: secretName: agent-hook-tls - - name: zarf-state - secret: - secretName: zarf-state # Required for OpenShift to mount k9s vendored directories - name: config emptyDir: {} diff --git a/src/internal/agent/hooks/argocd-application.go b/src/internal/agent/hooks/argocd-application.go index 260b1d53a3..90a5b98744 100644 --- a/src/internal/agent/hooks/argocd-application.go +++ b/src/internal/agent/hooks/argocd-application.go @@ -5,81 +5,90 @@ package hooks import ( + "context" "encoding/json" "fmt" "github.com/defenseunicorns/pkg/helpers" "github.com/defenseunicorns/zarf/src/config/lang" "github.com/defenseunicorns/zarf/src/internal/agent/operations" - "github.com/defenseunicorns/zarf/src/internal/agent/state" + "github.com/defenseunicorns/zarf/src/pkg/cluster" "github.com/defenseunicorns/zarf/src/pkg/message" "github.com/defenseunicorns/zarf/src/pkg/transform" "github.com/defenseunicorns/zarf/src/types" v1 "k8s.io/api/admission/v1" ) -// Source represents a subset of the Argo Source object needed for Zarf Git URL mutations -type Source struct { - RepoURL string `json:"repoURL"` +// Application is a definition of an ArgoCD Application resource. +// The ArgoCD Application structs in this file have been partially copied from upstream. +// +// https://github.com/argoproj/argo-cd/blob/v2.11.0/pkg/apis/application/v1alpha1/types.go +// +// There were errors encountered when trying to import argocd as a Go package. +// +// For more information: https://argo-cd.readthedocs.io/en/stable/user-guide/import/ +type Application struct { + Spec ApplicationSpec `json:"spec"` } -// ArgoApplication represents a subset of the Argo Application object needed for Zarf Git URL mutations -type ArgoApplication struct { - Spec struct { - Source Source `json:"source"` - Sources []Source `json:"sources"` - } `json:"spec"` +// ApplicationSpec represents desired application state. Contains link to repository with application definition. +type ApplicationSpec struct { + // Source is a reference to the location of the application's manifests or chart. + Source *ApplicationSource `json:"source,omitempty"` + Sources []ApplicationSource `json:"sources,omitempty"` } -var ( - zarfState *types.ZarfState - patches []operations.PatchOperation - isPatched bool - isCreate bool - isUpdate bool -) +// ApplicationSource contains all required information about the source of an application. +type ApplicationSource struct { + // RepoURL is the URL to the repository (Git or Helm) that contains the application manifests. + RepoURL string `json:"repoURL"` +} // NewApplicationMutationHook creates a new instance of the ArgoCD Application mutation hook. -func NewApplicationMutationHook() operations.Hook { +func NewApplicationMutationHook(ctx context.Context, cluster *cluster.Cluster) operations.Hook { message.Debug("hooks.NewApplicationMutationHook()") return operations.Hook{ - Create: mutateApplication, - Update: mutateApplication, + Create: func(r *v1.AdmissionRequest) (*operations.Result, error) { + return mutateApplication(ctx, r, cluster) + }, + Update: func(r *v1.AdmissionRequest) (*operations.Result, error) { + return mutateApplication(ctx, r, cluster) + }, } } // mutateApplication mutates the git repository url to point to the repository URL defined in the ZarfState. -func mutateApplication(r *v1.AdmissionRequest) (result *operations.Result, err error) { - - isCreate = r.Operation == v1.Create - isUpdate = r.Operation == v1.Update - - patches = []operations.PatchOperation{} - - // Form the zarfState.GitServer.Address from the zarfState - if zarfState, err = state.GetZarfStateFromAgentPod(); err != nil { +func mutateApplication(ctx context.Context, r *v1.AdmissionRequest, cluster *cluster.Cluster) (result *operations.Result, err error) { + state, err := cluster.LoadZarfState(ctx) + if err != nil { return nil, fmt.Errorf(lang.AgentErrGetState, err) } - message.Debugf("Using the url of (%s) to mutate the ArgoCD Application", zarfState.GitServer.Address) + message.Debugf("Using the url of (%s) to mutate the ArgoCD Application", state.GitServer.Address) - // parse to simple struct to read the git url - src := &ArgoApplication{} - - if err = json.Unmarshal(r.Object.Raw, &src); err != nil { + app := Application{} + if err = json.Unmarshal(r.Object.Raw, &app); err != nil { return nil, fmt.Errorf(lang.ErrUnmarshal, err) } message.Debugf("Data %v", string(r.Object.Raw)) - if src.Spec.Source != (Source{}) { - patchedURL, _ := getPatchedRepoURL(src.Spec.Source.RepoURL) + patches := []operations.PatchOperation{} + + if app.Spec.Source != nil { + patchedURL, err := getPatchedRepoURL(app.Spec.Source.RepoURL, state.GitServer, r) + if err != nil { + return nil, err + } patches = populateSingleSourceArgoApplicationPatchOperations(patchedURL, patches) } - if len(src.Spec.Sources) > 0 { - for idx, source := range src.Spec.Sources { - patchedURL, _ := getPatchedRepoURL(source.RepoURL) + if len(app.Spec.Sources) > 0 { + for idx, source := range app.Spec.Sources { + patchedURL, err := getPatchedRepoURL(source.RepoURL, state.GitServer, r) + if err != nil { + return nil, err + } patches = populateMultipleSourceArgoApplicationPatchOperations(idx, patchedURL, patches) } } @@ -90,15 +99,18 @@ func mutateApplication(r *v1.AdmissionRequest) (result *operations.Result, err e }, nil } -func getPatchedRepoURL(repoURL string) (string, error) { - var err error +func getPatchedRepoURL(repoURL string, gs types.GitServerInfo, r *v1.AdmissionRequest) (string, error) { + isCreate := r.Operation == v1.Create + isUpdate := r.Operation == v1.Update patchedURL := repoURL + var isPatched bool + var err error // Check if this is an update operation and the hostname is different from what we have in the zarfState // NOTE: We mutate on updates IF AND ONLY IF the hostname in the request is different from the hostname in the zarfState // NOTE: We are checking if the hostname is different before because we do not want to potentially mutate a URL that has already been mutated. if isUpdate { - isPatched, err = helpers.DoHostnamesMatch(zarfState.GitServer.Address, repoURL) + isPatched, err = helpers.DoHostnamesMatch(gs.Address, repoURL) if err != nil { return "", fmt.Errorf(lang.AgentErrHostnameMatch, err) } @@ -107,15 +119,15 @@ func getPatchedRepoURL(repoURL string) (string, error) { // Mutate the repoURL if necessary if isCreate || (isUpdate && !isPatched) { // Mutate the git URL so that the hostname matches the hostname in the Zarf state - transformedURL, err := transform.GitURL(zarfState.GitServer.Address, patchedURL, zarfState.GitServer.PushUsername) + transformedURL, err := transform.GitURL(gs.Address, patchedURL, gs.PushUsername) if err != nil { - message.Warnf("Unable to transform the repoURL, using the original url we have: %s", patchedURL) + return "", fmt.Errorf("%s: %w", AgentErrTransformGitURL, err) } patchedURL = transformedURL.String() message.Debugf("original repoURL of (%s) got mutated to (%s)", repoURL, patchedURL) } - return patchedURL, err + return patchedURL, nil } // Patch updates of the Argo source spec. diff --git a/src/internal/agent/hooks/argocd-application_test.go b/src/internal/agent/hooks/argocd-application_test.go new file mode 100644 index 0000000000..5d241dd571 --- /dev/null +++ b/src/internal/agent/hooks/argocd-application_test.go @@ -0,0 +1,95 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2021-Present The Zarf Authors + +package hooks + +import ( + "context" + "encoding/json" + "net/http" + "testing" + + "github.com/defenseunicorns/zarf/src/internal/agent/http/admission" + "github.com/defenseunicorns/zarf/src/internal/agent/operations" + "github.com/defenseunicorns/zarf/src/types" + "github.com/stretchr/testify/require" + v1 "k8s.io/api/admission/v1" + "k8s.io/apimachinery/pkg/runtime" +) + +func createArgoAppAdmissionRequest(t *testing.T, op v1.Operation, argoApp *Application) *v1.AdmissionRequest { + t.Helper() + raw, err := json.Marshal(argoApp) + require.NoError(t, err) + return &v1.AdmissionRequest{ + Operation: op, + Object: runtime.RawExtension{ + Raw: raw, + }, + } +} + +func TestArgoAppWebhook(t *testing.T) { + t.Parallel() + + ctx := context.Background() + state := &types.ZarfState{GitServer: types.GitServerInfo{ + Address: "https://git-server.com", + PushUsername: "a-push-user", + }} + c := createTestClientWithZarfState(ctx, t, state) + handler := admission.NewHandler().Serve(NewApplicationMutationHook(ctx, c)) + + tests := []admissionTest{ + { + name: "should be mutated", + admissionReq: createArgoAppAdmissionRequest(t, v1.Create, &Application{ + Spec: ApplicationSpec{ + Source: &ApplicationSource{RepoURL: "https://diff-git-server.com/peanuts"}, + Sources: []ApplicationSource{ + { + RepoURL: "https://diff-git-server.com/cashews", + }, + { + RepoURL: "https://diff-git-server.com/almonds", + }, + }, + }, + }), + patch: []operations.PatchOperation{ + operations.ReplacePatchOperation( + "/spec/source/repoURL", + "https://git-server.com/a-push-user/peanuts-3883081014", + ), + operations.ReplacePatchOperation( + "/spec/sources/0/repoURL", + "https://git-server.com/a-push-user/cashews-580170494", + ), + operations.ReplacePatchOperation( + "/spec/sources/1/repoURL", + "https://git-server.com/a-push-user/almonds-640159520", + ), + }, + code: http.StatusOK, + }, + { + name: "should return internal server error on bad git URL", + admissionReq: createArgoAppAdmissionRequest(t, v1.Create, &Application{ + Spec: ApplicationSpec{ + Source: &ApplicationSource{RepoURL: "https://bad-url"}, + }, + }), + code: http.StatusInternalServerError, + errContains: AgentErrTransformGitURL, + }, + } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + rr := sendAdmissionRequest(t, tt.admissionReq, handler) + verifyAdmission(t, rr, tt) + }) + } +} diff --git a/src/internal/agent/hooks/argocd-repository.go b/src/internal/agent/hooks/argocd-repository.go index a9b74cd72f..9e643414d7 100644 --- a/src/internal/agent/hooks/argocd-repository.go +++ b/src/internal/agent/hooks/argocd-repository.go @@ -5,6 +5,7 @@ package hooks import ( + "context" "encoding/base64" "encoding/json" "fmt" @@ -12,97 +13,100 @@ import ( "github.com/defenseunicorns/pkg/helpers" "github.com/defenseunicorns/zarf/src/config/lang" "github.com/defenseunicorns/zarf/src/internal/agent/operations" - "github.com/defenseunicorns/zarf/src/internal/agent/state" + "github.com/defenseunicorns/zarf/src/pkg/cluster" "github.com/defenseunicorns/zarf/src/pkg/message" "github.com/defenseunicorns/zarf/src/pkg/transform" "github.com/defenseunicorns/zarf/src/types" v1 "k8s.io/api/admission/v1" + corev1 "k8s.io/api/core/v1" ) -// ArgoRepository represents a subset of the Argo Repository object needed for Zarf Git URL mutations -type ArgoRepository struct { - Data struct { - URL string `json:"url"` - } +// RepoCreds holds the definition for repository credentials. +// This has been partially copied from upstream. +// +// https://github.com/argoproj/argo-cd/blob/v2.11.0/pkg/apis/application/v1alpha1/repository_types.go +// +// There were errors encountered when trying to import argocd as a Go package. +// +// For more information: https://argo-cd.readthedocs.io/en/stable/user-guide/import/ +type RepoCreds struct { + // URL is the URL that this credential matches to. + URL string `json:"url"` } -// NewRepositoryMutationHook creates a new instance of the ArgoCD Repository mutation hook. -func NewRepositoryMutationHook() operations.Hook { +// NewRepositorySecretMutationHook creates a new instance of the ArgoCD repository secret mutation hook. +func NewRepositorySecretMutationHook(ctx context.Context, cluster *cluster.Cluster) operations.Hook { message.Debug("hooks.NewRepositoryMutationHook()") return operations.Hook{ - Create: mutateRepository, - Update: mutateRepository, + Create: func(r *v1.AdmissionRequest) (*operations.Result, error) { + return mutateRepositorySecret(ctx, r, cluster) + }, + Update: func(r *v1.AdmissionRequest) (*operations.Result, error) { + return mutateRepositorySecret(ctx, r, cluster) + }, } } -// mutateRepository mutates the git repository URL to point to the repository URL defined in the ZarfState. -func mutateRepository(r *v1.AdmissionRequest) (result *operations.Result, err error) { - - var ( - zarfState *types.ZarfState - patches []operations.PatchOperation - isPatched bool - - isCreate = r.Operation == v1.Create - isUpdate = r.Operation == v1.Update - ) +// mutateRepositorySecret mutates the git URL in the ArgoCD repository secret to point to the repository URL defined in the ZarfState. +func mutateRepositorySecret(ctx context.Context, r *v1.AdmissionRequest, cluster *cluster.Cluster) (result *operations.Result, err error) { + isCreate := r.Operation == v1.Create + isUpdate := r.Operation == v1.Update + var isPatched bool - // Form the zarfState.GitServer.Address from the zarfState - if zarfState, err = state.GetZarfStateFromAgentPod(); err != nil { + state, err := cluster.LoadZarfState(ctx) + if err != nil { return nil, fmt.Errorf(lang.AgentErrGetState, err) } - message.Debugf("Using the url of (%s) to mutate the ArgoCD Repository Secret", zarfState.GitServer.Address) - - // parse to simple struct to read the git url - src := &ArgoRepository{} + message.Infof("Using the url of (%s) to mutate the ArgoCD Repository Secret", state.GitServer.Address) - if err = json.Unmarshal(r.Object.Raw, &src); err != nil { + secret := corev1.Secret{} + if err = json.Unmarshal(r.Object.Raw, &secret); err != nil { return nil, fmt.Errorf(lang.ErrUnmarshal, err) } - decodedURL, err := base64.StdEncoding.DecodeString(src.Data.URL) - if err != nil { - message.Fatalf("Error decoding URL from Repository Secret %s", src.Data.URL) + + url, exists := secret.Data["url"] + if !exists { + return nil, fmt.Errorf("url field not found in argocd repository secret data") } - src.Data.URL = string(decodedURL) - patchedURL := src.Data.URL + + var repoCreds RepoCreds + repoCreds.URL = string(url) // Check if this is an update operation and the hostname is different from what we have in the zarfState // NOTE: We mutate on updates IF AND ONLY IF the hostname in the request is different from the hostname in the zarfState // NOTE: We are checking if the hostname is different before because we do not want to potentially mutate a URL that has already been mutated. if isUpdate { - isPatched, err = helpers.DoHostnamesMatch(zarfState.GitServer.Address, src.Data.URL) + isPatched, err = helpers.DoHostnamesMatch(state.GitServer.Address, repoCreds.URL) if err != nil { return nil, fmt.Errorf(lang.AgentErrHostnameMatch, err) } } + patchedURL := repoCreds.URL // Mutate the repoURL if necessary if isCreate || (isUpdate && !isPatched) { // Mutate the git URL so that the hostname matches the hostname in the Zarf state - transformedURL, err := transform.GitURL(zarfState.GitServer.Address, patchedURL, zarfState.GitServer.PushUsername) + transformedURL, err := transform.GitURL(state.GitServer.Address, repoCreds.URL, state.GitServer.PushUsername) if err != nil { - message.Warnf("Unable to transform the url, using the original url we have: %s", patchedURL) + return nil, fmt.Errorf("unable the git url: %w", err) } patchedURL = transformedURL.String() - message.Debugf("original url of (%s) got mutated to (%s)", src.Data.URL, patchedURL) + message.Debugf("original url of (%s) got mutated to (%s)", repoCreds.URL, patchedURL) } - // Patch updates of the repo spec - patches = populateArgoRepositoryPatchOperations(patchedURL, zarfState.GitServer.PullPassword) - return &operations.Result{ Allowed: true, - PatchOps: patches, + PatchOps: populateArgoRepositoryPatchOperations(patchedURL, state.GitServer), }, nil } // Patch updates of the Argo Repository Secret. -func populateArgoRepositoryPatchOperations(repoURL string, zarfGitPullPassword string) []operations.PatchOperation { +func populateArgoRepositoryPatchOperations(repoURL string, gitServer types.GitServerInfo) []operations.PatchOperation { var patches []operations.PatchOperation patches = append(patches, operations.ReplacePatchOperation("/data/url", base64.StdEncoding.EncodeToString([]byte(repoURL)))) - patches = append(patches, operations.ReplacePatchOperation("/data/username", base64.StdEncoding.EncodeToString([]byte(types.ZarfGitReadUser)))) - patches = append(patches, operations.ReplacePatchOperation("/data/password", base64.StdEncoding.EncodeToString([]byte(zarfGitPullPassword)))) + patches = append(patches, operations.ReplacePatchOperation("/data/username", base64.StdEncoding.EncodeToString([]byte(gitServer.PullUsername)))) + patches = append(patches, operations.ReplacePatchOperation("/data/password", base64.StdEncoding.EncodeToString([]byte(gitServer.PullPassword)))) return patches } diff --git a/src/internal/agent/hooks/argocd-repository_test.go b/src/internal/agent/hooks/argocd-repository_test.go new file mode 100644 index 0000000000..b84a3e8d07 --- /dev/null +++ b/src/internal/agent/hooks/argocd-repository_test.go @@ -0,0 +1,119 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2021-Present The Zarf Authors + +package hooks + +import ( + "context" + b64 "encoding/base64" + "encoding/json" + "net/http" + "testing" + + "github.com/defenseunicorns/zarf/src/internal/agent/http/admission" + "github.com/defenseunicorns/zarf/src/internal/agent/operations" + "github.com/defenseunicorns/zarf/src/types" + "github.com/stretchr/testify/require" + v1 "k8s.io/api/admission/v1" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" +) + +func createArgoRepoAdmissionRequest(t *testing.T, op v1.Operation, argoRepo *corev1.Secret) *v1.AdmissionRequest { + t.Helper() + raw, err := json.Marshal(argoRepo) + require.NoError(t, err) + return &v1.AdmissionRequest{ + Operation: op, + Object: runtime.RawExtension{ + Raw: raw, + }, + } +} + +func TestArgoRepoWebhook(t *testing.T) { + t.Parallel() + + ctx := context.Background() + state := &types.ZarfState{GitServer: types.GitServerInfo{ + Address: "https://git-server.com", + PushUsername: "a-push-user", + PullPassword: "a-pull-password", + PullUsername: "a-pull-user", + }} + c := createTestClientWithZarfState(ctx, t, state) + handler := admission.NewHandler().Serve(NewRepositorySecretMutationHook(ctx, c)) + + tests := []admissionTest{ + { + name: "should be mutated", + admissionReq: createArgoRepoAdmissionRequest(t, v1.Create, &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{ + Labels: map[string]string{ + "argocd.argoproj.io/secret-type": "repository", + }, + Name: "argo-repo-secret", + Namespace: "argo", + }, + Data: map[string][]byte{ + "url": []byte("https://diff-git-server.com/podinfo"), + }, + }), + patch: []operations.PatchOperation{ + operations.ReplacePatchOperation( + "/data/url", + b64.StdEncoding.EncodeToString([]byte("https://git-server.com/a-push-user/podinfo-1868163476")), + ), + operations.ReplacePatchOperation( + "/data/username", + b64.StdEncoding.EncodeToString([]byte(state.GitServer.PullUsername)), + ), + operations.ReplacePatchOperation( + "/data/password", + b64.StdEncoding.EncodeToString([]byte(state.GitServer.PullPassword)), + ), + }, + code: http.StatusOK, + }, + { + name: "matching hostname on update should stay the same, but secret should be added", + admissionReq: createArgoRepoAdmissionRequest(t, v1.Update, &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{ + Labels: map[string]string{ + "argocd.argoproj.io/secret-type": "repository", + }, + Name: "argo-repo-secret", + Namespace: "argo", + }, + Data: map[string][]byte{ + "url": []byte("https://git-server.com/podinfo"), + }, + }), + patch: []operations.PatchOperation{ + operations.ReplacePatchOperation( + "/data/url", + b64.StdEncoding.EncodeToString([]byte("https://git-server.com/podinfo")), + ), + operations.ReplacePatchOperation( + "/data/username", + b64.StdEncoding.EncodeToString([]byte(state.GitServer.PullUsername)), + ), + operations.ReplacePatchOperation( + "/data/password", + b64.StdEncoding.EncodeToString([]byte(state.GitServer.PullPassword)), + ), + }, + code: http.StatusOK, + }, + } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + rr := sendAdmissionRequest(t, tt.admissionReq, handler) + verifyAdmission(t, rr, tt) + }) + } +} diff --git a/src/internal/agent/http/proxy.go b/src/internal/agent/http/proxy.go index ea0a54f024..860d147811 100644 --- a/src/internal/agent/http/proxy.go +++ b/src/internal/agent/http/proxy.go @@ -5,6 +5,7 @@ package http import ( + "context" "crypto/tls" "fmt" "io" @@ -14,7 +15,7 @@ import ( "strings" "github.com/defenseunicorns/zarf/src/config/lang" - "github.com/defenseunicorns/zarf/src/internal/agent/state" + "github.com/defenseunicorns/zarf/src/pkg/cluster" "github.com/defenseunicorns/zarf/src/pkg/message" "github.com/defenseunicorns/zarf/src/pkg/transform" ) @@ -45,7 +46,12 @@ func proxyRequestTransform(r *http.Request) error { // We remove this so that go will encode and decode on our behalf (see https://pkg.go.dev/net/http#Transport DisableCompression) r.Header.Del("Accept-Encoding") - zarfState, err := state.GetZarfStateFromAgentPod() + c, err := cluster.NewCluster() + if err != nil { + return err + } + ctx := context.Background() + state, err := c.LoadZarfState(ctx) if err != nil { return err } @@ -55,31 +61,31 @@ func proxyRequestTransform(r *http.Request) error { // Setup authentication for each type of service based on User Agent switch { case isGitUserAgent(r.UserAgent()): - r.SetBasicAuth(zarfState.GitServer.PushUsername, zarfState.GitServer.PushPassword) + r.SetBasicAuth(state.GitServer.PushUsername, state.GitServer.PushPassword) case isNpmUserAgent(r.UserAgent()): - r.Header.Set("Authorization", "Bearer "+zarfState.ArtifactServer.PushToken) + r.Header.Set("Authorization", "Bearer "+state.ArtifactServer.PushToken) default: - r.SetBasicAuth(zarfState.ArtifactServer.PushUsername, zarfState.ArtifactServer.PushToken) + r.SetBasicAuth(state.ArtifactServer.PushUsername, state.ArtifactServer.PushToken) } // Transform the URL; if we see the NoTransform prefix, strip it; otherwise, transform the URL based on User Agent if strings.HasPrefix(r.URL.Path, transform.NoTransform) { switch { case isGitUserAgent(r.UserAgent()): - targetURL, err = transform.NoTransformTarget(zarfState.GitServer.Address, r.URL.Path) + targetURL, err = transform.NoTransformTarget(state.GitServer.Address, r.URL.Path) default: - targetURL, err = transform.NoTransformTarget(zarfState.ArtifactServer.Address, r.URL.Path) + targetURL, err = transform.NoTransformTarget(state.ArtifactServer.Address, r.URL.Path) } } else { switch { case isGitUserAgent(r.UserAgent()): - targetURL, err = transform.GitURL(zarfState.GitServer.Address, getTLSScheme(r.TLS)+r.Host+r.URL.String(), zarfState.GitServer.PushUsername) + targetURL, err = transform.GitURL(state.GitServer.Address, getTLSScheme(r.TLS)+r.Host+r.URL.String(), state.GitServer.PushUsername) case isPipUserAgent(r.UserAgent()): - targetURL, err = transform.PipTransformURL(zarfState.ArtifactServer.Address, getTLSScheme(r.TLS)+r.Host+r.URL.String()) + targetURL, err = transform.PipTransformURL(state.ArtifactServer.Address, getTLSScheme(r.TLS)+r.Host+r.URL.String()) case isNpmUserAgent(r.UserAgent()): - targetURL, err = transform.NpmTransformURL(zarfState.ArtifactServer.Address, getTLSScheme(r.TLS)+r.Host+r.URL.String()) + targetURL, err = transform.NpmTransformURL(state.ArtifactServer.Address, getTLSScheme(r.TLS)+r.Host+r.URL.String()) default: - targetURL, err = transform.GenTransformURL(zarfState.ArtifactServer.Address, getTLSScheme(r.TLS)+r.Host+r.URL.String()) + targetURL, err = transform.GenTransformURL(state.ArtifactServer.Address, getTLSScheme(r.TLS)+r.Host+r.URL.String()) } } diff --git a/src/internal/agent/http/server.go b/src/internal/agent/http/server.go index 2c56428fd7..49fa5a6e7e 100644 --- a/src/internal/agent/http/server.go +++ b/src/internal/agent/http/server.go @@ -31,8 +31,8 @@ func NewAdmissionServer(port string) *http.Server { // Instances hooks podsMutation := hooks.NewPodMutationHook(ctx, c) fluxGitRepositoryMutation := hooks.NewGitRepositoryMutationHook(ctx, c) - argocdApplicationMutation := hooks.NewApplicationMutationHook() - argocdRepositoryMutation := hooks.NewRepositoryMutationHook() + argocdApplicationMutation := hooks.NewApplicationMutationHook(ctx, c) + argocdRepositoryMutation := hooks.NewRepositorySecretMutationHook(ctx, c) // Routers ah := admission.NewHandler() diff --git a/src/internal/agent/state/state.go b/src/internal/agent/state/state.go deleted file mode 100644 index 7c99acb4d2..0000000000 --- a/src/internal/agent/state/state.go +++ /dev/null @@ -1,26 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// SPDX-FileCopyrightText: 2021-Present The Zarf Authors - -// Package state provides helpers for interacting with the Zarf agent state. -package state - -import ( - "encoding/json" - "os" - - "github.com/defenseunicorns/zarf/src/types" -) - -const zarfStatePath = "/etc/zarf-state/state" - -// GetZarfStateFromAgentPod reads the state json file that was mounted into the agent pods. -func GetZarfStateFromAgentPod() (state *types.ZarfState, err error) { - // Read the state file - stateFile, err := os.ReadFile(zarfStatePath) - if err != nil { - return nil, err - } - - // Unmarshal the json file into a Go struct - return state, json.Unmarshal(stateFile, &state) -}