oauth.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. /*
  2. *
  3. * Copyright 2015 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. // Package oauth implements gRPC credentials using OAuth.
  19. package oauth
  20. import (
  21. "context"
  22. "fmt"
  23. "net/url"
  24. "os"
  25. "sync"
  26. "golang.org/x/oauth2"
  27. "golang.org/x/oauth2/google"
  28. "golang.org/x/oauth2/jwt"
  29. "google.golang.org/grpc/credentials"
  30. )
  31. // TokenSource supplies PerRPCCredentials from an oauth2.TokenSource.
  32. type TokenSource struct {
  33. oauth2.TokenSource
  34. }
  35. // GetRequestMetadata gets the request metadata as a map from a TokenSource.
  36. func (ts TokenSource) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
  37. token, err := ts.Token()
  38. if err != nil {
  39. return nil, err
  40. }
  41. ri, _ := credentials.RequestInfoFromContext(ctx)
  42. if err = credentials.CheckSecurityLevel(ri.AuthInfo, credentials.PrivacyAndIntegrity); err != nil {
  43. return nil, fmt.Errorf("unable to transfer TokenSource PerRPCCredentials: %v", err)
  44. }
  45. return map[string]string{
  46. "authorization": token.Type() + " " + token.AccessToken,
  47. }, nil
  48. }
  49. // RequireTransportSecurity indicates whether the credentials requires transport security.
  50. func (ts TokenSource) RequireTransportSecurity() bool {
  51. return true
  52. }
  53. // removeServiceNameFromJWTURI removes RPC service name from URI.
  54. func removeServiceNameFromJWTURI(uri string) (string, error) {
  55. parsed, err := url.Parse(uri)
  56. if err != nil {
  57. return "", err
  58. }
  59. parsed.Path = "/"
  60. return parsed.String(), nil
  61. }
  62. type jwtAccess struct {
  63. jsonKey []byte
  64. }
  65. // NewJWTAccessFromFile creates PerRPCCredentials from the given keyFile.
  66. func NewJWTAccessFromFile(keyFile string) (credentials.PerRPCCredentials, error) {
  67. jsonKey, err := os.ReadFile(keyFile)
  68. if err != nil {
  69. return nil, fmt.Errorf("credentials: failed to read the service account key file: %v", err)
  70. }
  71. return NewJWTAccessFromKey(jsonKey)
  72. }
  73. // NewJWTAccessFromKey creates PerRPCCredentials from the given jsonKey.
  74. func NewJWTAccessFromKey(jsonKey []byte) (credentials.PerRPCCredentials, error) {
  75. return jwtAccess{jsonKey}, nil
  76. }
  77. func (j jwtAccess) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
  78. // Remove RPC service name from URI that will be used as audience
  79. // in a self-signed JWT token. It follows https://google.aip.dev/auth/4111.
  80. aud, err := removeServiceNameFromJWTURI(uri[0])
  81. if err != nil {
  82. return nil, err
  83. }
  84. // TODO: the returned TokenSource is reusable. Store it in a sync.Map, with
  85. // uri as the key, to avoid recreating for every RPC.
  86. ts, err := google.JWTAccessTokenSourceFromJSON(j.jsonKey, aud)
  87. if err != nil {
  88. return nil, err
  89. }
  90. token, err := ts.Token()
  91. if err != nil {
  92. return nil, err
  93. }
  94. ri, _ := credentials.RequestInfoFromContext(ctx)
  95. if err = credentials.CheckSecurityLevel(ri.AuthInfo, credentials.PrivacyAndIntegrity); err != nil {
  96. return nil, fmt.Errorf("unable to transfer jwtAccess PerRPCCredentials: %v", err)
  97. }
  98. return map[string]string{
  99. "authorization": token.Type() + " " + token.AccessToken,
  100. }, nil
  101. }
  102. func (j jwtAccess) RequireTransportSecurity() bool {
  103. return true
  104. }
  105. // oauthAccess supplies PerRPCCredentials from a given token.
  106. type oauthAccess struct {
  107. token oauth2.Token
  108. }
  109. // NewOauthAccess constructs the PerRPCCredentials using a given token.
  110. //
  111. // Deprecated: use oauth.TokenSource instead.
  112. func NewOauthAccess(token *oauth2.Token) credentials.PerRPCCredentials {
  113. return oauthAccess{token: *token}
  114. }
  115. func (oa oauthAccess) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
  116. ri, _ := credentials.RequestInfoFromContext(ctx)
  117. if err := credentials.CheckSecurityLevel(ri.AuthInfo, credentials.PrivacyAndIntegrity); err != nil {
  118. return nil, fmt.Errorf("unable to transfer oauthAccess PerRPCCredentials: %v", err)
  119. }
  120. return map[string]string{
  121. "authorization": oa.token.Type() + " " + oa.token.AccessToken,
  122. }, nil
  123. }
  124. func (oa oauthAccess) RequireTransportSecurity() bool {
  125. return true
  126. }
  127. // NewComputeEngine constructs the PerRPCCredentials that fetches access tokens from
  128. // Google Compute Engine (GCE)'s metadata server. It is only valid to use this
  129. // if your program is running on a GCE instance.
  130. // TODO(dsymonds): Deprecate and remove this.
  131. func NewComputeEngine() credentials.PerRPCCredentials {
  132. return TokenSource{google.ComputeTokenSource("")}
  133. }
  134. // serviceAccount represents PerRPCCredentials via JWT signing key.
  135. type serviceAccount struct {
  136. mu sync.Mutex
  137. config *jwt.Config
  138. t *oauth2.Token
  139. }
  140. func (s *serviceAccount) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
  141. s.mu.Lock()
  142. defer s.mu.Unlock()
  143. if !s.t.Valid() {
  144. var err error
  145. s.t, err = s.config.TokenSource(ctx).Token()
  146. if err != nil {
  147. return nil, err
  148. }
  149. }
  150. ri, _ := credentials.RequestInfoFromContext(ctx)
  151. if err := credentials.CheckSecurityLevel(ri.AuthInfo, credentials.PrivacyAndIntegrity); err != nil {
  152. return nil, fmt.Errorf("unable to transfer serviceAccount PerRPCCredentials: %v", err)
  153. }
  154. return map[string]string{
  155. "authorization": s.t.Type() + " " + s.t.AccessToken,
  156. }, nil
  157. }
  158. func (s *serviceAccount) RequireTransportSecurity() bool {
  159. return true
  160. }
  161. // NewServiceAccountFromKey constructs the PerRPCCredentials using the JSON key slice
  162. // from a Google Developers service account.
  163. func NewServiceAccountFromKey(jsonKey []byte, scope ...string) (credentials.PerRPCCredentials, error) {
  164. config, err := google.JWTConfigFromJSON(jsonKey, scope...)
  165. if err != nil {
  166. return nil, err
  167. }
  168. return &serviceAccount{config: config}, nil
  169. }
  170. // NewServiceAccountFromFile constructs the PerRPCCredentials using the JSON key file
  171. // of a Google Developers service account.
  172. func NewServiceAccountFromFile(keyFile string, scope ...string) (credentials.PerRPCCredentials, error) {
  173. jsonKey, err := os.ReadFile(keyFile)
  174. if err != nil {
  175. return nil, fmt.Errorf("credentials: failed to read the service account key file: %v", err)
  176. }
  177. return NewServiceAccountFromKey(jsonKey, scope...)
  178. }
  179. // NewApplicationDefault returns "Application Default Credentials". For more
  180. // detail, see https://developers.google.com/accounts/docs/application-default-credentials.
  181. func NewApplicationDefault(ctx context.Context, scope ...string) (credentials.PerRPCCredentials, error) {
  182. creds, err := google.FindDefaultCredentials(ctx, scope...)
  183. if err != nil {
  184. return nil, err
  185. }
  186. // If JSON is nil, the authentication is provided by the environment and not
  187. // with a credentials file, e.g. when code is running on Google Cloud
  188. // Platform. Use the returned token source.
  189. if creds.JSON == nil {
  190. return TokenSource{creds.TokenSource}, nil
  191. }
  192. // If auth is provided by env variable or creds file, the behavior will be
  193. // different based on whether scope is set. Because the returned
  194. // creds.TokenSource does oauth with jwt by default, and it requires scope.
  195. // We can only use it if scope is not empty, otherwise it will fail with
  196. // missing scope error.
  197. //
  198. // If scope is set, use it, it should just work.
  199. //
  200. // If scope is not set, we try to use jwt directly without oauth (this only
  201. // works if it's a service account).
  202. if len(scope) != 0 {
  203. return TokenSource{creds.TokenSource}, nil
  204. }
  205. // Try to convert JSON to a jwt config without setting the optional scope
  206. // parameter to check if it's a service account (the function errors if it's
  207. // not). This is necessary because the returned config doesn't show the type
  208. // of the account.
  209. if _, err := google.JWTConfigFromJSON(creds.JSON); err != nil {
  210. // If this fails, it's not a service account, return the original
  211. // TokenSource from above.
  212. return TokenSource{creds.TokenSource}, nil
  213. }
  214. // If it's a service account, create a JWT only access with the key.
  215. return NewJWTAccessFromKey(creds.JSON)
  216. }