ktimoney | f27b513 | 2022-03-07 16:48:47 +0000 | [diff] [blame] | 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "flag" |
| 8 | "fmt" |
| 9 | "io/ioutil" |
| 10 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 11 | kubernetes "k8s.io/client-go/kubernetes" |
| 12 | "k8s.io/client-go/rest" |
| 13 | "net/http" |
| 14 | "net/url" |
| 15 | "strings" |
| 16 | "time" |
| 17 | ) |
| 18 | |
| 19 | type Jwttoken struct { |
| 20 | Access_token string |
| 21 | Expires_in int |
| 22 | Refresh_expires_in int |
| 23 | Refresh_token string |
| 24 | Token_type string |
| 25 | Not_before_policy int |
| 26 | Session_state string |
| 27 | Scope string |
| 28 | } |
| 29 | |
| 30 | var gatewayHost string |
| 31 | var gatewayPort string |
| 32 | var keycloakHost string |
| 33 | var keycloakPort string |
| 34 | var securityEnabled string |
| 35 | var useGateway string |
| 36 | var role string |
| 37 | var rapp string |
| 38 | var methods string |
| 39 | var healthy bool = true |
| 40 | var ttime time.Time |
| 41 | var jwt Jwttoken |
| 42 | |
| 43 | const ( |
| 44 | namespace = "istio-nonrtric" |
| 45 | ) |
| 46 | |
| 47 | func getToken(secretName string) string { |
| 48 | if ttime.Before(time.Now()) { |
| 49 | clientSecret, clientId, realmName := getSecret(secretName) |
| 50 | keycloakUrl := "http://" + keycloakHost + ":" + keycloakPort + "/auth/realms/" + realmName + "/protocol/openid-connect/token" |
| 51 | resp, err := http.PostForm(keycloakUrl, |
| 52 | url.Values{"client_secret": {clientSecret}, "grant_type": {"client_credentials"}, "client_id": {clientId}}) |
| 53 | if err != nil { |
| 54 | fmt.Println(err) |
| 55 | panic("Something wrong with the credentials or url ") |
| 56 | } |
| 57 | defer resp.Body.Close() |
| 58 | body, err := ioutil.ReadAll(resp.Body) |
| 59 | json.Unmarshal([]byte(body), &jwt) |
| 60 | ttime = time.Now() |
| 61 | ttime = ttime.Add(time.Second * time.Duration(jwt.Expires_in)) |
| 62 | } |
| 63 | return jwt.Access_token |
| 64 | } |
| 65 | |
| 66 | func getSecret(secretName string) (string, string, string) { |
| 67 | clientset := connectToK8s() |
| 68 | res, err := clientset.CoreV1().Secrets(namespace).Get(context.TODO(), secretName, metav1.GetOptions{}) |
| 69 | if err != nil { |
| 70 | fmt.Println(err.Error()) |
| 71 | } |
| 72 | return string(res.Data["client_secret"]), string(res.Data["client_id"]), string(res.Data["realm"]) |
| 73 | } |
| 74 | |
| 75 | func MakeRequest(client *http.Client, prefix string, method string, ch chan string) { |
| 76 | var service = strings.Split(prefix, "/")[1] |
| 77 | var gatewayUrl = "http://" + gatewayHost + ":" + gatewayPort |
| 78 | var token = "" |
| 79 | var jsonValue []byte = []byte{} |
| 80 | var restUrl string = "" |
| 81 | |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame^] | 82 | if securityEnabled == "true" { |
ktimoney | f27b513 | 2022-03-07 16:48:47 +0000 | [diff] [blame] | 83 | secretName := role + "-secret" |
| 84 | token = getToken(secretName) |
| 85 | } else { |
| 86 | useGateway = "N" |
| 87 | } |
| 88 | |
| 89 | if strings.ToUpper(useGateway) != "Y" { |
| 90 | gatewayUrl = "http://" + service + "."+namespace+":80" |
| 91 | prefix = "" |
| 92 | } |
| 93 | |
| 94 | restUrl = gatewayUrl + prefix |
| 95 | |
| 96 | req, err := http.NewRequest(method, restUrl, bytes.NewBuffer(jsonValue)) |
| 97 | if err != nil { |
| 98 | fmt.Printf("Got error %s", err.Error()) |
| 99 | } |
| 100 | req.Header.Set("Content-type", "application/json") |
| 101 | req.Header.Set("Authorization", "Bearer "+token) |
| 102 | |
| 103 | resp, err := client.Do(req) |
| 104 | if err != nil { |
| 105 | fmt.Printf("Got error %s", err.Error()) |
| 106 | } |
| 107 | defer resp.Body.Close() |
| 108 | body, _ := ioutil.ReadAll(resp.Body) |
| 109 | respString := string(body[:]) |
| 110 | if respString == "RBAC: access denied" { |
| 111 | respString += " for " + service + " " + strings.ToLower(method) + " request" |
| 112 | } |
| 113 | fmt.Printf("Received response for %s %s request - %s\n", service, strings.ToLower(method), respString) |
| 114 | ch <- prefix + "," + method |
| 115 | } |
| 116 | |
| 117 | func connectToK8s() *kubernetes.Clientset { |
| 118 | config, err := rest.InClusterConfig() |
| 119 | if err != nil { |
| 120 | fmt.Println("failed to create K8s config") |
| 121 | } |
| 122 | |
| 123 | clientset, err := kubernetes.NewForConfig(config) |
| 124 | if err != nil { |
| 125 | fmt.Println("Failed to create K8s clientset") |
| 126 | } |
| 127 | |
| 128 | return clientset |
| 129 | } |
| 130 | |
| 131 | func health(res http.ResponseWriter, req *http.Request) { |
| 132 | if healthy { |
| 133 | res.WriteHeader(http.StatusOK) |
| 134 | res.Write([]byte("healthy")) |
| 135 | } else { |
| 136 | res.WriteHeader(http.StatusInternalServerError) |
| 137 | res.Write([]byte("unhealthy")) |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | func main() { |
| 142 | ttime = time.Now() |
| 143 | time.Sleep(1 * time.Second) |
| 144 | flag.StringVar(&gatewayHost, "gatewayHost", "istio-ingressgateway.istio-system", "Gateway Host") |
| 145 | flag.StringVar(&gatewayPort, "gatewayPort", "80", "Gateway Port") |
ktimoney | 8ead72a | 2022-04-12 15:10:10 +0100 | [diff] [blame^] | 146 | flag.StringVar(&keycloakHost, "keycloakHost", "istio-ingressgateway.istio-system", "Keycloak Host") |
| 147 | flag.StringVar(&keycloakPort, "keycloakPort", "80", "Keycloak Port") |
ktimoney | f27b513 | 2022-03-07 16:48:47 +0000 | [diff] [blame] | 148 | flag.StringVar(&useGateway, "useGateway", "Y", "Connect to services through API gateway") |
| 149 | flag.StringVar(&securityEnabled, "securityEnabled", "true", "Security is required to use this application") |
| 150 | flag.StringVar(&role, "role", "provider-viewer", "Role granted to application") |
| 151 | flag.StringVar(&rapp, "rapp", "rapp-provider", "Name of rapp to invoke") |
| 152 | flag.StringVar(&methods, "methods", "GET", "Methods to access application") |
| 153 | flag.Parse() |
| 154 | |
| 155 | healthHandler := http.HandlerFunc(health) |
| 156 | http.Handle("/health", healthHandler) |
| 157 | go func() { |
| 158 | http.ListenAndServe(":9000", nil) |
| 159 | }() |
| 160 | |
| 161 | client := &http.Client{ |
| 162 | Timeout: time.Second * 10, |
| 163 | } |
| 164 | |
| 165 | ch := make(chan string) |
| 166 | var prefixArray []string = []string{"/" + rapp} |
| 167 | var methodArray []string = []string{methods} |
| 168 | for _, prefix := range prefixArray { |
| 169 | for _, method := range methodArray { |
| 170 | go MakeRequest(client, prefix, method, ch) |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | ioutil.WriteFile("init.txt", []byte("Initialization done."), 0644) |
| 175 | |
| 176 | for r := range ch { |
| 177 | go func(resp string) { |
| 178 | time.Sleep(10 * time.Second) |
| 179 | elements := strings.Split(resp, ",") |
| 180 | prefix := elements[0] |
| 181 | method := elements[1] |
| 182 | MakeRequest(client, prefix, method, ch) |
| 183 | }(r) |
| 184 | } |
| 185 | |
| 186 | } |