BAHAMAS
This commit is contained in:
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
package claims
|
||||
|
||||
import "oc-auth/conf"
|
||||
|
||||
// Tokenizer interface
|
||||
type ClaimService interface {
|
||||
AddClaimsToToken(userId string, host string) Claims
|
||||
DecodeClaimsInToken(host string, method string, forward string, sessionClaims map[string]interface{}, publicKey string) (bool, error)
|
||||
DecodeClaimsInToken(host string, method string, forward string, sessionClaims Claims, publicKey string) (bool, error)
|
||||
}
|
||||
|
||||
// SessionClaims struct
|
||||
@@ -16,3 +18,11 @@ type SessionClaims struct {
|
||||
type Claims struct {
|
||||
Session SessionClaims `json:"session"`
|
||||
}
|
||||
|
||||
var t = map[string]ClaimService{
|
||||
"hydra": HydraClaims{},
|
||||
}
|
||||
|
||||
func GetClaims() ClaimService {
|
||||
return t[conf.GetConfig().Auth]
|
||||
}
|
||||
|
||||
129
infrastructure/claims/crypto.go
Normal file
129
infrastructure/claims/crypto.go
Normal file
@@ -0,0 +1,129 @@
|
||||
package claims
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"log"
|
||||
)
|
||||
|
||||
func SignDefault(plaintext, privateKey []byte) (signature string, err error) {
|
||||
client, err := New(privateKey, nil)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
return
|
||||
}
|
||||
signatureByte, err := client.Sign(plaintext)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
return
|
||||
}
|
||||
signature = base64.StdEncoding.EncodeToString(signatureByte)
|
||||
return
|
||||
}
|
||||
|
||||
func VerifyDefault(plaintext, publicKey []byte, signature string) (err error) {
|
||||
publicKeys := make(map[string][]byte)
|
||||
publicKeys["default"] = publicKey
|
||||
client, err := New(nil, publicKeys)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
return
|
||||
}
|
||||
|
||||
signatureByte, err := base64.StdEncoding.DecodeString(signature)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
return
|
||||
}
|
||||
|
||||
err = client.Verify(plaintext, signatureByte, "default")
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (c *Client) Sign(plaintext []byte) (signature []byte, err error) {
|
||||
var opts rsa.PSSOptions
|
||||
opts.SaltLength = rsa.PSSSaltLengthAuto
|
||||
|
||||
newhash := crypto.SHA256
|
||||
pssh := newhash.New()
|
||||
pssh.Write(plaintext)
|
||||
hashed := pssh.Sum(nil)
|
||||
signature, err = rsa.SignPSS(
|
||||
rand.Reader,
|
||||
c.PrivateKey,
|
||||
newhash,
|
||||
hashed,
|
||||
&opts,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
func (c *Client) Verify(plaintext, signature []byte, target string) (err error) {
|
||||
var opts rsa.PSSOptions
|
||||
opts.SaltLength = rsa.PSSSaltLengthAuto
|
||||
|
||||
newhash := crypto.SHA256
|
||||
pssh := newhash.New()
|
||||
pssh.Write(plaintext)
|
||||
hashed := pssh.Sum(nil)
|
||||
err = rsa.VerifyPSS(
|
||||
c.PublicKeys[target],
|
||||
newhash,
|
||||
hashed,
|
||||
signature,
|
||||
&opts,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
func init() {
|
||||
log.SetFlags(log.LstdFlags | log.Lshortfile)
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
PrivateKey *rsa.PrivateKey
|
||||
PublicKeys map[string]*rsa.PublicKey
|
||||
}
|
||||
|
||||
func New(privateKey []byte, publicKeys map[string][]byte) (client *Client, err error) {
|
||||
client = &Client{}
|
||||
|
||||
if privateKey != nil {
|
||||
validPrivateKey, errPrivate := x509.ParsePKCS1PrivateKey(privateKey)
|
||||
if errPrivate != nil {
|
||||
err = errPrivate
|
||||
log.Println(err)
|
||||
return
|
||||
}
|
||||
client.PrivateKey = validPrivateKey
|
||||
}
|
||||
|
||||
if publicKeys != nil {
|
||||
validPublicKeysMap := make(map[string]*rsa.PublicKey)
|
||||
for k, v := range publicKeys {
|
||||
validPublicKey, errPublic := x509.ParsePKCS1PublicKey(v)
|
||||
if errPublic != nil {
|
||||
err = errPublic
|
||||
log.Println(err)
|
||||
return
|
||||
}
|
||||
if validPublicKey == nil {
|
||||
err = errors.New("Invalid Public Key Type")
|
||||
log.Println(err)
|
||||
return
|
||||
}
|
||||
validPublicKeysMap[k] = validPublicKey
|
||||
}
|
||||
client.PublicKeys = validPublicKeysMap
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
@@ -1,13 +1,10 @@
|
||||
package claims
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"oc-auth/conf"
|
||||
"oc-auth/infrastructure/perms_connectors"
|
||||
"oc-auth/infrastructure/utils"
|
||||
@@ -43,11 +40,10 @@ func (h HydraClaims) decodeKey(key string) (tools.METHOD, string, error) {
|
||||
}
|
||||
|
||||
func (h HydraClaims) DecodeSignature(host string, signature string, publicKey string) (bool, error) {
|
||||
fmt.Println("DecodeSignature", host)
|
||||
hashed := sha256.Sum256([]byte(host))
|
||||
// get public key into a variable
|
||||
spkiBlock, _ := pem.Decode([]byte(publicKey))
|
||||
key, _ := x509.ParsePKCS1PublicKey(spkiBlock.Bytes)
|
||||
err := rsa.VerifyPKCS1v15(key, crypto.SHA256, hashed[:], []byte(signature))
|
||||
spkiBlock, _ := pem.Decode([]byte(publicKey)) // get public key into a variable
|
||||
err := VerifyDefault(hashed[:], spkiBlock.Bytes, signature)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
@@ -55,32 +51,28 @@ func (h HydraClaims) DecodeSignature(host string, signature string, publicKey st
|
||||
}
|
||||
|
||||
func (h HydraClaims) encodeSignature(host string) (string, error) {
|
||||
fmt.Println("encodeSignature", host)
|
||||
hashed := sha256.Sum256([]byte(host))
|
||||
// READ FILE TO GET PRIVATE KEY FROM PVK PEM PATH
|
||||
content, err := os.ReadFile(conf.GetConfig().PVKPath)
|
||||
content, err := os.ReadFile(conf.GetConfig().PrivateKeyPath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
privateKey := string(content)
|
||||
spkiBlock, _ := pem.Decode([]byte(privateKey))
|
||||
key, _ := x509.ParsePKCS1PrivateKey(spkiBlock.Bytes)
|
||||
signature, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, hashed[:])
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(signature), nil
|
||||
return SignDefault(hashed[:], spkiBlock.Bytes)
|
||||
}
|
||||
|
||||
func (h HydraClaims) DecodeClaimsInToken(host string, method string, forward string, sessionClaims map[string]interface{}, publicKey string) (bool, error) {
|
||||
if sessionClaims["id_token"] == nil || sessionClaims["access_token"] == nil {
|
||||
return false, errors.New("invalid session claims")
|
||||
func (h HydraClaims) DecodeClaimsInToken(host string, method string, forward string, sessionClaims Claims, publicKey string) (bool, error) {
|
||||
idTokenClaims := sessionClaims.Session.IDToken
|
||||
if idTokenClaims["signature"] == nil {
|
||||
return false, errors.New("no signature found")
|
||||
}
|
||||
idTokenClaims := sessionClaims["id_token"].(map[string]interface{})
|
||||
signature := idTokenClaims["signature"].(string)
|
||||
if ok, err := h.DecodeSignature(host, signature, publicKey); !ok {
|
||||
return false, err
|
||||
}
|
||||
claims := sessionClaims["access_token"].(map[string]interface{})
|
||||
claims := sessionClaims.Session.AccessToken
|
||||
path := strings.ReplaceAll(forward, "http://"+host, "")
|
||||
splittedPath := strings.Split(path, "/")
|
||||
for m, p := range claims {
|
||||
@@ -114,6 +106,8 @@ func (h HydraClaims) AddClaimsToToken(userId string, host string) Claims {
|
||||
if err != nil {
|
||||
return claims
|
||||
}
|
||||
claims.Session.AccessToken = make(map[string]interface{})
|
||||
claims.Session.IDToken = make(map[string]interface{})
|
||||
for _, perm := range perms {
|
||||
key, err := h.generateKey(perm.Relation, perm.Object)
|
||||
if err != nil {
|
||||
@@ -127,7 +121,6 @@ func (h HydraClaims) AddClaimsToToken(userId string, host string) Claims {
|
||||
}
|
||||
claims.Session.IDToken["signature"] = sign
|
||||
return claims
|
||||
|
||||
}
|
||||
|
||||
// add signature in the token MISSING
|
||||
|
||||
@@ -9,10 +9,6 @@ import (
|
||||
"cloud.o-forge.io/core/oc-lib/tools"
|
||||
)
|
||||
|
||||
var t = map[string]claims.ClaimService{
|
||||
"hydra": claims.HydraClaims{},
|
||||
}
|
||||
|
||||
var a = map[string]auth_connectors.AuthConnector{
|
||||
"hydra": auth_connectors.HydraConnector{
|
||||
Caller: tools.NewHTTPCaller(map[tools.DataType]map[tools.METHOD]string{}),
|
||||
@@ -28,5 +24,5 @@ func GetPermissionConnector() perms_connectors.PermConnector {
|
||||
}
|
||||
|
||||
func GetClaims() claims.ClaimService {
|
||||
return t[conf.GetConfig().Auth]
|
||||
return claims.GetClaims()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user