2021-12-08 10:03:00 +01:00
|
|
|
package auth
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"crypto/ed25519"
|
|
|
|
"crypto/rand"
|
|
|
|
"database/sql"
|
|
|
|
"encoding/base64"
|
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"os"
|
|
|
|
"strings"
|
|
|
|
|
2022-01-27 10:35:26 +01:00
|
|
|
"github.com/ClusterCockpit/cc-backend/log"
|
2022-01-27 09:40:59 +01:00
|
|
|
"github.com/ClusterCockpit/cc-backend/templates"
|
2021-12-08 10:03:00 +01:00
|
|
|
sq "github.com/Masterminds/squirrel"
|
|
|
|
"github.com/golang-jwt/jwt/v4"
|
|
|
|
"github.com/gorilla/sessions"
|
|
|
|
"github.com/jmoiron/sqlx"
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
|
|
)
|
|
|
|
|
2022-01-17 13:35:49 +01:00
|
|
|
// TODO: Properly do this "roles" stuff.
|
|
|
|
// Add a roles array and `user.HasRole(...)` functions.
|
2021-12-08 10:03:00 +01:00
|
|
|
type User struct {
|
2022-01-27 09:29:11 +01:00
|
|
|
Username string
|
|
|
|
Password string
|
|
|
|
Name string
|
|
|
|
Roles []string
|
|
|
|
ViaLdap bool
|
|
|
|
Email string
|
|
|
|
}
|
|
|
|
|
|
|
|
const (
|
|
|
|
RoleAdmin string = "admin"
|
|
|
|
RoleApi string = "api"
|
|
|
|
RoleUser string = "user"
|
|
|
|
)
|
|
|
|
|
|
|
|
func (u *User) HasRole(role string) bool {
|
|
|
|
for _, r := range u.Roles {
|
|
|
|
if r == role {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
2021-12-08 10:03:00 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
type ContextKey string
|
|
|
|
|
|
|
|
const ContextUserKey ContextKey = "user"
|
|
|
|
|
|
|
|
var JwtPublicKey ed25519.PublicKey
|
|
|
|
var JwtPrivateKey ed25519.PrivateKey
|
|
|
|
|
|
|
|
var sessionStore *sessions.CookieStore
|
|
|
|
|
|
|
|
func Init(db *sqlx.DB, ldapConfig *LdapConfig) error {
|
|
|
|
_, err := db.Exec(`
|
|
|
|
CREATE TABLE IF NOT EXISTS user (
|
|
|
|
username varchar(255) PRIMARY KEY,
|
|
|
|
password varchar(255) DEFAULT NULL,
|
|
|
|
ldap tinyint DEFAULT 0,
|
|
|
|
name varchar(255) DEFAULT NULL,
|
|
|
|
roles varchar(255) DEFAULT NULL,
|
|
|
|
email varchar(255) DEFAULT NULL);`)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
sessKey := os.Getenv("SESSION_KEY")
|
|
|
|
if sessKey == "" {
|
2022-01-27 10:35:26 +01:00
|
|
|
log.Warn("environment variable 'SESSION_KEY' not set (will use non-persistent random key)")
|
2021-12-08 10:03:00 +01:00
|
|
|
bytes := make([]byte, 32)
|
|
|
|
if _, err := rand.Read(bytes); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
sessionStore = sessions.NewCookieStore(bytes)
|
|
|
|
} else {
|
|
|
|
bytes, err := base64.StdEncoding.DecodeString(sessKey)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
sessionStore = sessions.NewCookieStore(bytes)
|
|
|
|
}
|
|
|
|
|
|
|
|
pubKey, privKey := os.Getenv("JWT_PUBLIC_KEY"), os.Getenv("JWT_PRIVATE_KEY")
|
|
|
|
if pubKey == "" || privKey == "" {
|
2022-01-27 10:35:26 +01:00
|
|
|
log.Warn("environment variables 'JWT_PUBLIC_KEY' or 'JWT_PRIVATE_KEY' not set (token based authentication will not work)")
|
2021-12-08 10:03:00 +01:00
|
|
|
} else {
|
|
|
|
bytes, err := base64.StdEncoding.DecodeString(pubKey)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
JwtPublicKey = ed25519.PublicKey(bytes)
|
|
|
|
bytes, err = base64.StdEncoding.DecodeString(privKey)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
JwtPrivateKey = ed25519.PrivateKey(bytes)
|
|
|
|
}
|
|
|
|
|
|
|
|
if ldapConfig != nil {
|
|
|
|
if err := initLdap(ldapConfig); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// arg must be formated like this: "<username>:[admin]:<password>"
|
|
|
|
func AddUserToDB(db *sqlx.DB, arg string) error {
|
|
|
|
parts := strings.SplitN(arg, ":", 3)
|
2022-01-27 09:29:11 +01:00
|
|
|
if len(parts) != 3 || len(parts[0]) == 0 {
|
2021-12-08 10:03:00 +01:00
|
|
|
return errors.New("invalid argument format")
|
|
|
|
}
|
|
|
|
|
2022-01-27 09:29:11 +01:00
|
|
|
password := ""
|
|
|
|
if len(parts[2]) > 0 {
|
|
|
|
bytes, err := bcrypt.GenerateFromPassword([]byte(parts[2]), bcrypt.DefaultCost)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
password = string(bytes)
|
2021-12-08 10:03:00 +01:00
|
|
|
}
|
|
|
|
|
2022-01-27 09:29:11 +01:00
|
|
|
roles := []string{}
|
|
|
|
for _, role := range strings.Split(parts[1], ",") {
|
|
|
|
if len(role) == 0 {
|
|
|
|
continue
|
|
|
|
} else if role == RoleAdmin || role == RoleApi || role == RoleUser {
|
|
|
|
roles = append(roles, role)
|
|
|
|
} else {
|
|
|
|
return fmt.Errorf("invalid user role: %#v", role)
|
|
|
|
}
|
2022-01-10 16:14:54 +01:00
|
|
|
}
|
2021-12-08 10:03:00 +01:00
|
|
|
|
2022-01-27 09:29:11 +01:00
|
|
|
rolesJson, _ := json.Marshal(roles)
|
|
|
|
_, err := sq.Insert("user").Columns("username", "password", "roles").Values(parts[0], password, string(rolesJson)).RunWith(db).Exec()
|
2021-12-08 10:03:00 +01:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-01-27 10:35:26 +01:00
|
|
|
log.Infof("new user %#v added (roles: %s)", parts[0], roles)
|
2021-12-08 10:03:00 +01:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func DelUserFromDB(db *sqlx.DB, username string) error {
|
|
|
|
_, err := db.Exec(`DELETE FROM user WHERE user.username = ?`, username)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-01-10 16:14:54 +01:00
|
|
|
func FetchUserFromDB(db *sqlx.DB, username string) (*User, error) {
|
2021-12-08 10:03:00 +01:00
|
|
|
user := &User{Username: username}
|
|
|
|
var hashedPassword, name, rawRoles, email sql.NullString
|
|
|
|
if err := sq.Select("password", "ldap", "name", "roles", "email").From("user").
|
|
|
|
Where("user.username = ?", username).RunWith(db).
|
|
|
|
QueryRow().Scan(&hashedPassword, &user.ViaLdap, &name, &rawRoles, &email); err != nil {
|
|
|
|
return nil, fmt.Errorf("user '%s' not found (%s)", username, err.Error())
|
|
|
|
}
|
|
|
|
|
|
|
|
user.Password = hashedPassword.String
|
|
|
|
user.Name = name.String
|
|
|
|
user.Email = email.String
|
|
|
|
if rawRoles.Valid {
|
2022-01-27 09:29:11 +01:00
|
|
|
json.Unmarshal([]byte(rawRoles.String), &user.Roles)
|
2021-12-08 10:03:00 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
return user, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Handle a POST request that should log the user in,
|
|
|
|
// starting a new session.
|
|
|
|
func Login(db *sqlx.DB) http.Handler {
|
|
|
|
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
|
|
|
username, password := r.FormValue("username"), r.FormValue("password")
|
2022-01-10 16:14:54 +01:00
|
|
|
user, err := FetchUserFromDB(db, username)
|
2021-12-08 10:03:00 +01:00
|
|
|
if err == nil && user.ViaLdap && ldapAuthEnabled {
|
|
|
|
err = loginViaLdap(user, password)
|
|
|
|
} else if err == nil && !user.ViaLdap && user.Password != "" {
|
|
|
|
if e := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); e != nil {
|
|
|
|
err = fmt.Errorf("user '%s' provided the wrong password (%s)", username, e.Error())
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
err = errors.New("could not authenticate user")
|
|
|
|
}
|
|
|
|
|
|
|
|
if err != nil {
|
2022-01-27 10:35:26 +01:00
|
|
|
log.Warnf("login of user %#v failed: %s", username, err.Error())
|
2021-12-08 10:03:00 +01:00
|
|
|
rw.WriteHeader(http.StatusUnauthorized)
|
2022-02-01 17:48:56 +01:00
|
|
|
templates.Render(rw, r, "login.tmpl", &templates.Page{
|
2021-12-08 10:03:00 +01:00
|
|
|
Title: "Login failed",
|
2022-02-03 09:38:08 +01:00
|
|
|
Error: "Username or password incorrect",
|
2021-12-08 10:03:00 +01:00
|
|
|
})
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
session, err := sessionStore.New(r, "session")
|
|
|
|
if err != nil {
|
2022-01-27 10:35:26 +01:00
|
|
|
log.Errorf("session creation failed: %s", err.Error())
|
2021-12-08 10:03:00 +01:00
|
|
|
http.Error(rw, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-01-17 13:35:49 +01:00
|
|
|
session.Options.MaxAge = 30 * 24 * 60 * 60
|
2021-12-08 10:03:00 +01:00
|
|
|
session.Values["username"] = user.Username
|
2022-01-27 09:29:11 +01:00
|
|
|
session.Values["roles"] = user.Roles
|
2021-12-08 10:03:00 +01:00
|
|
|
if err := sessionStore.Save(r, rw, session); err != nil {
|
2022-01-27 10:35:26 +01:00
|
|
|
log.Errorf("session save failed: %s", err.Error())
|
2021-12-08 10:03:00 +01:00
|
|
|
http.Error(rw, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-01-27 10:35:26 +01:00
|
|
|
log.Infof("login successfull: user: %#v (roles: %v)", user.Username, user.Roles)
|
2021-12-08 10:03:00 +01:00
|
|
|
http.Redirect(rw, r, "/", http.StatusTemporaryRedirect)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
var ErrTokenInvalid error = errors.New("invalid token")
|
|
|
|
|
|
|
|
func authViaToken(r *http.Request) (*User, error) {
|
|
|
|
if JwtPublicKey == nil {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
rawtoken := r.Header.Get("X-Auth-Token")
|
|
|
|
if rawtoken == "" {
|
|
|
|
rawtoken = r.Header.Get("Authorization")
|
|
|
|
prefix := "Bearer "
|
|
|
|
if !strings.HasPrefix(rawtoken, prefix) {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
rawtoken = rawtoken[len(prefix):]
|
|
|
|
}
|
|
|
|
|
|
|
|
token, err := jwt.Parse(rawtoken, func(t *jwt.Token) (interface{}, error) {
|
|
|
|
if t.Method != jwt.SigningMethodEdDSA {
|
|
|
|
return nil, errors.New("only Ed25519/EdDSA supported")
|
|
|
|
}
|
|
|
|
return JwtPublicKey, nil
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return nil, ErrTokenInvalid
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := token.Claims.Valid(); err != nil {
|
|
|
|
return nil, ErrTokenInvalid
|
|
|
|
}
|
|
|
|
|
|
|
|
claims := token.Claims.(jwt.MapClaims)
|
|
|
|
sub, _ := claims["sub"].(string)
|
2022-01-27 09:29:11 +01:00
|
|
|
roles, _ := claims["roles"].([]string)
|
2022-01-17 13:35:49 +01:00
|
|
|
|
|
|
|
// TODO: Check if sub is still a valid user!
|
2021-12-08 10:03:00 +01:00
|
|
|
return &User{
|
2022-01-27 09:29:11 +01:00
|
|
|
Username: sub,
|
|
|
|
Roles: roles,
|
2021-12-08 10:03:00 +01:00
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Authenticate the user and put a User object in the
|
|
|
|
// context of the request. If authentication fails,
|
|
|
|
// do not continue but send client to the login screen.
|
|
|
|
func Auth(next http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
|
|
|
user, err := authViaToken(r)
|
|
|
|
if err == ErrTokenInvalid {
|
2022-01-27 10:35:26 +01:00
|
|
|
log.Warn("authentication failed: invalid token")
|
2021-12-08 10:03:00 +01:00
|
|
|
http.Error(rw, err.Error(), http.StatusUnauthorized)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if user != nil {
|
2022-01-17 13:35:49 +01:00
|
|
|
// Successfull authentication using a token
|
2021-12-08 10:03:00 +01:00
|
|
|
ctx := context.WithValue(r.Context(), ContextUserKey, user)
|
|
|
|
next.ServeHTTP(rw, r.WithContext(ctx))
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
session, err := sessionStore.Get(r, "session")
|
|
|
|
if err != nil {
|
2022-01-17 13:35:49 +01:00
|
|
|
// sessionStore.Get will return a new session if no current one is attached to this request.
|
2021-12-08 10:03:00 +01:00
|
|
|
http.Error(rw, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if session.IsNew {
|
2022-01-27 10:35:26 +01:00
|
|
|
log.Warn("authentication failed: no session or jwt found")
|
2021-12-08 10:03:00 +01:00
|
|
|
|
|
|
|
rw.WriteHeader(http.StatusUnauthorized)
|
2022-02-01 17:48:56 +01:00
|
|
|
templates.Render(rw, r, "login.tmpl", &templates.Page{
|
2021-12-08 10:03:00 +01:00
|
|
|
Title: "Authentication failed",
|
2022-02-03 09:38:08 +01:00
|
|
|
Error: "No valid session or JWT provided",
|
2021-12-08 10:03:00 +01:00
|
|
|
})
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-01-27 09:29:11 +01:00
|
|
|
username, _ := session.Values["username"].(string)
|
|
|
|
roles, _ := session.Values["roles"].([]string)
|
2021-12-08 10:03:00 +01:00
|
|
|
ctx := context.WithValue(r.Context(), ContextUserKey, &User{
|
2022-01-27 09:29:11 +01:00
|
|
|
Username: username,
|
|
|
|
Roles: roles,
|
2021-12-08 10:03:00 +01:00
|
|
|
})
|
|
|
|
next.ServeHTTP(rw, r.WithContext(ctx))
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// Generate a new JWT that can be used for authentication
|
|
|
|
func ProvideJWT(user *User) (string, error) {
|
|
|
|
if JwtPrivateKey == nil {
|
2022-01-27 09:29:11 +01:00
|
|
|
return "", errors.New("environment variable 'JWT_PRIVATE_KEY' not set")
|
2021-12-08 10:03:00 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
tok := jwt.NewWithClaims(jwt.SigningMethodEdDSA, jwt.MapClaims{
|
2022-01-27 09:29:11 +01:00
|
|
|
"sub": user.Username,
|
|
|
|
"roles": user.Roles,
|
2021-12-08 10:03:00 +01:00
|
|
|
})
|
|
|
|
|
|
|
|
return tok.SignedString(JwtPrivateKey)
|
|
|
|
}
|
|
|
|
|
|
|
|
func GetUser(ctx context.Context) *User {
|
|
|
|
x := ctx.Value(ContextUserKey)
|
|
|
|
if x == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return x.(*User)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Clears the session cookie
|
|
|
|
func Logout(rw http.ResponseWriter, r *http.Request) {
|
|
|
|
session, err := sessionStore.Get(r, "session")
|
|
|
|
if err != nil {
|
|
|
|
http.Error(rw, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if !session.IsNew {
|
|
|
|
session.Options.MaxAge = -1
|
|
|
|
if err := sessionStore.Save(r, rw, session); err != nil {
|
|
|
|
http.Error(rw, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-02-01 17:48:56 +01:00
|
|
|
templates.Render(rw, r, "login.tmpl", &templates.Page{
|
2021-12-08 10:03:00 +01:00
|
|
|
Title: "Logout successful",
|
2022-02-03 09:38:08 +01:00
|
|
|
Info: "Logout successful",
|
2021-12-08 10:03:00 +01:00
|
|
|
})
|
|
|
|
}
|