package server import ( "context" "net/http" "strings" "sync" "pageswiki/internal/store" ) type readPolicyContextKey struct{} type requestReadPolicy struct { mu sync.Mutex domain string filter func(string) bool } func withReadPolicyContext(r *http.Request) *http.Request { return r.WithContext(context.WithValue(r.Context(), readPolicyContextKey{}, &requestReadPolicy{})) } func (s *Server) pathReadFilter(r *http.Request) func(string) bool { domain := s.domainUUIDForRequest(r) if cached, ok := r.Context().Value(readPolicyContextKey{}).(*requestReadPolicy); ok { cached.mu.Lock() defer cached.mu.Unlock() if cached.filter == nil || cached.domain != domain { cached.domain, cached.filter = domain, s.loadPathReadFilter(r, domain) } return cached.filter } return s.loadPathReadFilter(r, domain) } func (s *Server) loadPathReadFilter(r *http.Request, domain string) func(string) bool { if p := publicNavigationFor(r); p != nil { return p.allows } deny := func(string) bool { return false } mode, err := s.store.GetConfigInDomain(domain, "authorization_mode") if err != nil { return deny } if mode != "enforcing" { return func(string) bool { return true } } principal, err := s.store.PrincipalForSession(domain, s.authTokenFromRequest(r)) if err != nil { return deny } policy, err := s.store.LoadReadPathPolicy(domain, principal.UUID) if err != nil { return deny } type userAudience struct { owner string policy store.UserSpacePolicy ok bool } userPolicies := map[string]userAudience{} var userPoliciesMu sync.Mutex isAdmin := s.store.IsBuiltinGroupAdmin(domain, principal.UUID, "domain_admin") return func(target string) bool { if !policy.Allows(target) { return false } username := store.UserSpaceUsername(target) if username == "" { return true } userPoliciesMu.Lock() defer userPoliciesMu.Unlock() entry, loaded := userPolicies[username] if !loaded { owner, ownerErr := s.store.PrincipalByUsername(domain, username) if ownerErr == nil { entry.owner = owner.UUID entry.policy, ownerErr = s.store.UserSpacePolicy(r.Context(), domain, owner.UUID) } entry.ok = ownerErr == nil userPolicies[username] = entry } if !entry.ok { return false } if isAdmin || principal.UUID == entry.owner { return true } root := "/u/" + username if target == root+"/_/avatar" { return entry.policy.AvatarVisibility != "private" } if strings.HasPrefix(target, root+"/_/") { return false } if target == root { return entry.policy.ProfileVisibility != "private" || entry.policy.RootVisibility != "private" } return store.EffectiveUserSpaceVisibility(entry.policy, target) != "private" } }