-
Notifications
You must be signed in to change notification settings - Fork 478
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Pubsub pulsar authentication ~OIDC~ OAuth2 (#3026)
Signed-off-by: joshvanl <[email protected]> Signed-off-by: Alessandro (Ale) Segala <[email protected]> Co-authored-by: Alessandro (Ale) Segala <[email protected]> Co-authored-by: Yaron Schneider <[email protected]> Co-authored-by: Bernd Verst <[email protected]>
- Loading branch information
1 parent
566c7fd
commit 7937d34
Showing
22 changed files
with
874 additions
and
80 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,165 @@ | ||
/* | ||
Copyright 2021 The Dapr Authors | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
*/ | ||
|
||
package oauth2 | ||
|
||
import ( | ||
"context" | ||
"crypto/tls" | ||
"crypto/x509" | ||
"errors" | ||
"fmt" | ||
"net/http" | ||
"net/url" | ||
"sync" | ||
"time" | ||
|
||
"golang.org/x/oauth2" | ||
ccreds "golang.org/x/oauth2/clientcredentials" | ||
|
||
"github.com/dapr/kit/logger" | ||
) | ||
|
||
// ClientCredentialsMetadata is the metadata fields which can be used by a | ||
// component to configure an OIDC client_credentials token source. | ||
type ClientCredentialsMetadata struct { | ||
TokenCAPEM string `mapstructure:"oauth2TokenCAPEM"` | ||
TokenURL string `mapstructure:"oauth2TokenURL"` | ||
ClientID string `mapstructure:"oauth2ClientID"` | ||
ClientSecret string `mapstructure:"oauth2ClientSecret"` | ||
Audiences []string `mapstructure:"oauth2Audiences"` | ||
Scopes []string `mapstructure:"oauth2Scopes"` | ||
} | ||
|
||
type ClientCredentialsOptions struct { | ||
Logger logger.Logger | ||
TokenURL string | ||
ClientID string | ||
ClientSecret string | ||
Scopes []string | ||
Audiences []string | ||
CAPEM []byte | ||
} | ||
|
||
// ClientCredentials is an OAuth2 Token Source that uses the client_credentials | ||
// grant type to fetch a token. | ||
type ClientCredentials struct { | ||
log logger.Logger | ||
currentToken *oauth2.Token | ||
httpClient *http.Client | ||
fetchTokenFn func(context.Context) (*oauth2.Token, error) | ||
|
||
lock sync.RWMutex | ||
} | ||
|
||
func NewClientCredentials(ctx context.Context, opts ClientCredentialsOptions) (*ClientCredentials, error) { | ||
conf, httpClient, err := opts.toConfig() | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
token, err := conf.Token(context.WithValue(ctx, oauth2.HTTPClient, httpClient)) | ||
if err != nil { | ||
return nil, fmt.Errorf("error fetching initial oauth2 client_credentials token: %w", err) | ||
} | ||
|
||
opts.Logger.Info("Fetched initial oauth2 client_credentials token") | ||
|
||
return &ClientCredentials{ | ||
log: opts.Logger, | ||
currentToken: token, | ||
httpClient: httpClient, | ||
fetchTokenFn: conf.Token, | ||
}, nil | ||
} | ||
|
||
func (c *ClientCredentialsOptions) toConfig() (*ccreds.Config, *http.Client, error) { | ||
if len(c.Scopes) == 0 { | ||
return nil, nil, errors.New("oauth2 client_credentials token source requires at least one scope") | ||
} | ||
|
||
if len(c.Audiences) == 0 { | ||
return nil, nil, errors.New("oauth2 client_credentials token source requires at least one audience") | ||
} | ||
|
||
_, err := url.Parse(c.TokenURL) | ||
if err != nil { | ||
return nil, nil, fmt.Errorf("error parsing token URL: %w", err) | ||
} | ||
|
||
conf := &ccreds.Config{ | ||
ClientID: c.ClientID, | ||
ClientSecret: c.ClientSecret, | ||
TokenURL: c.TokenURL, | ||
Scopes: c.Scopes, | ||
EndpointParams: url.Values{"audience": c.Audiences}, | ||
} | ||
|
||
// If caPool is nil, then the Go TLS library will use the system's root CA. | ||
var caPool *x509.CertPool | ||
if len(c.CAPEM) > 0 { | ||
caPool = x509.NewCertPool() | ||
if !caPool.AppendCertsFromPEM(c.CAPEM) { | ||
return nil, nil, errors.New("failed to parse CA PEM") | ||
} | ||
} | ||
|
||
return conf, &http.Client{ | ||
Timeout: time.Second * 30, | ||
Transport: &http.Transport{ | ||
TLSClientConfig: &tls.Config{ | ||
MinVersion: tls.VersionTLS12, | ||
RootCAs: caPool, | ||
}, | ||
}, | ||
}, nil | ||
} | ||
|
||
func (c *ClientCredentials) Token() (string, error) { | ||
c.lock.RLock() | ||
defer c.lock.RUnlock() | ||
|
||
if !c.currentToken.Valid() { | ||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) | ||
defer cancel() | ||
if err := c.renewToken(ctx); err != nil { | ||
return "", err | ||
} | ||
} | ||
|
||
return c.currentToken.AccessToken, nil | ||
} | ||
|
||
func (c *ClientCredentials) renewToken(ctx context.Context) error { | ||
c.lock.Lock() | ||
defer c.lock.Unlock() | ||
|
||
// We need to check if the current token is valid because we might have lost | ||
// the mutex lock race from the caller and we don't want to double-fetch a | ||
// token unnecessarily! | ||
if c.currentToken.Valid() { | ||
return nil | ||
} | ||
|
||
token, err := c.fetchTokenFn(context.WithValue(ctx, oauth2.HTTPClient, c.httpClient)) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
if !c.currentToken.Valid() { | ||
return errors.New("oauth2 client_credentials token source returned an invalid token") | ||
} | ||
|
||
c.currentToken = token | ||
return nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,95 @@ | ||
/* | ||
Copyright 2021 The Dapr Authors | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
*/ | ||
|
||
package oauth2 | ||
|
||
import ( | ||
"net/url" | ||
"testing" | ||
|
||
"github.com/stretchr/testify/assert" | ||
ccreds "golang.org/x/oauth2/clientcredentials" | ||
) | ||
|
||
func Test_toConfig(t *testing.T) { | ||
tests := map[string]struct { | ||
opts ClientCredentialsOptions | ||
expConfig *ccreds.Config | ||
expErr bool | ||
}{ | ||
"no scopes should error": { | ||
opts: ClientCredentialsOptions{ | ||
TokenURL: "https://localhost:8080", | ||
ClientID: "client-id", | ||
ClientSecret: "client-secret", | ||
Audiences: []string{"audience"}, | ||
}, | ||
expErr: true, | ||
}, | ||
"bad URL endpoint should error": { | ||
opts: ClientCredentialsOptions{ | ||
TokenURL: "&&htp:/f url", | ||
ClientID: "client-id", | ||
ClientSecret: "client-secret", | ||
Audiences: []string{"audience"}, | ||
Scopes: []string{"foo"}, | ||
}, | ||
expErr: true, | ||
}, | ||
"bad CA certificate should error": { | ||
opts: ClientCredentialsOptions{ | ||
TokenURL: "http://localhost:8080", | ||
ClientID: "client-id", | ||
ClientSecret: "client-secret", | ||
Audiences: []string{"audience"}, | ||
Scopes: []string{"foo"}, | ||
CAPEM: []byte("ca-pem"), | ||
}, | ||
expErr: true, | ||
}, | ||
"no audiences should error": { | ||
opts: ClientCredentialsOptions{ | ||
TokenURL: "http://localhost:8080", | ||
ClientID: "client-id", | ||
ClientSecret: "client-secret", | ||
Scopes: []string{"foo"}, | ||
}, | ||
expErr: true, | ||
}, | ||
"should default scope": { | ||
opts: ClientCredentialsOptions{ | ||
TokenURL: "http://localhost:8080", | ||
ClientID: "client-id", | ||
ClientSecret: "client-secret", | ||
Audiences: []string{"audience"}, | ||
Scopes: []string{"foo", "bar"}, | ||
}, | ||
expConfig: &ccreds.Config{ | ||
ClientID: "client-id", | ||
ClientSecret: "client-secret", | ||
TokenURL: "http://localhost:8080", | ||
Scopes: []string{"foo", "bar"}, | ||
EndpointParams: url.Values{"audience": []string{"audience"}}, | ||
}, | ||
expErr: false, | ||
}, | ||
} | ||
|
||
for name, test := range tests { | ||
t.Run(name, func(t *testing.T) { | ||
config, _, err := test.opts.toConfig() | ||
assert.Equalf(t, test.expErr, err != nil, "%v", err) | ||
assert.Equal(t, test.expConfig, config) | ||
}) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
32 changes: 32 additions & 0 deletions
32
tests/certification/pubsub/pulsar/components/auth-oauth2/consumer_five/pulsar.yml.tmpl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
apiVersion: dapr.io/v1alpha1 | ||
kind: Component | ||
metadata: | ||
name: messagebus | ||
spec: | ||
type: pubsub.pulsar | ||
version: v1 | ||
metadata: | ||
- name: host | ||
value: "localhost:6650" | ||
- name: consumerID | ||
value: certification5 | ||
- name: redeliveryDelay | ||
value: 200ms | ||
- name: publicKey | ||
value: public.key | ||
- name: privateKey | ||
value: private.key | ||
- name: keys | ||
value: myapp.key | ||
- name: oauth2TokenURL | ||
value: https://localhost:8085/issuer1/token | ||
- name: oauth2ClientID | ||
value: foo | ||
- name: oauth2ClientSecret | ||
value: bar | ||
- name: oauth2Scopes | ||
value: openid | ||
- name: oauth2Audiences | ||
value: pulsar | ||
- name: oauth2TokenCAPEM | ||
value: "{{ .OAuth2CAPEM }}" |
Oops, something went wrong.