2024-04-11 23:04:30 +02:00
|
|
|
// Copyright (C) NHR@FAU, University Erlangen-Nuremberg.
|
2024-03-13 09:37:12 +01:00
|
|
|
// 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 (
|
|
|
|
"context"
|
2024-03-13 17:09:36 +01:00
|
|
|
"crypto/rand"
|
|
|
|
"encoding/base64"
|
|
|
|
"io"
|
2024-03-13 09:37:12 +01:00
|
|
|
"net/http"
|
2024-03-28 12:01:13 +01:00
|
|
|
"os"
|
2024-03-13 17:09:36 +01:00
|
|
|
"time"
|
2024-03-13 09:37:12 +01:00
|
|
|
|
2024-03-13 17:09:36 +01:00
|
|
|
"github.com/ClusterCockpit/cc-backend/internal/config"
|
2024-03-28 12:01:13 +01:00
|
|
|
"github.com/ClusterCockpit/cc-backend/internal/repository"
|
|
|
|
"github.com/ClusterCockpit/cc-backend/pkg/log"
|
|
|
|
"github.com/ClusterCockpit/cc-backend/pkg/schema"
|
2024-03-13 09:37:12 +01:00
|
|
|
"github.com/coreos/go-oidc/v3/oidc"
|
|
|
|
"github.com/gorilla/mux"
|
|
|
|
"golang.org/x/oauth2"
|
|
|
|
)
|
|
|
|
|
|
|
|
type OIDC struct {
|
2024-03-28 12:01:13 +01:00
|
|
|
client *oauth2.Config
|
|
|
|
provider *oidc.Provider
|
|
|
|
authentication *Authentication
|
|
|
|
clientID string
|
2024-03-13 09:37:12 +01:00
|
|
|
}
|
|
|
|
|
2024-03-13 17:09:36 +01:00
|
|
|
func randString(nByte int) (string, error) {
|
|
|
|
b := make([]byte, nByte)
|
|
|
|
if _, err := io.ReadFull(rand.Reader, b); err != nil {
|
|
|
|
return "", err
|
2024-03-13 09:37:12 +01:00
|
|
|
}
|
2024-03-13 17:09:36 +01:00
|
|
|
return base64.RawURLEncoding.EncodeToString(b), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func setCallbackCookie(w http.ResponseWriter, r *http.Request, name, value string) {
|
|
|
|
c := &http.Cookie{
|
|
|
|
Name: name,
|
|
|
|
Value: value,
|
|
|
|
MaxAge: int(time.Hour.Seconds()),
|
|
|
|
Secure: r.TLS != nil,
|
|
|
|
HttpOnly: true,
|
|
|
|
}
|
|
|
|
http.SetCookie(w, c)
|
|
|
|
}
|
2024-03-13 09:37:12 +01:00
|
|
|
|
2024-03-28 12:01:13 +01:00
|
|
|
func NewOIDC(a *Authentication) *OIDC {
|
2024-03-28 14:22:23 +01:00
|
|
|
provider, err := oidc.NewProvider(context.Background(), config.Keys.OpenIDConfig.Provider)
|
2024-03-13 09:37:12 +01:00
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
2024-03-28 12:01:13 +01:00
|
|
|
clientID := os.Getenv("OID_CLIENT_ID")
|
|
|
|
if clientID == "" {
|
|
|
|
log.Warn("environment variable 'OID_CLIENT_ID' not set (Open ID connect auth will not work)")
|
|
|
|
}
|
|
|
|
clientSecret := os.Getenv("OID_CLIENT_SECRET")
|
|
|
|
if clientSecret == "" {
|
|
|
|
log.Warn("environment variable 'OID_CLIENT_SECRET' not set (Open ID connect auth will not work)")
|
|
|
|
}
|
2024-03-28 13:18:25 +01:00
|
|
|
|
2024-03-28 12:01:13 +01:00
|
|
|
client := &oauth2.Config{
|
|
|
|
ClientID: clientID,
|
|
|
|
ClientSecret: clientSecret,
|
2024-03-13 17:09:36 +01:00
|
|
|
Endpoint: provider.Endpoint(),
|
2024-03-28 13:18:25 +01:00
|
|
|
RedirectURL: "oidc-callback",
|
2024-03-13 17:09:36 +01:00
|
|
|
Scopes: []string{oidc.ScopeOpenID, "profile", "email"},
|
|
|
|
}
|
|
|
|
|
2024-03-28 12:01:13 +01:00
|
|
|
oa := &OIDC{provider: provider, client: client, clientID: clientID, authentication: a}
|
|
|
|
|
|
|
|
return oa
|
|
|
|
}
|
|
|
|
|
|
|
|
func (oa *OIDC) RegisterEndpoints(r *mux.Router) {
|
2024-03-13 09:37:12 +01:00
|
|
|
r.HandleFunc("/oidc-login", oa.OAuth2Login)
|
|
|
|
r.HandleFunc("/oidc-callback", oa.OAuth2Callback)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (oa *OIDC) OAuth2Callback(rw http.ResponseWriter, r *http.Request) {
|
2024-03-13 17:09:36 +01:00
|
|
|
c, err := r.Cookie("state")
|
|
|
|
if err != nil {
|
2024-03-28 12:01:13 +01:00
|
|
|
http.Error(rw, "state cookie not found", http.StatusBadRequest)
|
2024-03-13 17:09:36 +01:00
|
|
|
return
|
|
|
|
}
|
2024-03-28 12:01:13 +01:00
|
|
|
state := c.Value
|
2024-03-13 17:09:36 +01:00
|
|
|
|
2024-03-28 12:01:13 +01:00
|
|
|
c, err = r.Cookie("verifier")
|
2024-03-28 14:22:23 +01:00
|
|
|
if err != nil {
|
|
|
|
http.Error(rw, "verifier cookie not found", http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
2024-03-28 12:01:13 +01:00
|
|
|
codeVerifier := c.Value
|
2024-03-13 17:09:36 +01:00
|
|
|
|
2024-03-13 09:37:12 +01:00
|
|
|
_ = r.ParseForm()
|
2024-03-13 17:09:36 +01:00
|
|
|
if r.Form.Get("state") != state {
|
2024-03-13 09:37:12 +01:00
|
|
|
http.Error(rw, "State invalid", http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
code := r.Form.Get("code")
|
|
|
|
if code == "" {
|
|
|
|
http.Error(rw, "Code not found", http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
2024-03-13 17:09:36 +01:00
|
|
|
token, err := oa.client.Exchange(context.Background(), code, oauth2.VerifierOption(codeVerifier))
|
|
|
|
if err != nil {
|
|
|
|
http.Error(rw, "Failed to exchange token: "+err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
userInfo, err := oa.provider.UserInfo(context.Background(), oauth2.StaticTokenSource(token))
|
2024-03-13 09:37:12 +01:00
|
|
|
if err != nil {
|
2024-03-13 17:09:36 +01:00
|
|
|
http.Error(rw, "Failed to get userinfo: "+err.Error(), http.StatusInternalServerError)
|
2024-03-13 09:37:12 +01:00
|
|
|
return
|
|
|
|
}
|
2024-03-28 12:01:13 +01:00
|
|
|
|
|
|
|
// // Extract the ID Token from OAuth2 token.
|
|
|
|
// rawIDToken, ok := token.Extra("id_token").(string)
|
|
|
|
// if !ok {
|
|
|
|
// http.Error(rw, "Cannot access idToken", http.StatusInternalServerError)
|
|
|
|
// }
|
|
|
|
//
|
|
|
|
// verifier := oa.provider.Verifier(&oidc.Config{ClientID: oa.clientID})
|
|
|
|
// // Parse and verify ID Token payload.
|
|
|
|
// idToken, err := verifier.Verify(context.Background(), rawIDToken)
|
|
|
|
// if err != nil {
|
|
|
|
// http.Error(rw, "Failed to extract idToken: "+err.Error(), http.StatusInternalServerError)
|
|
|
|
// }
|
|
|
|
|
|
|
|
projects := make([]string, 0)
|
|
|
|
|
|
|
|
// Extract custom claims
|
|
|
|
var claims struct {
|
|
|
|
Username string `json:"preferred_username"`
|
|
|
|
Name string `json:"name"`
|
|
|
|
Profile struct {
|
|
|
|
Client struct {
|
|
|
|
Roles []string `json:"roles"`
|
|
|
|
} `json:"clustercockpit"`
|
|
|
|
} `json:"resource_access"`
|
|
|
|
}
|
|
|
|
if err := userInfo.Claims(&claims); err != nil {
|
|
|
|
http.Error(rw, "Failed to extract Claims: "+err.Error(), http.StatusInternalServerError)
|
|
|
|
}
|
|
|
|
|
|
|
|
var roles []string
|
|
|
|
for _, r := range claims.Profile.Client.Roles {
|
|
|
|
switch r {
|
|
|
|
case "user":
|
|
|
|
roles = append(roles, schema.GetRoleString(schema.RoleUser))
|
|
|
|
case "admin":
|
|
|
|
roles = append(roles, schema.GetRoleString(schema.RoleAdmin))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-03-28 14:22:23 +01:00
|
|
|
if len(roles) == 0 {
|
2024-03-28 12:01:13 +01:00
|
|
|
roles = append(roles, schema.GetRoleString(schema.RoleUser))
|
|
|
|
}
|
|
|
|
|
|
|
|
user := &schema.User{
|
|
|
|
Username: claims.Username,
|
|
|
|
Name: claims.Name,
|
|
|
|
Roles: roles,
|
|
|
|
Projects: projects,
|
|
|
|
AuthSource: schema.AuthViaOIDC,
|
|
|
|
}
|
2024-03-28 14:22:23 +01:00
|
|
|
|
|
|
|
if config.Keys.OpenIDConfig.SyncUserOnLogin {
|
|
|
|
persistUser(user)
|
|
|
|
}
|
|
|
|
|
2024-03-28 12:01:13 +01:00
|
|
|
oa.authentication.SaveSession(rw, r, user)
|
|
|
|
log.Infof("login successfull: user: %#v (roles: %v, projects: %v)", user.Username, user.Roles, user.Projects)
|
|
|
|
ctx := context.WithValue(r.Context(), repository.ContextUserKey, user)
|
|
|
|
http.RedirectHandler("/", http.StatusTemporaryRedirect).ServeHTTP(rw, r.WithContext(ctx))
|
2024-03-13 09:37:12 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func (oa *OIDC) OAuth2Login(rw http.ResponseWriter, r *http.Request) {
|
2024-03-13 17:09:36 +01:00
|
|
|
state, err := randString(16)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(rw, "Internal error", http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
2024-03-28 12:01:13 +01:00
|
|
|
setCallbackCookie(rw, r, "state", state)
|
2024-03-13 17:09:36 +01:00
|
|
|
|
2024-03-13 09:37:12 +01:00
|
|
|
// use PKCE to protect against CSRF attacks
|
2024-03-13 17:09:36 +01:00
|
|
|
codeVerifier := oauth2.GenerateVerifier()
|
2024-03-28 12:01:13 +01:00
|
|
|
setCallbackCookie(rw, r, "verifier", codeVerifier)
|
2024-03-13 09:37:12 +01:00
|
|
|
|
|
|
|
// Redirect user to consent page to ask for permission
|
2024-03-13 17:09:36 +01:00
|
|
|
url := oa.client.AuthCodeURL(state, oauth2.AccessTypeOffline, oauth2.S256ChallengeOption(codeVerifier))
|
2024-03-13 09:37:12 +01:00
|
|
|
http.Redirect(rw, r, url, http.StatusFound)
|
|
|
|
}
|