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
@@ -6,6 +6,8 @@ import (
|
||||
)
|
||||
|
||||
type userInfo struct {
|
||||
SessionState string `json:"sessionState,omitempty"`
|
||||
AuthMode string `json:"authMode,omitempty"`
|
||||
ID uint `json:"id"`
|
||||
Locale string `json:"locale"`
|
||||
ViewMode users.ViewMode `json:"viewMode"`
|
||||
|
||||
@@ -171,6 +171,9 @@ func craftDocumentHandler(manager *addons.Manager, cache FileCache) handleFunc {
|
||||
if err = d.user.Fs.Chmod(tempName, mode); err != nil {
|
||||
return 500, err
|
||||
}
|
||||
if err = checkOperationIdentity(r); err != nil {
|
||||
return http.StatusConflict, err
|
||||
}
|
||||
err = d.RunHook(func() error { return d.user.Fs.Rename(tempName, requested) }, "save", requested, "", d.user)
|
||||
if err != nil {
|
||||
return errToStatus(err), err
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
package fbhttp
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/diskcache"
|
||||
"github.com/filebrowser/filebrowser/v2/frontend"
|
||||
"github.com/filebrowser/filebrowser/v2/img"
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
// Optional integration: two real File Browser servers, one shared mock issuer,
|
||||
// separate host-only Secure cookies, and a second independent browser device.
|
||||
func TestInternalSessionBrowser(t *testing.T) {
|
||||
if os.Getenv("FILEBROWSER_INTERNAL_QA") != "1" {
|
||||
t.Skip("optional browser integration")
|
||||
}
|
||||
var mu sync.Mutex
|
||||
name, version, status := "Alice", "A-1", "authenticated"
|
||||
denied, offline := false, false
|
||||
control := randomSecret()
|
||||
provider := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/internal/session/frame" {
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.Write([]byte("<!doctype html><title>Session notification fixture</title>"))
|
||||
return
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if r.URL.Path == "/__qa/change" {
|
||||
if r.Header.Get("X-QA-Control") != control {
|
||||
w.WriteHeader(403)
|
||||
return
|
||||
}
|
||||
var p struct {
|
||||
Name string
|
||||
Version string
|
||||
Status string
|
||||
Denied bool
|
||||
Offline bool
|
||||
}
|
||||
if json.NewDecoder(r.Body).Decode(&p) != nil {
|
||||
w.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
name, version, status, denied, offline = p.Name, p.Version, p.Status, p.Denied, p.Offline
|
||||
w.WriteHeader(204)
|
||||
return
|
||||
}
|
||||
client, secret, ok := r.BasicAuth()
|
||||
if !ok || (client != "one" && client != "two") || secret != "qa-secret" || r.Header.Get("Cookie") != "" {
|
||||
t.Error("unexpected internal credentials or browser cookies")
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
r.ParseForm()
|
||||
if !strings.HasPrefix(r.Form.Get("session_handle"), client+"-") {
|
||||
w.WriteHeader(400)
|
||||
json.NewEncoder(w).Encode(map[string]string{"error": "invalid_handle"})
|
||||
return
|
||||
}
|
||||
if offline {
|
||||
w.WriteHeader(503)
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/internal/session/logout" {
|
||||
if r.Form.Get("session_state") != version {
|
||||
w.WriteHeader(409)
|
||||
return
|
||||
}
|
||||
status = "signed_out"
|
||||
version = "signed-out"
|
||||
w.WriteHeader(204)
|
||||
return
|
||||
}
|
||||
if r.URL.Path != "/internal/session/resolve" {
|
||||
t.Error("unexpected OAuth exchange or redirect")
|
||||
w.WriteHeader(404)
|
||||
return
|
||||
}
|
||||
who, revision, condition := name, version, status
|
||||
if strings.Contains(r.Form.Get("session_handle"), "device-two") {
|
||||
who, revision, condition = "Alice", "device-two-A", "authenticated"
|
||||
}
|
||||
if denied && client == "two" {
|
||||
condition = "access_denied"
|
||||
}
|
||||
state := internalState{Status: condition, State: revision}
|
||||
if condition == "authenticated" {
|
||||
roles := []string{"User"}
|
||||
if who == "Alice" {
|
||||
roles = []string{"FS Admin"}
|
||||
}
|
||||
state.Authenticated = true
|
||||
state.ClientID = client
|
||||
state.Expires = time.Now().Add(time.Hour).Unix()
|
||||
state.User = &ssoClaims{Subject: who, Username: who, Roles: roles}
|
||||
}
|
||||
json.NewEncoder(w).Encode(state)
|
||||
}))
|
||||
defer provider.Close()
|
||||
assets, err := fs.Sub(frontend.Assets(), "dist")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
urls := []string{}
|
||||
for _, id := range []string{"one", "two"} {
|
||||
root := t.TempDir()
|
||||
for _, who := range []string{"Alice", "Bob"} {
|
||||
os.Mkdir(filepath.Join(root, who), 0750)
|
||||
os.WriteFile(filepath.Join(root, who, who+"-private.txt"), []byte(who+" PRIVATE"), 0600)
|
||||
}
|
||||
st := scopedUserStorage(t, root, users.Permissions{Download: true, Create: true, Rename: true, Modify: true, Delete: true, Share: true}, []byte("key"))
|
||||
st.Users = st.Users.(*customFSUser).Store
|
||||
options, _ := st.Settings.Get()
|
||||
options.Defaults = settings.UserDefaults{Scope: ".", Locale: "en", Perm: users.Permissions{Download: true, Create: true, Rename: true, Modify: true, Delete: true, Share: true}}
|
||||
st.Settings.Save(options)
|
||||
cfg := &settings.Server{Root: root, SSOIssuer: provider.URL, SSOClientID: id}
|
||||
s := &SSO{issuer: provider.URL, store: st, server: cfg, client: provider.Client(), oauth: oauth2.Config{ClientID: id, ClientSecret: "qa-secret"}, avatars: map[string]avatarCache{}, uploads: map[string]uploadBinding{}}
|
||||
for _, who := range []string{"Alice", "Bob"} {
|
||||
i, e := s.provisionUser(ssoClaims{Subject: who, Username: who})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = st.Users.Update(&users.User{ID: i.ID, Scope: who}, "Scope"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
uploads, e := NewUploadCache("")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer uploads.Close()
|
||||
h, e := NewHandler(img.New(1), diskcache.NewNoOp(), uploads, st, cfg, assets)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
app := httptest.NewTLSServer(s.Wrap(h))
|
||||
defer app.Close()
|
||||
url := strings.Replace(app.URL, "127.0.0.1", id+".localhost", 1)
|
||||
s.origin = url
|
||||
urls = append(urls, url)
|
||||
}
|
||||
command := exec.Command("node", os.Getenv("FILEBROWSER_INTERNAL_QA_SCRIPT"))
|
||||
command.Env = append(os.Environ(), "QA_APP_ONE="+urls[0], "QA_APP_TWO="+urls[1], "QA_ISSUER="+provider.URL, "QA_CONTROL="+control)
|
||||
out, err := command.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("%v\n%s", err, out)
|
||||
}
|
||||
t.Log(string(out))
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
package fbhttp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
func TestInternalSessionTwoApplicationsAndAccountBoundaries(t *testing.T) {
|
||||
user, state, status := "A", "version-A", "authenticated"
|
||||
mode := ""
|
||||
resolves, logouts := 0, 0
|
||||
provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Cookie") != "" {
|
||||
t.Error("forwarded browser cookies")
|
||||
}
|
||||
client, secret, ok := r.BasicAuth()
|
||||
if !ok || (client != "one" && client != "two") || secret != "secret" {
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
r.ParseForm()
|
||||
handle := r.Form.Get("session_handle")
|
||||
if r.URL.Path == "/internal/session/logout" {
|
||||
logouts++
|
||||
if r.Form.Get("session_state") != state {
|
||||
w.WriteHeader(409)
|
||||
return
|
||||
}
|
||||
status = "signed_out"
|
||||
w.WriteHeader(204)
|
||||
return
|
||||
}
|
||||
resolves++
|
||||
if handle == "foreign-handle-000000000000" {
|
||||
w.WriteHeader(400)
|
||||
json.NewEncoder(w).Encode(map[string]string{"error": "invalid_handle"})
|
||||
return
|
||||
}
|
||||
if mode == "client-auth" {
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
if mode == "unavailable" {
|
||||
w.WriteHeader(503)
|
||||
return
|
||||
}
|
||||
if mode == "malformed" {
|
||||
w.Write([]byte("not-json"))
|
||||
return
|
||||
}
|
||||
current, version, condition := user, state, status
|
||||
if strings.HasPrefix(handle, "device-two-") {
|
||||
current, version, condition = "A", "device-two-A", "authenticated"
|
||||
}
|
||||
response := internalState{Status: condition, State: version, Factors: []string{"totp"}}
|
||||
if condition == "authenticated" {
|
||||
response.Authenticated = true
|
||||
response.ClientID = client
|
||||
response.Expires = time.Now().Add(time.Hour).Unix()
|
||||
response.User = &ssoClaims{Subject: current, Username: current, Roles: []string{"User"}}
|
||||
}
|
||||
switch mode {
|
||||
case "wrong-client":
|
||||
response.ClientID = "other"
|
||||
case "expired":
|
||||
response.Expires = time.Now().Add(-time.Minute).Unix()
|
||||
case "empty-sub":
|
||||
response.User.Subject = ""
|
||||
case "leaked-user":
|
||||
response.Status = "signed_out"
|
||||
response.Authenticated = false
|
||||
}
|
||||
json.NewEncoder(w).Encode(response)
|
||||
}))
|
||||
defer provider.Close()
|
||||
type application struct {
|
||||
s *SSO
|
||||
h http.Handler
|
||||
}
|
||||
apps := []application{}
|
||||
mutations := []string{}
|
||||
for _, client := range []string{"one", "two"} {
|
||||
root := t.TempDir()
|
||||
st := scopedUserStorage(t, root, users.Permissions{Create: true, Download: true}, []byte("key"))
|
||||
s := &SSO{issuer: provider.URL, origin: "https://" + client + ".test", store: st, server: &settings.Server{Root: root}, client: provider.Client(), oauth: oauth2.Config{ClientID: client, ClientSecret: "secret"}, avatars: map[string]avatarCache{}, uploads: map[string]uploadBinding{}}
|
||||
h := s.Wrap(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
i, ok := r.Context().Value(identityKey{}).(sessionIdentity)
|
||||
if !ok {
|
||||
t.Error("missing identity")
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
if r.Method == "POST" {
|
||||
mutations = append(mutations, i.Sub)
|
||||
}
|
||||
w.Header().Set("X-Subject", i.Sub)
|
||||
w.WriteHeader(204)
|
||||
}))
|
||||
apps = append(apps, application{s, h})
|
||||
}
|
||||
request := func(app int, method, path, expected, handle string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(method, path, nil)
|
||||
r.AddCookie(&http.Cookie{Name: internalCookie, Value: handle})
|
||||
r.Header.Set("X-FB-Request", "1")
|
||||
if expected != "" {
|
||||
r.Header.Set("X-FB-Session-State", expected)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
apps[app].h.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
handle := "device-one-handle-000000000"
|
||||
for i := range apps {
|
||||
w := request(i, "GET", "/api/private", "", handle)
|
||||
if w.Code != 204 || w.Header().Get("X-Subject") != "A" {
|
||||
t.Fatalf("app %d did not resolve A: %d", i, w.Code)
|
||||
}
|
||||
}
|
||||
user, state = "B", "version-B"
|
||||
for i := range apps {
|
||||
w := request(i, "GET", "/api/private", "", handle)
|
||||
if w.Code != 204 || w.Header().Get("X-Subject") != "B" {
|
||||
t.Fatalf("app %d kept old identity", i)
|
||||
}
|
||||
}
|
||||
if w := request(0, "GET", "/api/private", "", "device-two-handle-00000000"); w.Header().Get("X-Subject") != "A" {
|
||||
t.Fatal("another device was switched")
|
||||
}
|
||||
if w := request(0, "POST", "/api/private", "version-A", handle); w.Code != 409 || len(mutations) != 0 {
|
||||
t.Fatal("old form changed data as B")
|
||||
}
|
||||
if w := request(0, "POST", "/api/private", "version-B", handle); w.Code != 204 || len(mutations) != 1 || mutations[0] != "B" {
|
||||
t.Fatal("current form rejected")
|
||||
}
|
||||
for _, condition := range []string{"access_denied", "signed_out", "factor_required", "factor_enrollment_required", "rebind_required"} {
|
||||
status = condition
|
||||
w := request(0, "GET", "/auth/session", "", handle)
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `"status":"`+condition+`"`) || strings.Contains(w.Body.String(), `"user"`) {
|
||||
t.Fatalf("bad state %s: %d %s", condition, w.Code, w.Body.String())
|
||||
}
|
||||
if p := request(0, "POST", "/api/private", "version-B", handle); p.Code == 204 {
|
||||
t.Fatal("inactive identity retained access")
|
||||
}
|
||||
}
|
||||
status = "authenticated"
|
||||
for _, failure := range []string{"client-auth", "unavailable", "malformed", "wrong-client", "expired", "empty-sub", "leaked-user"} {
|
||||
mode = failure
|
||||
w := request(0, "GET", "/auth/session", "", handle)
|
||||
if w.Code != 503 || len(w.Result().Cookies()) != 0 {
|
||||
t.Fatalf("%s must fail closed without deleting cookie: %d", failure, w.Code)
|
||||
}
|
||||
}
|
||||
mode = ""
|
||||
if w := request(0, "GET", "/auth/session", "", "foreign-handle-000000000000"); w.Code != 200 || !strings.Contains(w.Body.String(), "rebind_required") {
|
||||
t.Fatal("foreign handle accepted")
|
||||
}
|
||||
before := resolves
|
||||
request(0, "GET", "/api/private", "", handle)
|
||||
request(0, "GET", "/api/private", "", handle)
|
||||
if resolves-before != 2 {
|
||||
t.Fatal("positive identity was cached between requests")
|
||||
}
|
||||
if w := request(0, "POST", "/auth/logout", "version-A", handle); w.Code != 409 || logouts != 0 {
|
||||
t.Fatal("stale logout reached provider")
|
||||
}
|
||||
if w := request(0, "POST", "/auth/logout", "version-B", handle); w.Code != 204 {
|
||||
t.Fatal("global logout failed")
|
||||
}
|
||||
if w := request(1, "GET", "/api/private", "", handle); w.Code != 401 {
|
||||
t.Fatal("second app retained access after logout")
|
||||
}
|
||||
if w := request(0, "GET", "/api/private", "", "device-two-handle-00000000"); w.Code != 204 {
|
||||
t.Fatal("logout affected another device")
|
||||
}
|
||||
status, user, state = "authenticated", "A", "version-A"
|
||||
if w := request(0, "POST", "/api/tus/upload.bin", state, handle); w.Code != 204 {
|
||||
t.Fatal("upload did not start")
|
||||
}
|
||||
user, state = "B", "version-B"
|
||||
if w := request(0, "PATCH", "/api/tus/upload.bin", state, handle); w.Code != 409 {
|
||||
t.Fatal("B continued A's transfer")
|
||||
}
|
||||
user, state = "A", "version-A2"
|
||||
if w := request(0, "PATCH", "/api/tus/upload.bin", state, handle); w.Code != 409 {
|
||||
t.Fatal("old transfer crossed a session-state boundary")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoSSOIsExplicitAndDoesNotNeedProvider(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
st := scopedUserStorage(t, root, users.Permissions{}, []byte("key"))
|
||||
server := &settings.Server{Root: root}
|
||||
n, err := NewNoSSO(st, server)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := n.Wrap(handle(withAdmin(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) { return http.StatusNoContent, nil }), "", st, server))
|
||||
for _, method := range []string{"GET", "POST"} {
|
||||
r := httptest.NewRequest(method, "/api/private", nil)
|
||||
r.Header.Set("X-FB-Request", "1")
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != 204 {
|
||||
t.Fatalf("passwordless mode: %d", w.Code)
|
||||
}
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, httptest.NewRequest("GET", "/auth/session", nil))
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `"authMode":"no-sso"`) || !strings.Contains(w.Body.String(), `"admin":true`) {
|
||||
t.Fatal(w.Body.String())
|
||||
}
|
||||
r := httptest.NewRequest("POST", "/api/private", nil)
|
||||
r.Header.Set("Origin", "https://evil.test")
|
||||
w = httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != 403 {
|
||||
t.Fatal("cross-origin passwordless write allowed")
|
||||
}
|
||||
u, err := st.Users.Get(root, false, "local:no-sso")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
n2, err := NewNoSSO(st, server)
|
||||
if err != nil || n2.identity.ID != u.ID {
|
||||
t.Fatal("no-sso created duplicate local user")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLongOperationRevalidatesIdentity(t *testing.T) {
|
||||
provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
json.NewEncoder(w).Encode(internalState{Status: "signed_out"})
|
||||
}))
|
||||
defer provider.Close()
|
||||
s := &SSO{issuer: provider.URL, client: provider.Client()}
|
||||
g := &identityGuard{s: s, identity: sessionIdentity{Sub: "A", State: "state", Handle: "long-operation-handle-00000"}, last: time.Now().Add(-3 * time.Second)}
|
||||
if g.check(context.Background()) == nil {
|
||||
t.Fatal("long connection retained revoked access")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParallelLoginTransactionsHaveSeparateBrowserCookies(t *testing.T) {
|
||||
s := &SSO{base: "", cookiePath: "/", secure: true, attempts: map[string]loginAttempt{}, oauth: oauth2.Config{ClientID: "client", Endpoint: oauth2.Endpoint{AuthURL: "https://sso.test/oauth/authorize"}}}
|
||||
first, second := httptest.NewRecorder(), httptest.NewRecorder()
|
||||
s.login(first, httptest.NewRequest("GET", "/auth/login", nil))
|
||||
s.login(second, httptest.NewRequest("GET", "/auth/login?silent=1", nil))
|
||||
a, b := first.Result().Cookies()[0], second.Result().Cookies()[0]
|
||||
if a.Name == b.Name || a.Value == b.Value || len(s.attempts) != 2 {
|
||||
t.Fatal("parallel flows overwrite each other")
|
||||
}
|
||||
if !a.HttpOnly || !a.Secure || a.SameSite != http.SameSiteLaxMode {
|
||||
t.Fatal("unprotected transaction cookie")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package fbhttp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
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"
|
||||
)
|
||||
|
||||
// This mode is selected only by an explicit process flag, never by failed SSO.
|
||||
type NoSSO struct {
|
||||
store *storage.Storage
|
||||
server *settings.Server
|
||||
identity sessionIdentity
|
||||
}
|
||||
|
||||
func NewNoSSO(store *storage.Storage, server *settings.Server) (*NoSSO, error) {
|
||||
u, err := store.Users.Get(server.Root, false, "local:no-sso")
|
||||
if errors.Is(err, fberrors.ErrNotExist) {
|
||||
st, e := store.Settings.Get()
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
u = &users.User{Username: "local:no-sso", Password: "!sso-disabled", LockPassword: true}
|
||||
st.Defaults.Apply(u)
|
||||
u.Scope = "/"
|
||||
u.Perm.Admin = false
|
||||
u.Perm.Execute = false
|
||||
u.Commands = []string{}
|
||||
if e = store.Users.SaveProvisioned(u, false); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
} else if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
server.NoSSO = true
|
||||
return &NoSSO{store: store, server: server, identity: sessionIdentity{ID: u.ID, Name: "Local", Admin: true, Sub: "local:no-sso", State: "local"}}, nil
|
||||
}
|
||||
func (n *NoSSO) Wrap(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
p := strings.TrimPrefix(r.URL.Path, n.server.BaseURL)
|
||||
if strings.HasPrefix(p, "/api/") || strings.HasPrefix(p, "/auth/") {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
}
|
||||
if isMutation(r) && !csrfAllowed(r, "") {
|
||||
http.Error(w, "Cross-origin request rejected", 403)
|
||||
return
|
||||
}
|
||||
if p == "/auth/session" || p == "/api/session" {
|
||||
if r.Method != "GET" {
|
||||
w.WriteHeader(405)
|
||||
return
|
||||
}
|
||||
u, err := n.store.Users.Get(n.server.Root, false, n.identity.ID)
|
||||
if err != nil {
|
||||
writeState(w, 503, browserState{Status: "unavailable"})
|
||||
return
|
||||
}
|
||||
applySSOIdentity(u, n.identity)
|
||||
profile := ssoUserInfo(u)
|
||||
profile.AuthMode = "no-sso"
|
||||
profile.SessionState = "local"
|
||||
if p == "/auth/session" {
|
||||
writeState(w, 200, browserState{Status: "authenticated", Authenticated: true, State: "local", User: &profile})
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(profile)
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(p, "/auth/") {
|
||||
if p == "/auth/login" && r.Method == "GET" {
|
||||
http.Redirect(w, r, n.server.BaseURL+"/files/", 303)
|
||||
} else {
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
return
|
||||
}
|
||||
for _, disabled := range []string{"/api/login", "/api/signup", "/api/renew", "/api/command"} {
|
||||
if p == disabled {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
}
|
||||
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), identityKey{}, n.identity)))
|
||||
})
|
||||
}
|
||||
+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) {
|
||||
|
||||
@@ -0,0 +1,476 @@
|
||||
package fbhttp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/coreos/go-oidc/v3/oidc"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
const internalCookie = "__Host-internal_session"
|
||||
|
||||
type internalState struct {
|
||||
Status string `json:"status"`
|
||||
Authenticated bool `json:"authenticated"`
|
||||
ClientID string `json:"client_id,omitempty"`
|
||||
State string `json:"session_state,omitempty"`
|
||||
Expires int64 `json:"expires_at,omitempty"`
|
||||
User *ssoClaims `json:"user,omitempty"`
|
||||
Factors []string `json:"required_factors,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
}
|
||||
type browserState struct {
|
||||
Status string `json:"status"`
|
||||
Authenticated bool `json:"authenticated"`
|
||||
State string `json:"session_state,omitempty"`
|
||||
User *userInfo `json:"user,omitempty"`
|
||||
Factors []string `json:"required_factors,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
}
|
||||
type uploadBinding struct {
|
||||
State string
|
||||
Expires time.Time
|
||||
}
|
||||
type avatarCache struct {
|
||||
Image string
|
||||
Until time.Time
|
||||
}
|
||||
|
||||
func loginCookieName(state string) string {
|
||||
h := sha256.Sum256([]byte(state))
|
||||
return "fb_login_" + base64.RawURLEncoding.EncodeToString(h[:12])
|
||||
}
|
||||
func writeState(w http.ResponseWriter, code int, state browserState) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(code)
|
||||
_ = json.NewEncoder(w).Encode(state)
|
||||
}
|
||||
func (s *SSO) bindingCookie(w http.ResponseWriter, value string, age int) {
|
||||
http.SetCookie(w, &http.Cookie{Name: internalCookie, Value: value, Path: "/", Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode, MaxAge: age})
|
||||
}
|
||||
func (s *SSO) login(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
w.WriteHeader(405)
|
||||
return
|
||||
}
|
||||
state := randomSecret()
|
||||
a := loginAttempt{Nonce: randomSecret(), Verifier: oauth2.GenerateVerifier(), Expires: time.Now().Add(10 * time.Minute), ReturnTo: s.base + "/files/", Silent: r.URL.Query().Get("silent") == "1"}
|
||||
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()
|
||||
for k, v := range s.attempts {
|
||||
if time.Now().After(v.Expires) {
|
||||
delete(s.attempts, k)
|
||||
}
|
||||
}
|
||||
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, loginCookieName(state), state, 600)
|
||||
options := []oauth2.AuthCodeOption{oidc.Nonce(a.Nonce), oauth2.S256ChallengeOption(a.Verifier), oauth2.SetAuthURLParam("internal_sync", "1")}
|
||||
if a.Silent {
|
||||
options = append(options, oauth2.SetAuthURLParam("prompt", "none"))
|
||||
}
|
||||
http.Redirect(w, r, s.oauth.AuthCodeURL(state, options...), http.StatusFound)
|
||||
}
|
||||
func (s *SSO) callback(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
w.WriteHeader(405)
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
state := q.Get("state")
|
||||
if len(q["state"]) != 1 || state == "" || len(state) > 256 {
|
||||
http.Error(w, "Invalid sign-in state", 400)
|
||||
return
|
||||
}
|
||||
c, err := r.Cookie(loginCookieName(state))
|
||||
if err != nil || 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, loginCookieName(state), "", -1)
|
||||
if !ok || time.Now().After(a.Expires) {
|
||||
http.Error(w, "Sign-in expired", 400)
|
||||
return
|
||||
}
|
||||
if q.Get("error") != "" {
|
||||
if a.Silent && q.Get("error") == "interaction_required" {
|
||||
http.Redirect(w, r, s.base+"/auth/login?return="+url.QueryEscape(a.ReturnTo), 303)
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, s.base+"/login?status=interaction_required", 303)
|
||||
return
|
||||
}
|
||||
if len(q["code"]) != 1 || q.Get("code") == "" {
|
||||
http.Error(w, "Invalid callback parameters", 400)
|
||||
return
|
||||
}
|
||||
ctx := oidc.ClientContext(r.Context(), s.client)
|
||||
token, err := s.oauth.Exchange(ctx, q.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 id.VerifyAccessToken(token.AccessToken) != nil {
|
||||
http.Error(w, "Invalid SSO token binding", 401)
|
||||
return
|
||||
}
|
||||
var claims ssoClaims
|
||||
if id.Claims(&claims) != nil || strings.TrimSpace(claims.Subject) == "" {
|
||||
http.Error(w, "Invalid SSO claims", 401)
|
||||
return
|
||||
}
|
||||
handle, _ := token.Extra("session_handle").(string)
|
||||
age, err := strconv.ParseFloat(strings.TrimSpace(toScalarString(token.Extra("session_handle_expires_in"))), 64)
|
||||
if err != nil || age < 1 || age > 30*24*60*60 || !validHandle(handle) {
|
||||
http.Error(w, "Internal SSO binding missing; configure an internal client", 502)
|
||||
return
|
||||
}
|
||||
// No provider access token, ID token or watch credential survives this request.
|
||||
s.bindingCookie(w, handle, int(age))
|
||||
s.cookie(w, "fb_session", "", -1)
|
||||
http.Redirect(w, r, a.ReturnTo, http.StatusSeeOther)
|
||||
}
|
||||
func toScalarString(v any) string { b, _ := json.Marshal(v); return strings.Trim(string(b), `"`) }
|
||||
func validHandle(v string) bool {
|
||||
return len(v) >= 16 && len(v) <= 4096 && !strings.ContainsAny(v, "\r\n\x00; ")
|
||||
}
|
||||
|
||||
func (s *SSO) internalCall(ctx context.Context, endpoint string, form url.Values) (*http.Response, error) {
|
||||
r, err := http.NewRequestWithContext(ctx, http.MethodPost, s.issuer+endpoint, strings.NewReader(form.Encode()))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r.SetBasicAuth(s.oauth.ClientID, s.oauth.ClientSecret)
|
||||
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
return s.client.Do(r)
|
||||
}
|
||||
func (s *SSO) resolve(ctx context.Context, handle string) (internalState, error) {
|
||||
if handle == "" {
|
||||
return internalState{Status: "rebind_required"}, nil
|
||||
}
|
||||
if !validHandle(handle) {
|
||||
return internalState{Status: "rebind_required"}, nil
|
||||
}
|
||||
res, err := s.internalCall(ctx, "/internal/session/resolve", url.Values{"session_handle": {handle}})
|
||||
if err != nil {
|
||||
return internalState{}, errors.New("SSO unavailable")
|
||||
}
|
||||
defer res.Body.Close()
|
||||
if res.StatusCode == 400 {
|
||||
var failure struct {
|
||||
Error string `json:"error"`
|
||||
}
|
||||
if json.NewDecoder(io.LimitReader(res.Body, 8192)).Decode(&failure) == nil && failure.Error == "invalid_handle" {
|
||||
return internalState{Status: "rebind_required"}, nil
|
||||
}
|
||||
return internalState{}, errors.New("Invalid SSO response")
|
||||
}
|
||||
if res.StatusCode != 200 {
|
||||
return internalState{}, errors.New("SSO unavailable or client configuration invalid")
|
||||
}
|
||||
b, err := io.ReadAll(io.LimitReader(res.Body, 128*1024+1))
|
||||
var state internalState
|
||||
if err != nil || len(b) > 128*1024 || json.Unmarshal(b, &state) != nil {
|
||||
return internalState{}, errors.New("Invalid SSO response")
|
||||
}
|
||||
if state.Authenticated {
|
||||
if state.Status != "authenticated" || state.ClientID != s.oauth.ClientID || state.Expires <= time.Now().Unix() || state.State == "" || len(state.State) > 1024 || state.User == nil || strings.TrimSpace(state.User.Subject) == "" || len(state.User.Subject) > 512 {
|
||||
return internalState{}, errors.New("Invalid SSO identity")
|
||||
}
|
||||
} else {
|
||||
if state.User != nil {
|
||||
return internalState{}, errors.New("Invalid signed-out SSO response")
|
||||
}
|
||||
switch state.Status {
|
||||
case "signed_out", "access_denied", "factor_required", "rebind_required", "factor_enrollment_required":
|
||||
default:
|
||||
return internalState{}, errors.New("Unknown SSO status")
|
||||
}
|
||||
}
|
||||
return state, nil
|
||||
}
|
||||
func (s *SSO) current(r *http.Request) (browserState, sessionIdentity, error) {
|
||||
handle := ""
|
||||
if c, e := r.Cookie(internalCookie); e == nil {
|
||||
handle = c.Value
|
||||
}
|
||||
state, err := s.resolve(r.Context(), handle)
|
||||
if err != nil {
|
||||
return browserState{}, sessionIdentity{}, err
|
||||
}
|
||||
view := browserState{Status: state.Status, Authenticated: state.Authenticated, State: state.State, Factors: state.Factors, Reason: state.Reason}
|
||||
if !state.Authenticated {
|
||||
return view, sessionIdentity{}, nil
|
||||
}
|
||||
i, err := s.provisionUser(*state.User)
|
||||
if err != nil {
|
||||
return browserState{}, sessionIdentity{}, errors.New("Cannot load current user")
|
||||
}
|
||||
i.State, i.Handle = state.State, handle
|
||||
u, err := s.store.Users.Get(s.server.Root, s.server.FollowExternalSymlinks, i.ID)
|
||||
if err != nil {
|
||||
return browserState{}, sessionIdentity{}, errors.New("Cannot load current profile")
|
||||
}
|
||||
applySSOIdentity(u, i)
|
||||
profile := ssoUserInfo(u)
|
||||
profile.SessionState = state.State
|
||||
profile.AuthMode = "sso"
|
||||
key := state.User.Subject + "\x00" + state.User.Picture
|
||||
if state.User.Picture != "" {
|
||||
s.mu.Lock()
|
||||
avatar, ok := s.avatars[key]
|
||||
s.mu.Unlock()
|
||||
if !ok || time.Now().After(avatar.Until) {
|
||||
avatar = avatarCache{Image: s.loadAvatar(r.Context(), state.User.Picture), Until: time.Now().Add(5 * time.Minute)}
|
||||
s.mu.Lock()
|
||||
if len(s.avatars) > 1000 {
|
||||
s.avatars = map[string]avatarCache{}
|
||||
}
|
||||
s.avatars[key] = avatar
|
||||
s.mu.Unlock()
|
||||
}
|
||||
profile.Picture = avatar.Image
|
||||
}
|
||||
view.User = &profile
|
||||
return view, i, nil
|
||||
}
|
||||
|
||||
func isMutation(r *http.Request) bool {
|
||||
return r.Method != "GET" && r.Method != "HEAD" && r.Method != "OPTIONS"
|
||||
}
|
||||
func csrfAllowed(r *http.Request, origin string) bool {
|
||||
if r.Header.Get("Sec-Fetch-Site") == "cross-site" {
|
||||
return false
|
||||
}
|
||||
actual := r.Header.Get("Origin")
|
||||
if actual == "" {
|
||||
return r.Header.Get("X-FB-Request") == "1"
|
||||
}
|
||||
if origin != "" {
|
||||
return actual == origin
|
||||
}
|
||||
u, err := url.Parse(actual)
|
||||
return err == nil && u.User == nil && u.Host == r.Host && (u.Scheme == "https" || u.Scheme == "http")
|
||||
}
|
||||
func privatePath(p string) bool {
|
||||
return (strings.HasPrefix(p, "/api/") && !strings.HasPrefix(p, "/api/public/")) || strings.HasPrefix(p, "/addons/")
|
||||
}
|
||||
|
||||
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 isMutation(r) && !csrfAllowed(r, s.origin) {
|
||||
http.Error(w, "Cross-origin request rejected", 403)
|
||||
return
|
||||
}
|
||||
switch p {
|
||||
case "/auth/login":
|
||||
s.login(w, r)
|
||||
return
|
||||
case "/auth/callback":
|
||||
s.callback(w, r)
|
||||
return
|
||||
case "/auth/account":
|
||||
if r.Method != "GET" {
|
||||
w.WriteHeader(405)
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, s.issuer+"/settings", 302)
|
||||
return
|
||||
case "/api/login", "/api/signup", "/api/renew", "/api/command":
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
check := p == "/auth/session" || p == "/api/session"
|
||||
logout := p == "/auth/logout"
|
||||
if (check && r.Method != "GET") || (logout && r.Method != "POST") {
|
||||
w.WriteHeader(405)
|
||||
return
|
||||
}
|
||||
if !check && !logout && !privatePath(p) {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
state, identity, err := s.current(r)
|
||||
if err != nil {
|
||||
writeState(w, 503, browserState{Status: "unavailable"})
|
||||
return
|
||||
}
|
||||
if p == "/auth/session" {
|
||||
writeState(w, 200, state)
|
||||
return
|
||||
}
|
||||
if !state.Authenticated {
|
||||
code := 401
|
||||
if state.Status == "access_denied" || state.Status == "factor_enrollment_required" {
|
||||
code = 403
|
||||
}
|
||||
if state.Status == "factor_required" {
|
||||
code = 428
|
||||
}
|
||||
writeState(w, code, state)
|
||||
return
|
||||
}
|
||||
expected := r.Header.Get("X-FB-Session-State")
|
||||
if (isMutation(r) || expected != "") && expected != identity.State {
|
||||
writeState(w, 409, browserState{Status: "session_changed"})
|
||||
return
|
||||
}
|
||||
if logout {
|
||||
response, e := s.internalCall(r.Context(), "/internal/session/logout", url.Values{"session_handle": {identity.Handle}, "session_state": {identity.State}})
|
||||
if e != nil {
|
||||
writeState(w, 503, browserState{Status: "unavailable"})
|
||||
return
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode == 409 {
|
||||
writeState(w, 409, browserState{Status: "session_changed"})
|
||||
return
|
||||
}
|
||||
if response.StatusCode != 204 {
|
||||
writeState(w, 503, browserState{Status: "unavailable"})
|
||||
return
|
||||
}
|
||||
s.bindingCookie(w, "", -1)
|
||||
s.cookie(w, "fb_session", "", -1)
|
||||
w.WriteHeader(204)
|
||||
return
|
||||
}
|
||||
if p == "/api/session" {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(state.User)
|
||||
return
|
||||
}
|
||||
// A TUS transfer belongs to the account/state that created it, even if
|
||||
// two accounts share the same filesystem scope and destination path.
|
||||
if strings.HasPrefix(p, "/api/tus/") {
|
||||
key := identity.Sub + "\x00" + p
|
||||
s.mu.Lock()
|
||||
owner, exists := s.uploads[key]
|
||||
if r.Method == "POST" {
|
||||
for k, v := range s.uploads {
|
||||
if time.Now().After(v.Expires) {
|
||||
delete(s.uploads, k)
|
||||
}
|
||||
}
|
||||
if len(s.uploads) > 10000 {
|
||||
s.mu.Unlock()
|
||||
http.Error(w, "Too many transfers", 503)
|
||||
return
|
||||
}
|
||||
owner = uploadBinding{State: identity.State, Expires: time.Now().Add(time.Hour)}
|
||||
s.uploads[key] = owner
|
||||
exists = true
|
||||
}
|
||||
if exists && owner.State == identity.State && time.Now().Before(owner.Expires) {
|
||||
owner.Expires = time.Now().Add(time.Hour)
|
||||
s.uploads[key] = owner
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if !exists || owner.State != identity.State || time.Now().After(owner.Expires) {
|
||||
writeState(w, 409, browserState{Status: "session_changed"})
|
||||
return
|
||||
}
|
||||
}
|
||||
r = r.WithContext(context.WithValue(r.Context(), identityKey{}, identity))
|
||||
guard := &identityGuard{s: s, identity: identity, last: time.Now()}
|
||||
r = r.WithContext(context.WithValue(r.Context(), guardKey{}, guard))
|
||||
if isMutation(r) && r.Body != nil {
|
||||
r.Body = &guardedBody{ReadCloser: r.Body, guard: guard, ctx: r.Context()}
|
||||
}
|
||||
next.ServeHTTP(&guardedResponse{ResponseWriter: w, guard: guard, ctx: r.Context()}, r)
|
||||
})
|
||||
}
|
||||
|
||||
type guardKey struct{}
|
||||
type identityGuard struct {
|
||||
s *SSO
|
||||
identity sessionIdentity
|
||||
last time.Time
|
||||
}
|
||||
|
||||
func (g *identityGuard) check(ctx context.Context) error { return g.verify(ctx, false) }
|
||||
func (g *identityGuard) verify(ctx context.Context, force bool) error {
|
||||
if !force && time.Since(g.last) < 2*time.Second {
|
||||
return nil
|
||||
}
|
||||
state, err := g.s.resolve(ctx, g.identity.Handle)
|
||||
if err != nil || !state.Authenticated || state.User.Subject != g.identity.Sub || state.State != g.identity.State {
|
||||
return errors.New("session changed or unavailable")
|
||||
}
|
||||
g.last = time.Now()
|
||||
return nil
|
||||
}
|
||||
func checkOperationIdentity(r *http.Request) error {
|
||||
if g, ok := r.Context().Value(guardKey{}).(*identityGuard); ok {
|
||||
return g.verify(r.Context(), true)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type guardedBody struct {
|
||||
io.ReadCloser
|
||||
guard *identityGuard
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
func (b *guardedBody) Read(p []byte) (int, error) {
|
||||
if err := b.guard.check(b.ctx); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return b.ReadCloser.Read(p)
|
||||
}
|
||||
|
||||
type guardedResponse struct {
|
||||
http.ResponseWriter
|
||||
guard *identityGuard
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
func (w *guardedResponse) Write(p []byte) (int, error) {
|
||||
if err := w.guard.check(w.ctx); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return w.ResponseWriter.Write(p)
|
||||
}
|
||||
func (w *guardedResponse) Unwrap() http.ResponseWriter { return w.ResponseWriter }
|
||||
func (w *guardedResponse) Flush() {
|
||||
if w.guard.check(w.ctx) == nil {
|
||||
if f, ok := w.ResponseWriter.(http.Flusher); ok {
|
||||
f.Flush()
|
||||
}
|
||||
}
|
||||
}
|
||||
+32
-17
@@ -42,6 +42,8 @@ func TestOIDCSessionLifecycle(t *testing.T) {
|
||||
profileSubject := "subject-123"
|
||||
roles := []string{"FS Admin"}
|
||||
enabled := true
|
||||
invalidNonce := false
|
||||
signedOut := false
|
||||
provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch r.URL.Path {
|
||||
@@ -63,10 +65,31 @@ func TestOIDCSessionLifecycle(t *testing.T) {
|
||||
}
|
||||
hash := sha256.Sum256([]byte("access"))
|
||||
claims := map[string]any{"iss": issuer, "aud": "client", "sub": "subject-123", "roles": roles, "nonce": nonce, "exp": time.Now().Add(5 * time.Minute).Unix(), "iat": time.Now().Unix(), "at_hash": base64.RawURLEncoding.EncodeToString(hash[:16])}
|
||||
if invalidNonce {
|
||||
claims["nonce"] = "wrong"
|
||||
}
|
||||
b, _ := json.Marshal(claims)
|
||||
signed, _ := signer.Sign(b)
|
||||
token, _ := signed.CompactSerialize()
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"access_token": "access", "id_token": token, "token_type": "Bearer", "expires_in": 300})
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"access_token": "access", "id_token": token, "token_type": "Bearer", "expires_in": 300, "session_handle": "test-browser-handle-123456789", "session_handle_expires_in": 2592000})
|
||||
case "/internal/session/resolve":
|
||||
r.ParseForm()
|
||||
if id, secret, ok := r.BasicAuth(); !ok || id != "client" || secret != "secret" || r.Form.Get("session_handle") != "test-browser-handle-123456789" {
|
||||
t.Error("invalid internal resolve request")
|
||||
}
|
||||
if signedOut {
|
||||
json.NewEncoder(w).Encode(internalState{Status: "signed_out"})
|
||||
return
|
||||
}
|
||||
if !enabled {
|
||||
json.NewEncoder(w).Encode(internalState{Status: "access_denied"})
|
||||
return
|
||||
}
|
||||
json.NewEncoder(w).Encode(internalState{Status: "authenticated", Authenticated: true, ClientID: "client", State: "state-1", Expires: time.Now().Add(time.Hour).Unix(), User: &ssoClaims{Subject: profileSubject, Username: "alice", Name: "Alice Example", Email: "alice@example.test", Picture: issuer + "/avatars/alice.png", Roles: roles}})
|
||||
case "/internal/session/logout":
|
||||
signedOut = true
|
||||
w.WriteHeader(204)
|
||||
|
||||
case "/userinfo":
|
||||
if !enabled {
|
||||
w.WriteHeader(401)
|
||||
@@ -100,7 +123,7 @@ func TestOIDCSessionLifecycle(t *testing.T) {
|
||||
u, _ := url.Parse(login.Header().Get("Location"))
|
||||
nonce = u.Query().Get("nonce")
|
||||
challenge = u.Query().Get("code_challenge")
|
||||
if u.Query().Get("code_challenge_method") != "S256" || nonce == "" {
|
||||
if u.Query().Get("code_challenge_method") != "S256" || nonce == "" || u.Query().Get("internal_sync") != "1" || u.Query().Has("prompt") || u.Query().Has("max_age") {
|
||||
t.Fatal("missing PKCE or nonce")
|
||||
}
|
||||
callback := httptest.NewRequest("GET", "/auth/callback?code=test&state="+u.Query().Get("state"), nil)
|
||||
@@ -112,11 +135,11 @@ func TestOIDCSessionLifecycle(t *testing.T) {
|
||||
}
|
||||
var sessionCookie *http.Cookie
|
||||
for _, c := range response.Result().Cookies() {
|
||||
if c.Name == "fb_session" {
|
||||
if c.Name == internalCookie {
|
||||
sessionCookie = c
|
||||
}
|
||||
}
|
||||
if sessionCookie == nil || !sessionCookie.HttpOnly {
|
||||
if sessionCookie == nil || !sessionCookie.HttpOnly || !sessionCookie.Secure || sessionCookie.Path != "/" || sessionCookie.Domain != "" || sessionCookie.SameSite != http.SameSiteLaxMode {
|
||||
t.Fatal("missing HttpOnly session")
|
||||
}
|
||||
request := func(method, path string) *httptest.ResponseRecorder {
|
||||
@@ -124,6 +147,7 @@ func TestOIDCSessionLifecycle(t *testing.T) {
|
||||
r.AddCookie(sessionCookie)
|
||||
if method == "POST" {
|
||||
r.Header.Set("X-FB-Request", "1")
|
||||
r.Header.Set("X-FB-Session-State", "state-1")
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
@@ -171,8 +195,8 @@ func TestOIDCSessionLifecycle(t *testing.T) {
|
||||
}
|
||||
roles = []string{"User"}
|
||||
check = request("GET", "/api/session")
|
||||
if check.Code != 200 || !strings.Contains(check.Body.String(), `"admin":true`) {
|
||||
t.Fatal("login role snapshot changed during local session")
|
||||
if check.Code != 200 || !strings.Contains(check.Body.String(), `"admin":false`) {
|
||||
t.Fatal("current roles were not refreshed")
|
||||
}
|
||||
|
||||
for _, p := range []string{"/api/login", "/api/signup", "/api/renew", "/api/command"} {
|
||||
@@ -200,13 +224,13 @@ func TestOIDCSessionLifecycle(t *testing.T) {
|
||||
h.ServeHTTP(login, httptest.NewRequest("GET", "/auth/login", nil))
|
||||
u, _ = url.Parse(login.Header().Get("Location"))
|
||||
nonce, challenge = u.Query().Get("nonce"), u.Query().Get("code_challenge")
|
||||
profileSubject = "another-subject"
|
||||
invalidNonce = true
|
||||
callback = httptest.NewRequest("GET", "/auth/callback?code=test&state="+u.Query().Get("state"), nil)
|
||||
callback.AddCookie(login.Result().Cookies()[0])
|
||||
w = httptest.NewRecorder()
|
||||
h.ServeHTTP(w, callback)
|
||||
if w.Code != 401 {
|
||||
t.Fatal("mismatched UserInfo subject accepted")
|
||||
t.Fatal("invalid nonce accepted")
|
||||
}
|
||||
// Expired/idle sessions are rejected, even with an otherwise valid cookie.
|
||||
restarted, err := NewSSO(context.Background(), st, &settings.Server{Root: root}, SSOConfig{Issuer: issuer, ClientID: "client", ClientSecret: "secret", PublicURL: "http://127.0.0.1:9111"})
|
||||
@@ -258,13 +282,4 @@ func TestOIDCSessionLifecycle(t *testing.T) {
|
||||
t.Fatalf("existing records changed: %d %v", len(all), err)
|
||||
}
|
||||
}
|
||||
sessionKey := sha256.Sum256([]byte(sessionCookie.Value))
|
||||
for _, tc := range []struct{ expires, touched time.Time }{{time.Now().Add(-time.Second), time.Now()}, {time.Now().Add(time.Hour), time.Now().Add(-31 * time.Minute)}} {
|
||||
s.mu.Lock()
|
||||
s.sessions[sessionKey] = &ssoSession{Identity: sessionIdentity{ID: 2, Name: "alice"}, Expires: tc.expires, Touched: tc.touched}
|
||||
s.mu.Unlock()
|
||||
if request("GET", "/api/session").Code != 401 {
|
||||
t.Fatal("expired/idle session accepted")
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
-2
@@ -9,6 +9,7 @@ import (
|
||||
"io"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
@@ -33,8 +34,10 @@ func handleWithStaticData(w http.ResponseWriter, _ *http.Request, d *data, fSys
|
||||
"Version": version.Version,
|
||||
"StaticURL": path.Join(d.server.BaseURL, "/static"),
|
||||
"Signup": false,
|
||||
"NoAuth": false,
|
||||
"NoAuth": d.server.NoSSO,
|
||||
"AuthMethod": "sso",
|
||||
"SSOIssuer": d.server.SSOIssuer,
|
||||
"SSOClientID": d.server.SSOClientID,
|
||||
"LogoutPage": "/auth/logout",
|
||||
"LoginPage": true,
|
||||
"ReCaptcha": false,
|
||||
@@ -52,6 +55,13 @@ func handleWithStaticData(w http.ResponseWriter, _ *http.Request, d *data, fSys
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
frameSource := ""
|
||||
if d.server.SSOIssuer != "" && !d.server.NoSSO {
|
||||
if issuer, e := url.Parse(d.server.SSOIssuer); e == nil {
|
||||
frameSource = " " + issuer.Scheme + "://" + issuer.Host
|
||||
}
|
||||
}
|
||||
data["FrameSource"] = frameSource
|
||||
data["Json"] = template.JS(strings.ReplaceAll(string(b), `'`, `\'`))
|
||||
|
||||
fileContents, err := fs.ReadFile(fSys, file)
|
||||
@@ -73,7 +83,7 @@ func handleWithStaticData(w http.ResponseWriter, _ *http.Request, d *data, fSys
|
||||
cached, _ = indexTemplates.LoadOrStore(contents, parsed)
|
||||
}
|
||||
index := cached.(*template.Template)
|
||||
w.Header().Set("Content-Security-Policy", fmt.Sprintf("default-src 'self'; script-src 'self' 'nonce-%s' 'strict-dynamic'; style-src 'self' 'unsafe-inline'; font-src 'self' data:; img-src 'self' data: blob:; media-src 'self' blob:; manifest-src 'self' blob:; worker-src 'self' blob:; frame-src 'self' blob:; object-src 'none'; base-uri 'self'; frame-ancestors 'none'", data["Nonce"]))
|
||||
w.Header().Set("Content-Security-Policy", fmt.Sprintf("default-src 'self'; script-src 'self' 'nonce-%s' 'strict-dynamic'; style-src 'self' 'unsafe-inline'; font-src 'self' data:; img-src 'self' data: blob:; media-src 'self' blob:; manifest-src 'self' blob:; worker-src 'self' blob:; frame-src 'self' blob:%s; object-src 'none'; base-uri 'self'; frame-ancestors 'none'", data["Nonce"], frameSource))
|
||||
err = index.Execute(w, data)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
|
||||
@@ -66,14 +66,21 @@ func TestWorkspaceBrowserQA(t *testing.T) {
|
||||
}
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
r = authorizeTestRequest(r, testSession(1, "QA", true))
|
||||
if r.URL.Path == "/api/session" {
|
||||
if r.URL.Path == "/api/session" || r.URL.Path == "/auth/session" {
|
||||
u, err := st.Users.Get(root, false, uint(1))
|
||||
if err != nil {
|
||||
http.Error(w, "user", 500)
|
||||
return
|
||||
}
|
||||
u.DisplayName = "QA Account"
|
||||
renderJSON(w, r, ssoUserInfo(u))
|
||||
profile := ssoUserInfo(u)
|
||||
profile.SessionState = "qa"
|
||||
profile.AuthMode = "no-sso"
|
||||
if r.URL.Path == "/auth/session" {
|
||||
writeState(w, 200, browserState{Status: "authenticated", Authenticated: true, State: "qa", User: &profile})
|
||||
} else {
|
||||
renderJSON(w, r, profile)
|
||||
}
|
||||
return
|
||||
}
|
||||
handler.ServeHTTP(w, r)
|
||||
|
||||
Reference in new issue
Block a user