|
| 1 | +/* |
| 2 | +Copyright 2021 The Dapr Authors |
| 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 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +Unless required by applicable law or agreed to in writing, software |
| 8 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 9 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 10 | +See the License for the specific language governing permissions and |
| 11 | +limitations under the License. |
| 12 | +*/ |
| 13 | + |
| 14 | +package oauth2 |
| 15 | + |
| 16 | +import ( |
| 17 | + "context" |
| 18 | + "crypto/tls" |
| 19 | + "crypto/x509" |
| 20 | + "errors" |
| 21 | + "fmt" |
| 22 | + "net/http" |
| 23 | + "net/url" |
| 24 | + "sync" |
| 25 | + "time" |
| 26 | + |
| 27 | + "golang.org/x/oauth2" |
| 28 | + ccreds "golang.org/x/oauth2/clientcredentials" |
| 29 | + |
| 30 | + "github.com/dapr/kit/logger" |
| 31 | +) |
| 32 | + |
| 33 | +// ClientCredentialsMetadata is the metadata fields which can be used by a |
| 34 | +// component to configure an OIDC client_credentials token source. |
| 35 | +type ClientCredentialsMetadata struct { |
| 36 | + TokenCAPEM string `mapstructure:"oauth2TokenCAPEM"` |
| 37 | + TokenURL string `mapstructure:"oauth2TokenURL"` |
| 38 | + ClientID string `mapstructure:"oauth2ClientID"` |
| 39 | + ClientSecret string `mapstructure:"oauth2ClientSecret"` |
| 40 | + Audiences []string `mapstructure:"oauth2Audiences"` |
| 41 | + Scopes []string `mapstructure:"oauth2Scopes"` |
| 42 | +} |
| 43 | + |
| 44 | +type ClientCredentialsOptions struct { |
| 45 | + Logger logger.Logger |
| 46 | + TokenURL string |
| 47 | + ClientID string |
| 48 | + ClientSecret string |
| 49 | + Scopes []string |
| 50 | + Audiences []string |
| 51 | + CAPEM []byte |
| 52 | +} |
| 53 | + |
| 54 | +// ClientCredentials is an OAuth2 Token Source that uses the client_credentials |
| 55 | +// grant type to fetch a token. |
| 56 | +type ClientCredentials struct { |
| 57 | + log logger.Logger |
| 58 | + currentToken *oauth2.Token |
| 59 | + httpClient *http.Client |
| 60 | + fetchTokenFn func(context.Context) (*oauth2.Token, error) |
| 61 | + |
| 62 | + lock sync.RWMutex |
| 63 | +} |
| 64 | + |
| 65 | +func NewClientCredentials(ctx context.Context, opts ClientCredentialsOptions) (*ClientCredentials, error) { |
| 66 | + conf, httpClient, err := opts.toConfig() |
| 67 | + if err != nil { |
| 68 | + return nil, err |
| 69 | + } |
| 70 | + |
| 71 | + token, err := conf.Token(context.WithValue(ctx, oauth2.HTTPClient, httpClient)) |
| 72 | + if err != nil { |
| 73 | + return nil, fmt.Errorf("error fetching initial oauth2 client_credentials token: %w", err) |
| 74 | + } |
| 75 | + |
| 76 | + opts.Logger.Info("Fetched initial oauth2 client_credentials token") |
| 77 | + |
| 78 | + return &ClientCredentials{ |
| 79 | + log: opts.Logger, |
| 80 | + currentToken: token, |
| 81 | + httpClient: httpClient, |
| 82 | + fetchTokenFn: conf.Token, |
| 83 | + }, nil |
| 84 | +} |
| 85 | + |
| 86 | +func (c *ClientCredentialsOptions) toConfig() (*ccreds.Config, *http.Client, error) { |
| 87 | + if len(c.Scopes) == 0 { |
| 88 | + return nil, nil, errors.New("oauth2 client_credentials token source requires at least one scope") |
| 89 | + } |
| 90 | + |
| 91 | + if len(c.Audiences) == 0 { |
| 92 | + return nil, nil, errors.New("oauth2 client_credentials token source requires at least one audience") |
| 93 | + } |
| 94 | + |
| 95 | + _, err := url.Parse(c.TokenURL) |
| 96 | + if err != nil { |
| 97 | + return nil, nil, fmt.Errorf("error parsing token URL: %w", err) |
| 98 | + } |
| 99 | + |
| 100 | + conf := &ccreds.Config{ |
| 101 | + ClientID: c.ClientID, |
| 102 | + ClientSecret: c.ClientSecret, |
| 103 | + TokenURL: c.TokenURL, |
| 104 | + Scopes: c.Scopes, |
| 105 | + EndpointParams: url.Values{"audience": c.Audiences}, |
| 106 | + } |
| 107 | + |
| 108 | + // If caPool is nil, then the Go TLS library will use the system's root CA. |
| 109 | + var caPool *x509.CertPool |
| 110 | + if len(c.CAPEM) > 0 { |
| 111 | + caPool = x509.NewCertPool() |
| 112 | + if !caPool.AppendCertsFromPEM(c.CAPEM) { |
| 113 | + return nil, nil, errors.New("failed to parse CA PEM") |
| 114 | + } |
| 115 | + } |
| 116 | + |
| 117 | + return conf, &http.Client{ |
| 118 | + Timeout: time.Second * 30, |
| 119 | + Transport: &http.Transport{ |
| 120 | + TLSClientConfig: &tls.Config{ |
| 121 | + MinVersion: tls.VersionTLS12, |
| 122 | + RootCAs: caPool, |
| 123 | + }, |
| 124 | + }, |
| 125 | + }, nil |
| 126 | +} |
| 127 | + |
| 128 | +func (c *ClientCredentials) Token() (string, error) { |
| 129 | + c.lock.RLock() |
| 130 | + defer c.lock.RUnlock() |
| 131 | + |
| 132 | + if !c.currentToken.Valid() { |
| 133 | + ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) |
| 134 | + defer cancel() |
| 135 | + if err := c.renewToken(ctx); err != nil { |
| 136 | + return "", err |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + return c.currentToken.AccessToken, nil |
| 141 | +} |
| 142 | + |
| 143 | +func (c *ClientCredentials) renewToken(ctx context.Context) error { |
| 144 | + c.lock.Lock() |
| 145 | + defer c.lock.Unlock() |
| 146 | + |
| 147 | + // We need to check if the current token is valid because we might have lost |
| 148 | + // the mutex lock race from the caller and we don't want to double-fetch a |
| 149 | + // token unnecessarily! |
| 150 | + if c.currentToken.Valid() { |
| 151 | + return nil |
| 152 | + } |
| 153 | + |
| 154 | + token, err := c.fetchTokenFn(context.WithValue(ctx, oauth2.HTTPClient, c.httpClient)) |
| 155 | + if err != nil { |
| 156 | + return err |
| 157 | + } |
| 158 | + |
| 159 | + if !c.currentToken.Valid() { |
| 160 | + return errors.New("oauth2 client_credentials token source returned an invalid token") |
| 161 | + } |
| 162 | + |
| 163 | + c.currentToken = token |
| 164 | + return nil |
| 165 | +} |
0 commit comments