You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by mm...@apache.org on 2019/05/14 16:34:14 UTC

[pulsar-client-go] 37/38: Added token auth provider

This is an automated email from the ASF dual-hosted git repository.

mmerli pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/pulsar-client-go.git

commit e058b846ceb683d06a0793fc8af0873705b35d68
Author: Matteo Merli <mm...@apache.org>
AuthorDate: Wed May 8 18:13:09 2019 -0700

    Added token auth provider
---
 Dockerfile                          |  9 +---
 integration-tests/tokens/secret.key |  1 +
 integration-tests/tokens/token.txt  |  1 +
 pulsar/client.go                    | 10 ++--
 pulsar/impl_client.go               | 28 -----------
 pulsar/impl_client_test.go          | 42 +++++++++++++++-
 pulsar/internal/auth/provider.go    |  3 ++
 pulsar/internal/auth/token.go       | 98 +++++++++++++++++++++++++++++++++++++
 pulsar/test_helper.go               |  3 +-
 9 files changed, 151 insertions(+), 44 deletions(-)

diff --git a/Dockerfile b/Dockerfile
index 3451983..1186f96 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -27,15 +27,8 @@ ENV PATH /root/go/bin:/usr/local/go/bin:$PATH
 ### Add test scripts
 
 COPY integration-tests/certs /pulsar/certs
+COPY integration-tests/tokens /pulsar/tokens
 COPY integration-tests/standalone.conf /pulsar/conf
 COPY integration-tests/client.conf /pulsar/conf
 COPY pulsar-test-service-start.sh /pulsar/bin
 COPY pulsar-test-service-stop.sh /pulsar/bin
