2 // ========================LICENSE_START=================================
5 // Copyright (C) 2022: Nordix Foundation
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
18 // ========================LICENSE_END===================================
34 log "github.com/sirupsen/logrus"
37 type JwtToken struct {
48 func NewContext(config *Config) *Context {
55 // @title Auth token fetcher
58 // @license.name Apache 2.0
59 // @license.url http://www.apache.org/licenses/LICENSE-2.0.html
62 configuration := NewConfig()
63 log.SetLevel(configuration.LogLevel)
65 log.Debug("Using configuration: ", configuration)
66 start(NewContext(configuration))
71 func start(context *Context) {
72 log.Debug("Initializing")
73 if err := validateConfiguration(context.Config); err != nil {
74 log.Fatalf("Stopping due to error: %v", err)
77 cert := loadCertificate(context.Config.CertPath, context.Config.KeyPath)
78 caCerts := loadCaCerts(context.Config.CACertsPath)
80 webClient := CreateHttpClient(cert, caCerts, 10*time.Second)
82 go periodicRefreshIwtToken(webClient, context)
85 func periodicRefreshIwtToken(webClient *http.Client, context *Context) {
87 jwtToken, err := fetchJwtToken(webClient, context.Config)
89 saveAccessToken(jwtToken, context.Config)
91 delayTime := calcDelayTime(jwtToken, err, context.Config)
92 log.WithFields(log.Fields{"seconds": delayTime.Seconds()}).Debug("Sleeping")
97 func calcDelayTime(token JwtToken, e error, confing *Config) time.Duration {
99 return time.Second * 1
101 remains := token.Expires_in - confing.RefreshMarginSeconds
105 return time.Second * time.Duration(remains)
108 func check(e error) bool {
110 log.Errorf("Failure reason: %v", e)
116 func saveAccessToken(token JwtToken, configuration *Config) {
117 log.WithFields(log.Fields{"file": configuration.AuthTokenOutputFileName}).Debug("Saving access token")
118 data := []byte(token.Access_token)
119 err := os.WriteFile(configuration.AuthTokenOutputFileName, data, 0644)
123 func fetchJwtToken(webClient *http.Client, configuration *Config) (JwtToken, error) {
124 log.WithFields(log.Fields{"url": configuration.AuthServiceUrl}).Debug("Fetching token")
127 resp, err := webClient.PostForm(configuration.AuthServiceUrl,
128 url.Values{"client_secret": {configuration.ClientSecret}, "grant_type": {configuration.GrantType}, "client_id": {configuration.ClientId}})
132 defer resp.Body.Close()
133 body, err = ioutil.ReadAll(resp.Body)
135 err = json.Unmarshal([]byte(body), &jwt)
141 func loadCertificate(certPath string, keyPath string) tls.Certificate {
142 log.WithFields(log.Fields{"certPath": certPath, "keyPath": keyPath}).Debug("Loading cert")
143 cert, err := tls.LoadX509KeyPair(certPath, keyPath)
147 log.Fatalf("cannot create x509 keypair from cert file %s and key file %s due to: %v", certPath, keyPath, err)
148 return tls.Certificate{}
152 func loadCaCerts(caCertsPath string) *x509.CertPool {
154 if caCertsPath == "" {
157 caCert, err := ioutil.ReadFile(caCertsPath)
159 caCertPool := x509.NewCertPool()
160 caCertPool.AppendCertsFromPEM(caCert)
165 channel := make(chan int)