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