ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame^] | 5 | "context" |
| 6 | "crypto/tls" |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 7 | "encoding/json" |
| 8 | "flag" |
| 9 | "fmt" |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame^] | 10 | "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" |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 15 | "io/ioutil" |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame^] | 16 | "net" |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 17 | "net/http" |
| 18 | "net/url" |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame^] | 19 | "rapps/utils/generatejwt" |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 20 | "strings" |
| 21 | "time" |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame^] | 22 | "log" |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 23 | ) |
| 24 | |
| 25 | type 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 | |
| 36 | var gatewayHost string |
| 37 | var gatewayPort string |
| 38 | var keycloakHost string |
| 39 | var keycloakPort string |
| 40 | var keycloakAlias string |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame^] | 41 | var elasticHost string |
| 42 | var elasticPort string |
| 43 | var elasticAlias string |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 44 | var securityEnabled string |
| 45 | var useGateway string |
| 46 | var role string |
| 47 | var rapp string |
| 48 | var methods string |
| 49 | var realmName string |
| 50 | var clientId string |
| 51 | var healthy bool = true |
| 52 | var ttime time.Time |
| 53 | var jwt Jwttoken |
| 54 | |
| 55 | const ( |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame^] | 56 | namespace = "istio-nonrtric" |
| 57 | scope = "email" |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 58 | client_assertion_type = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" |
| 59 | ) |
| 60 | |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame^] | 61 | var ( |
| 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 | |
| 73 | type 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 | |
| 83 | var client *elasticsearch.Client |
| 84 | |
| 85 | func 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 | |
| 133 | func 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 | |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 146 | func getToken() string { |
| 147 | if ttime.Before(time.Now()) { |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame^] | 148 | resp := &http.Response{} |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 149 | client_assertion := getClientAssertion() |
| 150 | keycloakUrl := "http://" + keycloakHost + ":" + keycloakPort + "/auth/realms/" + realmName + "/protocol/openid-connect/token" |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame^] | 151 | 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 | } |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 167 | if err != nil { |
| 168 | fmt.Println(err) |
| 169 | panic("Something wrong with the credentials or url ") |
| 170 | } |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame^] | 171 | |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 172 | defer resp.Body.Close() |
| 173 | body, err := ioutil.ReadAll(resp.Body) |
| 174 | json.Unmarshal([]byte(body), &jwt) |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame^] | 175 | |
| 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)) |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 182 | } |
| 183 | return jwt.Access_token |
| 184 | } |
| 185 | |
| 186 | func getClientAssertion() string { |
| 187 | realm := "http://" + keycloakHost + ":" + keycloakPort + "/auth/realms/" + realmName |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame^] | 188 | clientAssertion := generatejwt.CreateJWT("/certs/client.key", "/certs/client_pub.key", "", clientId, realm) |
| 189 | return clientAssertion |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 190 | } |
| 191 | |
| 192 | func 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 |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame^] | 211 | resp := &http.Response{} |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 212 | |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame^] | 213 | 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() |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 218 | 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 | |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame^] | 225 | resp, err = client.Do(req) |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 226 | if err != nil { |
| 227 | fmt.Printf("Got error %s", err.Error()) |
| 228 | } |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame^] | 229 | |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 230 | defer resp.Body.Close() |
| 231 | body, _ := ioutil.ReadAll(resp.Body) |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame^] | 232 | 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) |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 235 | |
| 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 | |
| 244 | func 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 | |
| 254 | func main() { |
| 255 | ttime = time.Now() |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame^] | 256 | time.Sleep(3 * time.Second) |
| 257 | prometheus.Register(reqDuration) |
| 258 | prometheus.Register(reqBytes) |
| 259 | |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 260 | 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") |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame^] | 264 | 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") |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 267 | 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) |
ktimoney | 90fcec9 | 2022-04-29 15:46:50 +0100 | [diff] [blame^] | 278 | http.Handle("/metrics", promhttp.Handler()) |
| 279 | client = connectToElasticsearch() |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 280 | 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 | } |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame] | 308 | } |