internal.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. // Copyright 2023 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. // http://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. package internal
  15. import (
  16. "context"
  17. "crypto/rsa"
  18. "crypto/x509"
  19. "encoding/json"
  20. "encoding/pem"
  21. "errors"
  22. "fmt"
  23. "io"
  24. "net/http"
  25. "os"
  26. "sync"
  27. "time"
  28. "cloud.google.com/go/compute/metadata"
  29. )
  30. const (
  31. // TokenTypeBearer is the auth header prefix for bearer tokens.
  32. TokenTypeBearer = "Bearer"
  33. // QuotaProjectEnvVar is the environment variable for setting the quota
  34. // project.
  35. QuotaProjectEnvVar = "GOOGLE_CLOUD_QUOTA_PROJECT"
  36. // UniverseDomainEnvVar is the environment variable for setting the default
  37. // service domain for a given Cloud universe.
  38. UniverseDomainEnvVar = "GOOGLE_CLOUD_UNIVERSE_DOMAIN"
  39. projectEnvVar = "GOOGLE_CLOUD_PROJECT"
  40. maxBodySize = 1 << 20
  41. // DefaultUniverseDomain is the default value for universe domain.
  42. // Universe domain is the default service domain for a given Cloud universe.
  43. DefaultUniverseDomain = "googleapis.com"
  44. )
  45. type clonableTransport interface {
  46. Clone() *http.Transport
  47. }
  48. // DefaultClient returns an [http.Client] with some defaults set. If
  49. // the current [http.DefaultTransport] is a [clonableTransport], as
  50. // is the case for an [*http.Transport], the clone will be used.
  51. // Otherwise the [http.DefaultTransport] is used directly.
  52. func DefaultClient() *http.Client {
  53. if transport, ok := http.DefaultTransport.(clonableTransport); ok {
  54. return &http.Client{
  55. Transport: transport.Clone(),
  56. Timeout: 30 * time.Second,
  57. }
  58. }
  59. return &http.Client{
  60. Transport: http.DefaultTransport,
  61. Timeout: 30 * time.Second,
  62. }
  63. }
  64. // ParseKey converts the binary contents of a private key file
  65. // to an *rsa.PrivateKey. It detects whether the private key is in a
  66. // PEM container or not. If so, it extracts the the private key
  67. // from PEM container before conversion. It only supports PEM
  68. // containers with no passphrase.
  69. func ParseKey(key []byte) (*rsa.PrivateKey, error) {
  70. block, _ := pem.Decode(key)
  71. if block != nil {
  72. key = block.Bytes
  73. }
  74. parsedKey, err := x509.ParsePKCS8PrivateKey(key)
  75. if err != nil {
  76. parsedKey, err = x509.ParsePKCS1PrivateKey(key)
  77. if err != nil {
  78. return nil, fmt.Errorf("private key should be a PEM or plain PKCS1 or PKCS8: %w", err)
  79. }
  80. }
  81. parsed, ok := parsedKey.(*rsa.PrivateKey)
  82. if !ok {
  83. return nil, errors.New("private key is invalid")
  84. }
  85. return parsed, nil
  86. }
  87. // GetQuotaProject retrieves quota project with precedence being: override,
  88. // environment variable, creds json file.
  89. func GetQuotaProject(b []byte, override string) string {
  90. if override != "" {
  91. return override
  92. }
  93. if env := os.Getenv(QuotaProjectEnvVar); env != "" {
  94. return env
  95. }
  96. if b == nil {
  97. return ""
  98. }
  99. var v struct {
  100. QuotaProject string `json:"quota_project_id"`
  101. }
  102. if err := json.Unmarshal(b, &v); err != nil {
  103. return ""
  104. }
  105. return v.QuotaProject
  106. }
  107. // GetProjectID retrieves project with precedence being: override,
  108. // environment variable, creds json file.
  109. func GetProjectID(b []byte, override string) string {
  110. if override != "" {
  111. return override
  112. }
  113. if env := os.Getenv(projectEnvVar); env != "" {
  114. return env
  115. }
  116. if b == nil {
  117. return ""
  118. }
  119. var v struct {
  120. ProjectID string `json:"project_id"` // standard service account key
  121. Project string `json:"project"` // gdch key
  122. }
  123. if err := json.Unmarshal(b, &v); err != nil {
  124. return ""
  125. }
  126. if v.ProjectID != "" {
  127. return v.ProjectID
  128. }
  129. return v.Project
  130. }
  131. // DoRequest executes the provided req with the client. It reads the response
  132. // body, closes it, and returns it.
  133. func DoRequest(client *http.Client, req *http.Request) (*http.Response, []byte, error) {
  134. resp, err := client.Do(req)
  135. if err != nil {
  136. return nil, nil, err
  137. }
  138. defer resp.Body.Close()
  139. body, err := ReadAll(io.LimitReader(resp.Body, maxBodySize))
  140. if err != nil {
  141. return nil, nil, err
  142. }
  143. return resp, body, nil
  144. }
  145. // ReadAll consumes the whole reader and safely reads the content of its body
  146. // with some overflow protection.
  147. func ReadAll(r io.Reader) ([]byte, error) {
  148. return io.ReadAll(io.LimitReader(r, maxBodySize))
  149. }
  150. // StaticCredentialsProperty is a helper for creating static credentials
  151. // properties.
  152. func StaticCredentialsProperty(s string) StaticProperty {
  153. return StaticProperty(s)
  154. }
  155. // StaticProperty always returns that value of the underlying string.
  156. type StaticProperty string
  157. // GetProperty loads the properly value provided the given context.
  158. func (p StaticProperty) GetProperty(context.Context) (string, error) {
  159. return string(p), nil
  160. }
  161. // ComputeUniverseDomainProvider fetches the credentials universe domain from
  162. // the google cloud metadata service.
  163. type ComputeUniverseDomainProvider struct {
  164. universeDomainOnce sync.Once
  165. universeDomain string
  166. universeDomainErr error
  167. }
  168. // GetProperty fetches the credentials universe domain from the google cloud
  169. // metadata service.
  170. func (c *ComputeUniverseDomainProvider) GetProperty(ctx context.Context) (string, error) {
  171. c.universeDomainOnce.Do(func() {
  172. c.universeDomain, c.universeDomainErr = getMetadataUniverseDomain(ctx)
  173. })
  174. if c.universeDomainErr != nil {
  175. return "", c.universeDomainErr
  176. }
  177. return c.universeDomain, nil
  178. }
  179. // httpGetMetadataUniverseDomain is a package var for unit test substitution.
  180. var httpGetMetadataUniverseDomain = func(ctx context.Context) (string, error) {
  181. ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
  182. defer cancel()
  183. return metadata.GetWithContext(ctx, "universe/universe-domain")
  184. }
  185. func getMetadataUniverseDomain(ctx context.Context) (string, error) {
  186. universeDomain, err := httpGetMetadataUniverseDomain(ctx)
  187. if err == nil {
  188. return universeDomain, nil
  189. }
  190. if _, ok := err.(metadata.NotDefinedError); ok {
  191. // http.StatusNotFound (404)
  192. return DefaultUniverseDomain, nil
  193. }
  194. return "", err
  195. }