Skip to content

Commit

Permalink
Updated proxy for tests
Browse files Browse the repository at this point in the history
Issue: AAH-2575
  • Loading branch information
bmclaughlin committed Sep 7, 2023
1 parent 275325b commit 84cb2b1
Showing 1 changed file with 62 additions and 42 deletions.
104 changes: 62 additions & 42 deletions dev/insights/proxy/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,6 @@ var refreshTokens = map[string]string{
"abcdefghijklmnopqrstuvwxyz1234567894": "notifications_admin",
}

var passwordMap = map[string]string{
"jdoe": "redhat",
"iqe_normal_user": "redhat",
"org-admin": "redhat",
"notifications_admin": "redhat",
}

// Access tokens will be stored here, and they can be generated using the refresh
// tokens listed above using the:
// curl -X POST localhost:8080/auth/realms/redhat-external/protocol/openid-connect/token -d refresh_token=1234567890
Expand Down Expand Up @@ -116,13 +109,10 @@ func randomString(length int) string {

func getAccessToken(rw http.ResponseWriter, req *http.Request) {
req.ParseForm()
grant_type := req.FormValue("grant_type")
refresh_token := req.FormValue("refresh_token")
username := req.FormValue("username")
password := req.FormValue("password")

if accountID, ok := refreshTokens[refresh_token]; ok {
fmt.Printf("Creating refresh token for: %s", accountID)
fmt.Printf("xxx Creating refresh token for: %s", accountID)

acces_token := randomString(32)
accessTokens[acces_token] = accountID
Expand All @@ -134,33 +124,12 @@ func getAccessToken(rw http.ResponseWriter, req *http.Request) {

rw.WriteHeader(http.StatusAccepted)
json.NewEncoder(rw).Encode(resp)

} else if _, found := passwordMap[username]; found{

if grant_type == "password" && passwordMap[username] == password {
fmt.Printf("Creating refresh token for: %s", accountID)

acces_token := randomString(32)
accessTokens[acces_token] = accountID

rw.Header().Set("Content-Type", "application/json")
resp := map[string]string{
"access_token": acces_token,
}

rw.WriteHeader(http.StatusAccepted)
json.NewEncoder(rw).Encode(resp)

} else {
rw.WriteHeader(http.StatusUnauthorized)
}

} else {
rw.WriteHeader(http.StatusUnauthorized)
}
}

func userToIdentityHeader(account Account) string {
func userToIentityHeader(account Account) string {

data, _ := json.Marshal(XRHItentity{
Entitlements: Entitlement{
Expand All @@ -187,21 +156,20 @@ func setRHIdentityHeader(req *http.Request) {
fmt.Printf("Authenticating with basic auth: %s:%s\n", user, pass)

if account, ok := accounts[user]; ok {
req.Header.Set("X-RH-IDENTITY", userToIdentityHeader(account))
req.Header.Set("X-RH-IDENTITY", userToIentityHeader(account))
} else {
fmt.Printf("User not found: %s", user)
}

} else if strings.Contains(auth_header, "Bearer") {

reqToken := req.Header.Get("Authorization")
splitToken := strings.Split(reqToken, "Bearer ")
reqToken = splitToken[1]

fmt.Printf("Authenticating with refresh token: %s\n", reqToken)

if userID, ok := accessTokens[reqToken]; ok {
req.Header.Set("X-RH-IDENTITY", userToIdentityHeader(accounts[userID]))
req.Header.Set("X-RH-IDENTITY", userToIentityHeader(accounts[userID]))
} else {
fmt.Printf("Token not found: %s", reqToken)
}
Expand All @@ -218,6 +186,22 @@ func getEnv(key string, fallback string) string {
return fallback
}

func createHTTPClient(url string) *http.Client {

if strings.Contains(url, ".tar.gz") {
return &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}

}

//return &http.Client{}
//return &http.DefaultClient
return &http.Client{}
}

func main() {
fmt.Println("Staring insights proxy.")

Expand All @@ -241,34 +225,69 @@ func main() {

// Handle the keycloak auth url
if req.URL.Path == "/auth/realms/redhat-external/protocol/openid-connect/token" {
fmt.Println(req.URL.Path)
getAccessToken(rw, req)

fmt.Println("")
return
}

// Set X-RH-IDENTITY header
setRHIdentityHeader(req)

fmt.Printf("req.Host: %s\n", req.Host)
fmt.Printf("req.URL.Host: %s\n", req.URL.Host)
fmt.Printf("req.URL.Scheme: %s\n", req.URL.Scheme)
fmt.Printf("req.URL.Path: %s\n", req.URL.Path)
fmt.Printf("urlToProxyTo.Host: %s\n", urlToProxyTo.Host)
fmt.Printf("urlToProxyTo.Scheme: %s\n", urlToProxyTo.Scheme)

// Rewrite the url on the incoming request and resend it
req.Host = urlToProxyTo.Host
req.URL.Host = urlToProxyTo.Host
req.URL.Scheme = urlToProxyTo.Scheme
req.RequestURI = ""
req.URL.Path = strings.ReplaceAll(req.URL.Path, "//", "/")

fmt.Printf("Proxying request to: %s\n", req.URL.RequestURI())
// fixme ...
// change http://localhost:11651 to http://pminio:8000

fmt.Printf("Proxying request to: %s\n", req.URL.RequestURI())

/*
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
*/

client := createHTTPClient(req.URL.Path)

//upstreamServerResponse, err := http.DefaultClient.Do(req)
upstreamServerResponse, err := client.Do(req)

// save the response from the origin server
upstreamServerResponse, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Println("error ...")
fmt.Println(err)
rw.WriteHeader(http.StatusInternalServerError)
_, _ = fmt.Fprint(rw, err)
fmt.Println("")

return
}

// if it's a 302 redirect, write the new url into the response headers ...
headers := upstreamServerResponse.Header
for key, values := range headers {
for _, value := range values {
fmt.Printf("HEADER %s: %s\n", key, value)
}
}

location := upstreamServerResponse.Header.Get("Location")
if location != "" {
rw.Header().Set("Location", location)
}

// replace any download urls that are found on the response so that they
// get redirected through the proxy
data, _ := ioutil.ReadAll(upstreamServerResponse.Body)
Expand All @@ -278,8 +297,9 @@ func main() {
rw.WriteHeader(upstreamServerResponse.StatusCode)
rw.Write(modified)

fmt.Println("request complete")
fmt.Println()
})

log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", proxyPort), reverseProxy))
}
}

0 comments on commit 84cb2b1

Please sign in to comment.