...

Source file src/cloud.google.com/go/iam/credentials/apiv1/iam_credentials_client.go

Documentation: cloud.google.com/go/iam/credentials/apiv1

     1  // Copyright 2024 Google LLC
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     https://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // Code generated by protoc-gen-go_gapic. DO NOT EDIT.
    16  
    17  package credentials
    18  
    19  import (
    20  	"bytes"
    21  	"context"
    22  	"fmt"
    23  	"io"
    24  	"math"
    25  	"net/http"
    26  	"net/url"
    27  	"time"
    28  
    29  	credentialspb "cloud.google.com/go/iam/credentials/apiv1/credentialspb"
    30  	gax "github.com/googleapis/gax-go/v2"
    31  	"google.golang.org/api/googleapi"
    32  	"google.golang.org/api/option"
    33  	"google.golang.org/api/option/internaloption"
    34  	gtransport "google.golang.org/api/transport/grpc"
    35  	httptransport "google.golang.org/api/transport/http"
    36  	"google.golang.org/grpc"
    37  	"google.golang.org/grpc/codes"
    38  	"google.golang.org/protobuf/encoding/protojson"
    39  )
    40  
    41  var newIamCredentialsClientHook clientHook
    42  
    43  // IamCredentialsCallOptions contains the retry settings for each method of IamCredentialsClient.
    44  type IamCredentialsCallOptions struct {
    45  	GenerateAccessToken []gax.CallOption
    46  	GenerateIdToken     []gax.CallOption
    47  	SignBlob            []gax.CallOption
    48  	SignJwt             []gax.CallOption
    49  }
    50  
    51  func defaultIamCredentialsGRPCClientOptions() []option.ClientOption {
    52  	return []option.ClientOption{
    53  		internaloption.WithDefaultEndpoint("iamcredentials.googleapis.com:443"),
    54  		internaloption.WithDefaultEndpointTemplate("iamcredentials.UNIVERSE_DOMAIN:443"),
    55  		internaloption.WithDefaultMTLSEndpoint("iamcredentials.mtls.googleapis.com:443"),
    56  		internaloption.WithDefaultUniverseDomain("googleapis.com"),
    57  		internaloption.WithDefaultAudience("https://iamcredentials.googleapis.com/"),
    58  		internaloption.WithDefaultScopes(DefaultAuthScopes()...),
    59  		internaloption.EnableJwtWithScope(),
    60  		option.WithGRPCDialOption(grpc.WithDefaultCallOptions(
    61  			grpc.MaxCallRecvMsgSize(math.MaxInt32))),
    62  	}
    63  }
    64  
    65  func defaultIamCredentialsCallOptions() *IamCredentialsCallOptions {
    66  	return &IamCredentialsCallOptions{
    67  		GenerateAccessToken: []gax.CallOption{
    68  			gax.WithTimeout(60000 * time.Millisecond),
    69  			gax.WithRetry(func() gax.Retryer {
    70  				return gax.OnCodes([]codes.Code{
    71  					codes.Unavailable,
    72  					codes.DeadlineExceeded,
    73  				}, gax.Backoff{
    74  					Initial:    100 * time.Millisecond,
    75  					Max:        60000 * time.Millisecond,
    76  					Multiplier: 1.30,
    77  				})
    78  			}),
    79  		},
    80  		GenerateIdToken: []gax.CallOption{
    81  			gax.WithTimeout(60000 * time.Millisecond),
    82  			gax.WithRetry(func() gax.Retryer {
    83  				return gax.OnCodes([]codes.Code{
    84  					codes.Unavailable,
    85  					codes.DeadlineExceeded,
    86  				}, gax.Backoff{
    87  					Initial:    100 * time.Millisecond,
    88  					Max:        60000 * time.Millisecond,
    89  					Multiplier: 1.30,
    90  				})
    91  			}),
    92  		},
    93  		SignBlob: []gax.CallOption{
    94  			gax.WithTimeout(60000 * time.Millisecond),
    95  			gax.WithRetry(func() gax.Retryer {
    96  				return gax.OnCodes([]codes.Code{
    97  					codes.Unavailable,
    98  					codes.DeadlineExceeded,
    99  				}, gax.Backoff{
   100  					Initial:    100 * time.Millisecond,
   101  					Max:        60000 * time.Millisecond,
   102  					Multiplier: 1.30,
   103  				})
   104  			}),
   105  		},
   106  		SignJwt: []gax.CallOption{
   107  			gax.WithTimeout(60000 * time.Millisecond),
   108  			gax.WithRetry(func() gax.Retryer {
   109  				return gax.OnCodes([]codes.Code{
   110  					codes.Unavailable,
   111  					codes.DeadlineExceeded,
   112  				}, gax.Backoff{
   113  					Initial:    100 * time.Millisecond,
   114  					Max:        60000 * time.Millisecond,
   115  					Multiplier: 1.30,
   116  				})
   117  			}),
   118  		},
   119  	}
   120  }
   121  
   122  func defaultIamCredentialsRESTCallOptions() *IamCredentialsCallOptions {
   123  	return &IamCredentialsCallOptions{
   124  		GenerateAccessToken: []gax.CallOption{
   125  			gax.WithTimeout(60000 * time.Millisecond),
   126  			gax.WithRetry(func() gax.Retryer {
   127  				return gax.OnHTTPCodes(gax.Backoff{
   128  					Initial:    100 * time.Millisecond,
   129  					Max:        60000 * time.Millisecond,
   130  					Multiplier: 1.30,
   131  				},
   132  					http.StatusServiceUnavailable,
   133  					http.StatusGatewayTimeout)
   134  			}),
   135  		},
   136  		GenerateIdToken: []gax.CallOption{
   137  			gax.WithTimeout(60000 * time.Millisecond),
   138  			gax.WithRetry(func() gax.Retryer {
   139  				return gax.OnHTTPCodes(gax.Backoff{
   140  					Initial:    100 * time.Millisecond,
   141  					Max:        60000 * time.Millisecond,
   142  					Multiplier: 1.30,
   143  				},
   144  					http.StatusServiceUnavailable,
   145  					http.StatusGatewayTimeout)
   146  			}),
   147  		},
   148  		SignBlob: []gax.CallOption{
   149  			gax.WithTimeout(60000 * time.Millisecond),
   150  			gax.WithRetry(func() gax.Retryer {
   151  				return gax.OnHTTPCodes(gax.Backoff{
   152  					Initial:    100 * time.Millisecond,
   153  					Max:        60000 * time.Millisecond,
   154  					Multiplier: 1.30,
   155  				},
   156  					http.StatusServiceUnavailable,
   157  					http.StatusGatewayTimeout)
   158  			}),
   159  		},
   160  		SignJwt: []gax.CallOption{
   161  			gax.WithTimeout(60000 * time.Millisecond),
   162  			gax.WithRetry(func() gax.Retryer {
   163  				return gax.OnHTTPCodes(gax.Backoff{
   164  					Initial:    100 * time.Millisecond,
   165  					Max:        60000 * time.Millisecond,
   166  					Multiplier: 1.30,
   167  				},
   168  					http.StatusServiceUnavailable,
   169  					http.StatusGatewayTimeout)
   170  			}),
   171  		},
   172  	}
   173  }
   174  
   175  // internalIamCredentialsClient is an interface that defines the methods available from IAM Service Account Credentials API.
   176  type internalIamCredentialsClient interface {
   177  	Close() error
   178  	setGoogleClientInfo(...string)
   179  	Connection() *grpc.ClientConn
   180  	GenerateAccessToken(context.Context, *credentialspb.GenerateAccessTokenRequest, ...gax.CallOption) (*credentialspb.GenerateAccessTokenResponse, error)
   181  	GenerateIdToken(context.Context, *credentialspb.GenerateIdTokenRequest, ...gax.CallOption) (*credentialspb.GenerateIdTokenResponse, error)
   182  	SignBlob(context.Context, *credentialspb.SignBlobRequest, ...gax.CallOption) (*credentialspb.SignBlobResponse, error)
   183  	SignJwt(context.Context, *credentialspb.SignJwtRequest, ...gax.CallOption) (*credentialspb.SignJwtResponse, error)
   184  }
   185  
   186  // IamCredentialsClient is a client for interacting with IAM Service Account Credentials API.
   187  // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
   188  //
   189  // A service account is a special type of Google account that belongs to your
   190  // application or a virtual machine (VM), instead of to an individual end user.
   191  // Your application assumes the identity of the service account to call Google
   192  // APIs, so that the users aren’t directly involved.
   193  //
   194  // Service account credentials are used to temporarily assume the identity
   195  // of the service account. Supported credential types include OAuth 2.0 access
   196  // tokens, OpenID Connect ID tokens, self-signed JSON Web Tokens (JWTs), and
   197  // more.
   198  type IamCredentialsClient struct {
   199  	// The internal transport-dependent client.
   200  	internalClient internalIamCredentialsClient
   201  
   202  	// The call options for this service.
   203  	CallOptions *IamCredentialsCallOptions
   204  }
   205  
   206  // Wrapper methods routed to the internal client.
   207  
   208  // Close closes the connection to the API service. The user should invoke this when
   209  // the client is no longer required.
   210  func (c *IamCredentialsClient) Close() error {
   211  	return c.internalClient.Close()
   212  }
   213  
   214  // setGoogleClientInfo sets the name and version of the application in
   215  // the `x-goog-api-client` header passed on each request. Intended for
   216  // use by Google-written clients.
   217  func (c *IamCredentialsClient) setGoogleClientInfo(keyval ...string) {
   218  	c.internalClient.setGoogleClientInfo(keyval...)
   219  }
   220  
   221  // Connection returns a connection to the API service.
   222  //
   223  // Deprecated: Connections are now pooled so this method does not always
   224  // return the same resource.
   225  func (c *IamCredentialsClient) Connection() *grpc.ClientConn {
   226  	return c.internalClient.Connection()
   227  }
   228  
   229  // GenerateAccessToken generates an OAuth 2.0 access token for a service account.
   230  func (c *IamCredentialsClient) GenerateAccessToken(ctx context.Context, req *credentialspb.GenerateAccessTokenRequest, opts ...gax.CallOption) (*credentialspb.GenerateAccessTokenResponse, error) {
   231  	return c.internalClient.GenerateAccessToken(ctx, req, opts...)
   232  }
   233  
   234  // GenerateIdToken generates an OpenID Connect ID token for a service account.
   235  func (c *IamCredentialsClient) GenerateIdToken(ctx context.Context, req *credentialspb.GenerateIdTokenRequest, opts ...gax.CallOption) (*credentialspb.GenerateIdTokenResponse, error) {
   236  	return c.internalClient.GenerateIdToken(ctx, req, opts...)
   237  }
   238  
   239  // SignBlob signs a blob using a service account’s system-managed private key.
   240  func (c *IamCredentialsClient) SignBlob(ctx context.Context, req *credentialspb.SignBlobRequest, opts ...gax.CallOption) (*credentialspb.SignBlobResponse, error) {
   241  	return c.internalClient.SignBlob(ctx, req, opts...)
   242  }
   243  
   244  // SignJwt signs a JWT using a service account’s system-managed private key.
   245  func (c *IamCredentialsClient) SignJwt(ctx context.Context, req *credentialspb.SignJwtRequest, opts ...gax.CallOption) (*credentialspb.SignJwtResponse, error) {
   246  	return c.internalClient.SignJwt(ctx, req, opts...)
   247  }
   248  
   249  // iamCredentialsGRPCClient is a client for interacting with IAM Service Account Credentials API over gRPC transport.
   250  //
   251  // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
   252  type iamCredentialsGRPCClient struct {
   253  	// Connection pool of gRPC connections to the service.
   254  	connPool gtransport.ConnPool
   255  
   256  	// Points back to the CallOptions field of the containing IamCredentialsClient
   257  	CallOptions **IamCredentialsCallOptions
   258  
   259  	// The gRPC API client.
   260  	iamCredentialsClient credentialspb.IAMCredentialsClient
   261  
   262  	// The x-goog-* metadata to be sent with each request.
   263  	xGoogHeaders []string
   264  }
   265  
   266  // NewIamCredentialsClient creates a new iam credentials client based on gRPC.
   267  // The returned client must be Closed when it is done being used to clean up its underlying connections.
   268  //
   269  // A service account is a special type of Google account that belongs to your
   270  // application or a virtual machine (VM), instead of to an individual end user.
   271  // Your application assumes the identity of the service account to call Google
   272  // APIs, so that the users aren’t directly involved.
   273  //
   274  // Service account credentials are used to temporarily assume the identity
   275  // of the service account. Supported credential types include OAuth 2.0 access
   276  // tokens, OpenID Connect ID tokens, self-signed JSON Web Tokens (JWTs), and
   277  // more.
   278  func NewIamCredentialsClient(ctx context.Context, opts ...option.ClientOption) (*IamCredentialsClient, error) {
   279  	clientOpts := defaultIamCredentialsGRPCClientOptions()
   280  	if newIamCredentialsClientHook != nil {
   281  		hookOpts, err := newIamCredentialsClientHook(ctx, clientHookParams{})
   282  		if err != nil {
   283  			return nil, err
   284  		}
   285  		clientOpts = append(clientOpts, hookOpts...)
   286  	}
   287  
   288  	connPool, err := gtransport.DialPool(ctx, append(clientOpts, opts...)...)
   289  	if err != nil {
   290  		return nil, err
   291  	}
   292  	client := IamCredentialsClient{CallOptions: defaultIamCredentialsCallOptions()}
   293  
   294  	c := &iamCredentialsGRPCClient{
   295  		connPool:             connPool,
   296  		iamCredentialsClient: credentialspb.NewIAMCredentialsClient(connPool),
   297  		CallOptions:          &client.CallOptions,
   298  	}
   299  	c.setGoogleClientInfo()
   300  
   301  	client.internalClient = c
   302  
   303  	return &client, nil
   304  }
   305  
   306  // Connection returns a connection to the API service.
   307  //
   308  // Deprecated: Connections are now pooled so this method does not always
   309  // return the same resource.
   310  func (c *iamCredentialsGRPCClient) Connection() *grpc.ClientConn {
   311  	return c.connPool.Conn()
   312  }
   313  
   314  // setGoogleClientInfo sets the name and version of the application in
   315  // the `x-goog-api-client` header passed on each request. Intended for
   316  // use by Google-written clients.
   317  func (c *iamCredentialsGRPCClient) setGoogleClientInfo(keyval ...string) {
   318  	kv := append([]string{"gl-go", gax.GoVersion}, keyval...)
   319  	kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "grpc", grpc.Version)
   320  	c.xGoogHeaders = []string{"x-goog-api-client", gax.XGoogHeader(kv...)}
   321  }
   322  
   323  // Close closes the connection to the API service. The user should invoke this when
   324  // the client is no longer required.
   325  func (c *iamCredentialsGRPCClient) Close() error {
   326  	return c.connPool.Close()
   327  }
   328  
   329  // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
   330  type iamCredentialsRESTClient struct {
   331  	// The http endpoint to connect to.
   332  	endpoint string
   333  
   334  	// The http client.
   335  	httpClient *http.Client
   336  
   337  	// The x-goog-* headers to be sent with each request.
   338  	xGoogHeaders []string
   339  
   340  	// Points back to the CallOptions field of the containing IamCredentialsClient
   341  	CallOptions **IamCredentialsCallOptions
   342  }
   343  
   344  // NewIamCredentialsRESTClient creates a new iam credentials rest client.
   345  //
   346  // A service account is a special type of Google account that belongs to your
   347  // application or a virtual machine (VM), instead of to an individual end user.
   348  // Your application assumes the identity of the service account to call Google
   349  // APIs, so that the users aren’t directly involved.
   350  //
   351  // Service account credentials are used to temporarily assume the identity
   352  // of the service account. Supported credential types include OAuth 2.0 access
   353  // tokens, OpenID Connect ID tokens, self-signed JSON Web Tokens (JWTs), and
   354  // more.
   355  func NewIamCredentialsRESTClient(ctx context.Context, opts ...option.ClientOption) (*IamCredentialsClient, error) {
   356  	clientOpts := append(defaultIamCredentialsRESTClientOptions(), opts...)
   357  	httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...)
   358  	if err != nil {
   359  		return nil, err
   360  	}
   361  
   362  	callOpts := defaultIamCredentialsRESTCallOptions()
   363  	c := &iamCredentialsRESTClient{
   364  		endpoint:    endpoint,
   365  		httpClient:  httpClient,
   366  		CallOptions: &callOpts,
   367  	}
   368  	c.setGoogleClientInfo()
   369  
   370  	return &IamCredentialsClient{internalClient: c, CallOptions: callOpts}, nil
   371  }
   372  
   373  func defaultIamCredentialsRESTClientOptions() []option.ClientOption {
   374  	return []option.ClientOption{
   375  		internaloption.WithDefaultEndpoint("https://iamcredentials.googleapis.com"),
   376  		internaloption.WithDefaultEndpointTemplate("https://iamcredentials.UNIVERSE_DOMAIN"),
   377  		internaloption.WithDefaultMTLSEndpoint("https://iamcredentials.mtls.googleapis.com"),
   378  		internaloption.WithDefaultUniverseDomain("googleapis.com"),
   379  		internaloption.WithDefaultAudience("https://iamcredentials.googleapis.com/"),
   380  		internaloption.WithDefaultScopes(DefaultAuthScopes()...),
   381  	}
   382  }
   383  
   384  // setGoogleClientInfo sets the name and version of the application in
   385  // the `x-goog-api-client` header passed on each request. Intended for
   386  // use by Google-written clients.
   387  func (c *iamCredentialsRESTClient) setGoogleClientInfo(keyval ...string) {
   388  	kv := append([]string{"gl-go", gax.GoVersion}, keyval...)
   389  	kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN")
   390  	c.xGoogHeaders = []string{"x-goog-api-client", gax.XGoogHeader(kv...)}
   391  }
   392  
   393  // Close closes the connection to the API service. The user should invoke this when
   394  // the client is no longer required.
   395  func (c *iamCredentialsRESTClient) Close() error {
   396  	// Replace httpClient with nil to force cleanup.
   397  	c.httpClient = nil
   398  	return nil
   399  }
   400  
   401  // Connection returns a connection to the API service.
   402  //
   403  // Deprecated: This method always returns nil.
   404  func (c *iamCredentialsRESTClient) Connection() *grpc.ClientConn {
   405  	return nil
   406  }
   407  func (c *iamCredentialsGRPCClient) GenerateAccessToken(ctx context.Context, req *credentialspb.GenerateAccessTokenRequest, opts ...gax.CallOption) (*credentialspb.GenerateAccessTokenResponse, error) {
   408  	hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))}
   409  
   410  	hds = append(c.xGoogHeaders, hds...)
   411  	ctx = gax.InsertMetadataIntoOutgoingContext(ctx, hds...)
   412  	opts = append((*c.CallOptions).GenerateAccessToken[0:len((*c.CallOptions).GenerateAccessToken):len((*c.CallOptions).GenerateAccessToken)], opts...)
   413  	var resp *credentialspb.GenerateAccessTokenResponse
   414  	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
   415  		var err error
   416  		resp, err = c.iamCredentialsClient.GenerateAccessToken(ctx, req, settings.GRPC...)
   417  		return err
   418  	}, opts...)
   419  	if err != nil {
   420  		return nil, err
   421  	}
   422  	return resp, nil
   423  }
   424  
   425  func (c *iamCredentialsGRPCClient) GenerateIdToken(ctx context.Context, req *credentialspb.GenerateIdTokenRequest, opts ...gax.CallOption) (*credentialspb.GenerateIdTokenResponse, error) {
   426  	hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))}
   427  
   428  	hds = append(c.xGoogHeaders, hds...)
   429  	ctx = gax.InsertMetadataIntoOutgoingContext(ctx, hds...)
   430  	opts = append((*c.CallOptions).GenerateIdToken[0:len((*c.CallOptions).GenerateIdToken):len((*c.CallOptions).GenerateIdToken)], opts...)
   431  	var resp *credentialspb.GenerateIdTokenResponse
   432  	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
   433  		var err error
   434  		resp, err = c.iamCredentialsClient.GenerateIdToken(ctx, req, settings.GRPC...)
   435  		return err
   436  	}, opts...)
   437  	if err != nil {
   438  		return nil, err
   439  	}
   440  	return resp, nil
   441  }
   442  
   443  func (c *iamCredentialsGRPCClient) SignBlob(ctx context.Context, req *credentialspb.SignBlobRequest, opts ...gax.CallOption) (*credentialspb.SignBlobResponse, error) {
   444  	hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))}
   445  
   446  	hds = append(c.xGoogHeaders, hds...)
   447  	ctx = gax.InsertMetadataIntoOutgoingContext(ctx, hds...)
   448  	opts = append((*c.CallOptions).SignBlob[0:len((*c.CallOptions).SignBlob):len((*c.CallOptions).SignBlob)], opts...)
   449  	var resp *credentialspb.SignBlobResponse
   450  	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
   451  		var err error
   452  		resp, err = c.iamCredentialsClient.SignBlob(ctx, req, settings.GRPC...)
   453  		return err
   454  	}, opts...)
   455  	if err != nil {
   456  		return nil, err
   457  	}
   458  	return resp, nil
   459  }
   460  
   461  func (c *iamCredentialsGRPCClient) SignJwt(ctx context.Context, req *credentialspb.SignJwtRequest, opts ...gax.CallOption) (*credentialspb.SignJwtResponse, error) {
   462  	hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))}
   463  
   464  	hds = append(c.xGoogHeaders, hds...)
   465  	ctx = gax.InsertMetadataIntoOutgoingContext(ctx, hds...)
   466  	opts = append((*c.CallOptions).SignJwt[0:len((*c.CallOptions).SignJwt):len((*c.CallOptions).SignJwt)], opts...)
   467  	var resp *credentialspb.SignJwtResponse
   468  	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
   469  		var err error
   470  		resp, err = c.iamCredentialsClient.SignJwt(ctx, req, settings.GRPC...)
   471  		return err
   472  	}, opts...)
   473  	if err != nil {
   474  		return nil, err
   475  	}
   476  	return resp, nil
   477  }
   478  
   479  // GenerateAccessToken generates an OAuth 2.0 access token for a service account.
   480  func (c *iamCredentialsRESTClient) GenerateAccessToken(ctx context.Context, req *credentialspb.GenerateAccessTokenRequest, opts ...gax.CallOption) (*credentialspb.GenerateAccessTokenResponse, error) {
   481  	m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true}
   482  	jsonReq, err := m.Marshal(req)
   483  	if err != nil {
   484  		return nil, err
   485  	}
   486  
   487  	baseUrl, err := url.Parse(c.endpoint)
   488  	if err != nil {
   489  		return nil, err
   490  	}
   491  	baseUrl.Path += fmt.Sprintf("/v1/%v:generateAccessToken", req.GetName())
   492  
   493  	params := url.Values{}
   494  	params.Add("$alt", "json;enum-encoding=int")
   495  
   496  	baseUrl.RawQuery = params.Encode()
   497  
   498  	// Build HTTP headers from client and context metadata.
   499  	hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))}
   500  
   501  	hds = append(c.xGoogHeaders, hds...)
   502  	hds = append(hds, "Content-Type", "application/json")
   503  	headers := gax.BuildHeaders(ctx, hds...)
   504  	opts = append((*c.CallOptions).GenerateAccessToken[0:len((*c.CallOptions).GenerateAccessToken):len((*c.CallOptions).GenerateAccessToken)], opts...)
   505  	unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
   506  	resp := &credentialspb.GenerateAccessTokenResponse{}
   507  	e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
   508  		if settings.Path != "" {
   509  			baseUrl.Path = settings.Path
   510  		}
   511  		httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq))
   512  		if err != nil {
   513  			return err
   514  		}
   515  		httpReq = httpReq.WithContext(ctx)
   516  		httpReq.Header = headers
   517  
   518  		httpRsp, err := c.httpClient.Do(httpReq)
   519  		if err != nil {
   520  			return err
   521  		}
   522  		defer httpRsp.Body.Close()
   523  
   524  		if err = googleapi.CheckResponse(httpRsp); err != nil {
   525  			return err
   526  		}
   527  
   528  		buf, err := io.ReadAll(httpRsp.Body)
   529  		if err != nil {
   530  			return err
   531  		}
   532  
   533  		if err := unm.Unmarshal(buf, resp); err != nil {
   534  			return err
   535  		}
   536  
   537  		return nil
   538  	}, opts...)
   539  	if e != nil {
   540  		return nil, e
   541  	}
   542  	return resp, nil
   543  }
   544  
   545  // GenerateIdToken generates an OpenID Connect ID token for a service account.
   546  func (c *iamCredentialsRESTClient) GenerateIdToken(ctx context.Context, req *credentialspb.GenerateIdTokenRequest, opts ...gax.CallOption) (*credentialspb.GenerateIdTokenResponse, error) {
   547  	m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true}
   548  	jsonReq, err := m.Marshal(req)
   549  	if err != nil {
   550  		return nil, err
   551  	}
   552  
   553  	baseUrl, err := url.Parse(c.endpoint)
   554  	if err != nil {
   555  		return nil, err
   556  	}
   557  	baseUrl.Path += fmt.Sprintf("/v1/%v:generateIdToken", req.GetName())
   558  
   559  	params := url.Values{}
   560  	params.Add("$alt", "json;enum-encoding=int")
   561  
   562  	baseUrl.RawQuery = params.Encode()
   563  
   564  	// Build HTTP headers from client and context metadata.
   565  	hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))}
   566  
   567  	hds = append(c.xGoogHeaders, hds...)
   568  	hds = append(hds, "Content-Type", "application/json")
   569  	headers := gax.BuildHeaders(ctx, hds...)
   570  	opts = append((*c.CallOptions).GenerateIdToken[0:len((*c.CallOptions).GenerateIdToken):len((*c.CallOptions).GenerateIdToken)], opts...)
   571  	unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
   572  	resp := &credentialspb.GenerateIdTokenResponse{}
   573  	e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
   574  		if settings.Path != "" {
   575  			baseUrl.Path = settings.Path
   576  		}
   577  		httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq))
   578  		if err != nil {
   579  			return err
   580  		}
   581  		httpReq = httpReq.WithContext(ctx)
   582  		httpReq.Header = headers
   583  
   584  		httpRsp, err := c.httpClient.Do(httpReq)
   585  		if err != nil {
   586  			return err
   587  		}
   588  		defer httpRsp.Body.Close()
   589  
   590  		if err = googleapi.CheckResponse(httpRsp); err != nil {
   591  			return err
   592  		}
   593  
   594  		buf, err := io.ReadAll(httpRsp.Body)
   595  		if err != nil {
   596  			return err
   597  		}
   598  
   599  		if err := unm.Unmarshal(buf, resp); err != nil {
   600  			return err
   601  		}
   602  
   603  		return nil
   604  	}, opts...)
   605  	if e != nil {
   606  		return nil, e
   607  	}
   608  	return resp, nil
   609  }
   610  
   611  // SignBlob signs a blob using a service account’s system-managed private key.
   612  func (c *iamCredentialsRESTClient) SignBlob(ctx context.Context, req *credentialspb.SignBlobRequest, opts ...gax.CallOption) (*credentialspb.SignBlobResponse, error) {
   613  	m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true}
   614  	jsonReq, err := m.Marshal(req)
   615  	if err != nil {
   616  		return nil, err
   617  	}
   618  
   619  	baseUrl, err := url.Parse(c.endpoint)
   620  	if err != nil {
   621  		return nil, err
   622  	}
   623  	baseUrl.Path += fmt.Sprintf("/v1/%v:signBlob", req.GetName())
   624  
   625  	params := url.Values{}
   626  	params.Add("$alt", "json;enum-encoding=int")
   627  
   628  	baseUrl.RawQuery = params.Encode()
   629  
   630  	// Build HTTP headers from client and context metadata.
   631  	hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))}
   632  
   633  	hds = append(c.xGoogHeaders, hds...)
   634  	hds = append(hds, "Content-Type", "application/json")
   635  	headers := gax.BuildHeaders(ctx, hds...)
   636  	opts = append((*c.CallOptions).SignBlob[0:len((*c.CallOptions).SignBlob):len((*c.CallOptions).SignBlob)], opts...)
   637  	unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
   638  	resp := &credentialspb.SignBlobResponse{}
   639  	e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
   640  		if settings.Path != "" {
   641  			baseUrl.Path = settings.Path
   642  		}
   643  		httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq))
   644  		if err != nil {
   645  			return err
   646  		}
   647  		httpReq = httpReq.WithContext(ctx)
   648  		httpReq.Header = headers
   649  
   650  		httpRsp, err := c.httpClient.Do(httpReq)
   651  		if err != nil {
   652  			return err
   653  		}
   654  		defer httpRsp.Body.Close()
   655  
   656  		if err = googleapi.CheckResponse(httpRsp); err != nil {
   657  			return err
   658  		}
   659  
   660  		buf, err := io.ReadAll(httpRsp.Body)
   661  		if err != nil {
   662  			return err
   663  		}
   664  
   665  		if err := unm.Unmarshal(buf, resp); err != nil {
   666  			return err
   667  		}
   668  
   669  		return nil
   670  	}, opts...)
   671  	if e != nil {
   672  		return nil, e
   673  	}
   674  	return resp, nil
   675  }
   676  
   677  // SignJwt signs a JWT using a service account’s system-managed private key.
   678  func (c *iamCredentialsRESTClient) SignJwt(ctx context.Context, req *credentialspb.SignJwtRequest, opts ...gax.CallOption) (*credentialspb.SignJwtResponse, error) {
   679  	m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true}
   680  	jsonReq, err := m.Marshal(req)
   681  	if err != nil {
   682  		return nil, err
   683  	}
   684  
   685  	baseUrl, err := url.Parse(c.endpoint)
   686  	if err != nil {
   687  		return nil, err
   688  	}
   689  	baseUrl.Path += fmt.Sprintf("/v1/%v:signJwt", req.GetName())
   690  
   691  	params := url.Values{}
   692  	params.Add("$alt", "json;enum-encoding=int")
   693  
   694  	baseUrl.RawQuery = params.Encode()
   695  
   696  	// Build HTTP headers from client and context metadata.
   697  	hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))}
   698  
   699  	hds = append(c.xGoogHeaders, hds...)
   700  	hds = append(hds, "Content-Type", "application/json")
   701  	headers := gax.BuildHeaders(ctx, hds...)
   702  	opts = append((*c.CallOptions).SignJwt[0:len((*c.CallOptions).SignJwt):len((*c.CallOptions).SignJwt)], opts...)
   703  	unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
   704  	resp := &credentialspb.SignJwtResponse{}
   705  	e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
   706  		if settings.Path != "" {
   707  			baseUrl.Path = settings.Path
   708  		}
   709  		httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq))
   710  		if err != nil {
   711  			return err
   712  		}
   713  		httpReq = httpReq.WithContext(ctx)
   714  		httpReq.Header = headers
   715  
   716  		httpRsp, err := c.httpClient.Do(httpReq)
   717  		if err != nil {
   718  			return err
   719  		}
   720  		defer httpRsp.Body.Close()
   721  
   722  		if err = googleapi.CheckResponse(httpRsp); err != nil {
   723  			return err
   724  		}
   725  
   726  		buf, err := io.ReadAll(httpRsp.Body)
   727  		if err != nil {
   728  			return err
   729  		}
   730  
   731  		if err := unm.Unmarshal(buf, resp); err != nil {
   732  			return err
   733  		}
   734  
   735  		return nil
   736  	}, opts...)
   737  	if e != nil {
   738  		return nil, e
   739  	}
   740  	return resp, nil
   741  }
   742  

View as plain text