2023-08-11 10:00:23 +02:00
|
|
|
// Copyright (C) 2023 NHR@FAU, University Erlangen-Nuremberg.
|
|
|
|
// All rights reserved.
|
|
|
|
// Use of this source code is governed by a MIT-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
package auth
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/ed25519"
|
2023-09-08 11:50:28 +02:00
|
|
|
"database/sql"
|
2023-08-11 10:00:23 +02:00
|
|
|
"encoding/base64"
|
|
|
|
"errors"
|
2023-08-18 08:49:25 +02:00
|
|
|
"fmt"
|
2023-08-11 10:00:23 +02:00
|
|
|
"net/http"
|
|
|
|
"os"
|
|
|
|
|
2023-08-18 10:43:06 +02:00
|
|
|
"github.com/ClusterCockpit/cc-backend/internal/config"
|
2023-08-17 14:02:04 +02:00
|
|
|
"github.com/ClusterCockpit/cc-backend/internal/repository"
|
2023-08-11 10:00:23 +02:00
|
|
|
"github.com/ClusterCockpit/cc-backend/pkg/log"
|
|
|
|
"github.com/ClusterCockpit/cc-backend/pkg/schema"
|
|
|
|
"github.com/golang-jwt/jwt/v4"
|
|
|
|
)
|
|
|
|
|
|
|
|
type JWTCookieSessionAuthenticator struct {
|
|
|
|
publicKey ed25519.PublicKey
|
|
|
|
privateKey ed25519.PrivateKey
|
|
|
|
publicKeyCrossLogin ed25519.PublicKey // For accepting externally generated JWTs
|
|
|
|
}
|
|
|
|
|
|
|
|
var _ Authenticator = (*JWTCookieSessionAuthenticator)(nil)
|
|
|
|
|
2023-08-18 10:43:06 +02:00
|
|
|
func (ja *JWTCookieSessionAuthenticator) Init() error {
|
2023-08-11 10:00:23 +02:00
|
|
|
pubKey, privKey := os.Getenv("JWT_PUBLIC_KEY"), os.Getenv("JWT_PRIVATE_KEY")
|
|
|
|
if pubKey == "" || privKey == "" {
|
|
|
|
log.Warn("environment variables 'JWT_PUBLIC_KEY' or 'JWT_PRIVATE_KEY' not set (token based authentication will not work)")
|
|
|
|
return errors.New("environment variables 'JWT_PUBLIC_KEY' or 'JWT_PRIVATE_KEY' not set (token based authentication will not work)")
|
|
|
|
} else {
|
|
|
|
bytes, err := base64.StdEncoding.DecodeString(pubKey)
|
|
|
|
if err != nil {
|
|
|
|
log.Warn("Could not decode JWT public key")
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
ja.publicKey = ed25519.PublicKey(bytes)
|
|
|
|
bytes, err = base64.StdEncoding.DecodeString(privKey)
|
|
|
|
if err != nil {
|
|
|
|
log.Warn("Could not decode JWT private key")
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
ja.privateKey = ed25519.PrivateKey(bytes)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Look for external public keys
|
|
|
|
pubKeyCrossLogin, keyFound := os.LookupEnv("CROSS_LOGIN_JWT_PUBLIC_KEY")
|
|
|
|
if keyFound && pubKeyCrossLogin != "" {
|
|
|
|
bytes, err := base64.StdEncoding.DecodeString(pubKeyCrossLogin)
|
|
|
|
if err != nil {
|
|
|
|
log.Warn("Could not decode cross login JWT public key")
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
ja.publicKeyCrossLogin = ed25519.PublicKey(bytes)
|
|
|
|
} else {
|
|
|
|
ja.publicKeyCrossLogin = nil
|
|
|
|
log.Debug("environment variable 'CROSS_LOGIN_JWT_PUBLIC_KEY' not set (cross login token based authentication will not work)")
|
|
|
|
return errors.New("environment variable 'CROSS_LOGIN_JWT_PUBLIC_KEY' not set (cross login token based authentication will not work)")
|
|
|
|
}
|
|
|
|
|
2023-08-18 10:43:06 +02:00
|
|
|
jc := config.Keys.JwtConfig
|
2023-08-11 10:00:23 +02:00
|
|
|
// Warn if other necessary settings are not configured
|
2023-08-18 10:43:06 +02:00
|
|
|
if jc != nil {
|
|
|
|
if jc.CookieName == "" {
|
|
|
|
log.Info("cookieName for JWTs not configured (cross login via JWT cookie will fail)")
|
2023-08-11 10:00:23 +02:00
|
|
|
return errors.New("cookieName for JWTs not configured (cross login via JWT cookie will fail)")
|
|
|
|
}
|
2023-08-18 10:43:06 +02:00
|
|
|
if !jc.ValidateUser {
|
|
|
|
log.Info("forceJWTValidationViaDatabase not set to true: CC will accept users and roles defined in JWTs regardless of its own database!")
|
2023-08-11 10:00:23 +02:00
|
|
|
}
|
2023-08-18 10:43:06 +02:00
|
|
|
if jc.TrustedIssuer == "" {
|
|
|
|
log.Info("trustedExternalIssuer for JWTs not configured (cross login via JWT cookie will fail)")
|
2023-08-11 10:00:23 +02:00
|
|
|
return errors.New("trustedExternalIssuer for JWTs not configured (cross login via JWT cookie will fail)")
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
log.Warn("config for JWTs not configured (cross login via JWT cookie will fail)")
|
|
|
|
return errors.New("config for JWTs not configured (cross login via JWT cookie will fail)")
|
|
|
|
}
|
|
|
|
|
2023-08-18 08:49:25 +02:00
|
|
|
log.Info("JWT Cookie Session authenticator successfully registered")
|
2023-08-11 10:00:23 +02:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ja *JWTCookieSessionAuthenticator) CanLogin(
|
2023-08-17 10:29:00 +02:00
|
|
|
user *schema.User,
|
2023-08-14 12:40:21 +02:00
|
|
|
username string,
|
2023-08-11 10:00:23 +02:00
|
|
|
rw http.ResponseWriter,
|
2023-08-17 14:02:04 +02:00
|
|
|
r *http.Request) (*schema.User, bool) {
|
2023-08-11 10:00:23 +02:00
|
|
|
|
2023-08-18 10:43:06 +02:00
|
|
|
jc := config.Keys.JwtConfig
|
2023-08-11 10:00:23 +02:00
|
|
|
cookieName := ""
|
2023-08-18 10:43:06 +02:00
|
|
|
if jc.CookieName != "" {
|
|
|
|
cookieName = jc.CookieName
|
2023-08-11 10:00:23 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Try to read the JWT cookie
|
|
|
|
if cookieName != "" {
|
|
|
|
jwtCookie, err := r.Cookie(cookieName)
|
|
|
|
|
|
|
|
if err == nil && jwtCookie.Value != "" {
|
2023-08-17 14:02:04 +02:00
|
|
|
return user, true
|
2023-08-11 10:00:23 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-08-17 14:02:04 +02:00
|
|
|
return nil, false
|
2023-08-11 10:00:23 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (ja *JWTCookieSessionAuthenticator) Login(
|
2023-08-17 10:29:00 +02:00
|
|
|
user *schema.User,
|
2023-08-11 10:00:23 +02:00
|
|
|
rw http.ResponseWriter,
|
2023-08-17 10:29:00 +02:00
|
|
|
r *http.Request) (*schema.User, error) {
|
2023-08-11 10:00:23 +02:00
|
|
|
|
2023-08-18 10:43:06 +02:00
|
|
|
jc := config.Keys.JwtConfig
|
|
|
|
jwtCookie, err := r.Cookie(jc.CookieName)
|
2023-08-11 10:00:23 +02:00
|
|
|
var rawtoken string
|
|
|
|
|
|
|
|
if err == nil && jwtCookie.Value != "" {
|
|
|
|
rawtoken = jwtCookie.Value
|
|
|
|
}
|
|
|
|
|
|
|
|
token, err := jwt.Parse(rawtoken, func(t *jwt.Token) (interface{}, error) {
|
|
|
|
if t.Method != jwt.SigningMethodEdDSA {
|
|
|
|
return nil, errors.New("only Ed25519/EdDSA supported")
|
|
|
|
}
|
|
|
|
|
|
|
|
unvalidatedIssuer, success := t.Claims.(jwt.MapClaims)["iss"].(string)
|
2023-08-18 10:43:06 +02:00
|
|
|
if success && unvalidatedIssuer == jc.TrustedIssuer {
|
2023-08-11 10:00:23 +02:00
|
|
|
// The (unvalidated) issuer seems to be the expected one,
|
|
|
|
// use public cross login key from config
|
|
|
|
return ja.publicKeyCrossLogin, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// No cross login key configured or issuer not expected
|
|
|
|
// Try own key
|
|
|
|
return ja.publicKey, nil
|
|
|
|
})
|
|
|
|
if err != nil {
|
2023-08-18 08:49:25 +02:00
|
|
|
log.Warn("JWT cookie session: error while parsing token")
|
2023-08-11 10:00:23 +02:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check token validity and extract paypload
|
|
|
|
if err := token.Claims.Valid(); err != nil {
|
|
|
|
log.Warn("jwt token claims are not valid")
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
claims := token.Claims.(jwt.MapClaims)
|
|
|
|
sub, _ := claims["sub"].(string)
|
|
|
|
|
|
|
|
var roles []string
|
2023-09-08 11:50:28 +02:00
|
|
|
projects := make([]string, 0)
|
2023-08-11 10:00:23 +02:00
|
|
|
|
2023-08-18 10:43:06 +02:00
|
|
|
if jc.ValidateUser {
|
2023-09-08 11:50:28 +02:00
|
|
|
var err error
|
|
|
|
user, err = repository.GetUserRepository().GetUser(sub)
|
|
|
|
if err != nil && err != sql.ErrNoRows {
|
|
|
|
log.Errorf("Error while loading user '%v'", sub)
|
|
|
|
}
|
|
|
|
|
2023-08-11 10:00:23 +02:00
|
|
|
// Deny any logins for unknown usernames
|
|
|
|
if user == nil {
|
|
|
|
log.Warn("Could not find user from JWT in internal database.")
|
|
|
|
return nil, errors.New("unknown user")
|
|
|
|
}
|
|
|
|
} else {
|
2023-09-08 12:11:49 +02:00
|
|
|
var name string
|
|
|
|
if wrap, ok := claims["name"].(map[string]interface{}); ok {
|
|
|
|
if vals, ok := wrap["values"].([]interface{}); ok {
|
|
|
|
if len(vals) != 0 {
|
|
|
|
name = fmt.Sprintf("%v", vals[0])
|
|
|
|
|
|
|
|
for i := 1; i < len(vals); i++ {
|
|
|
|
name += fmt.Sprintf(" %v", vals[i])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-08-11 10:00:23 +02:00
|
|
|
// Extract roles from JWT (if present)
|
|
|
|
if rawroles, ok := claims["roles"].([]interface{}); ok {
|
|
|
|
for _, rr := range rawroles {
|
|
|
|
if r, ok := rr.(string); ok {
|
|
|
|
roles = append(roles, r)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2023-08-17 10:29:00 +02:00
|
|
|
user = &schema.User{
|
2023-08-11 10:00:23 +02:00
|
|
|
Username: sub,
|
|
|
|
Name: name,
|
|
|
|
Roles: roles,
|
2023-08-18 08:49:25 +02:00
|
|
|
Projects: projects,
|
2023-08-17 10:29:00 +02:00
|
|
|
AuthType: schema.AuthSession,
|
|
|
|
AuthSource: schema.AuthViaToken,
|
2023-08-11 10:00:23 +02:00
|
|
|
}
|
2023-08-17 14:02:04 +02:00
|
|
|
|
2023-08-18 10:43:06 +02:00
|
|
|
if jc.SyncUserOnLogin {
|
2023-08-17 14:02:04 +02:00
|
|
|
if err := repository.GetUserRepository().AddUser(user); err != nil {
|
|
|
|
log.Errorf("Error while adding user '%s' to DB", user.Username)
|
|
|
|
}
|
|
|
|
}
|
2023-08-11 10:00:23 +02:00
|
|
|
}
|
|
|
|
|
2023-09-08 11:50:28 +02:00
|
|
|
// (Ask browser to) Delete JWT cookie
|
|
|
|
deletedCookie := &http.Cookie{
|
|
|
|
Name: jc.CookieName,
|
|
|
|
Value: "",
|
|
|
|
Path: "/",
|
|
|
|
MaxAge: -1,
|
|
|
|
HttpOnly: true,
|
|
|
|
}
|
|
|
|
http.SetCookie(rw, deletedCookie)
|
|
|
|
|
2023-08-11 10:00:23 +02:00
|
|
|
return user, nil
|
|
|
|
}
|