option.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. // Copyright 2017 Google LLC.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package option contains options for Google API clients.
  5. package option
  6. import (
  7. "crypto/tls"
  8. "net/http"
  9. "golang.org/x/oauth2"
  10. "golang.org/x/oauth2/google"
  11. "google.golang.org/api/internal"
  12. "google.golang.org/api/internal/impersonate"
  13. "google.golang.org/grpc"
  14. )
  15. // A ClientOption is an option for a Google API client.
  16. type ClientOption interface {
  17. Apply(*internal.DialSettings)
  18. }
  19. // WithTokenSource returns a ClientOption that specifies an OAuth2 token
  20. // source to be used as the basis for authentication.
  21. func WithTokenSource(s oauth2.TokenSource) ClientOption {
  22. return withTokenSource{s}
  23. }
  24. type withTokenSource struct{ ts oauth2.TokenSource }
  25. func (w withTokenSource) Apply(o *internal.DialSettings) {
  26. o.TokenSource = w.ts
  27. }
  28. type withCredFile string
  29. func (w withCredFile) Apply(o *internal.DialSettings) {
  30. o.CredentialsFile = string(w)
  31. }
  32. // WithCredentialsFile returns a ClientOption that authenticates
  33. // API calls with the given service account or refresh token JSON
  34. // credentials file.
  35. func WithCredentialsFile(filename string) ClientOption {
  36. return withCredFile(filename)
  37. }
  38. // WithServiceAccountFile returns a ClientOption that uses a Google service
  39. // account credentials file to authenticate.
  40. //
  41. // Deprecated: Use WithCredentialsFile instead.
  42. func WithServiceAccountFile(filename string) ClientOption {
  43. return WithCredentialsFile(filename)
  44. }
  45. // WithCredentialsJSON returns a ClientOption that authenticates
  46. // API calls with the given service account or refresh token JSON
  47. // credentials.
  48. func WithCredentialsJSON(p []byte) ClientOption {
  49. return withCredentialsJSON(p)
  50. }
  51. type withCredentialsJSON []byte
  52. func (w withCredentialsJSON) Apply(o *internal.DialSettings) {
  53. o.CredentialsJSON = make([]byte, len(w))
  54. copy(o.CredentialsJSON, w)
  55. }
  56. // WithEndpoint returns a ClientOption that overrides the default endpoint
  57. // to be used for a service.
  58. func WithEndpoint(url string) ClientOption {
  59. return withEndpoint(url)
  60. }
  61. type withEndpoint string
  62. func (w withEndpoint) Apply(o *internal.DialSettings) {
  63. o.Endpoint = string(w)
  64. }
  65. // WithScopes returns a ClientOption that overrides the default OAuth2 scopes
  66. // to be used for a service.
  67. //
  68. // If both WithScopes and WithTokenSource are used, scope settings from the
  69. // token source will be used instead.
  70. func WithScopes(scope ...string) ClientOption {
  71. return withScopes(scope)
  72. }
  73. type withScopes []string
  74. func (w withScopes) Apply(o *internal.DialSettings) {
  75. o.Scopes = make([]string, len(w))
  76. copy(o.Scopes, w)
  77. }
  78. // WithUserAgent returns a ClientOption that sets the User-Agent. This option
  79. // is incompatible with the [WithHTTPClient] option. If you wish to provide a
  80. // custom client you will need to add this header via RoundTripper middleware.
  81. func WithUserAgent(ua string) ClientOption {
  82. return withUA(ua)
  83. }
  84. type withUA string
  85. func (w withUA) Apply(o *internal.DialSettings) { o.UserAgent = string(w) }
  86. // WithHTTPClient returns a ClientOption that specifies the HTTP client to use
  87. // as the basis of communications. This option may only be used with services
  88. // that support HTTP as their communication transport. When used, the
  89. // WithHTTPClient option takes precedent over all other supplied options.
  90. func WithHTTPClient(client *http.Client) ClientOption {
  91. return withHTTPClient{client}
  92. }
  93. type withHTTPClient struct{ client *http.Client }
  94. func (w withHTTPClient) Apply(o *internal.DialSettings) {
  95. o.HTTPClient = w.client
  96. }
  97. // WithGRPCConn returns a ClientOption that specifies the gRPC client
  98. // connection to use as the basis of communications. This option may only be
  99. // used with services that support gRPC as their communication transport. When
  100. // used, the WithGRPCConn option takes precedent over all other supplied
  101. // options.
  102. func WithGRPCConn(conn *grpc.ClientConn) ClientOption {
  103. return withGRPCConn{conn}
  104. }
  105. type withGRPCConn struct{ conn *grpc.ClientConn }
  106. func (w withGRPCConn) Apply(o *internal.DialSettings) {
  107. o.GRPCConn = w.conn
  108. }
  109. // WithGRPCDialOption returns a ClientOption that appends a new grpc.DialOption
  110. // to an underlying gRPC dial. It does not work with WithGRPCConn.
  111. func WithGRPCDialOption(opt grpc.DialOption) ClientOption {
  112. return withGRPCDialOption{opt}
  113. }
  114. type withGRPCDialOption struct{ opt grpc.DialOption }
  115. func (w withGRPCDialOption) Apply(o *internal.DialSettings) {
  116. o.GRPCDialOpts = append(o.GRPCDialOpts, w.opt)
  117. }
  118. // WithGRPCConnectionPool returns a ClientOption that creates a pool of gRPC
  119. // connections that requests will be balanced between.
  120. func WithGRPCConnectionPool(size int) ClientOption {
  121. return withGRPCConnectionPool(size)
  122. }
  123. type withGRPCConnectionPool int
  124. func (w withGRPCConnectionPool) Apply(o *internal.DialSettings) {
  125. o.GRPCConnPoolSize = int(w)
  126. }
  127. // WithAPIKey returns a ClientOption that specifies an API key to be used
  128. // as the basis for authentication.
  129. //
  130. // API Keys can only be used for JSON-over-HTTP APIs, including those under
  131. // the import path google.golang.org/api/....
  132. func WithAPIKey(apiKey string) ClientOption {
  133. return withAPIKey(apiKey)
  134. }
  135. type withAPIKey string
  136. func (w withAPIKey) Apply(o *internal.DialSettings) { o.APIKey = string(w) }
  137. // WithAudiences returns a ClientOption that specifies an audience to be used
  138. // as the audience field ("aud") for the JWT token authentication.
  139. func WithAudiences(audience ...string) ClientOption {
  140. return withAudiences(audience)
  141. }
  142. type withAudiences []string
  143. func (w withAudiences) Apply(o *internal.DialSettings) {
  144. o.Audiences = make([]string, len(w))
  145. copy(o.Audiences, w)
  146. }
  147. // WithoutAuthentication returns a ClientOption that specifies that no
  148. // authentication should be used. It is suitable only for testing and for
  149. // accessing public resources, like public Google Cloud Storage buckets.
  150. // It is an error to provide both WithoutAuthentication and any of WithAPIKey,
  151. // WithTokenSource, WithCredentialsFile or WithServiceAccountFile.
  152. func WithoutAuthentication() ClientOption {
  153. return withoutAuthentication{}
  154. }
  155. type withoutAuthentication struct{}
  156. func (w withoutAuthentication) Apply(o *internal.DialSettings) { o.NoAuth = true }
  157. // WithQuotaProject returns a ClientOption that specifies the project used
  158. // for quota and billing purposes.
  159. //
  160. // For more information please read:
  161. // https://cloud.google.com/apis/docs/system-parameters
  162. func WithQuotaProject(quotaProject string) ClientOption {
  163. return withQuotaProject(quotaProject)
  164. }
  165. type withQuotaProject string
  166. func (w withQuotaProject) Apply(o *internal.DialSettings) {
  167. o.QuotaProject = string(w)
  168. }
  169. // WithRequestReason returns a ClientOption that specifies a reason for
  170. // making the request, which is intended to be recorded in audit logging.
  171. // An example reason would be a support-case ticket number.
  172. //
  173. // For more information please read:
  174. // https://cloud.google.com/apis/docs/system-parameters
  175. func WithRequestReason(requestReason string) ClientOption {
  176. return withRequestReason(requestReason)
  177. }
  178. type withRequestReason string
  179. func (w withRequestReason) Apply(o *internal.DialSettings) {
  180. o.RequestReason = string(w)
  181. }
  182. // WithTelemetryDisabled returns a ClientOption that disables default telemetry (OpenCensus)
  183. // settings on gRPC and HTTP clients.
  184. // An example reason would be to bind custom telemetry that overrides the defaults.
  185. func WithTelemetryDisabled() ClientOption {
  186. return withTelemetryDisabled{}
  187. }
  188. type withTelemetryDisabled struct{}
  189. func (w withTelemetryDisabled) Apply(o *internal.DialSettings) {
  190. o.TelemetryDisabled = true
  191. }
  192. // ClientCertSource is a function that returns a TLS client certificate to be used
  193. // when opening TLS connections.
  194. //
  195. // It follows the same semantics as crypto/tls.Config.GetClientCertificate.
  196. //
  197. // This is an EXPERIMENTAL API and may be changed or removed in the future.
  198. type ClientCertSource = func(*tls.CertificateRequestInfo) (*tls.Certificate, error)
  199. // WithClientCertSource returns a ClientOption that specifies a
  200. // callback function for obtaining a TLS client certificate.
  201. //
  202. // This option is used for supporting mTLS authentication, where the
  203. // server validates the client certifcate when establishing a connection.
  204. //
  205. // The callback function will be invoked whenever the server requests a
  206. // certificate from the client. Implementations of the callback function
  207. // should try to ensure that a valid certificate can be repeatedly returned
  208. // on demand for the entire life cycle of the transport client. If a nil
  209. // Certificate is returned (i.e. no Certificate can be obtained), an error
  210. // should be returned.
  211. //
  212. // This is an EXPERIMENTAL API and may be changed or removed in the future.
  213. func WithClientCertSource(s ClientCertSource) ClientOption {
  214. return withClientCertSource{s}
  215. }
  216. type withClientCertSource struct{ s ClientCertSource }
  217. func (w withClientCertSource) Apply(o *internal.DialSettings) {
  218. o.ClientCertSource = w.s
  219. }
  220. // ImpersonateCredentials returns a ClientOption that will impersonate the
  221. // target service account.
  222. //
  223. // In order to impersonate the target service account
  224. // the base service account must have the Service Account Token Creator role,
  225. // roles/iam.serviceAccountTokenCreator, on the target service account.
  226. // See https://cloud.google.com/iam/docs/understanding-service-accounts.
  227. //
  228. // Optionally, delegates can be used during impersonation if the base service
  229. // account lacks the token creator role on the target. When using delegates,
  230. // each service account must be granted roles/iam.serviceAccountTokenCreator
  231. // on the next service account in the chain.
  232. //
  233. // For example, if a base service account of SA1 is trying to impersonate target
  234. // service account SA2 while using delegate service accounts DSA1 and DSA2,
  235. // the following must be true:
  236. //
  237. // 1. Base service account SA1 has roles/iam.serviceAccountTokenCreator on
  238. // DSA1.
  239. // 2. DSA1 has roles/iam.serviceAccountTokenCreator on DSA2.
  240. // 3. DSA2 has roles/iam.serviceAccountTokenCreator on target SA2.
  241. //
  242. // The resulting impersonated credential will either have the default scopes of
  243. // the client being instantiating or the scopes from WithScopes if provided.
  244. // Scopes are required for creating impersonated credentials, so if this option
  245. // is used while not using a NewClient/NewService function, WithScopes must also
  246. // be explicitly passed in as well.
  247. //
  248. // If the base credential is an authorized user and not a service account, or if
  249. // the option WithQuotaProject is set, the target service account must have a
  250. // role that grants the serviceusage.services.use permission such as
  251. // roles/serviceusage.serviceUsageConsumer.
  252. //
  253. // This is an EXPERIMENTAL API and may be changed or removed in the future.
  254. //
  255. // Deprecated: This option has been replaced by `impersonate` package:
  256. // `google.golang.org/api/impersonate`. Please use the `impersonate` package
  257. // instead with the WithTokenSource option.
  258. func ImpersonateCredentials(target string, delegates ...string) ClientOption {
  259. return impersonateServiceAccount{
  260. target: target,
  261. delegates: delegates,
  262. }
  263. }
  264. type impersonateServiceAccount struct {
  265. target string
  266. delegates []string
  267. }
  268. func (i impersonateServiceAccount) Apply(o *internal.DialSettings) {
  269. o.ImpersonationConfig = &impersonate.Config{
  270. Target: i.target,
  271. }
  272. o.ImpersonationConfig.Delegates = make([]string, len(i.delegates))
  273. copy(o.ImpersonationConfig.Delegates, i.delegates)
  274. }
  275. type withCreds google.Credentials
  276. func (w *withCreds) Apply(o *internal.DialSettings) {
  277. o.Credentials = (*google.Credentials)(w)
  278. }
  279. // WithCredentials returns a ClientOption that authenticates API calls.
  280. func WithCredentials(creds *google.Credentials) ClientOption {
  281. return (*withCreds)(creds)
  282. }