This commit is contained in:
mr
2024-10-30 12:38:25 +01:00
parent 7198c40d30
commit d87883b57f
27 changed files with 536 additions and 755 deletions

View File

@@ -12,15 +12,17 @@ type AuthConnector interface {
Logout(token string, cookies ...*http.Cookie) (*Token, error)
Introspect(token string, cookie ...*http.Cookie) (bool, error)
Refresh(token *Token) (*Token, error)
CheckAuthForward(reqToken string, publicKey string, host string, method string, forward string) bool
}
type Token struct {
Active bool `json:"active"`
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
Challenge string `json:"challenge"`
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
TokenType string `json:"token_type"`
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
}
type Redirect struct {

View File

@@ -1,6 +1,7 @@
package auth_connectors
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
@@ -8,10 +9,12 @@ import (
"net/http"
"net/url"
"oc-auth/conf"
"oc-auth/infrastructure/claims"
"regexp"
"strconv"
"strings"
oclib "cloud.o-forge.io/core/oc-lib"
"cloud.o-forge.io/core/oc-lib/models/peer"
"cloud.o-forge.io/core/oc-lib/tools"
)
@@ -81,10 +84,18 @@ func (a HydraConnector) challenge(username string, url string, challenge string,
}
func (a HydraConnector) Refresh(token *Token) (*Token, error) {
access := strings.Split(token.AccessToken, ".")
if len(access) > 2 {
token.AccessToken = strings.Join(access[0:2], ".")
}
isValid, err := a.Introspect(token.AccessToken)
if err != nil || !isValid {
return nil, err
}
_, err = a.Logout(token.AccessToken)
if err != nil {
return nil, err
}
return a.Login(token.Username)
}
@@ -107,32 +118,6 @@ func (a HydraConnector) tryLog(username string, url string, subpath string, chal
return a.challenge(username, resp.Request.URL.String(), challenge, cookies...)
}
func (a HydraConnector) extractTokenFromFragment(fragment string) *Token {
splittedFragment := strings.Split(fragment, "#")
f := splittedFragment[0]
if len(splittedFragment) > 1 {
f = splittedFragment[1]
}
token := &Token{}
frags := strings.Split(f, "&")
for _, f := range frags {
splittedFrag := strings.Split(f, "=")
if len(splittedFrag) > 1 {
if splittedFrag[0] == "access_token" {
token.AccessToken = strings.ReplaceAll(splittedFrag[1], "ory_at_", "")
}
if splittedFrag[0] == "expires_in" {
i, err := strconv.Atoi(splittedFrag[1])
if err != nil {
return nil
}
token.ExpiresIn = i
}
}
}
return token
}
func (a HydraConnector) getClient() string {
resp, err := a.Caller.CallGet(a.getPath(true, false), "/clients")
if err != nil {
@@ -148,44 +133,63 @@ func (a HydraConnector) getClient() string {
func (a HydraConnector) Login(username string, cookies ...*http.Cookie) (t *Token, err error) {
clientID := a.getClient()
redirect, challenge, cookies, err := a.tryLog(username, a.getPath(false, true),
redirect, _, cookies, err := a.tryLog(username, a.getPath(false, true),
"/auth?client_id="+clientID+"&response_type="+strings.ReplaceAll(a.ResponseType, " ", "%20")+"&scope="+strings.ReplaceAll(a.Scopes, " ", "%20")+"&state="+a.State,
"login", cookies...)
if err != nil || redirect == nil {
return nil, err
}
redirect, challenge, cookies, err = a.tryLog(username, a.urlFormat(redirect.RedirectTo, a.getPath(false, true)), "", "consent", cookies...)
redirect, _, cookies, err = a.tryLog(username, a.urlFormat(redirect.RedirectTo, a.getPath(false, true)), "", "consent", cookies...)
if err != nil || redirect == nil {
return nil, err
}
// problem with consent THERE we need to accept the consent challenge && get the token
url := ""
resp, err := a.Caller.CallRaw(http.MethodGet, a.urlFormat(redirect.RedirectTo, a.getPath(false, true)), "", map[string]interface{}{},
_, err = a.Caller.CallRaw(http.MethodGet, a.urlFormat(redirect.RedirectTo, a.getPath(false, true)), "", map[string]interface{}{},
"application/json", true, cookies...)
fmt.Println(err)
if err != nil {
s := strings.Split(err.Error(), "\"")
if len(s) > 1 && strings.Contains(s[1], "access_token") {
url = s[1]
err = nil
} else {
return nil, err
}
} else {
url = resp.Request.Response.Request.URL.Fragment
}
token := a.extractTokenFromFragment(url)
fmt.Println(url, token)
if token == nil || token.AccessToken == "" {
return nil, errors.New("no token found")
token := &Token{
Username: username,
}
token.Challenge = challenge
token.Active = true
token.Username = username
fmt.Println(token)
urls := url.Values{}
urls.Add("client_id", clientID)
urls.Add("client_secret", conf.GetConfig().ClientSecret)
urls.Add("grant_type", "client_credentials")
resp, err := a.Caller.CallForm(http.MethodPost, a.getPath(false, true), "/token", urls,
"application/x-www-form-urlencoded", true, cookies...)
var m map[string]interface{}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
err = json.Unmarshal(b, &token)
if err != nil {
return nil, err
}
json.Unmarshal(b, &m)
pp := oclib.Search(nil, string(peer.SELF.EnumIndex()), oclib.LibDataEnum(oclib.PEER))
if len(pp.Data) == 0 || pp.Code >= 300 || pp.Err != "" {
return nil, errors.New("peer not found")
}
c := claims.GetClaims().AddClaimsToToken(username, pp.Data[0].(*peer.Peer).Url)
b, _ = json.Marshal(c)
token.AccessToken = strings.ReplaceAll(token.AccessToken, "ory_at_", "") + "." + base64.StdEncoding.EncodeToString(b)
return token, nil
}
func (a HydraConnector) Logout(token string, cookies ...*http.Cookie) (*Token, error) {
access := strings.Split(token, ".")
if len(access) > 2 {
token = strings.Join(access[0:2], ".")
}
p := a.getPath(false, true) + "/revoke"
urls := url.Values{}
urls.Add("token", token)
@@ -203,6 +207,10 @@ func (a HydraConnector) Logout(token string, cookies ...*http.Cookie) (*Token, e
func (a HydraConnector) Introspect(token string, cookie ...*http.Cookie) (bool, error) {
// check validity of the token by calling introspect endpoint
// if token is not active, we need to re-authenticate by sending the user to the login page
access := strings.Split(token, ".")
if len(access) > 2 {
token = strings.Join(access[0:2], ".")
}
urls := url.Values{}
urls.Add("token", token)
resp, err := a.Caller.CallForm(http.MethodPost, a.getPath(true, true), "/introspect", urls,
@@ -238,3 +246,29 @@ func (a HydraConnector) getPath(isAdmin bool, isOauth bool) string {
return "http://" + host + ":" + port + oauth
}
func (a HydraConnector) CheckAuthForward(reqToken string, publicKey string, host string, method string, forward string) bool {
fmt.Println("CheckAuthForward", reqToken, publicKey, host, method, forward)
if forward == "" || method == "" {
fmt.Println("Forwarded headers are missing")
return false
}
var c claims.Claims
token := strings.Split(reqToken, ".")
if len(token) > 2 {
bytes, err := base64.StdEncoding.DecodeString(token[2])
if err != nil {
return false
}
err = json.Unmarshal(bytes, &c)
if err != nil {
return false
}
}
// ask keto for permission is in claims
ok, err := claims.GetClaims().DecodeClaimsInToken(host, method, forward, c, publicKey)
if err != nil {
fmt.Println("Failed to decode claims", err)
}
return ok
}