Gcp
func DialGrpc(ctx context.Context, url string) (*grpc.ClientConn, error) {
endpoint, tls, aud := getGrpcEndpoint(url)
opts := []grpc.DialOption{}
if tls {
pool, err := x509.SystemCertPool()
if err != nil {
return nil, fmt.Errorf("failed to get system cert pool: %w", err)
}
creds := credentials.NewClientTLSFromCert(pool, "")
opts = append(opts, grpc.WithTransportCredentials(creds))
} else {
opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
}
if aud != "" {
source, err := idtoken.NewTokenSource(ctx, aud)
if err != nil {
//return nil, fmt.Errorf("failed to create token source: %w", err)
// If that fails, we use our Application Default Credentials to fetch an id_token on the fly
gts, err := google.DefaultTokenSource(ctx)
if err != nil {
return nil, err
}
source = oauth2.ReuseTokenSource(nil, &idTokenSource{TokenSource: gts})
}
opts = append(opts, grpc.WithPerRPCCredentials(oauth.TokenSource{TokenSource: source}))
}
return grpc_module.Dial(endpoint, opts...)
}
type idTokenSource struct {
TokenSource oauth2.TokenSource
}
func (s *idTokenSource) Token() (*oauth2.Token, error) {
token, err := s.TokenSource.Token()
if err != nil {
return nil, err
}
idToken, ok := token.Extra("id_token").(string)
if !ok {
return nil, fmt.Errorf("token did not contain an id_token")
}
return &oauth2.Token{
AccessToken: idToken,
TokenType: "Bearer",
Expiry: token.Expiry,
}, nil
}