273 lines
9.5 KiB
Go
273 lines
9.5 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"errors"
|
|
"net/http"
|
|
"net/url"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/coreos/go-oidc/v3/oidc"
|
|
"golang.org/x/oauth2"
|
|
|
|
"sea-vhost/internal/auth"
|
|
"sea-vhost/internal/store"
|
|
)
|
|
|
|
const oidcProviderName = "oidc"
|
|
|
|
func (s *Server) oidcStatus(w http.ResponseWriter, r *http.Request) {
|
|
cfg := s.readServiceConfig(r, "oidc_config")
|
|
writeJSON(w, http.StatusOK, map[string]any{"enabled": validOIDCConfig(cfg), "autoCreate": cfg.AutoCreate, "userPasswordLogin": oidcPasswordAllowed(cfg, "tenant"), "adminPasswordLogin": oidcPasswordAllowed(cfg, "admin"), "hostPasswordLogin": true})
|
|
}
|
|
|
|
func (s *Server) oidcStart(w http.ResponseWriter, r *http.Request) {
|
|
if _, err := r.Cookie(impersonationCookie); err == nil {
|
|
writeError(w, 403, "请先退出代入模式再进行第三方登录或绑定")
|
|
return
|
|
}
|
|
cfg := s.readServiceConfig(r, "oidc_config")
|
|
if !validOIDCConfig(cfg) {
|
|
writeError(w, http.StatusServiceUnavailable, "OIDC 登录尚未启用")
|
|
return
|
|
}
|
|
mode := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("mode")))
|
|
if mode == "" {
|
|
mode = "login"
|
|
}
|
|
var userID *uint64
|
|
var parentSession string
|
|
if mode == "bind" {
|
|
cookie, err := r.Cookie("sea_session")
|
|
if err != nil {
|
|
writeError(w, http.StatusUnauthorized, "请先使用密码登录后绑定")
|
|
return
|
|
}
|
|
user, err := s.userFromToken(r.Context(), cookie.Value)
|
|
if err != nil {
|
|
writeError(w, http.StatusUnauthorized, "登录已失效")
|
|
return
|
|
}
|
|
if user.Role == "host" {
|
|
writeError(w, 403, "主机账号不可绑定 SSO")
|
|
return
|
|
}
|
|
userID = &user.ID
|
|
parentSession = cookie.Value
|
|
} else if mode != "login" {
|
|
writeError(w, http.StatusBadRequest, "OIDC 模式无效")
|
|
return
|
|
}
|
|
provider, oauth, err := oidcClient(r.Context(), cfg)
|
|
if err != nil {
|
|
writeError(w, http.StatusBadGateway, "无法连接 OIDC 服务")
|
|
return
|
|
}
|
|
_ = provider
|
|
state, err := randomURLToken(32)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "无法创建 OIDC 状态")
|
|
return
|
|
}
|
|
verifier, err := randomURLToken(48)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "无法创建 OIDC 校验参数")
|
|
return
|
|
}
|
|
nonce, err := randomURLToken(32)
|
|
if err != nil || s.store.CreateScopedOIDCState(r.Context(), state, userID, mode, verifier, nonce, oidcProviderKey(cfg), parentSession, time.Now().Add(10*time.Minute)) != nil {
|
|
writeError(w, http.StatusInternalServerError, "无法保存 OIDC 状态")
|
|
return
|
|
}
|
|
challenge := sha256.Sum256([]byte(verifier))
|
|
authorizationURL := oauth.AuthCodeURL(state,
|
|
oidc.Nonce(nonce),
|
|
oauth2.SetAuthURLParam("code_challenge", base64.RawURLEncoding.EncodeToString(challenge[:])),
|
|
oauth2.SetAuthURLParam("code_challenge_method", "S256"),
|
|
)
|
|
setOIDCCookie(w, "sea_oidc_flow", state, 600)
|
|
writeJSON(w, http.StatusOK, map[string]string{"url": authorizationURL})
|
|
}
|
|
|
|
func (s *Server) oidcCallback(w http.ResponseWriter, r *http.Request) {
|
|
if _, err := r.Cookie(impersonationCookie); err == nil {
|
|
writeError(w, 403, "请先退出代入模式再进行第三方登录或绑定")
|
|
return
|
|
}
|
|
stateValue := strings.TrimSpace(r.URL.Query().Get("state"))
|
|
code := strings.TrimSpace(r.URL.Query().Get("code"))
|
|
if stateValue == "" || code == "" || len(stateValue) > 256 || len(code) > 4096 {
|
|
redirectOIDCResult(w, r, "error")
|
|
return
|
|
}
|
|
flow, flowErr := r.Cookie("sea_oidc_flow")
|
|
if flowErr != nil || flow.Value != stateValue {
|
|
redirectOIDCResult(w, r, "expired")
|
|
return
|
|
}
|
|
setOIDCCookie(w, "sea_oidc_flow", "", -1)
|
|
state, err := s.store.ConsumeOIDCState(r.Context(), stateValue)
|
|
if err != nil {
|
|
redirectOIDCResult(w, r, "expired")
|
|
return
|
|
}
|
|
cfg := s.readServiceConfig(r, "oidc_config")
|
|
if state.ProviderKey != oidcProviderKey(cfg) {
|
|
redirectOIDCResult(w, r, "provider_changed")
|
|
return
|
|
}
|
|
if state.Mode == "bind" && state.UserID != nil && !s.store.ActiveOIDCBindSession(r.Context(), state.SessionHash, *state.UserID) {
|
|
redirectOIDCResult(w, r, "expired")
|
|
return
|
|
}
|
|
|
|
provider, oauth, err := oidcClient(r.Context(), cfg)
|
|
if err != nil {
|
|
redirectOIDCResult(w, r, "provider")
|
|
return
|
|
}
|
|
token, err := oauth.Exchange(r.Context(), code, oauth2.SetAuthURLParam("code_verifier", state.Verifier))
|
|
if err != nil {
|
|
redirectOIDCResult(w, r, "exchange")
|
|
return
|
|
}
|
|
rawIDToken, ok := token.Extra("id_token").(string)
|
|
if !ok || rawIDToken == "" {
|
|
redirectOIDCResult(w, r, "token")
|
|
return
|
|
}
|
|
idToken, err := provider.Verifier(&oidc.Config{ClientID: cfg.ClientID}).Verify(r.Context(), rawIDToken)
|
|
if err != nil {
|
|
redirectOIDCResult(w, r, "verify")
|
|
return
|
|
}
|
|
var claims struct {
|
|
Subject string `json:"sub"`
|
|
Name string `json:"name"`
|
|
EmailVerified bool `json:"email_verified"`
|
|
Email string `json:"email"`
|
|
Nonce string `json:"nonce"`
|
|
}
|
|
if idToken.Claims(&claims) != nil || claims.Subject == "" || claims.Nonce != state.Nonce || len(claims.Subject) > 255 || len(claims.Email) > 190 {
|
|
redirectOIDCResult(w, r, "claims")
|
|
return
|
|
}
|
|
if state.Mode == "bind" && state.UserID != nil {
|
|
if err = s.store.BindOIDCIdentity(r.Context(), *state.UserID, oidcProviderKey(cfg), claims.Subject, claims.Email); err != nil {
|
|
redirectOIDCResult(w, r, "conflict")
|
|
return
|
|
}
|
|
user, _ := s.store.UserByID(r.Context(), *state.UserID)
|
|
s.store.Log(r.Context(), user.TenantID, user.ID, "bind", "oidc_identity", "", requestClientIP(r), true, "绑定第三方 OIDC 身份")
|
|
redirectOIDCResult(w, r, "bound")
|
|
return
|
|
}
|
|
user, err := s.store.UserByOIDC(r.Context(), oidcProviderKey(cfg), claims.Subject)
|
|
if err != nil {
|
|
if !errors.Is(err, store.ErrNotFound) {
|
|
redirectOIDCResult(w, r, "session")
|
|
return
|
|
}
|
|
ticket, e := randomURLToken(32)
|
|
if e != nil {
|
|
redirectOIDCResult(w, r, "session")
|
|
return
|
|
}
|
|
pending := store.PendingOIDCLogin{Provider: oidcProviderKey(cfg), Subject: claims.Subject, Email: strings.ToLower(strings.TrimSpace(claims.Email)), DisplayName: truncateOIDCName(claims.Name), EmailVerified: claims.EmailVerified, ExpiresAt: time.Now().UTC().Add(5 * time.Minute)}
|
|
if e = s.store.CreatePendingOIDCLogin(r.Context(), ticket, pending); e != nil {
|
|
redirectOIDCResult(w, r, "session")
|
|
return
|
|
}
|
|
setOIDCCookie(w, "sea_oidc_pending", ticket, 300)
|
|
redirectOIDCResult(w, r, "complete")
|
|
return
|
|
}
|
|
if user.Role == "host" {
|
|
redirectOIDCResult(w, r, "host_not_allowed")
|
|
return
|
|
}
|
|
if err = s.issueSession(w, r, user); err != nil {
|
|
redirectOIDCResult(w, r, "session")
|
|
return
|
|
}
|
|
s.store.Log(r.Context(), user.TenantID, user.ID, "login", "oidc_session", "", requestClientIP(r), true, "通过已绑定的 OIDC 身份登录")
|
|
redirectOIDCResult(w, r, "login")
|
|
}
|
|
|
|
func (s *Server) accountOIDC(w http.ResponseWriter, r *http.Request) {
|
|
user := currentUser(r)
|
|
cfg := s.readServiceConfig(r, "oidc_config")
|
|
if user.Role == "host" {
|
|
if r.Method == http.MethodGet {
|
|
writeJSON(w, 200, map[string]any{"enabled": false, "bound": false, "email": ""})
|
|
return
|
|
}
|
|
writeError(w, 403, "主机账号不可绑定 SSO")
|
|
return
|
|
}
|
|
if r.Method == http.MethodGet {
|
|
identity, err := s.store.OIDCIdentity(r.Context(), user.ID, oidcProviderKey(cfg))
|
|
writeJSON(w, http.StatusOK, map[string]any{"enabled": validOIDCConfig(cfg), "bound": err == nil, "email": identity.Email, "canUnbind": oidcPasswordAllowed(cfg, user.Role)})
|
|
return
|
|
}
|
|
if !oidcPasswordAllowed(cfg, user.Role) {
|
|
writeError(w, 409, "请先恢复该类账号的密码登录,再解除 SSO 绑定")
|
|
return
|
|
}
|
|
var input struct {
|
|
CurrentPassword string `json:"currentPassword"`
|
|
}
|
|
if decodeJSON(r, &input) != nil {
|
|
writeError(w, http.StatusBadRequest, "请求格式错误")
|
|
return
|
|
}
|
|
security, err := s.store.UserSecurity(r.Context(), user.ID)
|
|
if err != nil || !auth.VerifyPasswordConstantWork(security.PasswordHash, input.CurrentPassword) {
|
|
writeError(w, http.StatusUnauthorized, "当前密码不正确")
|
|
return
|
|
}
|
|
if err = s.store.DeleteOIDCIdentity(r.Context(), user.ID, oidcProviderKey(cfg)); err != nil && !errors.Is(err, store.ErrNotFound) {
|
|
writeError(w, http.StatusInternalServerError, "无法解除 OIDC 绑定")
|
|
return
|
|
}
|
|
s.store.Log(r.Context(), user.TenantID, user.ID, "unbind", "oidc_identity", "", requestClientIP(r), true, "解除第三方 OIDC 身份绑定")
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
func oidcClient(ctx context.Context, cfg secretServiceConfig) (*oidc.Provider, *oauth2.Config, error) {
|
|
if !validOIDCConfig(cfg) {
|
|
return nil, nil, errors.New("invalid OIDC config")
|
|
}
|
|
provider, err := oidc.NewProvider(ctx, strings.TrimSuffix(cfg.Issuer, "/"))
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
oauth := &oauth2.Config{ClientID: cfg.ClientID, ClientSecret: cfg.Secret, Endpoint: provider.Endpoint(), RedirectURL: cfg.RedirectURI, Scopes: []string{oidc.ScopeOpenID, "profile", "email"}}
|
|
return provider, oauth, nil
|
|
}
|
|
|
|
func validOIDCConfig(cfg secretServiceConfig) bool {
|
|
if !cfg.Enabled || cfg.Secret == "" || cfg.ClientID == "" || cfg.Issuer == "" || cfg.RedirectURI == "" {
|
|
return false
|
|
}
|
|
issuer, issuerErr := url.Parse(cfg.Issuer)
|
|
redirect, redirectErr := url.Parse(cfg.RedirectURI)
|
|
return issuerErr == nil && redirectErr == nil && issuer.Scheme == "https" && issuer.Host != "" && issuer.User == nil && redirect.Scheme == "https" && redirect.Host != "" && redirect.User == nil
|
|
}
|
|
|
|
func randomURLToken(size int) (string, error) {
|
|
data := make([]byte, size)
|
|
if _, err := rand.Read(data); err != nil {
|
|
return "", err
|
|
}
|
|
return base64.RawURLEncoding.EncodeToString(data), nil
|
|
}
|
|
|
|
func redirectOIDCResult(w http.ResponseWriter, r *http.Request, result string) {
|
|
http.Redirect(w, r, "/?oidc="+url.QueryEscape(result), http.StatusSeeOther)
|
|
}
|