golang.org/x/build@v0.0.0-20240506185731-218518f32b70/internal/gitauth/gitauth.go (about)

     1  // Copyright 2018 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package gitauth writes gitcookies files so git will authenticate
     6  // to Gerrit as gopherbot for quota purposes.
     7  package gitauth
     8  
     9  import (
    10  	"bytes"
    11  	"context"
    12  	"fmt"
    13  	"log"
    14  	"os"
    15  	"os/exec"
    16  	"path/filepath"
    17  	"strings"
    18  	"time"
    19  
    20  	"cloud.google.com/go/compute/metadata"
    21  	"golang.org/x/build/internal/secret"
    22  )
    23  
    24  func Init() error {
    25  	cookieFile := filepath.Join(homeDir(), ".gitcookies")
    26  	if err := exec.Command("git", "config", "--global", "http.cookiefile", cookieFile).Run(); err != nil {
    27  		return fmt.Errorf("running git config to set cookiefile: %v", err)
    28  	}
    29  	if !metadata.OnGCE() {
    30  		// Do nothing for now.
    31  		return nil
    32  	}
    33  
    34  	sc := secret.MustNewClient()
    35  	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    36  	defer cancel()
    37  
    38  	slurp, err := sc.Retrieve(ctx, secret.NameGobotPassword)
    39  	if err != nil {
    40  		proj, _ := metadata.ProjectID()
    41  		if proj != "symbolic-datum-552" { // TODO: don't hard-code this; use buildenv package
    42  			log.Printf("gitauth: ignoring %q secret manager lookup on non-prod project: %v", secret.NameGobotPassword, err)
    43  			return nil
    44  		}
    45  		return fmt.Errorf("gitauth: getting %s secret manager: %v", secret.NameGobotPassword, err)
    46  	}
    47  	slurp = strings.TrimSpace(slurp)
    48  	var buf bytes.Buffer
    49  	fmt.Fprintf(&buf, "go.googlesource.com\tFALSE\t/\tTRUE\t2147483647\to\tgit-gobot.gmail.com=%s\n", slurp)
    50  	fmt.Fprintf(&buf, "go-review.googlesource.com\tFALSE\t/\tTRUE\t2147483647\to\tgit-gobot.gmail.com=%s\n", slurp)
    51  	return os.WriteFile(cookieFile, buf.Bytes(), 0644)
    52  }
    53  
    54  func homeDir() string {
    55  	if h := os.Getenv("HOME"); h != "" {
    56  		return h
    57  	}
    58  	log.Fatalf("No HOME set in environment.")
    59  	panic("unreachable")
    60  }