Skip to content

Commit

Permalink
Add --only-metadata option to prevent falling back to other ADC sources
Browse files Browse the repository at this point in the history
If running in CI and a step does a GCP login using a different service
account, those credentials will get picked up over the node's service
which is likelier the preferred account to use since it stays constant.
  • Loading branch information
drcapulet committed Mar 20, 2024
1 parent 3933eae commit 0c2a2ab
Showing 1 changed file with 26 additions and 6 deletions.
32 changes: 26 additions & 6 deletions cmd/gcp-artifact-registry-docker-proxy/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,16 @@ import (
"os"
"strings"

"cloud.google.com/go/compute/metadata"
"github.com/spf13/pflag"
"github.com/spf13/viper"
auth "golang.org/x/oauth2/google"
)

type Config struct {
Listen string
Registry string
Listen string `mapstructure:"listen"`
OnlyMetadata bool `mapstructure:"only-metadata"`
Registry string `mapstructure:"registry"`
}

func main() {
Expand Down Expand Up @@ -46,10 +48,27 @@ func main() {
proxy := httputil.NewSingleHostReverseProxy(remote)

// Configure our GCP authentication.
gcpCredentials, err := auth.FindDefaultCredentials(context.Background(), "https://www.googleapis.com/auth/cloud-platform")
if err != nil {
slog.Error("Unable to setup GCP credentials", slog.Any("err", err))
os.Exit(1)
gcpScopes := []string{"https://www.googleapis.com/auth/cloud-platform"}

var gcpCredentials *auth.Credentials
if config.OnlyMetadata {

Check failure on line 54 in cmd/gcp-artifact-registry-docker-proxy/main.go

View workflow job for this annotation

GitHub Actions / lint

if statements should only be cuddled with assignments used in the if statement itself (wsl)
if !metadata.OnGCE() {
slog.Error("Not running on GCE instance to use metadata server")
os.Exit(1)
}

id, _ := metadata.ProjectID()

gcpCredentials = &auth.Credentials{
ProjectID: id,
TokenSource: auth.ComputeTokenSource("", gcpScopes...),
}
} else {
gcpCredentials, err = auth.FindDefaultCredentials(context.Background(), gcpScopes...)
if err != nil {
slog.Error("Unable to setup GCP credentials", slog.Any("err", err))
os.Exit(1)
}
}

if _, err = gcpCredentials.TokenSource.Token(); err != nil {
Expand Down Expand Up @@ -99,6 +118,7 @@ func parseConfiguration() (*Config, error) {
viper.GetViper().SetDefault("listen", "localhost:8000")

pflag.String("listen", "", "Address for the mirror to listen on.")
pflag.Bool("only-metadata", false, "Only rely upon on the GCE metadata server for authentication.")
pflag.String("registry", "", "URL of the registry to proxy requests to.")

pflag.Parse()
Expand Down

0 comments on commit 0c2a2ab

Please sign in to comment.