Correction

This commit is contained in:
mr 2025-02-18 09:20:13 +01:00
parent 37a0ceddf4
commit b684ba841f

View File

@ -1,8 +1,6 @@
package auth_connectors package auth_connectors
import ( import (
"bytes"
"context"
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"errors" "errors"
@ -12,7 +10,6 @@ import (
"net/url" "net/url"
"oc-auth/conf" "oc-auth/conf"
"oc-auth/infrastructure/claims" "oc-auth/infrastructure/claims"
"os"
"regexp" "regexp"
"strconv" "strconv"
"strings" "strings"
@ -21,10 +18,6 @@ import (
oclib "cloud.o-forge.io/core/oc-lib" oclib "cloud.o-forge.io/core/oc-lib"
"cloud.o-forge.io/core/oc-lib/models/peer" "cloud.o-forge.io/core/oc-lib/models/peer"
"cloud.o-forge.io/core/oc-lib/tools" "cloud.o-forge.io/core/oc-lib/tools"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
) )
type HydraConnector struct { type HydraConnector struct {
@ -108,26 +101,12 @@ func (a HydraConnector) Refresh(client_id string, token *Token) (*Token, error)
} }
func (a HydraConnector) tryLog(username string, url string, subpath string, challenge string, cookies ...*http.Cookie) (*Redirect, string, []*http.Cookie, error) { func (a HydraConnector) tryLog(username string, url string, subpath string, challenge string, cookies ...*http.Cookie) (*Redirect, string, []*http.Cookie, error) {
resp, err := a.Caller.CallRaw(http.MethodGet, url, subpath,
postBody, _ := json.Marshal(map[string]interface{}{}) map[string]interface{}{}, "application/json", true, cookies...)
responseBody := bytes.NewBuffer(postBody) if err != nil || resp.Request.Response == nil || resp.Request.Response.Header["Set-Cookie"] == nil {
req, _ := http.NewRequest(http.MethodGet, url+subpath, responseBody)
req.Header.Set("Content-Type", "application/json")
req.Header.Add("X-Forwarded-Proto", "https")
for _, c := range cookies {
req.AddCookie(c)
}
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse // No redirect, doesn't make sense; hydra redirect user to login page, we are not the user here due to wrong oauth flow implementation
},
}
resp, err := client.Do(req)
if err != nil || resp == nil || resp.Header["Set-Cookie"] == nil {
return nil, "", cookies, err return nil, "", cookies, err
} }
cc := resp.Header["Set-Cookie"] // retrieve oauth2 csrf token cookie cc := resp.Request.Response.Header["Set-Cookie"] // retrieve oauth2 csrf token cookie
if len(cc) > 0 { if len(cc) > 0 {
for _, c := range cc { for _, c := range cc {
first := strings.Split(c, ";") first := strings.Split(c, ";")
@ -137,7 +116,7 @@ func (a HydraConnector) tryLog(username string, url string, subpath string, chal
}) })
} }
} }
return a.challenge(username, resp.Header.Get("Location"), challenge, cookies...) return a.challenge(username, resp.Request.URL.String(), challenge, cookies...)
} }
func (a HydraConnector) getClient(clientID string) string { func (a HydraConnector) getClient(clientID string) string {
@ -172,22 +151,8 @@ func (a HydraConnector) Login(clientID string, username string, cookies ...*http
return nil, err return nil, err
} }
// problem with consent THERE we need to accept the consent challenge && get the token // problem with consent THERE we need to accept the consent challenge && get the token
_, err = a.Caller.CallRaw(http.MethodGet, a.urlFormat(redirect.RedirectTo, a.getPath(false, true)), "", map[string]interface{}{},
postBody, _ := json.Marshal(map[string]interface{}{}) "application/json", true, cookies...)
responseBody := bytes.NewBuffer(postBody)
req, _ := http.NewRequest(http.MethodGet, a.urlFormat(redirect.RedirectTo, a.getPath(false, true)), responseBody)
req.Header.Set("Content-Type", "application/json")
req.Header.Add("X-Forwarded-Proto", "https")
for _, c := range cookies {
req.AddCookie(c)
}
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse // No redirect, doesn't make sense; hydra redirect user to login page, we are not the user here due to wrong oauth flow implementation
},
}
_, err = client.Do(req)
if err != nil { if err != nil {
s := strings.Split(err.Error(), "\"") s := strings.Split(err.Error(), "\"")
if len(s) > 1 && strings.Contains(s[1], "access_token") { if len(s) > 1 && strings.Contains(s[1], "access_token") {
@ -200,15 +165,6 @@ func (a HydraConnector) Login(clientID string, username string, cookies ...*http
Username: username, Username: username,
} }
urls := url.Values{} urls := url.Values{}
// Using k8s secrets gen by hydra, eventually
clientID, clientSecret, err := a.getOAuth2Conf(conf.GetConfig().OAuth2ClientSecretNamespace, conf.GetConfig().OAuth2ClientSecretName)
if err == nil {
urls.Add("client_id", clientID)
urls.Add("client_secret", clientSecret)
}
// Fallback on manually set client secret
urls.Add("client_id", clientID) urls.Add("client_id", clientID)
urls.Add("client_secret", conf.GetConfig().ClientSecret) urls.Add("client_secret", conf.GetConfig().ClientSecret)
urls.Add("grant_type", "client_credentials") urls.Add("grant_type", "client_credentials")
@ -244,54 +200,6 @@ func (a HydraConnector) Login(clientID string, username string, cookies ...*http
return token, nil return token, nil
} }
func (a HydraConnector) getOAuth2Conf(namespace string, secretName string) (string, string, error) {
clientset, err := a.getClientset()
if err != nil {
return "", "", fmt.Errorf("error creating Kubernetes client: %v", err)
}
secret, err := clientset.CoreV1().Secrets(namespace).Get(context.TODO(), secretName, metav1.GetOptions{})
if err != nil {
return "", "", fmt.Errorf("error retrieving secret %s/%s: %v", namespace, secretName, err)
}
clientIDEncoded, found := secret.Data["CLIENT_ID"]
if !found {
return "", "", fmt.Errorf("CLIENT_ID key not found in secret")
}
clientSecretEncoded, found := secret.Data["CLIENT_SECRET"]
if !found {
return "", "", fmt.Errorf("CLIENT_SECRET key not found in secret")
}
clientID := string(clientIDEncoded)
clientSecret := string(clientSecretEncoded)
return clientID, clientSecret, nil
}
func (a HydraConnector) getClientset() (*kubernetes.Clientset, error) {
var config *rest.Config
var err error
// Check if running inside cluster
if _, inCluster := os.LookupEnv("KUBERNETES_SERVICE_HOST"); inCluster {
config, err = rest.InClusterConfig() // Use in-cluster config
} else {
kubeconfig := os.Getenv("KUBECONFIG") // Use local kubeconfig file
if kubeconfig == "" {
kubeconfig = clientcmd.RecommendedHomeFile
}
config, err = clientcmd.BuildConfigFromFlags("", kubeconfig)
}
if err != nil {
return nil, err
}
return kubernetes.NewForConfig(config)
}
func (a HydraConnector) Logout(clientID string, token string, cookies ...*http.Cookie) (*Token, error) { func (a HydraConnector) Logout(clientID string, token string, cookies ...*http.Cookie) (*Token, error) {
clientID = a.getClient(clientID) clientID = a.getClient(clientID)
access := strings.Split(token, ".") access := strings.Split(token, ".")
@ -341,10 +249,9 @@ func (a HydraConnector) Introspect(token string, cookie ...*http.Cookie) (bool,
} }
func (a HydraConnector) getPath(isAdmin bool, isOauth bool) string { func (a HydraConnector) getPath(isAdmin bool, isOauth bool) string {
host := conf.GetConfig().AuthConnectPublicHost host := conf.GetConfig().AuthConnectorHost
port := fmt.Sprintf("%v", conf.GetConfig().AuthConnectorPort) port := fmt.Sprintf("%v", conf.GetConfig().AuthConnectorPort)
if isAdmin { if isAdmin {
host = conf.GetConfig().AuthConnectorHost
port = fmt.Sprintf("%v", conf.GetConfig().AuthConnectorAdminPort) + "/admin" port = fmt.Sprintf("%v", conf.GetConfig().AuthConnectorAdminPort) + "/admin"
} }
oauth := "" oauth := ""