oc-auth OAUTH2

This commit is contained in:
mr
2026-02-19 14:56:15 +01:00
parent 048707bfe5
commit 078aae8172
14 changed files with 1360 additions and 610 deletions

View File

@@ -4,14 +4,13 @@ import (
"crypto/sha256"
"encoding/pem"
"errors"
"fmt"
"oc-auth/conf"
"oc-auth/infrastructure/perms_connectors"
"oc-auth/infrastructure/utils"
"os"
"strings"
"time"
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"
)
@@ -27,7 +26,7 @@ func (h HydraClaims) generateKey(relation string, path string) (string, error) {
return strings.ToUpper(method.String()) + "_" + strings.ReplaceAll(p, ":", ""), nil
}
// decode key expect to extract method and path from key
// decodeKey extracts method and path from a permission key
func (h HydraClaims) decodeKey(key string, external bool) (tools.METHOD, string, error) {
s := strings.Split(key, "_")
if len(s) < 2 {
@@ -46,7 +45,10 @@ func (h HydraClaims) decodeKey(key string, external bool) (tools.METHOD, string,
func (h HydraClaims) DecodeSignature(host string, signature string, publicKey string) (bool, error) {
hashed := sha256.Sum256([]byte(host))
spkiBlock, _ := pem.Decode([]byte(publicKey)) // get public key into a variable
spkiBlock, _ := pem.Decode([]byte(publicKey))
if spkiBlock == nil {
return false, errors.New("failed to decode public key PEM")
}
err := VerifyDefault(hashed[:], spkiBlock.Bytes, signature)
if err != nil {
return false, err
@@ -56,18 +58,19 @@ func (h HydraClaims) DecodeSignature(host string, signature string, publicKey st
func (h HydraClaims) encodeSignature(host string) (string, error) {
hashed := sha256.Sum256([]byte(host))
// READ FILE TO GET PRIVATE KEY FROM PVK PEM PATH
content, err := os.ReadFile(conf.GetConfig().PrivateKeyPath)
if err != nil {
return "", err
}
privateKey := string(content)
spkiBlock, _ := pem.Decode([]byte(privateKey))
if spkiBlock == nil {
return "", errors.New("failed to decode private key PEM")
}
return SignDefault(hashed[:], spkiBlock.Bytes)
}
func (h HydraClaims) clearBlank(path []string) []string {
// clear blank
newPath := []string{}
for _, p := range path {
if p != "" {
@@ -77,29 +80,33 @@ func (h HydraClaims) clearBlank(path []string) []string {
return newPath
}
func (a HydraClaims) CheckExpiry(exp int64) bool {
now := time.Now().UTC().Unix()
return now <= exp
}
// DecodeClaimsInToken verifies permissions from claims in a standard JWT (via introspection)
func (h HydraClaims) DecodeClaimsInToken(host string, method string, forward string, sessionClaims Claims, publicKey string, external bool) (bool, error) {
logger := oclib.GetLogger()
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
// Signature verification: skip if signature is empty (internal requests)
if sig, ok := idTokenClaims["signature"].(string); ok && sig != "" {
if ok, err := h.DecodeSignature(host, sig, publicKey); !ok {
return false, err
}
}
claims := sessionClaims.Session.AccessToken
if claims == nil {
return false, errors.New("no access_token claims found")
}
path := strings.ReplaceAll(forward, "http://"+host, "")
splittedPath := h.clearBlank(strings.Split(path, "/"))
if _, ok := claims["exp"].(float64); !ok || !h.CheckExpiry(int64(claims["exp"].(float64))) {
return false, errors.New("token is expired")
}
for m, p := range claims {
pStr, ok := p.(string)
if !ok {
continue
}
match := true
splittedP := h.clearBlank(strings.Split(p.(string), "/"))
splittedP := h.clearBlank(strings.Split(pStr, "/"))
if len(splittedP) != len(splittedPath) {
continue
}
@@ -118,45 +125,53 @@ func (h HydraClaims) DecodeClaimsInToken(host string, method string, forward str
}
perm := perms_connectors.Permission{
Relation: "permits" + strings.ToUpper(meth.String()),
Object: p.(string),
Object: pStr,
}
return perms_connectors.GetPermissionConnector("").CheckPermission(perm, nil, true), nil
}
}
logger.Error().Msg("No permission found for " + method + " " + forward)
return false, errors.New("no permission found")
}
// add claims to token method of HydraTokenizer
func (h HydraClaims) AddClaimsToToken(clientID string, userId string, p *peer.Peer) Claims {
claims := Claims{}
// BuildConsentSession builds the session payload for Hydra consent accept.
// Claims are injected into the Hydra JWT — not appended to the token as before.
func (h HydraClaims) BuildConsentSession(clientID string, userId string, p *peer.Peer) Claims {
logger := oclib.GetLogger()
c := Claims{}
perms, err := perms_connectors.KetoConnector{}.GetPermissionByUser(userId, true)
if err != nil {
return claims
logger.Error().Msg("Failed to get permissions for user " + userId + ": " + err.Error())
return c
}
claims.Session.AccessToken = make(map[string]interface{})
claims.Session.IDToken = make(map[string]interface{})
fmt.Println("PERMS err 1", perms, err)
c.Session.AccessToken = make(map[string]interface{})
c.Session.IDToken = make(map[string]interface{})
for _, perm := range perms {
key, err := h.generateKey(strings.ReplaceAll(perm.Relation, "permits", ""), perm.Subject)
if err != nil {
continue
}
claims.Session.AccessToken[key] = perm.Subject
c.Session.AccessToken[key] = perm.Subject
}
sign, err := h.encodeSignature(p.APIUrl)
if err != nil {
return claims
logger.Error().Msg("Failed to encode signature: " + err.Error())
return c
}
claims.Session.IDToken["username"] = userId
claims.Session.IDToken["peer_id"] = p.UUID
// we should get group from user
c.Session.IDToken["username"] = userId
c.Session.IDToken["peer_id"] = p.UUID
c.Session.IDToken["client_id"] = clientID
groups, err := perms_connectors.KetoConnector{}.GetGroupByUser(userId)
if err != nil {
return claims
logger.Error().Msg("Failed to get groups for user " + userId + ": " + err.Error())
return c
}
claims.Session.IDToken["client_id"] = clientID
claims.Session.IDToken["groups"] = groups
claims.Session.IDToken["signature"] = sign
return claims
c.Session.IDToken["groups"] = groups
c.Session.IDToken["signature"] = sign
return c
}