2024-02-07 01:18:17 +00:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
2024-02-07 10:54:37 +00:00
|
|
|
"context"
|
2024-02-08 01:16:14 +00:00
|
|
|
"database/sql"
|
2024-02-07 10:54:37 +00:00
|
|
|
"encoding/json"
|
2024-02-08 01:16:14 +00:00
|
|
|
"errors"
|
2024-02-10 11:59:45 +00:00
|
|
|
"fmt"
|
2024-02-08 01:16:14 +00:00
|
|
|
"github.com/1f349/lavender/database"
|
|
|
|
"github.com/1f349/lavender/issuer"
|
2024-02-07 01:18:17 +00:00
|
|
|
"github.com/1f349/lavender/pages"
|
2024-05-16 03:06:10 +01:00
|
|
|
"github.com/1f349/mjwt"
|
2024-02-15 15:23:10 +00:00
|
|
|
"github.com/1f349/mjwt/auth"
|
|
|
|
"github.com/golang-jwt/jwt/v4"
|
2024-02-07 01:18:17 +00:00
|
|
|
"github.com/google/uuid"
|
|
|
|
"github.com/julienschmidt/httprouter"
|
|
|
|
"golang.org/x/oauth2"
|
|
|
|
"net/http"
|
|
|
|
"net/url"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2024-02-07 10:54:37 +00:00
|
|
|
func (h *HttpServer) loginGet(rw http.ResponseWriter, req *http.Request, _ httprouter.Params, auth UserAuth) {
|
|
|
|
if !auth.IsGuest() {
|
|
|
|
h.SafeRedirect(rw, req)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-02-07 01:18:17 +00:00
|
|
|
cookie, err := req.Cookie("lavender-login-name")
|
|
|
|
if err == nil && cookie.Valid() == nil {
|
|
|
|
pages.RenderPageTemplate(rw, "login-memory", map[string]any{
|
|
|
|
"ServiceName": h.conf.ServiceName,
|
|
|
|
"LoginName": cookie.Value,
|
2024-02-10 02:53:58 +00:00
|
|
|
"Redirect": req.URL.Query().Get("redirect"),
|
2024-02-07 01:18:17 +00:00
|
|
|
})
|
|
|
|
return
|
|
|
|
}
|
|
|
|
pages.RenderPageTemplate(rw, "login", map[string]any{
|
|
|
|
"ServiceName": h.conf.ServiceName,
|
2024-02-10 02:53:58 +00:00
|
|
|
"Redirect": req.URL.Query().Get("redirect"),
|
2024-02-07 01:18:17 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2024-02-07 10:54:37 +00:00
|
|
|
func (h *HttpServer) loginPost(rw http.ResponseWriter, req *http.Request, _ httprouter.Params, auth UserAuth) {
|
|
|
|
if !auth.IsGuest() {
|
|
|
|
h.SafeRedirect(rw, req)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-02-07 01:18:17 +00:00
|
|
|
if req.PostFormValue("not-you") == "1" {
|
|
|
|
http.SetCookie(rw, &http.Cookie{
|
|
|
|
Name: "lavender-login-name",
|
|
|
|
Value: "",
|
|
|
|
Path: "/",
|
|
|
|
MaxAge: -1,
|
|
|
|
Secure: true,
|
2024-02-15 14:44:58 +00:00
|
|
|
SameSite: http.SameSiteLaxMode,
|
2024-02-07 01:18:17 +00:00
|
|
|
})
|
|
|
|
http.Redirect(rw, req, (&url.URL{
|
|
|
|
Path: "/login",
|
|
|
|
}).String(), http.StatusFound)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
loginName := req.PostFormValue("loginname")
|
|
|
|
login := h.manager.FindServiceFromLogin(loginName)
|
|
|
|
if login == nil {
|
|
|
|
http.Error(rw, "No login service defined for this username", http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
// the @ must exist if the service is defined
|
|
|
|
n := strings.IndexByte(loginName, '@')
|
|
|
|
loginUn := loginName[:n]
|
|
|
|
|
|
|
|
now := time.Now()
|
|
|
|
future := now.AddDate(1, 0, 0)
|
|
|
|
http.SetCookie(rw, &http.Cookie{
|
|
|
|
Name: "lavender-login-name",
|
|
|
|
Value: loginName,
|
|
|
|
Path: "/",
|
|
|
|
Expires: future,
|
|
|
|
MaxAge: int(future.Sub(now).Seconds()),
|
|
|
|
Secure: true,
|
2024-02-15 14:44:58 +00:00
|
|
|
SameSite: http.SameSiteLaxMode,
|
2024-02-07 01:18:17 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
// save state for use later
|
|
|
|
state := login.Config.Namespace + ":" + uuid.NewString()
|
2024-05-31 13:51:44 +01:00
|
|
|
h.flowState.Set(state, flowStateData{loginName, login, req.PostFormValue("redirect")}, time.Now().Add(15*time.Minute))
|
2024-02-07 01:18:17 +00:00
|
|
|
|
|
|
|
// generate oauth2 config and redirect to authorize URL
|
|
|
|
oa2conf := login.OAuth2Config
|
|
|
|
oa2conf.RedirectURL = h.conf.BaseUrl + "/callback"
|
|
|
|
nextUrl := oa2conf.AuthCodeURL(state, oauth2.SetAuthURLParam("login_name", loginUn))
|
|
|
|
http.Redirect(rw, req, nextUrl, http.StatusFound)
|
|
|
|
}
|
2024-02-07 10:54:37 +00:00
|
|
|
|
2024-05-31 13:51:44 +01:00
|
|
|
func (h *HttpServer) loginCallback(rw http.ResponseWriter, req *http.Request, _ httprouter.Params, userAuth UserAuth) {
|
2024-02-07 10:54:37 +00:00
|
|
|
flowState, ok := h.flowState.Get(req.FormValue("state"))
|
|
|
|
if !ok {
|
|
|
|
http.Error(rw, "Invalid flow state", http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
token, err := flowState.sso.OAuth2Config.Exchange(context.Background(), req.FormValue("code"), oauth2.SetAuthURLParam("redirect_uri", h.conf.BaseUrl+"/callback"))
|
|
|
|
if err != nil {
|
|
|
|
http.Error(rw, "Failed to exchange code for token", http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-05-31 13:51:44 +01:00
|
|
|
userAuth, err = h.updateExternalUserInfo(req, flowState.sso, token)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(rw, "Failed to update external user info", http.StatusInternalServerError)
|
2024-02-07 10:54:37 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-05-31 13:51:44 +01:00
|
|
|
if h.setLoginDataCookie(rw, userAuth, flowState.loginName) {
|
|
|
|
http.Error(rw, "Failed to save login cookie", http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if flowState.redirect != "" {
|
|
|
|
req.Form.Set("redirect", flowState.redirect)
|
|
|
|
}
|
|
|
|
h.SafeRedirect(rw, req)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *HttpServer) updateExternalUserInfo(req *http.Request, sso *issuer.WellKnownOIDC, token *oauth2.Token) (UserAuth, error) {
|
|
|
|
sessionData, err := h.fetchUserInfo(sso, token)
|
|
|
|
if err != nil || sessionData.Subject == "" {
|
|
|
|
return UserAuth{}, fmt.Errorf("failed to fetch user info")
|
|
|
|
}
|
|
|
|
|
|
|
|
err = h.DbTxError(func(tx *database.Queries) error {
|
2024-02-22 12:41:21 +00:00
|
|
|
jBytes, err := json.Marshal(sessionData.UserInfo)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2024-05-17 21:40:31 +01:00
|
|
|
_, err = tx.GetUser(req.Context(), sessionData.Subject)
|
2024-02-08 01:16:14 +00:00
|
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
|
|
uEmail := sessionData.UserInfo.GetStringOrDefault("email", "unknown@localhost")
|
|
|
|
uEmailVerified, _ := sessionData.UserInfo.GetBoolean("email_verified")
|
2024-05-17 21:40:31 +01:00
|
|
|
return tx.AddUser(req.Context(), database.AddUserParams{
|
|
|
|
Subject: sessionData.Subject,
|
|
|
|
Email: uEmail,
|
|
|
|
EmailVerified: uEmailVerified,
|
|
|
|
Roles: "",
|
|
|
|
Userinfo: string(jBytes),
|
|
|
|
UpdatedAt: time.Now(),
|
|
|
|
Active: true,
|
|
|
|
})
|
2024-02-08 01:16:14 +00:00
|
|
|
}
|
2024-02-22 12:41:21 +00:00
|
|
|
uEmail := sessionData.UserInfo.GetStringOrDefault("email", "unknown@localhost")
|
|
|
|
uEmailVerified, _ := sessionData.UserInfo.GetBoolean("email_verified")
|
2024-05-17 21:40:31 +01:00
|
|
|
return tx.UpdateUserInfo(req.Context(), database.UpdateUserInfoParams{
|
|
|
|
Email: sessionData.Subject,
|
|
|
|
EmailVerified: uEmailVerified,
|
|
|
|
Userinfo: string(jBytes),
|
|
|
|
Subject: uEmail,
|
|
|
|
})
|
2024-05-31 13:51:44 +01:00
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return UserAuth{}, err
|
2024-02-07 10:54:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// only continues if the above tx succeeds
|
2024-05-31 13:51:44 +01:00
|
|
|
if err := h.DbTxError(func(tx *database.Queries) error {
|
2024-05-17 21:40:31 +01:00
|
|
|
return tx.UpdateUserToken(req.Context(), database.UpdateUserTokenParams{
|
2024-05-18 01:27:54 +01:00
|
|
|
AccessToken: sql.NullString{String: token.AccessToken, Valid: true},
|
|
|
|
RefreshToken: sql.NullString{String: token.RefreshToken, Valid: true},
|
|
|
|
Expiry: sql.NullTime{Time: token.Expiry, Valid: true},
|
2024-05-31 13:51:44 +01:00
|
|
|
Subject: sessionData.Subject,
|
2024-05-17 21:40:31 +01:00
|
|
|
})
|
2024-05-31 13:51:44 +01:00
|
|
|
}); err != nil {
|
|
|
|
return UserAuth{}, err
|
2024-02-10 11:59:45 +00:00
|
|
|
}
|
|
|
|
|
2024-05-31 13:51:44 +01:00
|
|
|
return sessionData, nil
|
2024-02-07 10:54:37 +00:00
|
|
|
}
|
|
|
|
|
2024-05-31 13:51:44 +01:00
|
|
|
const twelveHours = 12 * time.Hour
|
|
|
|
const oneWeek = 7 * 24 * time.Hour
|
2024-02-15 15:23:10 +00:00
|
|
|
|
2024-05-31 13:51:44 +01:00
|
|
|
type lavenderLoginAccess struct {
|
2024-05-16 03:06:10 +01:00
|
|
|
UserInfo UserInfoFields `json:"user_info"`
|
|
|
|
auth.AccessTokenClaims
|
|
|
|
}
|
|
|
|
|
2024-05-31 13:51:44 +01:00
|
|
|
func (l lavenderLoginAccess) Valid() error { return l.AccessTokenClaims.Valid() }
|
|
|
|
|
|
|
|
func (l lavenderLoginAccess) Type() string { return "lavender-login-access" }
|
|
|
|
|
|
|
|
type lavenderLoginRefresh struct {
|
|
|
|
Login string `json:"login"`
|
|
|
|
auth.RefreshTokenClaims
|
|
|
|
}
|
|
|
|
|
|
|
|
func (l lavenderLoginRefresh) Valid() error { return l.RefreshTokenClaims.Valid() }
|
2024-05-16 03:06:10 +01:00
|
|
|
|
2024-05-31 13:51:44 +01:00
|
|
|
func (l lavenderLoginRefresh) Type() string { return "lavender-login-refresh" }
|
2024-05-16 03:06:10 +01:00
|
|
|
|
2024-05-31 13:51:44 +01:00
|
|
|
func (h *HttpServer) setLoginDataCookie(rw http.ResponseWriter, authData UserAuth, loginName string) bool {
|
2024-07-27 21:46:58 +01:00
|
|
|
ps := auth.NewPermStorage()
|
2024-05-31 13:51:44 +01:00
|
|
|
accId := uuid.NewString()
|
|
|
|
gen, err := h.signingKey.GenerateJwt(authData.Subject, accId, jwt.ClaimStrings{h.conf.BaseUrl}, twelveHours, lavenderLoginAccess{
|
2024-05-16 03:06:10 +01:00
|
|
|
UserInfo: authData.UserInfo,
|
|
|
|
AccessTokenClaims: auth.AccessTokenClaims{Perms: ps},
|
|
|
|
})
|
2024-02-08 01:16:14 +00:00
|
|
|
if err != nil {
|
2024-02-15 15:23:10 +00:00
|
|
|
http.Error(rw, "Failed to generate cookie token", http.StatusInternalServerError)
|
2024-02-08 01:16:14 +00:00
|
|
|
return true
|
|
|
|
}
|
2024-05-31 13:51:44 +01:00
|
|
|
ref, err := h.signingKey.GenerateJwt(authData.Subject, uuid.NewString(), jwt.ClaimStrings{h.conf.BaseUrl}, oneWeek, lavenderLoginRefresh{
|
|
|
|
Login: loginName,
|
|
|
|
RefreshTokenClaims: auth.RefreshTokenClaims{AccessTokenId: accId},
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
http.Error(rw, "Failed to generate cookie token", http.StatusInternalServerError)
|
|
|
|
return true
|
|
|
|
}
|
2024-02-07 10:54:37 +00:00
|
|
|
http.SetCookie(rw, &http.Cookie{
|
2024-05-31 13:51:44 +01:00
|
|
|
Name: "lavender-login-access",
|
2024-02-15 15:23:10 +00:00
|
|
|
Value: gen,
|
2024-02-07 10:54:37 +00:00
|
|
|
Path: "/",
|
|
|
|
Secure: true,
|
2024-05-31 13:51:44 +01:00
|
|
|
HttpOnly: true,
|
|
|
|
SameSite: http.SameSiteLaxMode,
|
|
|
|
})
|
|
|
|
http.SetCookie(rw, &http.Cookie{
|
|
|
|
Name: "lavender-login-refresh",
|
|
|
|
Value: ref,
|
|
|
|
Path: "/",
|
|
|
|
Expires: time.Now().AddDate(0, 0, 10),
|
|
|
|
Secure: true,
|
|
|
|
HttpOnly: true,
|
2024-02-15 14:44:58 +00:00
|
|
|
SameSite: http.SameSiteLaxMode,
|
2024-02-07 10:54:37 +00:00
|
|
|
})
|
|
|
|
return false
|
|
|
|
}
|
2024-02-08 01:16:14 +00:00
|
|
|
|
2024-07-27 21:46:58 +01:00
|
|
|
func readJwtCookie[T mjwt.Claims](req *http.Request, cookieName string, signingKey *mjwt.KeyStore) (mjwt.BaseTypeClaims[T], error) {
|
2024-05-31 13:51:44 +01:00
|
|
|
loginCookie, err := req.Cookie(cookieName)
|
|
|
|
if err != nil {
|
|
|
|
return mjwt.BaseTypeClaims[T]{}, err
|
|
|
|
}
|
|
|
|
_, b, err := mjwt.ExtractClaims[T](signingKey, loginCookie.Value)
|
|
|
|
if err != nil {
|
|
|
|
return mjwt.BaseTypeClaims[T]{}, err
|
|
|
|
}
|
|
|
|
return b, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *HttpServer) readLoginAccessCookie(rw http.ResponseWriter, req *http.Request, u *UserAuth) error {
|
2024-07-27 21:46:58 +01:00
|
|
|
loginData, err := readJwtCookie[lavenderLoginAccess](req, "lavender-login-access", h.signingKey.KeyStore())
|
2024-05-31 13:51:44 +01:00
|
|
|
if err != nil {
|
|
|
|
return h.readLoginRefreshCookie(rw, req, u)
|
|
|
|
}
|
|
|
|
*u = UserAuth{
|
|
|
|
Subject: loginData.Subject,
|
|
|
|
UserInfo: loginData.Claims.UserInfo,
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *HttpServer) readLoginRefreshCookie(rw http.ResponseWriter, req *http.Request, userAuth *UserAuth) error {
|
2024-07-27 21:46:58 +01:00
|
|
|
refreshData, err := readJwtCookie[lavenderLoginRefresh](req, "lavender-login-refresh", h.signingKey.KeyStore())
|
2024-02-08 01:16:14 +00:00
|
|
|
if err != nil {
|
2024-05-16 03:06:10 +01:00
|
|
|
return err
|
2024-02-08 01:16:14 +00:00
|
|
|
}
|
2024-05-31 13:51:44 +01:00
|
|
|
|
|
|
|
sso := h.manager.FindServiceFromLogin(refreshData.Claims.Login)
|
|
|
|
|
|
|
|
var oauthToken *oauth2.Token
|
|
|
|
|
|
|
|
err = h.DbTxError(func(tx *database.Queries) error {
|
|
|
|
token, err := tx.GetUserToken(req.Context(), refreshData.Subject)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if !token.AccessToken.Valid || !token.RefreshToken.Valid || !token.Expiry.Valid {
|
|
|
|
return fmt.Errorf("invalid oauth token")
|
|
|
|
}
|
|
|
|
oauthToken = &oauth2.Token{
|
|
|
|
AccessToken: token.AccessToken.String,
|
|
|
|
RefreshToken: token.RefreshToken.String,
|
|
|
|
Expiry: token.Expiry.Time,
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
|
|
|
|
*userAuth, err = h.updateExternalUserInfo(req, sso, oauthToken)
|
2024-02-08 01:16:14 +00:00
|
|
|
if err != nil {
|
2024-05-16 03:06:10 +01:00
|
|
|
return err
|
2024-02-08 01:16:14 +00:00
|
|
|
}
|
2024-05-31 13:51:44 +01:00
|
|
|
|
|
|
|
if h.setLoginDataCookie(rw, *userAuth, refreshData.Claims.Login) {
|
|
|
|
http.Error(rw, "Failed to save login cookie", http.StatusInternalServerError)
|
|
|
|
return fmt.Errorf("failed to save login cookie: %w", ErrAuthHttpError)
|
2024-02-08 01:16:14 +00:00
|
|
|
}
|
2024-05-16 03:06:10 +01:00
|
|
|
return nil
|
2024-02-08 01:16:14 +00:00
|
|
|
}
|
|
|
|
|
2024-02-15 15:09:14 +00:00
|
|
|
func (h *HttpServer) fetchUserInfo(sso *issuer.WellKnownOIDC, token *oauth2.Token) (UserAuth, error) {
|
2024-02-08 01:16:14 +00:00
|
|
|
res, err := sso.OAuth2Config.Client(context.Background(), token).Get(sso.UserInfoEndpoint)
|
|
|
|
if err != nil || res.StatusCode != http.StatusOK {
|
2024-02-15 15:09:14 +00:00
|
|
|
return UserAuth{}, fmt.Errorf("request failed")
|
2024-02-08 01:16:14 +00:00
|
|
|
}
|
|
|
|
defer res.Body.Close()
|
|
|
|
|
|
|
|
var userInfoJson UserInfoFields
|
|
|
|
if err := json.NewDecoder(res.Body).Decode(&userInfoJson); err != nil {
|
2024-02-15 15:09:14 +00:00
|
|
|
return UserAuth{}, err
|
2024-02-08 01:16:14 +00:00
|
|
|
}
|
|
|
|
subject, ok := userInfoJson.GetString("sub")
|
|
|
|
if !ok {
|
2024-02-15 15:09:14 +00:00
|
|
|
return UserAuth{}, fmt.Errorf("invalid subject")
|
2024-02-08 01:16:14 +00:00
|
|
|
}
|
|
|
|
subject += "@" + sso.Config.Namespace
|
|
|
|
|
2024-02-15 15:09:14 +00:00
|
|
|
return UserAuth{
|
2024-05-16 03:06:10 +01:00
|
|
|
Subject: subject,
|
|
|
|
UserInfo: userInfoJson,
|
2024-02-10 11:59:45 +00:00
|
|
|
}, nil
|
2024-02-08 01:16:14 +00:00
|
|
|
}
|