Merge "Sample consumer to get kafka broker from ICS"
[nonrtric.git] / auth-token-fetch / main.go
index 9a63534..0136688 100644 (file)
@@ -22,8 +22,8 @@ package main
 
 import (
        "crypto/tls"
+       "crypto/x509"
        "encoding/json"
-       "fmt"
        "io/ioutil"
        "net/http"
        "net/url"
@@ -53,7 +53,7 @@ func NewContext(config *Config) *Context {
 }
 
 // @title Auth token fetcher
-// @version 0.0.0
+// @version 1.1.0
 
 // @license.name  Apache 2.0
 // @license.url   http://www.apache.org/licenses/LICENSE-2.0.html
@@ -74,14 +74,10 @@ func start(context *Context) {
                log.Fatalf("Stopping due to error: %v", err)
        }
 
-       var cert tls.Certificate
-       if c, err := loadCertificate(context.Config.CertPath, context.Config.KeyPath); err == nil {
-               cert = c
-       } else {
-               log.Fatalf("Stopping due to error: %v", err)
-       }
+       cert := loadCertificate(context.Config.CertPath, context.Config.KeyPath)
+       caCerts := loadCaCerts(context.Config.CACertsPath)
 
-       webClient := CreateHttpClient(cert, 10*time.Second)
+       webClient := CreateHttpClient(cert, caCerts, 10*time.Second)
 
        go periodicRefreshIwtToken(webClient, context)
 }
@@ -142,15 +138,29 @@ func fetchJwtToken(webClient *http.Client, configuration *Config) (JwtToken, err
        return jwt, err
 }
 
-func loadCertificate(certPath string, keyPath string) (tls.Certificate, error) {
+func loadCertificate(certPath string, keyPath string) tls.Certificate {
        log.WithFields(log.Fields{"certPath": certPath, "keyPath": keyPath}).Debug("Loading cert")
-       if cert, err := tls.LoadX509KeyPair(certPath, keyPath); err == nil {
-               return cert, nil
+       cert, err := tls.LoadX509KeyPair(certPath, keyPath)
+       if check(err) {
+               return cert
        } else {
-               return tls.Certificate{}, fmt.Errorf("cannot create x509 keypair from cert file %s and key file %s due to: %v", certPath, keyPath, err)
+               log.Fatalf("cannot create x509 keypair from cert file %s and key file %s due to: %v", certPath, keyPath, err)
+               return tls.Certificate{}
        }
 }
 
+func loadCaCerts(caCertsPath string) *x509.CertPool {
+       var err error
+       if caCertsPath == "" {
+               return nil
+       }
+       caCert, err := ioutil.ReadFile(caCertsPath)
+       check(err)
+       caCertPool := x509.NewCertPool()
+       caCertPool.AppendCertsFromPEM(caCert)
+       return caCertPool
+}
+
 func keepAlive() {
        channel := make(chan int)
        <-channel