feat: adopt shared internal SSO sessions and add no-sso launch mode
This commit is contained in:
1 parent
c209f1effc
commit
c02bf755f2
51 files changed
+2131
-362
No files matched your search
+19
-256
@@ -5,7 +5,6 @@ import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
@@ -28,6 +27,9 @@ type sessionIdentity struct {
|
||||
Admin bool
|
||||
Name string
|
||||
Picture string
|
||||
Sub string
|
||||
State string
|
||||
Handle string `json:"-"`
|
||||
}
|
||||
type ssoClaims struct {
|
||||
Subject string `json:"sub"`
|
||||
@@ -40,16 +42,10 @@ type ssoClaims struct {
|
||||
type loginAttempt struct {
|
||||
Nonce, Verifier, ReturnTo string
|
||||
Expires time.Time
|
||||
}
|
||||
type ssoSession struct {
|
||||
sync.Mutex
|
||||
Identity sessionIdentity
|
||||
Expires time.Time
|
||||
Touched time.Time
|
||||
Silent bool
|
||||
}
|
||||
|
||||
// SSO owns opaque server-side sessions (8h absolute, 30m idle). Roles are
|
||||
// captured at login. Provider tokens are discarded after OIDC verification.
|
||||
// Identities are resolved afresh from the browser binding for every request.
|
||||
type SSO struct {
|
||||
provider *oidc.Provider
|
||||
verifier *oidc.IDTokenVerifier
|
||||
@@ -57,17 +53,20 @@ type SSO struct {
|
||||
origin, base, cookiePath string
|
||||
secure bool
|
||||
issuer string
|
||||
client *http.Client
|
||||
store *storage.Storage
|
||||
server *settings.Server
|
||||
mu sync.Mutex
|
||||
provision sync.Mutex
|
||||
userIDs map[string]uint
|
||||
attempts map[string]loginAttempt
|
||||
sessions map[[32]byte]*ssoSession
|
||||
avatars map[string]avatarCache
|
||||
uploads map[string]uploadBinding
|
||||
}
|
||||
|
||||
type SSOConfig struct {
|
||||
Issuer string `json:"issuer"`
|
||||
RedirectURI string `json:"redirectURI,omitempty"`
|
||||
ClientID string `json:"clientID"`
|
||||
ClientSecret string `json:"clientSecret"`
|
||||
PublicURL string `json:"publicURL"`
|
||||
@@ -90,7 +89,7 @@ func NewSSO(ctx context.Context, store *storage.Storage, server *settings.Server
|
||||
if base != strings.TrimRight(server.BaseURL, "/") {
|
||||
return nil, errors.New("sso.publicURL path must match baseURL")
|
||||
}
|
||||
client := &http.Client{Timeout: 15 * time.Second}
|
||||
client := &http.Client{Timeout: 10 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
|
||||
ctx = oidc.ClientContext(ctx, client)
|
||||
provider, err := oidc.NewProvider(ctx, strings.TrimRight(issuer, "/"))
|
||||
if err != nil {
|
||||
@@ -98,8 +97,15 @@ func NewSSO(ctx context.Context, store *storage.Storage, server *settings.Server
|
||||
}
|
||||
endpoint := provider.Endpoint()
|
||||
endpoint.AuthStyle = oauth2.AuthStyleInHeader
|
||||
s := &SSO{provider: provider, verifier: provider.Verifier(&oidc.Config{ClientID: clientID, SupportedSigningAlgs: []string{oidc.RS256}}), origin: u.Scheme + "://" + u.Host, base: base, cookiePath: base + "/", secure: u.Scheme == "https", issuer: strings.TrimRight(issuer, "/"), store: store, server: server, attempts: map[string]loginAttempt{}, sessions: map[[32]byte]*ssoSession{}}
|
||||
s := &SSO{provider: provider, verifier: provider.Verifier(&oidc.Config{ClientID: clientID, SupportedSigningAlgs: []string{oidc.RS256}}), origin: u.Scheme + "://" + u.Host, base: base, cookiePath: base + "/", secure: u.Scheme == "https", issuer: strings.TrimRight(issuer, "/"), store: store, server: server, attempts: map[string]loginAttempt{}, client: client, avatars: map[string]avatarCache{}, uploads: map[string]uploadBinding{}}
|
||||
s.oauth = oauth2.Config{ClientID: clientID, ClientSecret: secret, Endpoint: endpoint, RedirectURL: strings.TrimRight(publicURL, "/") + "/auth/callback", Scopes: []string{oidc.ScopeOpenID, "profile", "email"}}
|
||||
if config.RedirectURI != "" {
|
||||
if config.RedirectURI != s.oauth.RedirectURL {
|
||||
return nil, errors.New("sso.redirectURI must exactly match publicURL/auth/callback")
|
||||
}
|
||||
s.oauth.RedirectURL = config.RedirectURI
|
||||
}
|
||||
server.SSOIssuer, server.SSOClientID = s.issuer, clientID
|
||||
// Remove usable local credentials when migrating an existing installation.
|
||||
legacy, err := store.Users.Gets(server.Root, false)
|
||||
if err != nil && !errors.Is(err, fberrors.ErrNotExist) {
|
||||
@@ -155,149 +161,6 @@ func ssoAdmin(roles []string) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
func (s *SSO) cleanupLocked() {
|
||||
now := time.Now()
|
||||
for k, a := range s.attempts {
|
||||
if now.After(a.Expires) {
|
||||
delete(s.attempts, k)
|
||||
}
|
||||
}
|
||||
for k, v := range s.sessions {
|
||||
if !now.Before(v.Expires) {
|
||||
delete(s.sessions, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *SSO) login(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != "GET" {
|
||||
w.WriteHeader(405)
|
||||
return
|
||||
}
|
||||
state := randomSecret()
|
||||
a := loginAttempt{Nonce: randomSecret(), Verifier: oauth2.GenerateVerifier(), Expires: time.Now().Add(10 * time.Minute), ReturnTo: s.base + "/files/"}
|
||||
if target := r.URL.Query().Get("return"); strings.HasPrefix(target, s.base+"/") && !strings.HasPrefix(target, "//") && !strings.ContainsAny(target, "\\\r\n") && !strings.HasPrefix(target, s.base+"/auth/") && !strings.HasPrefix(target, s.base+"/login") {
|
||||
a.ReturnTo = target
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.cleanupLocked()
|
||||
if len(s.attempts) >= 1000 {
|
||||
s.mu.Unlock()
|
||||
http.Error(w, "Too many sign-in attempts", 429)
|
||||
return
|
||||
}
|
||||
s.attempts[state] = a
|
||||
s.mu.Unlock()
|
||||
s.cookie(w, "fb_login", state, 600)
|
||||
http.Redirect(w, r, s.oauth.AuthCodeURL(state, oidc.Nonce(a.Nonce), oauth2.S256ChallengeOption(a.Verifier)), http.StatusFound)
|
||||
}
|
||||
|
||||
func (s *SSO) callback(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != "GET" {
|
||||
w.WriteHeader(405)
|
||||
return
|
||||
}
|
||||
if len(r.URL.Query()["state"]) != 1 || len(r.URL.Query()["code"]) != 1 {
|
||||
http.Error(w, "Invalid callback parameters", 400)
|
||||
return
|
||||
}
|
||||
state := r.URL.Query().Get("state")
|
||||
c, err := r.Cookie("fb_login")
|
||||
if err != nil || state == "" || c.Value != state {
|
||||
http.Error(w, "Invalid sign-in state", 400)
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
a, ok := s.attempts[state]
|
||||
delete(s.attempts, state)
|
||||
s.mu.Unlock()
|
||||
s.cookie(w, "fb_login", "", -1)
|
||||
if !ok || time.Now().After(a.Expires) {
|
||||
http.Error(w, "Sign-in expired. Please try again.", 400)
|
||||
return
|
||||
}
|
||||
ctx := oidc.ClientContext(r.Context(), &http.Client{Timeout: 15 * time.Second})
|
||||
token, err := s.oauth.Exchange(ctx, r.URL.Query().Get("code"), oauth2.VerifierOption(a.Verifier))
|
||||
if err != nil {
|
||||
http.Error(w, "SSO code exchange failed", 401)
|
||||
return
|
||||
}
|
||||
raw, _ := token.Extra("id_token").(string)
|
||||
id, err := s.verifier.Verify(ctx, raw)
|
||||
if err != nil || id.Nonce != a.Nonce {
|
||||
http.Error(w, "Invalid SSO identity", 401)
|
||||
return
|
||||
}
|
||||
if err = id.VerifyAccessToken(token.AccessToken); err != nil {
|
||||
http.Error(w, "Invalid SSO token binding", 401)
|
||||
return
|
||||
}
|
||||
var claims ssoClaims
|
||||
if err = id.Claims(&claims); err != nil || claims.Subject == "" {
|
||||
http.Error(w, "Invalid SSO claims", 401)
|
||||
return
|
||||
}
|
||||
if token.Expiry.IsZero() || time.Now().After(token.Expiry) {
|
||||
http.Error(w, "Invalid SSO expiry", 401)
|
||||
return
|
||||
}
|
||||
// Fetch profile data as VTNL Panel does, retaining signed identity and roles.
|
||||
var metadata struct {
|
||||
UserInfoURL string `json:"userinfo_endpoint"`
|
||||
}
|
||||
if err = s.provider.Claims(&metadata); err != nil {
|
||||
http.Error(w, "Invalid SSO metadata", 401)
|
||||
return
|
||||
}
|
||||
if metadata.UserInfoURL != "" {
|
||||
profile, profileErr := s.provider.UserInfo(ctx, oauth2.StaticTokenSource(token))
|
||||
if profileErr != nil || profile.Subject != claims.Subject {
|
||||
http.Error(w, "Invalid SSO profile", 401)
|
||||
return
|
||||
}
|
||||
var info ssoClaims
|
||||
if err = profile.Claims(&info); err != nil {
|
||||
http.Error(w, "Invalid SSO profile claims", 401)
|
||||
return
|
||||
}
|
||||
if claims.Username == "" {
|
||||
claims.Username = info.Username
|
||||
}
|
||||
if claims.Name == "" {
|
||||
claims.Name = info.Name
|
||||
}
|
||||
if claims.Email == "" {
|
||||
claims.Email = info.Email
|
||||
}
|
||||
if claims.Picture == "" {
|
||||
claims.Picture = info.Picture
|
||||
}
|
||||
}
|
||||
identity, err := s.provisionUser(claims)
|
||||
if err != nil {
|
||||
http.Error(w, "Cannot provision SSO user", 500)
|
||||
return
|
||||
}
|
||||
identity.Picture = s.loadAvatar(ctx, claims.Picture)
|
||||
sid := randomSecret()
|
||||
key := sha256.Sum256([]byte(sid))
|
||||
s.mu.Lock()
|
||||
s.cleanupLocked()
|
||||
if len(s.sessions) >= 10000 {
|
||||
s.mu.Unlock()
|
||||
http.Error(w, "Too many sessions", 503)
|
||||
return
|
||||
}
|
||||
if old, e := r.Cookie("fb_session"); e == nil {
|
||||
delete(s.sessions, sha256.Sum256([]byte(old.Value)))
|
||||
}
|
||||
expires := time.Now().Add(8 * time.Hour)
|
||||
s.sessions[key] = &ssoSession{Identity: identity, Expires: expires, Touched: time.Now()}
|
||||
s.mu.Unlock()
|
||||
s.cookie(w, "fb_session", sid, int(time.Until(expires).Seconds()))
|
||||
http.Redirect(w, r, a.ReturnTo, http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func (s *SSO) provisionUser(c ssoClaims) (sessionIdentity, error) {
|
||||
s.provision.Lock()
|
||||
defer s.provision.Unlock()
|
||||
@@ -348,107 +211,7 @@ func (s *SSO) provisionUser(c ssoClaims) (sessionIdentity, error) {
|
||||
return sessionIdentity{}, err
|
||||
}
|
||||
}
|
||||
return sessionIdentity{ID: u.ID, Name: name, Admin: ssoAdmin(c.Roles)}, nil
|
||||
}
|
||||
|
||||
func (s *SSO) identify(r *http.Request) (sessionIdentity, bool) {
|
||||
c, err := r.Cookie("fb_session")
|
||||
if err != nil {
|
||||
return sessionIdentity{}, false
|
||||
}
|
||||
key := sha256.Sum256([]byte(c.Value))
|
||||
s.mu.Lock()
|
||||
session := s.sessions[key]
|
||||
s.mu.Unlock()
|
||||
if session == nil {
|
||||
return sessionIdentity{}, false
|
||||
}
|
||||
session.Lock()
|
||||
defer session.Unlock()
|
||||
valid := time.Now().Before(session.Expires) && time.Since(session.Touched) < 30*time.Minute
|
||||
if !valid {
|
||||
s.mu.Lock()
|
||||
delete(s.sessions, key)
|
||||
s.mu.Unlock()
|
||||
return sessionIdentity{}, false
|
||||
}
|
||||
session.Touched = time.Now()
|
||||
return session.Identity, true
|
||||
}
|
||||
|
||||
func (s *SSO) Wrap(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
p := strings.TrimPrefix(r.URL.Path, s.base)
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Referrer-Policy", "same-origin")
|
||||
if strings.HasPrefix(p, "/api/") || strings.HasPrefix(p, "/auth/") {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
}
|
||||
if r.Method != "GET" && r.Method != "HEAD" && r.Method != "OPTIONS" {
|
||||
origin := r.Header.Get("Origin")
|
||||
if (origin != "" && origin != s.origin) || (origin == "" && r.Header.Get("X-FB-Request") != "1") || r.Header.Get("Sec-Fetch-Site") == "cross-site" {
|
||||
http.Error(w, "Cross-origin request rejected", 403)
|
||||
return
|
||||
}
|
||||
}
|
||||
switch p {
|
||||
case "/auth/account":
|
||||
if r.Method != http.MethodGet {
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, strings.TrimRight(s.issuer, "/")+"/settings", http.StatusFound)
|
||||
return
|
||||
case "/auth/login":
|
||||
s.login(w, r)
|
||||
return
|
||||
case "/auth/callback":
|
||||
s.callback(w, r)
|
||||
return
|
||||
case "/auth/logout":
|
||||
if r.Method != "POST" {
|
||||
w.WriteHeader(405)
|
||||
return
|
||||
}
|
||||
if c, e := r.Cookie("fb_session"); e == nil {
|
||||
s.mu.Lock()
|
||||
delete(s.sessions, sha256.Sum256([]byte(c.Value)))
|
||||
s.mu.Unlock()
|
||||
}
|
||||
s.cookie(w, "fb_session", "", -1)
|
||||
w.WriteHeader(204)
|
||||
return
|
||||
case "/api/login", "/api/signup", "/api/renew", "/api/command":
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
identity, ok := s.identify(r)
|
||||
if p == "/api/session" {
|
||||
if r.Method != "GET" {
|
||||
w.WriteHeader(405)
|
||||
return
|
||||
}
|
||||
if !ok {
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
u, err := s.store.Users.Get(s.server.Root, s.server.FollowExternalSymlinks, identity.ID)
|
||||
if err != nil {
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
applySSOIdentity(u, identity)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
profile := ssoUserInfo(u)
|
||||
profile.Picture = identity.Picture
|
||||
_ = json.NewEncoder(w).Encode(profile)
|
||||
return
|
||||
}
|
||||
if ok {
|
||||
r = r.WithContext(context.WithValue(r.Context(), identityKey{}, identity))
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
return sessionIdentity{ID: u.ID, Name: name, Admin: ssoAdmin(c.Roles), Sub: c.Subject}, nil
|
||||
}
|
||||
|
||||
func applySSOIdentity(u *users.User, i sessionIdentity) {
|
||||
|
||||
Reference in new issue
Block a user