| 1 |
// Package util provides helper funtions to prepare materials for talking to attestation verifiers. |
| 2 |
package util |
| 3 |
|
| 4 |
import ( |
| 5 |
"context" |
| 6 |
"fmt" |
| 7 |
"io" |
| 8 |
"net/url" |
| 9 |
"strings" |
| 10 |
|
| 11 |
"cloud.google.com/go/compute/metadata" |
| 12 |
"github.com/google/go-tpm-tools/client" |
| 13 |
"github.com/google/go-tpm-tools/verifier" |
| 14 |
"github.com/google/go-tpm-tools/verifier/rest" |
| 15 |
"golang.org/x/oauth2/google" |
| 16 |
"google.golang.org/api/option" |
| 17 |
) |
| 18 |
|
| 19 |
// TpmKeyFetcher abstracts the fetching of various types of Attestation Key from TPM |
| 20 |
type TpmKeyFetcher func(rw io.ReadWriter) (*client.Key, error) |
| 21 |
|
| 22 |
// PrincipalFetcher fetch ID token with specific audience from Metadata server. |
| 23 |
// See https://cloud.google.com/functions/docs/securing/authenticating#functions-bearer-token-example-go. |
| 24 |
func PrincipalFetcher(audience string, mdsClient *metadata.Client) ([][]byte, error) { |
| 25 |
u := url.URL{ |
| 26 |
Path: "instance/service-accounts/default/identity", |
| 27 |
RawQuery: url.Values{ |
| 28 |
"audience": {audience}, |
| 29 |
"format": {"full"}, |
| 30 |
}.Encode(), |
| 31 |
} |
| 32 |
idToken, err := mdsClient.Get(u.String()) |
| 33 |
if err != nil { |
| 34 |
return nil, fmt.Errorf("failed to get principal tokens: %w", err) |
| 35 |
} |
| 36 |
|
| 37 |
tokens := [][]byte{[]byte(idToken)} |
| 38 |
return tokens, nil |
| 39 |
} |
| 40 |
|
| 41 |
// NewRESTClient returns a REST verifier.Client that points to the given address. |
| 42 |
// It defaults to the Attestation Verifier instance at |
| 43 |
// https://confidentialcomputing.googleapis.com. |
| 44 |
func NewRESTClient(ctx context.Context, asAddr string, ProjectID string, Region string) (verifier.Client, error) { |
| 45 |
httpClient, err := google.DefaultClient(ctx) |
| 46 |
if err != nil { |
| 47 |
return nil, fmt.Errorf("failed to create HTTP client: %v", err) |
| 48 |
} |
| 49 |
|
| 50 |
opts := []option.ClientOption{option.WithHTTPClient(httpClient)} |
| 51 |
if asAddr != "" { |
| 52 |
opts = append(opts, option.WithEndpoint(asAddr)) |
| 53 |
} |
| 54 |
|
| 55 |
restClient, err := rest.NewClient(ctx, ProjectID, Region, opts...) |
| 56 |
if err != nil { |
| 57 |
return nil, err |
| 58 |
} |
| 59 |
return restClient, nil |
| 60 |
} |
| 61 |
|
| 62 |
// GetRegion retrieves region information from GCE metadata server |
| 63 |
func GetRegion(client *metadata.Client) (string, error) { |
| 64 |
zone, err := client.Zone() |
| 65 |
if err != nil { |
| 66 |
return "", fmt.Errorf("failed to retrieve zone from MDS: %v", err) |
| 67 |
} |
| 68 |
lastDash := strings.LastIndex(zone, "-") |
| 69 |
if lastDash == -1 { |
| 70 |
return "", fmt.Errorf("got malformed zone from MDS: %v", zone) |
| 71 |
} |
| 72 |
return zone[:lastDash], nil |
| 73 |
} |