package server import ( "crypto/rand" "crypto/sha256" "crypto/subtle" "database/sql" "encoding/base64" "errors" "log" "net/http" "net/url" "strings" "pageswiki/internal/store" ) const authCookieName = "pageswiki_session" const mfaChallengeCookieName = "pageswiki_mfa" func (s *Server) ensureBootstrapToken(domainUUID string) error { if value, _ := s.store.GetConfigInDomain(domainUUID, "auth_bootstrap_token_hash"); value != "" { return nil } raw := make([]byte, 24) if _, err := rand.Read(raw); err != nil { return err } token := base64.RawURLEncoding.EncodeToString(raw) sum := sha256.Sum256([]byte(token)) if err := s.store.SetConfigInDomain(domainUUID, "auth_bootstrap_token_hash", base64.RawURLEncoding.EncodeToString(sum[:])); err != nil { return err } log.Printf("AUTH BOOTSTRAP TOKEN domain=%s token=%s (one-time; create the owner at /_/auth/login)", domainUUID, token) return nil } func (s *Server) validBootstrapToken(domainUUID, token string) bool { want, err := s.store.GetConfigInDomain(domainUUID, "auth_bootstrap_token_hash") if err != nil || want == "" { return false } sum := sha256.Sum256([]byte(strings.TrimSpace(token))) got := base64.RawURLEncoding.EncodeToString(sum[:]) return subtle.ConstantTimeCompare([]byte(want), []byte(got)) == 1 } func safeReturnPath(value string) string { value = strings.TrimSpace(value) parsed, err := url.Parse(value) if err != nil || !strings.HasPrefix(parsed.Path, "/") || strings.HasPrefix(parsed.Path, "//") || strings.ContainsAny(parsed.Path, "\\\r\n\x00") || parsed.IsAbs() || parsed.Host != "" { return "/" } return parsed.RequestURI() } func requestIsHTTPS(r *http.Request) bool { if r.TLS != nil { return true } return strings.EqualFold(strings.TrimSpace(strings.Split(r.Header.Get("X-Forwarded-Proto"), ",")[0]), "https") } func (s *Server) setAuthCookie(w http.ResponseWriter, r *http.Request, token string) { http.SetCookie(w, &http.Cookie{Name: authCookieName, Value: token, Path: "/", HttpOnly: true, Secure: requestIsHTTPS(r), SameSite: http.SameSiteLaxMode, MaxAge: 24 * 60 * 60}) } func (s *Server) authTokenFromRequest(r *http.Request) string { if headers := r.Header.Values("Authorization"); len(headers) != 0 { // An explicitly supplied but invalid credential must never fall back to // an ambient browser session (including unknown credential schemes). if len(headers) != 1 { return "" } parts := strings.Fields(headers[0]) if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") || len(parts[1]) > 4096 || strings.Contains(parts[1], ",") { return "" } if strings.HasPrefix(parts[1], "pw_browser_") { return "" } return parts[1] } var token string count := 0 for _, cookie := range r.Cookies() { if cookie.Name == authCookieName { token = cookie.Value count++ } } if count == 1 { if strings.HasPrefix(token, "pw_api_") { return "" } return token } return "" } func (s *Server) handleAuth(w http.ResponseWriter, r *http.Request) { action := strings.Trim(strings.TrimPrefix(r.URL.Path, "/_/auth"), "/") domainUUID := s.domainUUIDForRequest(r) switch action { case "wallpaper": s.handleAuthWallpaper(w, r) return case "oidc": s.beginOIDC(w, r) return case "ldap": s.handleLDAPLogin(w, r) return case "callback/oidc": s.completeOIDC(w, r) return case "magic-link": if r.Method == http.MethodPost { s.requestMagicLink(w, r) return } case "magic-link/verify": s.verifyMagicLink(w, r) return } if action == "logout" { s.handleLogout(w, r) return } if action != "login" && action != "setup" && action != "totp" { http.NotFound(w, r) return } if r.Method != http.MethodGet && r.Method != http.MethodHead && r.Method != http.MethodPost { w.Header().Set("Allow", "GET, HEAD, POST") http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } count, err := s.store.PrincipalCount() if err != nil { http.Error(w, err.Error(), 500) return } setup := count == 0 if setup { if err := s.ensureBootstrapToken(domainUUID); err != nil { http.Error(w, err.Error(), 500) return } } if r.Method == http.MethodPost { r.Body = http.MaxBytesReader(w, r.Body, 64<<10) if err := r.ParseForm(); err != nil { http.Error(w, err.Error(), 400) return } var principal *store.Principal mfaLevel := 0 if action == "setup" && setup && s.validBootstrapToken(domainUUID, r.FormValue("bootstrap_token")) { principal, err = s.store.BootstrapOwner(domainUUID, r.FormValue("username"), r.FormValue("password"), r.FormValue("display_name"), r.FormValue("email")) if err == nil { err = s.store.SetConfigInDomain(domainUUID, "authorization_mode", "enforcing") if err == nil { _ = s.store.SetConfigInDomain(domainUUID, "auth_bootstrap_token_hash", "") } } } else if action == "login" && !setup { principal, err = s.store.AuthenticatePassword(r.FormValue("username"), r.FormValue("password")) if err == nil && s.store.HasTOTP(principal.UUID) { challenge, challengeErr := s.store.CreateTOTPLoginChallenge(domainUUID, principal.UUID) if challengeErr != nil { err = challengeErr } else if strings.Contains(r.Header.Get("Accept"), "application/json") { writeEventJSON(w, http.StatusUnauthorized, map[string]any{"mfa_required": true, "challenge_token": challenge, "method": "totp"}) return } else { http.SetCookie(w, &http.Cookie{Name: mfaChallengeCookieName, Value: challenge, Path: "/_/auth/", HttpOnly: true, Secure: requestIsHTTPS(r), SameSite: http.SameSiteStrictMode, MaxAge: 300}) s.renderAuthPage(w, r, map[string]any{"MFA": true, "Return": safeReturnPath(r.FormValue("return"))}) return } } } else if action == "totp" && !setup { challenge := r.FormValue("challenge_token") if challenge == "" { if cookie, cookieErr := r.Cookie(mfaChallengeCookieName); cookieErr == nil { challenge = cookie.Value } } var principalUUID string principalUUID, err = s.store.CompleteTOTPLoginChallenge(domainUUID, challenge, r.FormValue("code")) if err == nil { principal = &store.Principal{UUID: principalUUID} mfaLevel = 1 http.SetCookie(w, &http.Cookie{Name: mfaChallengeCookieName, Path: "/_/auth/", MaxAge: -1, HttpOnly: true, Secure: requestIsHTTPS(r), SameSite: http.SameSiteStrictMode}) } } else { err = store.ErrAccessDenied } if err == nil { var token string if strings.Contains(r.Header.Get("Accept"), "application/json") { token, err = s.store.CreateAuthSessionWithMFA(domainUUID, principal.UUID, mfaLevel) } else { token, err = s.store.CreateBrowserAuthSession(domainUUID, principal.UUID, mfaLevel) } if err == nil { if strings.Contains(r.Header.Get("Accept"), "application/json") { writeEventJSON(w, http.StatusOK, map[string]any{"access_token": token, "token_type": "Bearer", "expires_in": 86400}) return } s.setAuthCookie(w, r, token) http.Redirect(w, r, safeReturnPath(r.FormValue("return")), http.StatusSeeOther) return } } if action == "totp" { s.renderAuthPage(w, r, map[string]any{"MFA": true, "Error": translate(s.getLocale(domainUUID), "auth.totp_invalid"), "Return": safeReturnPath(r.FormValue("return"))}) return } s.renderAuthPage(w, r, map[string]any{"Setup": setup, "Error": translate(s.getLocale(domainUUID), "auth.invalid_credentials"), "Return": safeReturnPath(r.FormValue("return"))}) return } s.renderAuthPage(w, r, map[string]any{"Setup": setup, "Return": safeReturnPath(r.URL.Query().Get("return"))}) } func authorizationTargetForRequest(r *http.Request, domainUUID string) (string, string) { policy := policyForRequest(r) if policy.Target == targetDomain { return string(targetDomain), domainUUID } path := r.URL.Path if strings.HasPrefix(path, "/e/") { return "path", semanticEditorPath(path) } return string(targetPath), path } func (s *Server) authorizePathRequest(r *http.Request, capability, path string) error { domainUUID := s.domainUUIDForRequest(r) mode, err := s.store.GetConfigInDomain(domainUUID, "authorization_mode") if err != nil { return err } if mode != "enforcing" { return nil } principal, err := s.store.PrincipalForSession(domainUUID, s.authTokenFromRequest(r)) if err != nil { return err } return s.store.Authorize(store.AuthorizationRequest{DomainUUID: domainUUID, PrincipalUUID: principal.UUID, Capability: capability, TargetType: "path", TargetID: path}) } func ownUserEditorPath(path, username string) bool { for _, prefix := range []string{"/e/-/u/", "/e/u/"} { if strings.HasPrefix(path, prefix) { owner := strings.Split(strings.TrimPrefix(path, prefix), "/")[0] return owner == username } } return false } func (s *Server) withAuthorization(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // HTML and dynamic listings contain per-principal data. They must not // enter shared caches even in legacy mode; immutable projections can // choose a more specific private cache policy in their own handlers. if r.URL.Path != "/health" && !strings.HasPrefix(r.URL.Path, "/static/") && !strings.HasPrefix(r.URL.Path, "/o/path:/system/static/") { w.Header().Set("Cache-Control", "private, no-store") w.Header().Add("Vary", "Cookie, Authorization") } // Runs before handler-owned auth and legacy-mode bypasses, protecting // login, groups, configuration and upload forms as well as JSON APIs. if !validBrowserMutationOrigin(r) { rejectBrowserMutation(w, r) return } // No process-wide principal/policy cache: revocation is observed by the // next request. Read snapshots never authorize mutating store operations. r = cacheRequestDomain(withReadPolicyContext(r)) if r.URL.Path == "/g" || strings.HasPrefix(r.URL.Path, "/g/") { next.ServeHTTP(w, r) return } if strings.HasPrefix(r.URL.Path, "/_/auth/") || r.URL.Path == "/health" || strings.HasPrefix(r.URL.Path, "/static/") || strings.HasPrefix(r.URL.Path, adapterGatewayPrefix+"/") || strings.HasPrefix(r.URL.Path, "/_/api/v1/adapter/session/") || r.URL.Path == "/_/api/v1/federation/enroll" { next.ServeHTTP(w, r) return } policy := policyForRequest(r) // Calendar handlers enforce per-calendar ACLs, including public reads, // regardless of the domain's legacy/enforcing switch. if taskRoute(r.URL.Path) || calendarRoute(r.URL.Path) { next.ServeHTTP(w, r) return } // Compatibility URL for public application assets, not document objects. // Serve from a confined static FileServer, never from object resolution. if (r.Method == http.MethodGet || r.Method == http.MethodHead) && strings.HasPrefix(r.URL.Path, "/o/path:/system/static/") { http.StripPrefix("/o/path:/system/static/", http.FileServer(http.Dir("./static"))).ServeHTTP(w, r) return } if policy.Capability == "deny" { http.Error(w, "forbidden: endpoint authorization policy is not defined", http.StatusForbidden) return } domainUUID := s.domainUUIDForRequest(r) mode, configErr := s.store.GetConfigInDomain(domainUUID, "authorization_mode") if configErr != nil { http.Error(w, "authorization policy unavailable", http.StatusServiceUnavailable) return } userSpacePath := "" if store.IsUserSpacePath(r.URL.Path) { userSpacePath = r.URL.Path } else if strings.HasPrefix(r.URL.Path, "/v/raw/path:/u/") { userSpacePath = strings.TrimPrefix(r.URL.Path, "/v/raw/path:") } else if username := publicUserNavigationUsername(r); username != "" { if r.URL.Path == "/v/children" { userSpacePath = r.URL.Query().Get("path") } else { userSpacePath = "/u/" + username } } if mode != "enforcing" && userSpacePath == "" { next.ServeHTTP(w, r) return } token := s.authTokenFromRequest(r) if token == "" { if s.tryAnonymousProjection(w, r) { return } s.authRequired(w, r) return } principal, err := s.store.PrincipalForSession(domainUUID, token) if err != nil { s.authRequired(w, r) return } if userSpacePath != "" { allowed, audienceErr := s.store.UserSpaceCanReadAuthenticated(r.Context(), domainUUID, principal.UUID, userSpacePath) if audienceErr != nil || !allowed { http.Error(w, "forbidden", http.StatusForbidden) return } } if mode != "enforcing" { next.ServeHTTP(w, r) return } if strings.HasPrefix(r.URL.Path, "/-/sys/config") { domain := s.domainForRequest(r) if s.store.IsBuiltinGroupAdmin(domainUUID, principal.UUID, "domain_admin") || (domain != nil && s.store.IsCampusAdmin(domain.CampusUUID, principal.UUID)) { next.ServeHTTP(w, r) return } } if strings.HasPrefix(r.URL.Path, "/_/api/v1/city/") && r.Method != http.MethodGet && r.Method != http.MethodHead && s.store.IsBuiltinGroupAdmin(domainUUID, principal.UUID, "domain_admin") { next.ServeHTTP(w, r) return } capability := policy.Capability if capability == "write" && principal.State == "active" && ownUserEditorPath(r.URL.Path, principal.Username) && s.store.CheckLocalityAccessCaps(domainUUID, principal.UUID, "write", semanticEditorPath(r.URL.Path)) == nil { next.ServeHTTP(w, r) return } if handled, resolvedErr := s.authorizeResolvedEndpoint(r, principal, policy); handled { if resolvedErr != nil { if errors.Is(resolvedErr, store.ErrAccessDenied) { http.Error(w, "forbidden", http.StatusForbidden) return } http.Error(w, resolvedErr.Error(), http.StatusInternalServerError) return } next.ServeHTTP(w, r) return } targetType, targetID := authorizationTargetForRequest(r, domainUUID) if capability == "write" && targetType == "path" { if _, resolveErr := s.store.ResolvePathInDomain(domainUUID, targetID); errors.Is(resolveErr, sql.ErrNoRows) { capability = "create" } } err = s.store.Authorize(store.AuthorizationRequest{DomainUUID: domainUUID, PrincipalUUID: principal.UUID, Capability: capability, TargetType: targetType, TargetID: targetID}) if err != nil { if errors.Is(err, store.ErrAccessDenied) { http.Error(w, "forbidden", http.StatusForbidden) return } http.Error(w, err.Error(), 500) return } next.ServeHTTP(w, r) }) } func (s *Server) authRequired(w http.ResponseWriter, r *http.Request) { if strings.HasPrefix(r.URL.Path, "/_/api/") { writeEventJSON(w, http.StatusUnauthorized, map[string]string{"error": "authentication required"}) return } http.Redirect(w, r, "/_/auth/login?return="+url.QueryEscape(r.URL.RequestURI()), http.StatusSeeOther) }