Skip to content

Commit d2a517f

Browse files
authored
feat: Support GKE workload identity for Syft image pulling (#776)
Fixes: #775
1 parent a460f95 commit d2a517f

File tree

1 file changed

+41
-1
lines changed

1 file changed

+41
-1
lines changed

internal/syft/syft.go

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import (
2929
"github.com/ckotzbauer/libk8soci/pkg/oci"
3030
"github.com/ckotzbauer/sbom-operator/internal/kubernetes"
3131
"github.com/sirupsen/logrus"
32+
"golang.org/x/oauth2/google"
3233
)
3334

3435
type Syft struct {
@@ -63,7 +64,21 @@ func (s *Syft) ExecuteSyft(img *oci.RegistryImage) (string, error) {
6364
return "", err
6465
}
6566

66-
opts := &image.RegistryOptions{Credentials: oci.ConvertSecrets(*img, s.proxyRegistryMap)}
67+
credentials := oci.ConvertSecrets(*img, s.proxyRegistryMap)
68+
69+
var opts *image.RegistryOptions
70+
if len(credentials) == 0 && isGCPArtifactRegistry(img.ImageID) {
71+
logrus.Debugf("No pull secrets found for GCP Artifact Registry %s, attempting Workload Identity", img.ImageID)
72+
if gcpCreds := getGCPCredentials(context.Background()); gcpCreds != nil {
73+
opts = &image.RegistryOptions{Credentials: []image.RegistryCredentials{*gcpCreds}}
74+
} else {
75+
logrus.Debugf("Failed to get GCP credentials, using empty options")
76+
opts = &image.RegistryOptions{}
77+
}
78+
} else {
79+
opts = &image.RegistryOptions{Credentials: credentials}
80+
}
81+
6782
src, err := getSource(context.Background(), opts, img.ImageID)
6883

6984
// revert image info to the original value - we want to register with original names
@@ -217,3 +232,28 @@ func closeOrLog(c io.Closer) {
217232
logrus.WithError(err).Warnf("Could not close file")
218233
}
219234
}
235+
236+
func isGCPArtifactRegistry(imageID string) bool {
237+
return strings.Contains(imageID, "-docker.pkg.dev/")
238+
}
239+
240+
func getGCPCredentials(ctx context.Context) *image.RegistryCredentials {
241+
creds, err := google.FindDefaultCredentials(ctx, "https://www.googleapis.com/auth/cloud-platform")
242+
if err != nil {
243+
logrus.WithError(err).Debug("Failed to find default GCP credentials")
244+
return nil
245+
}
246+
247+
token, err := creds.TokenSource.Token()
248+
if err != nil {
249+
logrus.WithError(err).Debug("Failed to get GCP access token")
250+
return nil
251+
}
252+
253+
logrus.Debugf("Successfully obtained GCP access token via default credentials (expires: %v)", token.Expiry)
254+
255+
return &image.RegistryCredentials{
256+
Username: "oauth2accesstoken",
257+
Password: token.AccessToken,
258+
}
259+
}

0 commit comments

Comments
 (0)