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() } } }