Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ServiceAccountName to ImageRepository API #252

Merged
merged 1 commit into from
May 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions api/v1beta1/imagerepository_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@ type ImageRepositorySpec struct {
// +optional
SecretRef *meta.LocalObjectReference `json:"secretRef,omitempty"`

// ServiceAccountName is the name of the Kubernetes ServiceAccount used to authenticate
// the image pull if the service account has attached pull secrets.
// +optional
ServiceAccountName string `json:"serviceAccountName,omitempty"`

// CertSecretRef can be given the name of a secret containing
// either or both of
//
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -451,6 +451,11 @@ spec:
required:
- name
type: object
serviceAccountName:
description: ServiceAccountName is the name of the Kubernetes ServiceAccount
used to authenticate the image pull if the service account has attached
pull secrets.
type: string
suspend:
description: This flag tells the controller to suspend subsequent
image scans. It does not apply to already started scans. Defaults
Expand Down
1 change: 1 addition & 0 deletions config/rbac/role.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ rules:
resources:
- namespaces
- secrets
- serviceaccounts
verbs:
- get
- list
Expand Down
51 changes: 50 additions & 1 deletion controllers/imagerepository_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import (
"time"

"github.com/google/go-containerregistry/pkg/authn"
"github.com/google/go-containerregistry/pkg/authn/k8schain"
"github.com/google/go-containerregistry/pkg/name"
"github.com/google/go-containerregistry/pkg/v1/remote"
corev1 "k8s.io/api/core/v1"
Expand Down Expand Up @@ -108,7 +109,7 @@ type gceToken struct {
// +kubebuilder:rbac:groups=image.toolkit.fluxcd.io,resources=imagerepositories/status,verbs=get;update;patch
// +kubebuilder:rbac:groups="",resources=secrets,verbs=get;list;watch
// +kubebuilder:rbac:groups="",resources=events,verbs=create;patch

// +kubebuilder:rbac:groups="",resources=serviceaccounts,verbs=get;list;watch
func (r *ImageRepositoryReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
reconcileStart := time.Now()

Expand Down Expand Up @@ -420,6 +421,54 @@ func (r *ImageRepositoryReconciler) scan(ctx context.Context, imageRepo *imagev1
options = append(options, remote.WithTransport(tr))
}

if imageRepo.Spec.ServiceAccountName != "" {

serviceAccount := corev1.ServiceAccount{}
// lookup service account
if err := r.Get(ctx, types.NamespacedName{
Namespace: imageRepo.GetNamespace(),
Name: imageRepo.Spec.ServiceAccountName,
}, &serviceAccount); err != nil {
imagev1.SetImageRepositoryReadiness(
imageRepo,
metav1.ConditionFalse,
imagev1.ReconciliationFailedReason,
err.Error(),
)
return err
}

if len(serviceAccount.ImagePullSecrets) > 0 {
imagePullSecrets := make([]corev1.Secret, len(serviceAccount.ImagePullSecrets))

for i, ips := range serviceAccount.ImagePullSecrets {
var saAuthSecret corev1.Secret

if err := r.Get(ctx, types.NamespacedName{
Namespace: imageRepo.GetNamespace(),
Name: ips.Name,
}, &saAuthSecret); err != nil {
imagev1.SetImageRepositoryReadiness(
imageRepo,
metav1.ConditionFalse,
imagev1.ReconciliationFailedReason,
err.Error(),
)
return err
}

imagePullSecrets[i] = saAuthSecret
}

keychain, err := k8schain.NewFromPullSecrets(ctx, imagePullSecrets)
if err != nil {
return err
}

options = append(options, remote.WithAuthFromKeychain(keychain))
}
}

tags, err := remote.ListWithContext(ctx, ref.Context(), options...)
if err != nil {
imagev1.SetImageRepositoryReadiness(
Expand Down
76 changes: 76 additions & 0 deletions controllers/scan_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -350,3 +350,79 @@ func TestImageRepositoryReconciler_imageAttribute_hostPort(t *testing.T) {
g.Expect(repo.Status.CanonicalImageName).To(Equal(imgRepo))
g.Expect(testEnv.Delete(ctx, &repo)).To(Succeed())
}

func TestImageRepositoryReconciler_authRegistryWithServiceAccount(t *testing.T) {
g := NewWithT(t)

username, password := "authuser", "authpass"
registryServer := test.NewAuthenticatedRegistryServer(username, password)
defer registryServer.Close()

// this mimics what you get if you use
// kubectl create secret docker-registry ...
secret := &corev1.Secret{
Type: "kubernetes.io/dockerconfigjson",
StringData: map[string]string{
".dockerconfigjson": fmt.Sprintf(`
{
"auths": {
%q: {
"username": %q,
"password": %q
}
}
}
`, test.RegistryName(registryServer), username, password),
},
}
secret.Namespace = "default"
secret.Name = "docker"

serviceAccount := &corev1.ServiceAccount{
ImagePullSecrets: []corev1.LocalObjectReference{{Name: "docker"}},
}
serviceAccount.Name = "test-sa"
serviceAccount.Namespace = "default"
g.Expect(testEnv.Create(context.Background(), secret)).To(Succeed())
g.Expect(testEnv.Create(context.Background(), serviceAccount)).To(Succeed())
defer func() {
g.Expect(testEnv.Delete(context.Background(), secret)).To(Succeed())
g.Expect(testEnv.Delete(context.Background(), serviceAccount)).To(Succeed())
}()

versions := []string{"0.1.0", "0.1.1", "0.2.0", "1.0.0", "1.0.1", "1.0.2", "1.1.0-alpha"}
imgRepo, err := test.LoadImages(registryServer, "test-authn-"+randStringRunes(5),
versions, remote.WithAuth(&authn.Basic{
Username: username,
Password: password,
}))
g.Expect(err).ToNot(HaveOccurred())

repo := imagev1.ImageRepository{
Spec: imagev1.ImageRepositorySpec{
Interval: metav1.Duration{Duration: reconciliationInterval},
Image: imgRepo,
ServiceAccountName: "test-sa",
},
}
objectName := types.NamespacedName{
Name: "test-auth-reg-" + randStringRunes(5),
Namespace: "default",
}

repo.Name = objectName.Name
repo.Namespace = objectName.Namespace

ctx, cancel := context.WithTimeout(context.Background(), contextTimeout)
defer cancel()
g.Expect(testEnv.Create(ctx, &repo)).To(Succeed())

g.Eventually(func() bool {
err := testEnv.Get(ctx, objectName, &repo)
return err == nil && repo.Status.LastScanResult != nil
}, timeout, interval).Should(BeTrue())
g.Expect(repo.Status.CanonicalImageName).To(Equal(imgRepo))
g.Expect(repo.Status.LastScanResult.TagCount).To(Equal(len(versions)))
// Cleanup.
g.Expect(testEnv.Delete(ctx, &repo)).To(Succeed())
}
26 changes: 26 additions & 0 deletions docs/api/image-reflector.md
Original file line number Diff line number Diff line change
Expand Up @@ -438,6 +438,19 @@ equivalent.</p>
</tr>
<tr>
<td>
<code>serviceAccountName</code><br>
<em>
string
</em>
</td>
<td>
<em>(Optional)</em>
<p>ServiceAccountName is the name of the Kubernetes ServiceAccount used to authenticate
the image pull if the service account has attached pull secrets.</p>
</td>
</tr>
<tr>
<td>
<code>certSecretRef</code><br>
<em>
<a href="https://godoc.org/github.com/fluxcd/pkg/apis/meta#LocalObjectReference">
Expand Down Expand Up @@ -582,6 +595,19 @@ equivalent.</p>
</tr>
<tr>
<td>
<code>serviceAccountName</code><br>
<em>
string
</em>
</td>
<td>
<em>(Optional)</em>
<p>ServiceAccountName is the name of the Kubernetes ServiceAccount used to authenticate
the image pull if the service account has attached pull secrets.</p>
</td>
</tr>
<tr>
<td>
<code>certSecretRef</code><br>
<em>
<a href="https://godoc.org/github.com/fluxcd/pkg/apis/meta#LocalObjectReference">
Expand Down
35 changes: 25 additions & 10 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ require (
github.com/fluxcd/pkg/runtime v0.14.1
github.com/fluxcd/pkg/version v0.1.0
github.com/google/go-containerregistry v0.8.0
github.com/google/go-containerregistry/pkg/authn/k8schain v0.0.0-20220105220605-d9bfbcb99e52
github.com/onsi/gomega v1.18.1
github.com/spf13/pflag v1.0.5
k8s.io/api v0.23.5
Expand All @@ -25,13 +26,22 @@ require (
)

require (
cloud.google.com/go v0.99.0 // indirect
cloud.google.com/go/compute v1.5.0 // indirect
github.com/Azure/azure-sdk-for-go v62.0.0+incompatible // indirect
github.com/Azure/azure-sdk-for-go/sdk/internal v0.9.1 // indirect
github.com/Azure/go-autorest v14.2.0+incompatible // indirect
github.com/Azure/go-autorest/autorest v0.11.24 // indirect
github.com/Azure/go-autorest/autorest/adal v0.9.18 // indirect
github.com/Azure/go-autorest/autorest/date v0.3.0 // indirect
github.com/Azure/go-autorest/autorest/to v0.3.0 // indirect
github.com/Azure/go-autorest/autorest/validation v0.1.0 // indirect
github.com/Azure/go-autorest/logger v0.2.1 // indirect
github.com/Azure/go-autorest/tracing v0.6.0 // indirect
github.com/AzureAD/microsoft-authentication-library-for-go v0.4.0 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash v1.1.0 // indirect
github.com/cespare/xxhash/v2 v2.1.2 // indirect
github.com/containerd/stargz-snapshotter/estargz v0.10.1 // indirect
github.com/containerd/stargz-snapshotter/estargz v0.11.1 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dgraph-io/ristretto v0.1.0 // indirect
github.com/docker/cli v20.10.12+incompatible // indirect
Expand All @@ -45,6 +55,7 @@ require (
github.com/go-logr/zapr v1.2.0 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang-jwt/jwt v3.2.1+incompatible // indirect
github.com/golang-jwt/jwt/v4 v4.3.0 // indirect
github.com/golang/glog v1.0.0 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/golang/protobuf v1.5.2 // indirect
Expand All @@ -59,14 +70,14 @@ require (
github.com/imdario/mergo v0.3.12 // indirect
github.com/jmespath/go-jmespath v0.4.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/compress v1.13.6 // indirect
github.com/klauspost/compress v1.14.4 // indirect
github.com/kylelemons/godebug v1.1.0 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/opencontainers/image-spec v1.0.2 // indirect
github.com/opencontainers/image-spec v1.0.3-0.20220114050600-8b9d41f48198 // indirect
github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/prometheus/client_golang v1.12.1 // indirect
Expand All @@ -75,30 +86,34 @@ require (
github.com/prometheus/procfs v0.7.3 // indirect
github.com/sirupsen/logrus v1.8.1 // indirect
github.com/vbatts/tar-split v0.11.2 // indirect
github.com/vdemeester/k8s-pkg-credentialprovider v1.21.0-1 // indirect
go.opencensus.io v0.23.0 // indirect
go.uber.org/atomic v1.7.0 // indirect
go.uber.org/multierr v1.6.0 // indirect
go.uber.org/zap v1.21.0 // indirect
golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa // indirect
golang.org/x/crypto v0.0.0-20220214200702-86341886e292 // indirect
golang.org/x/net v0.0.0-20220225172249-27dd8689420f // indirect
golang.org/x/oauth2 v0.0.0-20211104180415-d3ed0bb246c8 // indirect
golang.org/x/oauth2 v0.0.0-20220223155221-ee480838109b // indirect
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect
golang.org/x/sys v0.0.0-20220114195835-da31bd327af9 // indirect
golang.org/x/sys v0.0.0-20220227234510-4e6760a101f9 // indirect
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 // indirect
golang.org/x/text v0.3.7 // indirect
golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac // indirect
golang.org/x/time v0.0.0-20220224211638-0e9765cccd65 // indirect
gomodules.xyz/jsonpatch/v2 v2.2.0 // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/protobuf v1.27.1 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
gotest.tools/v3 v3.1.0 // indirect
k8s.io/apiextensions-apiserver v0.23.5 // indirect
k8s.io/cloud-provider v0.21.0 // indirect
k8s.io/component-base v0.23.5 // indirect
k8s.io/klog/v2 v2.50.0 // indirect
k8s.io/kube-openapi v0.0.0-20211115234752-e816edb12b65 // indirect
k8s.io/kube-openapi v0.0.0-20220124234850-424119656bbf // indirect
k8s.io/legacy-cloud-providers v0.21.0 // indirect
k8s.io/utils v0.0.0-20220210201930-3a6ce19ff2f9 // indirect
sigs.k8s.io/json v0.0.0-20211020170558-c049b76a60c6 // indirect
sigs.k8s.io/json v0.0.0-20211208200746-9f7c6b3444d2 // indirect
sigs.k8s.io/structured-merge-diff/v4 v4.2.1 // indirect
sigs.k8s.io/yaml v1.3.0 // indirect
)
Expand Down
Loading