Skip to content

Commit

Permalink
Use instance service account credentials if available. (#462)
Browse files Browse the repository at this point in the history
  • Loading branch information
ser-io authored Mar 4, 2024
1 parent 7c8ce08 commit 58bec06
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,12 @@ func (a *CreateCVDAction) launchWithCanonicalConfig(op apiv1.Operation) (*apiv1.
}
}()
args = append(args, "--credential_source="+filename)
} else if isRunningOnGCE() {
if ok, err := hasServiceAccountAccessToken(); err != nil {
log.Printf("service account token check failed: %s", err)
} else if ok {
args = append(args, "--credential_source=gce")
}
}
opts := cvd.CommandOpts{
Timeout: a.cvdStartTimeout,
Expand Down
28 changes: 28 additions & 0 deletions frontend/src/host_orchestrator/orchestrator/instancemanager.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import (
"encoding/json"
"fmt"
"log"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
Expand Down Expand Up @@ -322,6 +324,12 @@ func (f *fetchCVDCommandArtifactsFetcher) Fetch(outDir, buildID, target string,
// The actual fd number is not retained, the lowest available number is used instead.
fd := 3 + len(fetchCmd.ExtraFiles) - 1
fetchCmd.Args = append(fetchCmd.Args, fmt.Sprintf("--credential_source=/proc/self/fd/%d", fd))
} else if isRunningOnGCE() {
if ok, err := hasServiceAccountAccessToken(); err != nil {
log.Printf("service account token check failed: %s", err)
} else if ok {
fetchCmd.Args = append(fetchCmd.Args, "--credential_source=gce")
}
}
out, err := fetchCmd.CombinedOutput()
if err != nil {
Expand Down Expand Up @@ -586,3 +594,23 @@ func contains(s []uint32, e uint32) bool {
}
return false
}

func isRunningOnGCE() bool {
_, err := net.LookupIP("metadata.google.internal")
return err == nil
}

// For instances running on GCE, checks whether the instance was created with a service account having an access token.
func hasServiceAccountAccessToken() (bool, error) {
req, err := http.NewRequest("GET", "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token", nil)
if err != nil {
return false, err
}
req.Header.Set("Metadata-Flavor", "Google")
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
return false, err
}
return res.StatusCode == http.StatusOK, nil
}

0 comments on commit 58bec06

Please sign in to comment.