2023-08-11 10:00:23 +02:00
|
|
|
// Copyright (C) 2023 NHR@FAU, University Erlangen-Nuremberg.
|
2022-07-29 06:29:21 +02:00
|
|
|
// All rights reserved.
|
|
|
|
// Use of this source code is governed by a MIT-style
|
|
|
|
// license that can be found in the LICENSE file.
|
2021-12-08 10:03:00 +01:00
|
|
|
package auth
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2022-07-25 09:33:36 +02:00
|
|
|
"crypto/rand"
|
2023-08-11 10:00:23 +02:00
|
|
|
"database/sql"
|
2022-07-25 09:33:36 +02:00
|
|
|
"encoding/base64"
|
|
|
|
"errors"
|
2021-12-08 10:03:00 +01:00
|
|
|
"net/http"
|
2022-07-25 09:33:36 +02:00
|
|
|
"os"
|
2022-02-16 11:50:25 +01:00
|
|
|
"time"
|
2021-12-08 10:03:00 +01:00
|
|
|
|
2022-06-21 17:52:36 +02:00
|
|
|
"github.com/ClusterCockpit/cc-backend/pkg/log"
|
2021-12-08 10:03:00 +01:00
|
|
|
"github.com/gorilla/sessions"
|
|
|
|
"github.com/jmoiron/sqlx"
|
|
|
|
)
|
|
|
|
|
2023-03-06 11:44:38 +01:00
|
|
|
type AuthSource int
|
|
|
|
|
2022-01-27 09:29:11 +01:00
|
|
|
const (
|
2023-03-06 11:44:38 +01:00
|
|
|
AuthViaLocalPassword AuthSource = iota
|
|
|
|
AuthViaLDAP
|
|
|
|
AuthViaToken
|
2022-01-27 09:29:11 +01:00
|
|
|
)
|
|
|
|
|
2023-08-11 10:00:23 +02:00
|
|
|
type AuthType int
|
|
|
|
|
|
|
|
const (
|
|
|
|
AuthToken AuthType = iota
|
|
|
|
AuthSession
|
|
|
|
)
|
|
|
|
|
2023-03-06 11:44:38 +01:00
|
|
|
type User struct {
|
|
|
|
Username string `json:"username"`
|
|
|
|
Password string `json:"-"`
|
|
|
|
Name string `json:"name"`
|
|
|
|
Roles []string `json:"roles"`
|
2023-08-11 10:00:23 +02:00
|
|
|
AuthType AuthType `json:"authType"`
|
|
|
|
AuthSource AuthSource `json:"authSource"`
|
2023-03-06 11:44:38 +01:00
|
|
|
Email string `json:"email"`
|
|
|
|
Projects []string `json:"projects"`
|
|
|
|
}
|
|
|
|
|
2023-01-27 18:36:58 +01:00
|
|
|
func (u *User) HasProject(project string) bool {
|
2023-02-17 15:45:31 +01:00
|
|
|
for _, p := range u.Projects {
|
|
|
|
if p == project {
|
|
|
|
return true
|
|
|
|
}
|
2023-01-27 18:36:58 +01:00
|
|
|
}
|
2023-02-17 15:45:31 +01:00
|
|
|
return false
|
2023-01-27 18:36:58 +01:00
|
|
|
}
|
|
|
|
|
2022-07-07 14:08:37 +02:00
|
|
|
func GetUser(ctx context.Context) *User {
|
|
|
|
x := ctx.Value(ContextUserKey)
|
|
|
|
if x == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return x.(*User)
|
|
|
|
}
|
|
|
|
|
|
|
|
type Authenticator interface {
|
|
|
|
Init(auth *Authentication, config interface{}) error
|
2023-08-14 12:40:21 +02:00
|
|
|
CanLogin(user *User, username string, rw http.ResponseWriter, r *http.Request) bool
|
2022-07-07 14:08:37 +02:00
|
|
|
Login(user *User, rw http.ResponseWriter, r *http.Request) (*User, error)
|
|
|
|
}
|
|
|
|
|
2021-12-08 10:03:00 +01:00
|
|
|
type ContextKey string
|
|
|
|
|
|
|
|
const ContextUserKey ContextKey = "user"
|
|
|
|
|
2022-02-14 14:22:44 +01:00
|
|
|
type Authentication struct {
|
|
|
|
db *sqlx.DB
|
|
|
|
sessionStore *sessions.CookieStore
|
2022-02-16 11:50:25 +01:00
|
|
|
SessionMaxAge time.Duration
|
2022-07-07 14:08:37 +02:00
|
|
|
|
|
|
|
authenticators []Authenticator
|
2022-09-07 12:24:45 +02:00
|
|
|
LdapAuth *LdapAuthenticator
|
2022-07-07 14:08:37 +02:00
|
|
|
JwtAuth *JWTAuthenticator
|
|
|
|
LocalAuth *LocalAuthenticator
|
2022-02-14 14:22:44 +01:00
|
|
|
}
|
2021-12-08 10:03:00 +01:00
|
|
|
|
2023-08-11 10:00:23 +02:00
|
|
|
func (auth *Authentication) AuthViaSession(
|
|
|
|
rw http.ResponseWriter,
|
|
|
|
r *http.Request) (*User, error) {
|
|
|
|
session, err := auth.sessionStore.Get(r, "session")
|
|
|
|
if err != nil {
|
|
|
|
log.Error("Error while getting session store")
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if session.IsNew {
|
|
|
|
return nil, nil
|
|
|
|
}
|
2023-08-12 09:02:41 +02:00
|
|
|
//
|
|
|
|
// var username string
|
|
|
|
// var projects, roles []string
|
|
|
|
//
|
|
|
|
// if val, ok := session.Values["username"]; ok {
|
|
|
|
// username, _ = val.(string)
|
|
|
|
// } else {
|
|
|
|
// return nil, errors.New("no key username in session")
|
|
|
|
// }
|
|
|
|
// if val, ok := session.Values["projects"]; ok {
|
|
|
|
// projects, _ = val.([]string)
|
|
|
|
// } else {
|
|
|
|
// return nil, errors.New("no key projects in session")
|
|
|
|
// }
|
|
|
|
// if val, ok := session.Values["projects"]; ok {
|
|
|
|
// roles, _ = val.([]string)
|
|
|
|
// } else {
|
|
|
|
// return nil, errors.New("no key roles in session")
|
|
|
|
// }
|
|
|
|
//
|
|
|
|
username, _ := session.Values["username"].(string)
|
|
|
|
projects, _ := session.Values["projects"].([]string)
|
|
|
|
roles, _ := session.Values["roles"].([]string)
|
2023-08-11 10:00:23 +02:00
|
|
|
return &User{
|
|
|
|
Username: username,
|
|
|
|
Projects: projects,
|
|
|
|
Roles: roles,
|
|
|
|
AuthType: AuthSession,
|
|
|
|
AuthSource: -1,
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
2022-09-06 15:43:57 +02:00
|
|
|
func Init(db *sqlx.DB,
|
|
|
|
configs map[string]interface{}) (*Authentication, error) {
|
2022-07-07 14:08:37 +02:00
|
|
|
auth := &Authentication{}
|
2022-02-14 14:22:44 +01:00
|
|
|
auth.db = db
|
2022-03-03 14:54:37 +01:00
|
|
|
|
2022-07-25 09:33:36 +02:00
|
|
|
sessKey := os.Getenv("SESSION_KEY")
|
|
|
|
if sessKey == "" {
|
|
|
|
log.Warn("environment variable 'SESSION_KEY' not set (will use non-persistent random key)")
|
|
|
|
bytes := make([]byte, 32)
|
|
|
|
if _, err := rand.Read(bytes); err != nil {
|
2023-01-31 18:28:44 +01:00
|
|
|
log.Error("Error while initializing authentication -> failed to generate random bytes for session key")
|
2022-07-25 09:33:36 +02:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
auth.sessionStore = sessions.NewCookieStore(bytes)
|
|
|
|
} else {
|
|
|
|
bytes, err := base64.StdEncoding.DecodeString(sessKey)
|
|
|
|
if err != nil {
|
2023-01-31 18:28:44 +01:00
|
|
|
log.Error("Error while initializing authentication -> decoding session key failed")
|
2022-07-25 09:33:36 +02:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
auth.sessionStore = sessions.NewCookieStore(bytes)
|
|
|
|
}
|
|
|
|
|
2022-07-07 14:08:37 +02:00
|
|
|
auth.JwtAuth = &JWTAuthenticator{}
|
|
|
|
if err := auth.JwtAuth.Init(auth, configs["jwt"]); err != nil {
|
2023-01-31 18:28:44 +01:00
|
|
|
log.Error("Error while initializing authentication -> jwtAuth init failed")
|
2022-07-07 14:08:37 +02:00
|
|
|
return nil, err
|
2021-12-08 10:03:00 +01:00
|
|
|
}
|
|
|
|
|
2022-07-07 14:08:37 +02:00
|
|
|
if config, ok := configs["ldap"]; ok {
|
2023-08-16 09:19:41 +02:00
|
|
|
ldapAuth := &LdapAuthenticator{}
|
|
|
|
if err := ldapAuth.Init(auth, config); err != nil {
|
|
|
|
log.Warn("Error while initializing authentication -> ldapAuth init failed")
|
|
|
|
} else {
|
|
|
|
auth.LdapAuth = ldapAuth
|
|
|
|
auth.authenticators = append(auth.authenticators, auth.LdapAuth)
|
2022-02-14 14:22:44 +01:00
|
|
|
}
|
2021-12-08 10:03:00 +01:00
|
|
|
}
|
|
|
|
|
2023-08-11 10:00:23 +02:00
|
|
|
jwtSessionAuth := &JWTSessionAuthenticator{}
|
|
|
|
if err := jwtSessionAuth.Init(auth, configs["jwt"]); err != nil {
|
|
|
|
log.Warn("Error while initializing authentication -> jwtSessionAuth init failed")
|
|
|
|
} else {
|
|
|
|
auth.authenticators = append(auth.authenticators, jwtSessionAuth)
|
|
|
|
}
|
2022-09-07 12:24:45 +02:00
|
|
|
|
2023-08-11 10:00:23 +02:00
|
|
|
jwtCookieSessionAuth := &JWTCookieSessionAuthenticator{}
|
2023-08-16 09:19:41 +02:00
|
|
|
if err := jwtCookieSessionAuth.Init(auth, configs["jwt"]); err != nil {
|
2023-08-11 10:00:23 +02:00
|
|
|
log.Warn("Error while initializing authentication -> jwtCookieSessionAuth init failed")
|
|
|
|
} else {
|
|
|
|
auth.authenticators = append(auth.authenticators, jwtCookieSessionAuth)
|
2022-03-15 11:04:54 +01:00
|
|
|
}
|
|
|
|
|
2023-08-11 10:00:23 +02:00
|
|
|
auth.LocalAuth = &LocalAuthenticator{}
|
|
|
|
if err := auth.LocalAuth.Init(auth, nil); err != nil {
|
|
|
|
log.Error("Error while initializing authentication -> localAuth init failed")
|
|
|
|
return nil, err
|
2022-03-15 11:04:54 +01:00
|
|
|
}
|
2023-08-11 10:00:23 +02:00
|
|
|
auth.authenticators = append(auth.authenticators, auth.LocalAuth)
|
2022-03-17 10:54:17 +01:00
|
|
|
|
2023-08-11 10:00:23 +02:00
|
|
|
return auth, nil
|
2022-03-15 11:04:54 +01:00
|
|
|
}
|
|
|
|
|
2022-09-07 12:24:45 +02:00
|
|
|
func (auth *Authentication) Login(
|
|
|
|
onsuccess http.Handler,
|
|
|
|
onfailure func(rw http.ResponseWriter, r *http.Request, loginErr error)) http.Handler {
|
|
|
|
|
2021-12-08 10:03:00 +01:00
|
|
|
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
2023-06-14 14:35:25 +02:00
|
|
|
err := errors.New("no authenticator applied")
|
2022-07-07 14:08:37 +02:00
|
|
|
username := r.FormValue("username")
|
2023-08-11 10:00:23 +02:00
|
|
|
dbUser := (*User)(nil)
|
2023-07-05 09:50:44 +02:00
|
|
|
|
2022-07-07 14:08:37 +02:00
|
|
|
if username != "" {
|
2023-08-11 10:00:23 +02:00
|
|
|
dbUser, err = auth.GetUser(username)
|
|
|
|
if err != nil && err != sql.ErrNoRows {
|
|
|
|
log.Errorf("Error while loading user '%v'", username)
|
|
|
|
}
|
2021-12-08 10:03:00 +01:00
|
|
|
}
|
|
|
|
|
2022-07-07 14:08:37 +02:00
|
|
|
for _, authenticator := range auth.authenticators {
|
2023-08-14 12:40:21 +02:00
|
|
|
if !authenticator.CanLogin(dbUser, username, rw, r) {
|
2022-07-07 14:08:37 +02:00
|
|
|
continue
|
|
|
|
}
|
2021-12-08 10:03:00 +01:00
|
|
|
|
2023-08-11 10:00:23 +02:00
|
|
|
user, err := authenticator.Login(dbUser, rw, r)
|
2022-07-07 14:08:37 +02:00
|
|
|
if err != nil {
|
2023-06-14 14:35:25 +02:00
|
|
|
log.Warnf("user login failed: %s", err.Error())
|
2022-07-07 14:08:37 +02:00
|
|
|
onfailure(rw, r, err)
|
|
|
|
return
|
|
|
|
}
|
2021-12-08 10:03:00 +01:00
|
|
|
|
2022-07-07 14:08:37 +02:00
|
|
|
session, err := auth.sessionStore.New(r, "session")
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("session creation failed: %s", err.Error())
|
|
|
|
http.Error(rw, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
2021-12-08 10:03:00 +01:00
|
|
|
|
2022-07-07 14:08:37 +02:00
|
|
|
if auth.SessionMaxAge != 0 {
|
|
|
|
session.Options.MaxAge = int(auth.SessionMaxAge.Seconds())
|
|
|
|
}
|
|
|
|
session.Values["username"] = user.Username
|
2023-02-17 15:45:31 +01:00
|
|
|
session.Values["projects"] = user.Projects
|
2022-07-07 14:08:37 +02:00
|
|
|
session.Values["roles"] = user.Roles
|
|
|
|
if err := auth.sessionStore.Save(r, rw, session); err != nil {
|
2023-02-01 11:58:27 +01:00
|
|
|
log.Warnf("session save failed: %s", err.Error())
|
2022-07-07 14:08:37 +02:00
|
|
|
http.Error(rw, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
2021-12-08 10:03:00 +01:00
|
|
|
|
2023-08-11 10:00:23 +02:00
|
|
|
if dbUser == nil {
|
|
|
|
if err := auth.AddUser(user); err != nil {
|
|
|
|
// TODO Add AuthSource
|
|
|
|
log.Errorf("Error while adding user '%v' to auth from XX",
|
|
|
|
user.Username)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-02-17 15:45:31 +01:00
|
|
|
log.Infof("login successfull: user: %#v (roles: %v, projects: %v)", user.Username, user.Roles, user.Projects)
|
2022-07-07 14:08:37 +02:00
|
|
|
ctx := context.WithValue(r.Context(), ContextUserKey, user)
|
|
|
|
onsuccess.ServeHTTP(rw, r.WithContext(ctx))
|
2022-07-25 09:33:36 +02:00
|
|
|
return
|
2021-12-08 10:03:00 +01:00
|
|
|
}
|
|
|
|
|
2023-06-20 15:47:38 +02:00
|
|
|
log.Debugf("login failed: no authenticator applied")
|
2022-07-07 14:08:37 +02:00
|
|
|
onfailure(rw, r, err)
|
2021-12-08 10:03:00 +01:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2022-09-07 12:24:45 +02:00
|
|
|
func (auth *Authentication) Auth(
|
|
|
|
onsuccess http.Handler,
|
|
|
|
onfailure func(rw http.ResponseWriter, r *http.Request, authErr error)) http.Handler {
|
|
|
|
|
2021-12-08 10:03:00 +01:00
|
|
|
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
2023-08-11 10:00:23 +02:00
|
|
|
|
|
|
|
user, err := auth.JwtAuth.AuthViaJWT(rw, r)
|
2023-08-12 09:02:41 +02:00
|
|
|
if err != nil {
|
|
|
|
log.Infof("authentication failed: %s", err.Error())
|
|
|
|
http.Error(rw, err.Error(), http.StatusUnauthorized)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-08-11 10:00:23 +02:00
|
|
|
if user == nil {
|
|
|
|
user, err = auth.AuthViaSession(rw, r)
|
2022-07-07 14:08:37 +02:00
|
|
|
if err != nil {
|
2023-06-20 15:47:38 +02:00
|
|
|
log.Infof("authentication failed: %s", err.Error())
|
2022-07-07 14:08:37 +02:00
|
|
|
http.Error(rw, err.Error(), http.StatusUnauthorized)
|
|
|
|
return
|
|
|
|
}
|
2023-08-11 10:00:23 +02:00
|
|
|
}
|
2022-07-07 14:08:37 +02:00
|
|
|
|
2023-08-11 10:00:23 +02:00
|
|
|
if user != nil {
|
2021-12-08 10:03:00 +01:00
|
|
|
ctx := context.WithValue(r.Context(), ContextUserKey, user)
|
2022-02-14 14:22:44 +01:00
|
|
|
onsuccess.ServeHTTP(rw, r.WithContext(ctx))
|
2022-07-25 09:33:36 +02:00
|
|
|
return
|
2021-12-08 10:03:00 +01:00
|
|
|
}
|
|
|
|
|
2023-08-12 09:02:41 +02:00
|
|
|
log.Debug("authentication failed")
|
2023-08-11 10:00:23 +02:00
|
|
|
onfailure(rw, r, errors.New("unauthorized (please login first)"))
|
2021-12-08 10:03:00 +01:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2022-02-14 14:22:44 +01:00
|
|
|
func (auth *Authentication) Logout(onsuccess http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
|
|
|
session, err := auth.sessionStore.Get(r, "session")
|
|
|
|
if err != nil {
|
2021-12-08 10:03:00 +01:00
|
|
|
http.Error(rw, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-02-14 14:22:44 +01:00
|
|
|
if !session.IsNew {
|
|
|
|
session.Options.MaxAge = -1
|
|
|
|
if err := auth.sessionStore.Save(r, rw, session); err != nil {
|
|
|
|
http.Error(rw, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
onsuccess.ServeHTTP(rw, r)
|
2021-12-08 10:03:00 +01:00
|
|
|
})
|
|
|
|
}
|