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 var cert tls.Certificate
78 if c, err := loadCertificate(context.Config.CertPath, context.Config.KeyPath); err == nil {
81 log.Fatalf("Stopping due to error: %v", err)
84 webClient := CreateHttpClient(cert, 10*time.Second)
86 go periodicRefreshIwtToken(webClient, context)
89 func periodicRefreshIwtToken(webClient *http.Client, context *Context) {
91 jwtToken, err := fetchJwtToken(webClient, context.Config)
93 saveAccessToken(jwtToken, context.Config)
95 delayTime := calcDelayTime(jwtToken, err, context.Config)
96 log.WithFields(log.Fields{"seconds": delayTime.Seconds()}).Debug("Sleeping")
101 func calcDelayTime(token JwtToken, e error, confing *Config) time.Duration {
103 return time.Second * 1
105 remains := token.Expires_in - confing.RefreshMarginSeconds
109 return time.Second * time.Duration(remains)
112 func check(e error) bool {
114 log.Errorf("Failure reason: %v", e)
120 func saveAccessToken(token JwtToken, configuration *Config) {
121 log.WithFields(log.Fields{"file": configuration.AuthTokenOutputFileName}).Debug("Saving access token")
122 data := []byte(token.Access_token)
123 err := os.WriteFile(configuration.AuthTokenOutputFileName, data, 0644)
127 func fetchJwtToken(webClient *http.Client, configuration *Config) (JwtToken, error) {
128 log.WithFields(log.Fields{"url": configuration.AuthServiceUrl}).Debug("Fetching token")
131 resp, err := webClient.PostForm(configuration.AuthServiceUrl,
132 url.Values{"client_secret": {configuration.ClientSecret}, "grant_type": {configuration.GrantType}, "client_id": {configuration.ClientId}})
136 defer resp.Body.Close()
137 body, err = ioutil.ReadAll(resp.Body)
139 err = json.Unmarshal([]byte(body), &jwt)
145 func loadCertificate(certPath string, keyPath string) (tls.Certificate, error) {
146 log.WithFields(log.Fields{"certPath": certPath, "keyPath": keyPath}).Debug("Loading cert")
147 if cert, err := tls.LoadX509KeyPair(certPath, keyPath); err == nil {
150 return tls.Certificate{}, fmt.Errorf("cannot create x509 keypair from cert file %s and key file %s due to: %v", certPath, keyPath, err)
155 channel := make(chan int)