forked from jsteenb2/mess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
41 lines (33 loc) · 1.18 KB
/
auth.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package client
import (
"context"
"fmt"
"strings"
"cloud.google.com/go/compute/metadata"
"github.com/pkg/errors"
"google.golang.org/grpc/credentials"
)
type metadataServerToken struct {
serviceURL string
}
func newMetadataServerToken(grpcAddr string) credentials.PerRPCCredentials {
// based on https://cloud.google.com/run/docs/authenticating/service-to-service#go
// service need to have https prefix without port
serviceURL := "https://" + strings.Split(grpcAddr, ":")[0]
return metadataServerToken{serviceURL}
}
// GetRequestMetadata is called on every request, so we are sure that token is always not expired
func (t metadataServerToken) GetRequestMetadata(ctx context.Context, in ...string) (map[string]string, error) {
// based on https://cloud.google.com/run/docs/authenticating/service-to-service#go
tokenURL := fmt.Sprintf("/instance/service-accounts/default/identity?audience=%s", t.serviceURL)
idToken, err := metadata.Get(tokenURL)
if err != nil {
return nil, errors.Wrap(err, "cannot query id token for gRPC")
}
return map[string]string{
"authorization": "Bearer " + idToken,
}, nil
}
func (metadataServerToken) RequireTransportSecurity() bool {
return true
}