ktimoney | 3570d5a | 2022-05-24 13:54:55 +0100 | [diff] [blame] | 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 | |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 21 | package main |
| 22 | |
| 23 | import ( |
| 24 | "bytes" |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame] | 25 | "context" |
| 26 | "crypto/tls" |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 27 | "encoding/json" |
| 28 | "flag" |
| 29 | "fmt" |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame] | 30 | "github.com/elastic/go-elasticsearch/v8" |
| 31 | "github.com/elastic/go-elasticsearch/esapi" |
| 32 | "github.com/google/uuid" |
| 33 | "github.com/prometheus/client_golang/prometheus" |
| 34 | "github.com/prometheus/client_golang/prometheus/promhttp" |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 35 | "io/ioutil" |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame] | 36 | "net" |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 37 | "net/http" |
| 38 | "net/url" |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame] | 39 | "rapps/utils/generatejwt" |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 40 | "strings" |
| 41 | "time" |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame] | 42 | "log" |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 43 | ) |
| 44 | |
| 45 | type Jwttoken struct { |
| 46 | Access_token string |
| 47 | Expires_in int |
| 48 | Refresh_expires_in int |
| 49 | Refresh_token string |
| 50 | Token_type string |
| 51 | Not_before_policy int |
| 52 | Session_state string |
| 53 | Scope string |
| 54 | } |
| 55 | |
| 56 | var gatewayHost string |
| 57 | var gatewayPort string |
| 58 | var keycloakHost string |
| 59 | var keycloakPort string |
| 60 | var keycloakAlias string |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame] | 61 | var elasticHost string |
| 62 | var elasticPort string |
| 63 | var elasticAlias string |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 64 | var securityEnabled string |
| 65 | var useGateway string |
| 66 | var role string |
| 67 | var rapp string |
| 68 | var methods string |
| 69 | var realmName string |
| 70 | var clientId string |
| 71 | var healthy bool = true |
| 72 | var ttime time.Time |
| 73 | var jwt Jwttoken |
| 74 | |
| 75 | const ( |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame] | 76 | namespace = "istio-nonrtric" |
| 77 | scope = "email" |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 78 | client_assertion_type = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" |
| 79 | ) |
| 80 | |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame] | 81 | var ( |
| 82 | reqDuration = prometheus.NewHistogramVec(prometheus.HistogramOpts{ |
| 83 | Name: "rapp_http_request_duration_seconds", |
| 84 | Help: "Duration of the last request call.", |
| 85 | Buckets: []float64{0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10}, |
| 86 | }, []string{"app", "func", "handler", "method", "code"}) |
| 87 | reqBytes = prometheus.NewSummaryVec(prometheus.SummaryOpts{ |
| 88 | Name: "rapp_bytes_summary", |
| 89 | Help: "Summary of bytes transferred over http", |
| 90 | }, []string{"app", "func", "handler", "method", "code"}) |
| 91 | ) |
| 92 | |
| 93 | type MyDocument struct { |
| 94 | Timestamp string `json:"@timestamp"` |
| 95 | App string `json:"app"` |
| 96 | Func string `json:"func"` |
| 97 | Handler string `json:"handler"` |
| 98 | Method string `json:"method"` |
| 99 | Code string `json:"code"` |
| 100 | Bytes int64 `json:"bytes"` |
| 101 | } |
| 102 | |
| 103 | var client *elasticsearch.Client |
| 104 | |
| 105 | func connectToElasticsearch() *elasticsearch.Client { |
| 106 | clusterURLs := []string{"https://" + elasticAlias + ":" + elasticPort } |
| 107 | username := "elastic" |
| 108 | password := "secret" |
| 109 | cert, _ := ioutil.ReadFile("/ca/ca.crt") |
| 110 | |
| 111 | dialer := &net.Dialer{ |
| 112 | Timeout: 30 * time.Second, |
| 113 | KeepAlive: 30 * time.Second, |
| 114 | DualStack: true, |
| 115 | } |
| 116 | |
| 117 | // client configuration |
| 118 | cfg := elasticsearch.Config{ |
| 119 | Addresses: clusterURLs, |
| 120 | Username: username, |
| 121 | Password: password, |
| 122 | CACert: cert, |
| 123 | Transport: &http.Transport{ |
| 124 | DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { |
| 125 | //fmt.Println("address original =", addr) |
| 126 | if addr == elasticAlias+":"+elasticPort { |
| 127 | addr = elasticHost + ":" + elasticPort |
| 128 | //fmt.Println("address modified =", addr) |
| 129 | } |
| 130 | return dialer.DialContext(ctx, network, addr) |
| 131 | }, |
| 132 | TLSClientConfig: &tls.Config{ |
| 133 | MinVersion: tls.VersionTLS12, |
| 134 | }, |
| 135 | }, |
| 136 | } |
| 137 | |
| 138 | es, err := elasticsearch.NewClient(cfg) |
| 139 | if err != nil { |
| 140 | log.Fatalf("Error creating the client: %s", err) |
| 141 | } |
| 142 | log.Println(elasticsearch.Version) |
| 143 | |
| 144 | resp, err := es.Info() |
| 145 | if err != nil { |
| 146 | log.Fatalf("Error getting response: %s", err) |
| 147 | } |
| 148 | defer resp.Body.Close() |
| 149 | log.Println(resp) |
| 150 | return es |
| 151 | } |
| 152 | |
| 153 | func addEsIndex(app, fnc, hnd, meth, code string, bytes int64){ |
| 154 | ts := time.Now().Format(time.RFC3339) |
| 155 | doc := MyDocument{Timestamp: ts, App: app, Func: fnc, Handler: hnd, Method: meth, Code: code, Bytes: bytes } |
| 156 | jsonString, _ := json.Marshal(doc) |
| 157 | uid := fmt.Sprintf("%v", uuid.New()) |
| 158 | indexName := "gostash-"+time.Now().Format("2006.01.02") |
| 159 | request := esapi.IndexRequest{Index: indexName, DocumentID: uid, Body: strings.NewReader(string(jsonString))} |
| 160 | _, err := request.Do(context.Background(), client) |
| 161 | if err != nil { |
| 162 | fmt.Println(err) |
| 163 | } |
| 164 | } |
| 165 | |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 166 | func getToken() string { |
| 167 | if ttime.Before(time.Now()) { |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame] | 168 | resp := &http.Response{} |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 169 | client_assertion := getClientAssertion() |
| 170 | keycloakUrl := "http://" + keycloakHost + ":" + keycloakPort + "/auth/realms/" + realmName + "/protocol/openid-connect/token" |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame] | 171 | fmt.Printf("Making token request to %s\n", keycloakUrl) |
| 172 | timer := prometheus.NewTimer(prometheus.ObserverFunc(func(v float64) { |
| 173 | reqDuration.WithLabelValues("rapp-jwt-invoker", "getToken", resp.Request.URL.Path, resp.Request.Method, |
| 174 | resp.Status).Observe(v) |
| 175 | })) |
| 176 | defer timer.ObserveDuration() |
| 177 | var err error |
| 178 | if jwt.Refresh_token != "" { |
| 179 | resp, err = http.PostForm(keycloakUrl, url.Values{"client_assertion_type": {client_assertion_type}, |
| 180 | "client_assertion": {client_assertion}, "grant_type": {"refresh_token"}, |
| 181 | "refresh_token": {jwt.Refresh_token}, "client_id": {clientId}, "scope": {scope}}) |
| 182 | } else { |
| 183 | resp, err = http.PostForm(keycloakUrl, url.Values{"client_assertion_type": {client_assertion_type}, |
| 184 | "client_assertion": {client_assertion}, "grant_type": {"client_credentials"}, |
| 185 | "client_id": {clientId}, "scope": {scope}}) |
| 186 | } |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 187 | if err != nil { |
| 188 | fmt.Println(err) |
| 189 | panic("Something wrong with the credentials or url ") |
| 190 | } |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame] | 191 | |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 192 | defer resp.Body.Close() |
| 193 | body, err := ioutil.ReadAll(resp.Body) |
| 194 | json.Unmarshal([]byte(body), &jwt) |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame] | 195 | |
| 196 | reqBytes.WithLabelValues("rapp-jwt-invoker", "getToken", resp.Request.URL.Path, resp.Request.Method, |
| 197 | resp.Status).Observe(float64(resp.ContentLength)) |
| 198 | addEsIndex("rapp-jwt-invoker", "getToken", resp.Request.URL.Path, resp.Request.Method, |
| 199 | resp.Status, resp.ContentLength) |
| 200 | ttime = time.Now() |
| 201 | ttime = ttime.Add(time.Second * time.Duration(jwt.Expires_in)) |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 202 | } |
| 203 | return jwt.Access_token |
| 204 | } |
| 205 | |
| 206 | func getClientAssertion() string { |
| 207 | realm := "http://" + keycloakHost + ":" + keycloakPort + "/auth/realms/" + realmName |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame] | 208 | clientAssertion := generatejwt.CreateJWT("/certs/client.key", "/certs/client_pub.key", "", clientId, realm) |
| 209 | return clientAssertion |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 210 | } |
| 211 | |
| 212 | func MakeRequest(client *http.Client, prefix string, method string, ch chan string) { |
| 213 | var service = strings.Split(prefix, "/")[1] |
| 214 | var gatewayUrl = "http://" + gatewayHost + ":" + gatewayPort |
| 215 | var token = "" |
| 216 | var jsonValue []byte = []byte{} |
| 217 | var restUrl string = "" |
| 218 | |
| 219 | if securityEnabled == "true" { |
| 220 | token = getToken() |
| 221 | } else { |
| 222 | useGateway = "N" |
| 223 | } |
| 224 | |
| 225 | if strings.ToUpper(useGateway) != "Y" { |
| 226 | gatewayUrl = "http://" + service + "." + namespace + ":80" |
| 227 | prefix = "" |
| 228 | } |
| 229 | |
| 230 | restUrl = gatewayUrl + prefix |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame] | 231 | resp := &http.Response{} |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 232 | |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame] | 233 | timer := prometheus.NewTimer(prometheus.ObserverFunc(func(v float64) { |
| 234 | reqDuration.WithLabelValues("rapp-jwt-invoker", "MakeRequest", resp.Request.URL.Path, resp.Request.Method, |
| 235 | resp.Status).Observe(v) |
| 236 | })) |
| 237 | defer timer.ObserveDuration() |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 238 | req, err := http.NewRequest(method, restUrl, bytes.NewBuffer(jsonValue)) |
| 239 | if err != nil { |
| 240 | fmt.Printf("Got error %s", err.Error()) |
| 241 | } |
| 242 | req.Header.Set("Content-type", "application/json") |
| 243 | req.Header.Set("Authorization", "Bearer "+token) |
| 244 | |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame] | 245 | resp, err = client.Do(req) |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 246 | if err != nil { |
| 247 | fmt.Printf("Got error %s", err.Error()) |
| 248 | } |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame] | 249 | |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 250 | defer resp.Body.Close() |
| 251 | body, _ := ioutil.ReadAll(resp.Body) |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame] | 252 | reqBytes.WithLabelValues("rapp-jwt-invoker", "MakeRequest", req.URL.Path, req.Method, |
| 253 | resp.Status).Observe(float64(resp.ContentLength)) |
| 254 | addEsIndex("rapp-jwt-invoker", "MakeRequest", req.URL.Path, req.Method, resp.Status, resp.ContentLength) |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 255 | |
| 256 | respString := string(body[:]) |
| 257 | if respString == "RBAC: access denied" { |
| 258 | respString += " for " + service + " " + strings.ToLower(method) + " request" |
| 259 | } |
| 260 | fmt.Printf("Received response for %s %s request - %s\n", service, strings.ToLower(method), respString) |
| 261 | ch <- prefix + "," + method |
| 262 | } |
| 263 | |
| 264 | func health(res http.ResponseWriter, req *http.Request) { |
| 265 | if healthy { |
| 266 | res.WriteHeader(http.StatusOK) |
| 267 | res.Write([]byte("healthy")) |
| 268 | } else { |
| 269 | res.WriteHeader(http.StatusInternalServerError) |
| 270 | res.Write([]byte("unhealthy")) |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | func main() { |
| 275 | ttime = time.Now() |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame] | 276 | time.Sleep(3 * time.Second) |
| 277 | prometheus.Register(reqDuration) |
| 278 | prometheus.Register(reqBytes) |
| 279 | |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 280 | flag.StringVar(&gatewayHost, "gatewayHost", "istio-ingressgateway.istio-system", "Gateway Host") |
| 281 | flag.StringVar(&gatewayPort, "gatewayPort", "80", "Gateway Port") |
| 282 | flag.StringVar(&keycloakHost, "keycloakHost", "istio-ingressgateway.istio-system", "Keycloak Host") |
| 283 | flag.StringVar(&keycloakPort, "keycloakPort", "80", "Keycloak Port") |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame] | 284 | flag.StringVar(&elasticHost, "elasticHost", "istio-ingressgateway.istio-system", "Elasticsearch Host") |
| 285 | flag.StringVar(&elasticPort, "elasticPort", "443", "Elasticsearch Port") |
| 286 | flag.StringVar(&elasticAlias, "elasticAlias", "elasticsearch.est.tech", "Elasticsearch URL Alias") |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 287 | flag.StringVar(&useGateway, "useGateway", "Y", "Connect to services through API gateway") |
| 288 | flag.StringVar(&securityEnabled, "securityEnabled", "true", "Security is required to use this application") |
| 289 | flag.StringVar(&realmName, "realm", "jwt", "Keycloak realm") |
| 290 | flag.StringVar(&clientId, "client", "jwtprovider-cli", "Keycloak client") |
| 291 | flag.StringVar(&role, "role", "provider-viewer", "Role granted to application") |
| 292 | flag.StringVar(&rapp, "rapp", "rapp-jwt-provider", "Name of rapp to invoke") |
| 293 | flag.StringVar(&methods, "methods", "GET", "Methods to access application") |
| 294 | flag.Parse() |
| 295 | |
| 296 | healthHandler := http.HandlerFunc(health) |
| 297 | http.Handle("/health", healthHandler) |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame] | 298 | http.Handle("/metrics", promhttp.Handler()) |
| 299 | client = connectToElasticsearch() |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 300 | go func() { |
| 301 | http.ListenAndServe(":9000", nil) |
| 302 | }() |
| 303 | |
| 304 | client := &http.Client{ |
| 305 | Timeout: time.Second * 10, |
| 306 | } |
| 307 | |
| 308 | ch := make(chan string) |
| 309 | var prefixArray []string = []string{"/" + rapp} |
| 310 | var methodArray []string = []string{methods} |
| 311 | for _, prefix := range prefixArray { |
| 312 | for _, method := range methodArray { |
| 313 | go MakeRequest(client, prefix, method, ch) |
| 314 | } |
| 315 | } |
| 316 | |
| 317 | ioutil.WriteFile("init.txt", []byte("Initialization done."), 0644) |
| 318 | |
| 319 | for r := range ch { |
| 320 | go func(resp string) { |
| 321 | time.Sleep(10 * time.Second) |
| 322 | elements := strings.Split(resp, ",") |
| 323 | prefix := elements[0] |
| 324 | method := elements[1] |
| 325 | MakeRequest(client, prefix, method, ch) |
| 326 | }(r) |
| 327 | } |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 328 | } |