Skip to content

Commit

Permalink
feat(sgcloudrun): avoid credentials conflict
Browse files Browse the repository at this point in the history
if two processes run LocalDevelopment command, they should use
different credes.json to avoid conflict.
  • Loading branch information
ngalaiko committed Sep 16, 2024
1 parent d8cae42 commit 5ea4347
Showing 1 changed file with 20 additions and 1 deletion.
21 changes: 20 additions & 1 deletion tools/sgcloudrun/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"errors"
"fmt"
"io"
"math/rand/v2"
"net/http"
"os"
"os/exec"
Expand Down Expand Up @@ -128,7 +129,7 @@ func LocalDevelopCommand(
if err := os.MkdirAll(workDir, 0o755); err != nil {
return nil, fmt.Errorf("unable to create path to store gcloud credentials: %v", err)
}
credsPath := filepath.Join(workDir, "creds.json")
credsPath := filepath.Join(workDir, fmt.Sprintf("creds-%s.json", randomLower(5)))
if err := os.WriteFile(credsPath, delegateCredsJSON, 0o600); err != nil {
return nil, err
}
Expand All @@ -140,6 +141,12 @@ func LocalDevelopCommand(
cmd.Env = append(cmd.Env, "GOOGLE_APPLICATION_CREDENTIALS="+credsPath)
cmd.Env = append(cmd.Env, env...)
cmd.Env = append(cmd.Env, os.Environ()...) // allow environment overrides
cmd.Cancel = func() error {
if err := cmd.Process.Kill(); err != nil {
return err
}
return os.Remove(credsPath)
}
return cmd, nil
}

Expand Down Expand Up @@ -370,3 +377,15 @@ func fetchImpersonatedAccessToken(ctx context.Context, serviceAccountEmail strin

return tokens.AccessToken, nil
}

//nolint:gochecknoglobals
var lower = []rune("abcdefghijklmnopqrstuvwxyz")

func randomLower(n uint32) string {
b := make([]rune, n)
for i := range b {
//nolint:gosec
b[i] = lower[rand.IntN(len(lower))]
}
return string(b)
}

0 comments on commit 5ea4347

Please sign in to comment.