package claims import ( "crypto/sha256" "encoding/pem" "errors" "oc-auth/conf" "oc-auth/infrastructure/perms_connectors" "oc-auth/infrastructure/utils" "os" "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" ) type HydraClaims struct{} func (h HydraClaims) generateKey(relation string, path string) (string, error) { method, err := utils.ExtractMethod(relation, true) if err != nil { return "", err } p := strings.ReplaceAll(strings.ToUpper(path), "/", "_") return strings.ToUpper(method.String()) + "_" + strings.ReplaceAll(p, ":", ""), nil } // 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 { return tools.GET, "", errors.New("invalid key") } 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 } 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)) 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 } return true, nil } func (h HydraClaims) encodeSignature(host string) (string, error) { hashed := sha256.Sum256([]byte(host)) 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 { newPath := []string{} for _, p := range path { if p != "" { newPath = append(newPath, p) } } return newPath } // 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 // 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, "/")) for m, p := range claims { pStr, ok := p.(string) if !ok { continue } match := true splittedP := h.clearBlank(strings.Split(pStr, "/")) if len(splittedP) != len(splittedPath) { continue } for i, v := range splittedP { if strings.Contains(v, ":") { // is a param continue } else if v != splittedPath[i] { 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: 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") } // 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 { logger.Error().Msg("Failed to get permissions for user " + userId + ": " + err.Error()) return c } 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 } c.Session.AccessToken[key] = perm.Subject } sign, err := h.encodeSignature(p.APIUrl) if err != nil { logger.Error().Msg("Failed to encode signature: " + err.Error()) return c } 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 { logger.Error().Msg("Failed to get groups for user " + userId + ": " + err.Error()) return c } c.Session.IDToken["groups"] = groups c.Session.IDToken["signature"] = sign return c }