-
-# Initialize test configuration and credentials
-RUN mkdir /pulsar/tokens
-RUN /pulsar/bin/pulsar tokens create-secret-key --output /pulsar/tokens/secret.key
-RUN /pulsar/bin/pulsar tokens create \
-                --subject token-principal \
-                --secret-key file:///pulsar/tokens/secret.key \
-                > /pulsar/tokens/token.txt
diff --git a/integration-tests/tokens/secret.key b/integration-tests/tokens/secret.key
new file mode 100644
index 0000000..92e05b9
--- /dev/null
+++ b/integration-tests/tokens/secret.key
@@ -0,0 +1 @@
+=Z��k؁HKX��w<��H�߾V�`}
h�
\ No newline at end of file
diff --git a/integration-tests/tokens/token.txt b/integration-tests/tokens/token.txt
new file mode 100644
index 0000000..b1b8309
--- /dev/null
+++ b/integration-tests/tokens/token.txt
@@ -0,0 +1 @@
+eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0b2tlbi1wcmluY2lwYWwifQ.tSfgR8l7dKC6LoWCxQgNkuSB8our7xV_nAM7wpgCbG4
diff --git a/pulsar/client.go b/pulsar/client.go
index 1a838ac..0225a83 100644
--- a/pulsar/client.go
+++ b/pulsar/client.go
@@ -37,14 +37,12 @@ func NewAuthentication(name string, params string) (Authentication, error) {
 
 // Create new Authentication provider with specified auth token
 func NewAuthenticationToken(token string) Authentication {
-	// TODO: return newAuthenticationToken(token)
-	return nil
+	return auth.NewAuthenticationToken(token)
 }
 
-// Create new Authentication provider with specified auth token supplier
-func NewAuthenticationTokenSupplier(tokenSupplier func() string) Authentication {
-	// TODO:  return newAuthenticationTokenSupplier(tokenSupplier)
-	return nil
+// Create new Authentication provider with specified auth token from a file
+func NewAuthenticationTokenFromFile(tokenFilePath string) Authentication {
+	return auth.NewAuthenticationTokenFromFile(tokenFilePath)
 }
 
 // Create new Authentication provider with specified TLS certificate and private key
diff --git a/pulsar/impl_client.go b/pulsar/impl_client.go
index b84ac82..a952efc 100644
--- a/pulsar/impl_client.go
+++ b/pulsar/impl_client.go
@@ -20,12 +20,9 @@
 package pulsar
 
 import (
-	"crypto/tls"
-	"crypto/x509"
 	"fmt"
 	"github.com/pkg/errors"
 	log "github.com/sirupsen/logrus"
-	"io/ioutil"
 	"net/url"
 	"pulsar-client-go/pulsar/internal"
 	"pulsar-client-go/pulsar/internal/auth"
@@ -153,28 +150,3 @@ func (client *client) Close() error {
 
 	return nil
 }
-
-func getTlsConfig(options ClientOptions) (*tls.Config, error) {
-	tlsConfig := &tls.Config{
-		InsecureSkipVerify: options.TLSAllowInsecureConnection,
-	}
-
-	if options.TLSTrustCertsFilePath != "" {
-		caCerts, err := ioutil.ReadFile(options.TLSTrustCertsFilePath)
-		if err != nil {
-			return nil, err
-		}
-
-		tlsConfig.RootCAs = x509.NewCertPool()
-		ok := tlsConfig.RootCAs.AppendCertsFromPEM([]byte(caCerts))
-		if !ok {
-			return nil, errors.New("failed to parse root CAs certificates")
-		}
-	}
-
-	if options.TLSValidateHostname {
-		tlsConfig.ServerName = options.URL
-	}
-
-	return tlsConfig, nil
-}
diff --git a/pulsar/impl_client_test.go b/pulsar/impl_client_test.go
index 218587f..4d11ee6 100644
--- a/pulsar/impl_client_test.go
+++ b/pulsar/impl_client_test.go
@@ -20,6 +20,7 @@
 package pulsar
 
 import (
+	"io/ioutil"
 	"testing"
 
 	"github.com/stretchr/testify/assert"
@@ -147,7 +148,46 @@ func TestTLSAuth(t *testing.T) {
 	client, err := NewClient(ClientOptions{
 		URL:                   serviceUrlTls,
 		TLSTrustCertsFilePath: caCertsPath,
-		Authentication: NewAuthenticationTLS(tlsClientCertPath, tlsClientKeyPath),
+		Authentication:        NewAuthenticationTLS(tlsClientCertPath, tlsClientKeyPath),
+	})
+	assert.NoError(t, err)
+
+	producer, err := client.CreateProducer(ProducerOptions{
+		Topic: newAuthTopicName(),
+	})
+
+	assert.NoError(t, err)
+	assert.NotNil(t, producer)
+
+	err = client.Close()
+	assert.NoError(t, err)
+}
+
+func TestTokenAuth(t *testing.T) {
+	token, err := ioutil.ReadFile(tokenFilePath)
+	assert.NoError(t, err)
+
+	client, err := NewClient(ClientOptions{
+		URL:            serviceUrl,
+		Authentication: NewAuthenticationToken(string(token)),
+	})
+	assert.NoError(t, err)
+
+	producer, err := client.CreateProducer(ProducerOptions{
+		Topic: newAuthTopicName(),
+	})
+
+	assert.NoError(t, err)
+	assert.NotNil(t, producer)
+
+	err = client.Close()
+	assert.NoError(t, err)
+}
+
+func TestTokenAuthFromFile(t *testing.T) {
+	client, err := NewClient(ClientOptions{
+		URL:            serviceUrl,
+		Authentication: NewAuthenticationTokenFromFile(tokenFilePath),
 	})
 	assert.NoError(t, err)
 
diff --git a/pulsar/internal/auth/provider.go b/pulsar/internal/auth/provider.go
index c23a662..48c20dc 100644
--- a/pulsar/internal/auth/provider.go
+++ b/pulsar/internal/auth/provider.go
@@ -50,6 +50,9 @@ func NewProvider(name string, params string) (Provider, error) {
 	case "tls", "org.apache.pulsar.client.impl.auth.AuthenticationTls":
 		return NewAuthenticationTLSWithParams(m), nil
 
+	case "token", "org.apache.pulsar.client.impl.auth.AuthenticationToken":
+		return NewAuthenticationTokenWithParams(m)
+
 	default:
 		return nil, errors.New(fmt.Sprintf("invalid auth provider '%s'", name))
 	}
diff --git a/pulsar/internal/auth/token.go b/pulsar/internal/auth/token.go
new file mode 100644
index 0000000..d14279b
--- /dev/null
+++ b/pulsar/internal/auth/token.go
@@ -0,0 +1,98 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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 auth
+
+import (
+	"crypto/tls"
+	"github.com/pkg/errors"
+	"io/ioutil"
+	"strings"
+)
+
+type tokenAuthProvider struct {
+	tokenSupplier func() (string, error)
+}
+
+func NewAuthenticationTokenWithParams(params map[string]string) (Provider, error) {
+	if params["token"] != "" {
+		return NewAuthenticationToken(params["token"]), nil
+	} else if params["file"] != "" {
+		return NewAuthenticationTokenFromFile(params["file"]), nil
+	} else {
+		return nil, errors.New("missing configuration for token auth")
+	}
+}
+
+func NewAuthenticationToken(token string) Provider {
+	return &tokenAuthProvider{
+		tokenSupplier: func() (string, error) {
+			if token == "" {
+				return "", errors.New("empty token credentials")
+			} else {
+				return token, nil
+			}
+		},
+	}
+}
+
+func NewAuthenticationTokenFromFile(tokenFilePath string) Provider {
+	return &tokenAuthProvider{
+		tokenSupplier: func() (string, error) {
+			data, err := ioutil.ReadFile(tokenFilePath)
+			if err != nil {
+				return "", err
+			}
+
+			token := strings.Trim(string(data), " \n")
+			if token == "" {
+				return "", errors.New("empty token credentials")
+			} else {
+				return token, nil
+			}
+		},
+	}
+}
+
+func (p *tokenAuthProvider) Init() error {
+	// Try to read certificates immediately to provide better error at startup
+	_, err := p.GetData()
+	return err
+}
+
+func (p *tokenAuthProvider) Name() string {
+	return "token"
+}
+
+func (p *tokenAuthProvider) GetTlsCertificate() (*tls.Certificate, error) {
+	return nil, nil
+}
+
+func (p *tokenAuthProvider) GetData() ([]byte, error) {
+	t, err := p.tokenSupplier()
+	if err != nil {
+		return nil, err
+	} else {
+		return []byte(t), nil
+	}
+}
+
+func (tokenAuthProvider) Close() error {
+	return nil
+}
diff --git a/pulsar/test_helper.go b/pulsar/test_helper.go
index 1e84a92..f4c9d7d 100644
--- a/pulsar/test_helper.go
+++ b/pulsar/test_helper.go
@@ -30,7 +30,8 @@ const (
 
 	caCertsPath       = "../integration-tests/certs/cacert.pem"
 	tlsClientCertPath = "../integration-tests/certs/client-cert.pem"
-	tlsClientKeyPath = "../integration-tests/certs/client-key.pem"
+	tlsClientKeyPath  = "../integration-tests/certs/client-key.pem"
+	tokenFilePath     = "../integration-tests/tokens/token.txt"
 )
 
 func newTopicName() string {