blob: 9fc513a55482714870c2bd7a8fa66cc8a23b7fd4 [file] [log] [blame]
ktimoney3570d5a2022-05-24 13:54:55 +01001// -
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
ktimoney8ead72a2022-04-12 15:10:10 +010021package main
22
23import (
24 "bytes"
ktimoney90fcec92022-04-29 15:46:50 +010025 "context"
26 "crypto/tls"
ktimoney8ead72a2022-04-12 15:10:10 +010027 "encoding/json"
28 "flag"
29 "fmt"
ktimoney90fcec92022-04-29 15:46:50 +010030 "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"
ktimoney8ead72a2022-04-12 15:10:10 +010035 "io/ioutil"
ktimoney90fcec92022-04-29 15:46:50 +010036 "net"
ktimoney8ead72a2022-04-12 15:10:10 +010037 "net/http"
38 "net/url"
ktimoney90fcec92022-04-29 15:46:50 +010039 "rapps/utils/generatejwt"
ktimoney8ead72a2022-04-12 15:10:10 +010040 "strings"
41 "time"
ktimoney90fcec92022-04-29 15:46:50 +010042 "log"
ktimoney8ead72a2022-04-12 15:10:10 +010043)
44
45type 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
56var gatewayHost string
57var gatewayPort string
58var keycloakHost string
59var keycloakPort string
60var keycloakAlias string
ktimoney90fcec92022-04-29 15:46:50 +010061var elasticHost string
62var elasticPort string
63var elasticAlias string
ktimoney8ead72a2022-04-12 15:10:10 +010064var securityEnabled string
65var useGateway string
66var role string
67var rapp string
68var methods string
69var realmName string
70var clientId string
71var healthy bool = true
72var ttime time.Time
73var jwt Jwttoken
74
75const (
ktimoney90fcec92022-04-29 15:46:50 +010076 namespace = "istio-nonrtric"
77 scope = "email"
ktimoney8ead72a2022-04-12 15:10:10 +010078 client_assertion_type = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
79)
80
ktimoney90fcec92022-04-29 15:46:50 +010081var (
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
93type 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
103var client *elasticsearch.Client
104
105func 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
153func 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
ktimoney8ead72a2022-04-12 15:10:10 +0100166func getToken() string {
167 if ttime.Before(time.Now()) {
ktimoney90fcec92022-04-29 15:46:50 +0100168 resp := &http.Response{}
ktimoney8ead72a2022-04-12 15:10:10 +0100169 client_assertion := getClientAssertion()
170 keycloakUrl := "http://" + keycloakHost + ":" + keycloakPort + "/auth/realms/" + realmName + "/protocol/openid-connect/token"
ktimoney90fcec92022-04-29 15:46:50 +0100171 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 }
ktimoney8ead72a2022-04-12 15:10:10 +0100187 if err != nil {
188 fmt.Println(err)
189 panic("Something wrong with the credentials or url ")
190 }
ktimoney90fcec92022-04-29 15:46:50 +0100191
ktimoney8ead72a2022-04-12 15:10:10 +0100192 defer resp.Body.Close()
193 body, err := ioutil.ReadAll(resp.Body)
194 json.Unmarshal([]byte(body), &jwt)
ktimoney90fcec92022-04-29 15:46:50 +0100195
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))
ktimoney8ead72a2022-04-12 15:10:10 +0100202 }
203 return jwt.Access_token
204}
205
206func getClientAssertion() string {
207 realm := "http://" + keycloakHost + ":" + keycloakPort + "/auth/realms/" + realmName
ktimoney90fcec92022-04-29 15:46:50 +0100208 clientAssertion := generatejwt.CreateJWT("/certs/client.key", "/certs/client_pub.key", "", clientId, realm)
209 return clientAssertion
ktimoney8ead72a2022-04-12 15:10:10 +0100210}
211
212func 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
ktimoney90fcec92022-04-29 15:46:50 +0100231 resp := &http.Response{}
ktimoney8ead72a2022-04-12 15:10:10 +0100232
ktimoney90fcec92022-04-29 15:46:50 +0100233 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()
ktimoney8ead72a2022-04-12 15:10:10 +0100238 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
ktimoney90fcec92022-04-29 15:46:50 +0100245 resp, err = client.Do(req)
ktimoney8ead72a2022-04-12 15:10:10 +0100246 if err != nil {
247 fmt.Printf("Got error %s", err.Error())
248 }
ktimoney90fcec92022-04-29 15:46:50 +0100249
ktimoney8ead72a2022-04-12 15:10:10 +0100250 defer resp.Body.Close()
251 body, _ := ioutil.ReadAll(resp.Body)
ktimoney90fcec92022-04-29 15:46:50 +0100252 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)
ktimoney8ead72a2022-04-12 15:10:10 +0100255
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
264func 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
274func main() {
275 ttime = time.Now()
ktimoney90fcec92022-04-29 15:46:50 +0100276 time.Sleep(3 * time.Second)
277 prometheus.Register(reqDuration)
278 prometheus.Register(reqBytes)
279
ktimoney8ead72a2022-04-12 15:10:10 +0100280 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")
ktimoney90fcec92022-04-29 15:46:50 +0100284 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")
ktimoney8ead72a2022-04-12 15:10:10 +0100287 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)
ktimoney90fcec92022-04-29 15:46:50 +0100298 http.Handle("/metrics", promhttp.Handler())
299 client = connectToElasticsearch()
ktimoney8ead72a2022-04-12 15:10:10 +0100300 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 }
ktimoney8ead72a2022-04-12 15:10:10 +0100328}