Fetch of authorization token
[nonrtric.git] / auth-token-fetch / main.go
1 // -
2 //   ========================LICENSE_START=================================
3 //   O-RAN-SC
4 //   %%
5 //   Copyright (C) 2022: Nordix Foundation
6 //   %%
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
10 //
11 //        http://www.apache.org/licenses/LICENSE-2.0
12 //
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===================================
19 //
20
21 package main
22
23 import (
24         "crypto/tls"
25         "encoding/json"
26         "fmt"
27         "io/ioutil"
28         "net/http"
29         "net/url"
30         "time"
31
32         "os"
33
34         log "github.com/sirupsen/logrus"
35 )
36
37 type JwtToken struct {
38         Access_token string
39         Expires_in   int
40         Token_type   string
41 }
42
43 type Context struct {
44         Running bool
45         Config  *Config
46 }
47
48 func NewContext(config *Config) *Context {
49         return &Context{
50                 Running: true,
51                 Config:  config,
52         }
53 }
54
55 // @title Auth token fetcher
56 // @version 0.0.0
57
58 // @license.name  Apache 2.0
59 // @license.url   http://www.apache.org/licenses/LICENSE-2.0.html
60
61 func main() {
62         configuration := NewConfig()
63         log.SetLevel(configuration.LogLevel)
64
65         log.Debug("Using configuration: ", configuration)
66         start(NewContext(configuration))
67
68         keepAlive()
69 }
70
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)
75         }
76
77         var cert tls.Certificate
78         if c, err := loadCertificate(context.Config.CertPath, context.Config.KeyPath); err == nil {
79                 cert = c
80         } else {
81                 log.Fatalf("Stopping due to error: %v", err)
82         }
83
84         webClient := CreateHttpClient(cert, 10*time.Second)
85
86         go periodicRefreshIwtToken(webClient, context)
87 }
88
89 func periodicRefreshIwtToken(webClient *http.Client, context *Context) {
90         for context.Running {
91                 jwtToken, err := fetchJwtToken(webClient, context.Config)
92                 if check(err) {
93                         saveAccessToken(jwtToken, context.Config)
94                 }
95                 delayTime := calcDelayTime(jwtToken, err, context.Config)
96                 log.WithFields(log.Fields{"seconds": delayTime.Seconds()}).Debug("Sleeping")
97                 time.Sleep(delayTime)
98         }
99 }
100
101 func calcDelayTime(token JwtToken, e error, confing *Config) time.Duration {
102         if e != nil {
103                 return time.Second * 1
104         }
105         remains := token.Expires_in - confing.RefreshMarginSeconds
106         if remains < 1 {
107                 remains = 1
108         }
109         return time.Second * time.Duration(remains)
110 }
111
112 func check(e error) bool {
113         if e != nil {
114                 log.Errorf("Failure reason: %v", e)
115                 return false
116         }
117         return true
118 }
119
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)
124         check(err)
125 }
126
127 func fetchJwtToken(webClient *http.Client, configuration *Config) (JwtToken, error) {
128         log.WithFields(log.Fields{"url": configuration.AuthServiceUrl}).Debug("Fetching token")
129         var jwt JwtToken
130         var err error
131         resp, err := webClient.PostForm(configuration.AuthServiceUrl,
132                 url.Values{"client_secret": {configuration.ClientSecret}, "grant_type": {configuration.GrantType}, "client_id": {configuration.ClientId}})
133
134         if check(err) {
135                 var body []byte
136                 defer resp.Body.Close()
137                 body, err = ioutil.ReadAll(resp.Body)
138                 if check(err) {
139                         err = json.Unmarshal([]byte(body), &jwt)
140                 }
141         }
142         return jwt, err
143 }
144
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 {
148                 return cert, nil
149         } else {
150                 return tls.Certificate{}, fmt.Errorf("cannot create x509 keypair from cert file %s and key file %s due to: %v", certPath, keyPath, err)
151         }
152 }
153
154 func keepAlive() {
155         channel := make(chan int)
156         <-channel
157 }