Files

230 lines
8.7 KiB
Go

package fbhttp
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/coreos/go-oidc/v3/oidc"
fberrors "github.com/filebrowser/filebrowser/v2/errors"
"github.com/filebrowser/filebrowser/v2/settings"
"github.com/filebrowser/filebrowser/v2/storage"
"github.com/filebrowser/filebrowser/v2/users"
"golang.org/x/oauth2"
)
type identityKey struct{}
type sessionIdentity struct {
ID uint
Admin bool
Name string
Picture string
Sub string
State string
Handle string `json:"-"`
}
type ssoClaims struct {
Subject string `json:"sub"`
Username string `json:"preferred_username"`
Name string `json:"name"`
Email string `json:"email"`
Picture string `json:"picture"`
Roles []string `json:"roles"`
}
type loginAttempt struct {
Nonce, Verifier, ReturnTo string
Expires time.Time
Silent bool
}
// Identities are resolved afresh from the browser binding for every request.
type SSO struct {
provider *oidc.Provider
verifier *oidc.IDTokenVerifier
oauth oauth2.Config
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
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"`
}
func NewSSO(ctx context.Context, store *storage.Storage, server *settings.Server, config SSOConfig) (*SSO, error) {
issuer, clientID, secret, publicURL := config.Issuer, config.ClientID, config.ClientSecret, config.PublicURL
if issuer == "" || clientID == "" || secret == "" || publicURL == "" {
return nil, errors.New("SSO is required: run filebrowser init first")
}
u, err := url.Parse(publicURL)
if err != nil || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Scheme != "https" && !(u.Scheme == "http" && (u.Hostname() == "localhost" || u.Hostname() == "127.0.0.1"))) {
return nil, errors.New("sso.publicURL must be an HTTPS URL (HTTP allowed only on loopback)")
}
i, err := url.Parse(issuer)
if err != nil || i.Host == "" || i.User != nil || (i.Scheme != "https" && !(i.Scheme == "http" && (i.Hostname() == "localhost" || i.Hostname() == "127.0.0.1"))) {
return nil, errors.New("sso.issuer must use HTTPS (HTTP allowed only on loopback)")
}
base := strings.TrimRight(u.Path, "/")
if base != strings.TrimRight(server.BaseURL, "/") {
return nil, errors.New("sso.publicURL path must match baseURL")
}
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 {
return nil, fmt.Errorf("SSO discovery: %w", err)
}
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{}, 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) {
return nil, err
}
for _, u := range legacy {
if s.userIDs == nil {
s.userIDs = map[string]uint{}
}
if previous, ok := s.userIDs[u.Username]; !ok || u.ID < previous {
s.userIDs[u.Username] = u.ID
}
if u.Password != "!sso-disabled" || !u.LockPassword || u.Perm.Execute || len(u.Commands) > 0 || u.Perm.Admin {
u.Password = "!sso-disabled"
u.LockPassword = true
u.Perm.Admin = false
u.Perm.Execute = false
u.Commands = []string{}
if err = store.Users.Update(u, "Password", "LockPassword", "Perm", "Commands"); err != nil {
return nil, err
}
}
}
// A previous build may have created duplicate rows after corrupting the
// username index. Keep the currently indexed record when it is valid, so
// updating its profile cannot collide with that same identity's other row.
for username := range s.userIDs {
indexed, lookupErr := store.Users.Get(server.Root, server.FollowExternalSymlinks, username)
if lookupErr == nil && indexed.Username == username {
s.userIDs[username] = indexed.ID
} else if lookupErr != nil && !errors.Is(lookupErr, fberrors.ErrNotExist) {
return nil, lookupErr
}
}
return s, nil
}
func randomSecret() string {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
panic(err)
}
return base64.RawURLEncoding.EncodeToString(b)
}
func (s *SSO) cookie(w http.ResponseWriter, name, value string, maxAge int) {
http.SetCookie(w, &http.Cookie{Name: name, Value: value, Path: s.cookiePath, HttpOnly: true, Secure: s.secure, SameSite: http.SameSiteLaxMode, MaxAge: maxAge})
}
func ssoAdmin(roles []string) bool {
for _, role := range roles {
if role == "Master Admin" || role == "FS Admin" {
return true
}
}
return false
}
func (s *SSO) provisionUser(c ssoClaims) (sessionIdentity, error) {
s.provision.Lock()
defer s.provision.Unlock()
// Stable subject IDs cannot claim a pre-existing local username or administrator.
// Namespace by issuer and subject, never by a renameable login or email.
identityHash := sha256.Sum256([]byte(s.issuer + "\x00" + c.Subject))
username := "sso:" + base64.RawURLEncoding.EncodeToString(identityHash[:])
var lookup interface{} = username
if id, ok := s.userIDs[username]; ok {
lookup = id
}
u, err := s.store.Users.Get(s.server.Root, s.server.FollowExternalSymlinks, lookup)
if errors.Is(err, fberrors.ErrNotExist) {
st, err := s.store.Settings.Get()
if err != nil {
return sessionIdentity{}, err
}
u = &users.User{Username: username, DisplayName: c.Username, Password: "!sso-disabled", LockPassword: true}
st.Defaults.Apply(u)
u.Perm.Admin = false
u.Perm.Execute = false
u.Commands = []string{}
u.ViewMode = users.ListViewMode
derived, err := st.CreateUserHome(u, s.server.Root, false)
if err != nil {
return sessionIdentity{}, err
}
if err = s.store.Users.SaveProvisioned(u, derived); err != nil {
return sessionIdentity{}, err
}
if s.userIDs == nil {
s.userIDs = map[string]uint{}
}
s.userIDs[username] = u.ID
} else if err != nil {
return sessionIdentity{}, err
}
name := c.Username
if name == "" {
name = c.Name
}
if name == "" {
name = c.Subject
}
if u.DisplayName != name || u.ProfileName != c.Name || u.Email != c.Email {
u.DisplayName, u.ProfileName, u.Email = name, c.Name, c.Email
if err = s.store.Users.Update(u, "DisplayName", "ProfileName", "Email"); err != nil {
return sessionIdentity{}, err
}
}
return sessionIdentity{ID: u.ID, Name: name, Admin: ssoAdmin(c.Roles), Sub: c.Subject}, nil
}
func applySSOIdentity(u *users.User, i sessionIdentity) {
u.Perm.Admin = i.Admin
if i.Admin {
u.Perm = users.Permissions{Admin: true, Create: true, Rename: true, Modify: true, Delete: true, Share: true, Download: true}
}
u.Perm.Execute = false
u.LockPassword = true
u.Commands = []string{}
u.DisplayName = i.Name
}
func ssoUserInfo(u *users.User) userInfo {
return userInfo{ID: u.ID, Username: u.DisplayName, ProfileName: u.ProfileName, Email: u.Email, Locale: u.Locale, ViewMode: u.ViewMode, SingleClick: u.SingleClick, RedirectAfterCopyMove: u.RedirectAfterCopyMove, Perm: u.Perm, Commands: []string{}, LockPassword: true, HideDotfiles: u.HideDotfiles, HidePreviews: u.HidePreviews, Dicom3D: u.Dicom3D.Normalized(), DateFormat: u.DateFormat, AceEditorTheme: u.AceEditorTheme}
}