oc-auth/infrastructure/claims/hydra_claims.go

160 lines
4.5 KiB
Go
Raw Normal View History

package claims
import (
"crypto/sha256"
"encoding/pem"
"errors"
"oc-auth/conf"
"oc-auth/infrastructure/perms_connectors"
"oc-auth/infrastructure/utils"
"os"
"strings"
2024-11-05 10:11:39 +01:00
"time"
2024-11-27 12:36:37 +01:00
"cloud.o-forge.io/core/oc-lib/models/peer"
"cloud.o-forge.io/core/oc-lib/tools"
)
type HydraClaims struct{}
func (h HydraClaims) generateKey(relation string, path string) (string, error) {
2024-10-30 16:39:52 +01:00
method, err := utils.ExtractMethod(relation, true)
if err != nil {
return "", err
}
p := strings.ReplaceAll(strings.ToUpper(path), "/", "_")
2024-11-21 11:07:19 +01:00
return strings.ToUpper(method.String()) + "_" + strings.ReplaceAll(p, ":", ""), nil
}
// decode key expect to extract method and path from key
2024-10-30 16:39:52 +01:00
func (h HydraClaims) decodeKey(key string, external bool) (tools.METHOD, string, error) {
s := strings.Split(key, "_")
if len(s) < 2 {
return tools.GET, "", errors.New("invalid key")
}
2024-10-30 16:39:52 +01:00
if strings.Contains(strings.ToUpper(s[0]), "INTERNAL") && external {
return tools.GET, "", errors.New("external ask for internal key")
}
meth, err := utils.ExtractMethod(s[0], false)
if err != nil {
return meth, "", err
}
2024-11-21 11:07:19 +01:00
p := strings.ReplaceAll(strings.ToUpper(s[1]), "_", "/")
return meth, p, nil
}
func (h HydraClaims) DecodeSignature(host string, signature string, publicKey string) (bool, error) {
hashed := sha256.Sum256([]byte(host))
2024-10-30 12:38:25 +01:00
spkiBlock, _ := pem.Decode([]byte(publicKey)) // get public key into a variable
err := VerifyDefault(hashed[:], spkiBlock.Bytes, signature)
if err != nil {
return false, err
}
return true, nil
}
func (h HydraClaims) encodeSignature(host string) (string, error) {
hashed := sha256.Sum256([]byte(host))
// READ FILE TO GET PRIVATE KEY FROM PVK PEM PATH
2024-10-30 12:38:25 +01:00
content, err := os.ReadFile(conf.GetConfig().PrivateKeyPath)
if err != nil {
return "", err
}
privateKey := string(content)
spkiBlock, _ := pem.Decode([]byte(privateKey))
2024-10-30 12:38:25 +01:00
return SignDefault(hashed[:], spkiBlock.Bytes)
}
2024-11-04 09:43:35 +01:00
func (h HydraClaims) clearBlank(path []string) []string {
// clear blank
newPath := []string{}
for _, p := range path {
if p != "" {
newPath = append(newPath, p)
}
}
return newPath
}
2024-11-05 10:11:39 +01:00
func (a HydraClaims) CheckExpiry(exp int64) bool {
now := time.Now().UTC().Unix()
return now <= exp
}
2024-10-30 16:39:52 +01:00
func (h HydraClaims) DecodeClaimsInToken(host string, method string, forward string, sessionClaims Claims, publicKey string, external bool) (bool, error) {
2024-10-30 12:38:25 +01:00
idTokenClaims := sessionClaims.Session.IDToken
if idTokenClaims["signature"] == nil {
return false, errors.New("no signature found")
}
signature := idTokenClaims["signature"].(string)
if ok, err := h.DecodeSignature(host, signature, publicKey); !ok {
return false, err
}
2024-10-30 12:38:25 +01:00
claims := sessionClaims.Session.AccessToken
path := strings.ReplaceAll(forward, "http://"+host, "")
2024-11-04 09:43:35 +01:00
splittedPath := h.clearBlank(strings.Split(path, "/"))
2024-11-05 10:11:39 +01:00
if _, ok := claims["exp"].(float64); !ok || !h.CheckExpiry(int64(claims["exp"].(float64))) {
return false, errors.New("token is expired")
}
for m, p := range claims {
2024-11-04 09:43:35 +01:00
match := true
splittedP := h.clearBlank(strings.Split(p.(string), "/"))
if len(splittedP) != len(splittedPath) {
2024-10-30 17:05:12 +01:00
continue
}
for i, v := range splittedP {
if strings.Contains(v, ":") { // is a param
continue
} else if v != splittedPath[i] {
2024-11-04 09:43:35 +01:00
match = false
break
}
}
if match {
meth, _, err := h.decodeKey(m, external)
if err != nil {
continue
}
perm := perms_connectors.Permission{
Relation: "permits" + strings.ToUpper(meth.String()),
Object: p.(string),
}
2024-11-04 09:43:35 +01:00
return perms_connectors.GetPermissionConnector().CheckPermission(perm, nil, true), nil
}
}
return false, errors.New("no permission found")
}
// add claims to token method of HydraTokenizer
2024-11-27 12:36:37 +01:00
func (h HydraClaims) AddClaimsToToken(userId string, p *peer.Peer) Claims {
claims := Claims{}
2024-10-30 16:39:52 +01:00
perms, err := perms_connectors.KetoConnector{}.GetPermissionByUser(userId, true)
if err != nil {
return claims
}
2024-10-30 12:38:25 +01:00
claims.Session.AccessToken = make(map[string]interface{})
claims.Session.IDToken = make(map[string]interface{})
for _, perm := range perms {
2024-11-04 09:43:35 +01:00
key, err := h.generateKey(strings.ReplaceAll(perm.Relation, "permits", ""), perm.Subject)
if err != nil {
continue
}
2024-11-04 09:43:35 +01:00
claims.Session.AccessToken[key] = perm.Subject
}
2024-11-27 12:36:37 +01:00
sign, err := h.encodeSignature(p.Url)
if err != nil {
return claims
}
2024-11-27 12:36:37 +01:00
claims.Session.IDToken["peer_id"] = p.UUID
// we should get group from user
groups, err := perms_connectors.KetoConnector{}.GetGroupByUser(userId)
if err != nil {
return claims
}
claims.Session.IDToken["groups"] = groups
claims.Session.IDToken["signature"] = sign
return claims
}
// add signature in the token MISSING