Files
filebrowser/backend/internal/database/access/access.go
T
3c8c02414e Beta/v2.0.1 (#2800)
Co-authored-by: Mattijs Bliek <mattijs@mattijsbliek.com>
Co-authored-by: GammelSami <39372285+GammelSami@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-08-15 11:06:07 -05:00

1394 lines
42 KiB
Go

package access
import (
"fmt"
"maps"
"path/filepath"
"slices"
"sort"
"strings"
"sync"
"time"
"github.com/gtsteffaniak/filebrowser/backend/internal/errors"
"github.com/gtsteffaniak/filebrowser/backend/pkg/settings"
"github.com/gtsteffaniak/filebrowser/backend/internal/utils"
"github.com/gtsteffaniak/filebrowser/backend/internal/database/users"
"github.com/gtsteffaniak/go-cache/cache"
"github.com/gtsteffaniak/go-logger/logger"
)
var (
accessCache = cache.NewCache[string](1 * time.Minute) // for accessChangedKey
versionCache = cache.NewCache[int](1 * time.Minute) // for version keys
permissionCache = cache.NewCache[bool](1 * time.Minute) // for permission keys
rulesCache = cache.NewCache[map[string]FrontendAccessRule](1 * time.Minute) // for rules
)
const accessChangedKey = "newRule:"
type RuleMap map[string]*AccessRule
type SourceRuleMap map[string]RuleMap
type StringSet map[string]struct{}
// RuleSet groups users and groups for allow/deny lists.
type RuleSet struct {
Users StringSet
Groups StringSet
}
// AccessRule defines allow/deny lists for a path.
type AccessRule struct {
DenyAll bool `json:"denyAll,omitempty"`
Deny RuleSet
Allow RuleSet
}
type FrontendRuleSet struct {
Users []string `json:"users"`
Groups []string `json:"groups"`
}
type FrontendAccessRule struct {
DenyAll bool `json:"denyAll,omitempty"`
Deny FrontendRuleSet `json:"deny"`
Allow FrontendRuleSet `json:"allow"`
SourceDenyDefault bool `json:"sourceDenyDefault"`
PathExists bool `json:"pathExists"`
}
// GroupMap maps group names to a set of usernames.
type GroupMap map[string]StringSet
// Storage manages access rules and group membership.
type Storage struct {
mux sync.RWMutex
AllRules SourceRuleMap // AllRules[sourcePath][indexPath] - in-memory authoritative state
Groups GroupMap // key: group name, value: set of usernames - in-memory authoritative state
RevokedTokens map[string]struct{} // set of revoked token hashes - in-memory authoritative state
HashedTokens map[string]uint64 // maps token hash → owner user id - in-memory authoritative state
Users *users.Storage // Reference to users storage
sqlStore SQLPersister // SQL store for persistence
}
// SQLPersister interface for SQL persistence operations
type SQLPersister interface {
SaveAccessRule(source, path string, rule *AccessRule) error
DeleteAccessRule(source, path string) error
SaveGroup(name string, members StringSet) error
DeleteGroup(name string) error
SaveRevokedToken(tokenHash string) error
SaveHashedToken(tokenHash string, userID uint64) error
DeleteHashedToken(tokenHash string) error
DeleteHashedTokensByUserID(userID uint64) error
}
// SetSQLStore sets the SQL store for persistence operations
func (s *Storage) SetSQLStore(sqlStore SQLPersister) {
s.sqlStore = sqlStore
}
// Flush is a no-op; access rule and group updates already write through sqlStore when configured.
func (s *Storage) Flush() error {
return nil
}
// persistGroupSQLNL upserts or deletes one groups row to match in-memory state.
// Caller must hold s.mux. If the group is absent from s.Groups, it is deleted from SQL.
func (s *Storage) persistGroupSQLNL(groupname string) {
if s.sqlStore == nil {
return
}
members, ok := s.Groups[groupname]
if !ok {
if err := s.sqlStore.DeleteGroup(groupname); err != nil {
logger.Errorf("failed to delete group %q from sql: %v", groupname, err)
}
return
}
if err := s.sqlStore.SaveGroup(groupname, members); err != nil {
logger.Errorf("failed to save group %q: %v", groupname, err)
}
}
// ensureGroupExistsNL creates an empty in-memory group if missing and write-through persists it.
// Caller must hold s.mux.
func (s *Storage) ensureGroupExistsNL(groupname string) {
if _, ok := s.Groups[groupname]; ok {
return
}
s.Groups[groupname] = make(StringSet)
s.persistGroupSQLNL(groupname)
}
// NewStorage creates a new Storage instance.
func NewStorage(usersStore *users.Storage) *Storage {
var s = &Storage{
AllRules: make(SourceRuleMap),
Groups: make(GroupMap),
RevokedTokens: make(map[string]struct{}),
HashedTokens: make(map[string]uint64),
Users: usersStore,
}
return s
}
// ClearCache clears the access cache (useful for testing)
func ClearCache() {
// Recreate the caches to clear them
accessCache = cache.NewCache[string](1 * time.Minute)
versionCache = cache.NewCache[int](1 * time.Minute)
permissionCache = cache.NewCache[bool](1 * time.Minute)
rulesCache = cache.NewCache[map[string]FrontendAccessRule](1 * time.Minute)
}
// clearAllCaches clears ALL caches. This should be called whenever rules are created, updated, or deleted.
func (s *Storage) clearAllCaches() {
accessCache.ClearAll()
versionCache.ClearAll()
permissionCache.ClearAll()
rulesCache.ClearAll()
}
func accessRuleHasPayload(rule *AccessRule) bool {
if rule == nil {
return false
}
return rule.DenyAll ||
len(rule.Allow.Users) > 0 || len(rule.Allow.Groups) > 0 ||
len(rule.Deny.Users) > 0 || len(rule.Deny.Groups) > 0
}
// persistRuleSQLNL upserts or deletes one access_rules row to match in-memory state.
// Caller must hold s.mux (write lock). normalizedPath must match rule map keys (see getOrCreateRuleNL).
func (s *Storage) persistRuleSQLNL(sourcePath, normalizedPath string) {
if s.sqlStore == nil {
return
}
var rule *AccessRule
if bySrc, ok := s.AllRules[sourcePath]; ok {
rule = bySrc[normalizedPath]
}
if !accessRuleHasPayload(rule) {
if err := s.sqlStore.DeleteAccessRule(sourcePath, normalizedPath); err != nil {
logger.Warningf("access rules SQL delete (source=%s path=%s): %v", sourcePath, normalizedPath, err)
}
return
}
if err := s.sqlStore.SaveAccessRule(sourcePath, normalizedPath, rule); err != nil {
logger.Warningf("access rules SQL save (source=%s path=%s): %v", sourcePath, normalizedPath, err)
}
}
// RemoveRuleByPath removes a rule by normalized index path.
func (s *Storage) RemoveRuleByPath(sourcePath string, indexPath utils.IndexPath) {
s.RemoveRuleByPathKey(sourcePath, ruleKey(indexPath))
}
// RemoveRuleByPathKey removes a rule by its exact storage key (for legacy migration paths).
func (s *Storage) RemoveRuleByPathKey(sourcePath, pathKey string) {
s.mux.Lock()
defer s.mux.Unlock()
rulesBySource, ok := s.AllRules[sourcePath]
if !ok {
return
}
if _, exists := rulesBySource[pathKey]; !exists {
return
}
delete(rulesBySource, pathKey)
if len(rulesBySource) == 0 {
delete(s.AllRules, sourcePath)
}
s.clearAllCaches()
s.persistRuleSQLNL(sourcePath, pathKey)
if s.sqlStore != nil {
_ = s.sqlStore.DeleteAccessRule(sourcePath, pathKey)
normalized := utils.AddTrailingSlashIfNotExists(pathKey)
if normalized != pathKey {
_ = s.sqlStore.DeleteAccessRule(sourcePath, normalized)
}
}
}
// getOrCreateRuleNL ensures a rule exists for the given source and index path.
// The caller must hold the lock.
func (s *Storage) getOrCreateRuleNL(sourcePath string, indexPath utils.IndexPath) *AccessRule {
normalizedPath := ruleKey(indexPath)
if _, ok := s.AllRules[sourcePath]; !ok {
s.AllRules[sourcePath] = make(RuleMap)
}
rule, ok := s.AllRules[sourcePath][normalizedPath]
if !ok {
rule = &AccessRule{
Deny: RuleSet{Users: make(StringSet), Groups: make(StringSet)},
Allow: RuleSet{Users: make(StringSet), Groups: make(StringSet)},
}
s.AllRules[sourcePath][normalizedPath] = rule
}
return rule
}
// DenyUser adds a user to the deny list for a given source and index path.
// Rules are keyed by login name (username), not user id.
func (s *Storage) DenyUser(sourcePath string, indexPath utils.IndexPath, username string) error {
s.mux.Lock()
defer s.mux.Unlock()
rule := s.getOrCreateRuleNL(sourcePath, indexPath)
if _, ok := rule.Deny.Users[username]; ok {
return errors.ErrExist
}
rule.Deny.Users[username] = struct{}{}
s.clearAllCaches()
s.persistRuleSQLNL(sourcePath, ruleKey(indexPath))
return nil
}
// AllowUser adds a user to the allow list for a given source and index path.
// Rules are keyed by login name (username), not user id.
func (s *Storage) AllowUser(sourcePath string, indexPath utils.IndexPath, username string) error {
s.mux.Lock()
defer s.mux.Unlock()
rule := s.getOrCreateRuleNL(sourcePath, indexPath)
if _, ok := rule.Allow.Users[username]; ok {
return errors.ErrExist
}
rule.Allow.Users[username] = struct{}{}
s.clearAllCaches()
s.persistRuleSQLNL(sourcePath, ruleKey(indexPath))
return nil
}
// DenyGroup adds a group to the deny list for a given source and index path.
// Unknown groups are auto-created (empty) so admins can configure rules before first SSO sync.
func (s *Storage) DenyGroup(sourcePath string, indexPath utils.IndexPath, groupname string) error {
s.mux.Lock()
defer s.mux.Unlock()
s.ensureGroupExistsNL(groupname)
rule := s.getOrCreateRuleNL(sourcePath, indexPath)
if _, ok := rule.Deny.Groups[groupname]; ok {
return errors.ErrExist
}
rule.Deny.Groups[groupname] = struct{}{}
s.clearAllCaches()
s.persistRuleSQLNL(sourcePath, ruleKey(indexPath))
return nil
}
// AllowGroup adds a group to the allow list for a given source and index path.
// Unknown groups are auto-created (empty) so admins can configure rules before first SSO sync.
func (s *Storage) AllowGroup(sourcePath string, indexPath utils.IndexPath, groupname string) error {
s.mux.Lock()
defer s.mux.Unlock()
s.ensureGroupExistsNL(groupname)
rule := s.getOrCreateRuleNL(sourcePath, indexPath)
if _, ok := rule.Allow.Groups[groupname]; ok {
return errors.ErrExist
}
rule.Allow.Groups[groupname] = struct{}{}
s.clearAllCaches()
s.persistRuleSQLNL(sourcePath, ruleKey(indexPath))
return nil
}
// DenyAll sets a rule to deny all access for a given source and index path.
func (s *Storage) DenyAll(sourcePath string, indexPath utils.IndexPath) error {
s.mux.Lock()
defer s.mux.Unlock()
rule := s.getOrCreateRuleNL(sourcePath, indexPath)
if rule.DenyAll {
return errors.ErrExist
}
rule.DenyAll = true
s.clearAllCaches()
s.persistRuleSQLNL(sourcePath, ruleKey(indexPath))
return nil
}
// Permitted checks if a username is permitted for a given sourcePath and indexPath, recursively checking parent directories.
func (s *Storage) Permitted(sourcePath string, indexPath utils.IndexPath, username string) bool {
indexPath = checkPath(indexPath)
pathStr := indexPath.String()
// Get current version for the sourcePath
versionKey := "version:" + sourcePath
version := 0
if v, ok := versionCache.Get(versionKey); ok {
version = v
}
// Check cache with versioned key
permKey := fmt.Sprintf("perm:%s:%d:%s:%s", sourcePath, version, pathStr, username)
if p, ok := permissionCache.Get(permKey); ok {
return p
}
// Not in cache, compute, then cache it.
result := s.computePermitted(sourcePath, indexPath, username)
permissionCache.Set(permKey, result)
return result
}
func (s *Storage) computePermitted(sourcePath string, indexPath utils.IndexPath, username string) bool {
var rulesFound []*AccessRule
currentPath := checkPath(indexPath)
for {
rule, found := s.getRuleAtExactPath(sourcePath, currentPath)
if found {
rulesFound = append(rulesFound, rule)
}
if currentPath.IsRoot() {
break
}
currentPath = currentPath.Parent()
}
// Now evaluate the rules, starting from the most specific (indexPath) to the least specific (root)
for _, rule := range rulesFound {
permitted, hasSpecificRule := s.evaluateRuleForUser(rule, username)
if hasSpecificRule {
return permitted
}
}
// No specific user or group rule found in the hierarchy.
// Check for any DenyAll rule in the path.
for _, rule := range rulesFound {
if rule.DenyAll {
return false
}
}
// No specific rules found anywhere in the path hierarchy.
// Fallback to the source's DenyByDefault setting.
sourceInfo, ok := settings.Config.Server.SourceMap[sourcePath]
if !ok {
logger.Errorf("source %s not found in config during access check", sourcePath)
return false
}
return !sourceInfo.Config.DenyByDefault
}
// getRuleAtExactPath is a helper to get a rule without the recursive logic.
func (s *Storage) getRuleAtExactPath(sourcePath string, indexPath utils.IndexPath) (*AccessRule, bool) {
s.mux.RLock()
defer s.mux.RUnlock()
rulesBySource, ok := s.AllRules[sourcePath]
if !ok {
return nil, false
}
rule, ok := rulesBySource[ruleKey(indexPath)]
return rule, ok
}
// evaluateRuleForUser evaluates a single rule for a user and returns if a specific rule was found.
func (s *Storage) evaluateRuleForUser(rule *AccessRule, username string) (permitted bool, hasSpecificRule bool) {
// Check user deny first
if _, found := rule.Deny.Users[username]; found {
return false, true
}
// Check group deny
for group := range rule.Deny.Groups {
if s.isUserInGroup(username, group) {
return false, true
}
}
// Check user allow
if _, found := rule.Allow.Users[username]; found {
return true, true
}
// Check group allow
for group := range rule.Allow.Groups {
if s.isUserInGroup(username, group) {
return true, true
}
}
// No specific rule for this user in this rule set.
return false, false
}
// isUserInGroup checks if a username is in a group.
func (s *Storage) isUserInGroup(username, group string) bool {
s.mux.RLock()
defer s.mux.RUnlock()
users, ok := s.Groups[group]
if !ok {
return false
}
_, found := users[username]
return found
}
// GetRule retrieves a rule for a sourcePath and indexPath.
func (s *Storage) GetFrontendRules(sourcePath string, indexPath utils.IndexPath) (FrontendAccessRule, bool) {
s.mux.RLock()
defer s.mux.RUnlock()
// Get source configuration
sourceDenyDefault := false
sourceInfo, sourceExists := settings.Config.Server.SourceMap[sourcePath]
if sourceExists {
sourceDenyDefault = sourceInfo.Config.DenyByDefault
}
// Check if path exists on filesystem
pathExists := utils.CheckPathExists(filepath.Join(sourcePath, indexPath.String()))
frontendRules := FrontendAccessRule{
SourceDenyDefault: sourceDenyDefault,
PathExists: pathExists,
Deny: FrontendRuleSet{
Users: make([]string, 0),
Groups: make([]string, 0),
},
Allow: FrontendRuleSet{
Users: make([]string, 0),
Groups: make([]string, 0),
},
}
rulesBySource, ok := s.AllRules[sourcePath]
if !ok {
return frontendRules, false
}
rule, ok := rulesBySource[ruleKey(indexPath)]
if !ok || rule == nil {
return frontendRules, false
}
// Convert AccessRule to FrontendAccessRule
frontendRules.DenyAll = rule.DenyAll
frontendRules.Deny.Users = utils.NonNilSlice(slices.Collect(maps.Keys(rule.Deny.Users)))
frontendRules.Deny.Groups = utils.NonNilSlice(slices.Collect(maps.Keys(rule.Deny.Groups)))
frontendRules.Allow.Users = utils.NonNilSlice(slices.Collect(maps.Keys(rule.Allow.Users)))
frontendRules.Allow.Groups = utils.NonNilSlice(slices.Collect(maps.Keys(rule.Allow.Groups)))
return frontendRules, ok
}
// GetAllRules returns all access rules as a map.
func (s *Storage) GetAllRules(sourcePath string) (map[string]FrontendAccessRule, error) {
// Check if rules have changed by looking at the access cache
_, hasChanged := accessCache.Get(accessChangedKey + sourcePath)
if !hasChanged {
// If no change marker, check if we have cached rules
value, ok := rulesCache.Get(accessChangedKey + sourcePath)
if ok {
return value, nil
}
}
s.mux.RLock()
defer s.mux.RUnlock()
// Get source configuration
sourceDenyDefault := false
sourceInfo, sourceExists := settings.Config.Server.SourceMap[sourcePath]
if sourceExists {
sourceDenyDefault = sourceInfo.Config.DenyByDefault
}
// Return a copy to avoid external mutation
frontendRules := make(map[string]FrontendAccessRule, len(s.AllRules))
rules, ok := s.AllRules[sourcePath]
if !ok {
return frontendRules, nil
}
for indexPath, rule := range rules {
// Use the internal path as the frontend path (with trailing slash)
// This ensures consistency between internal storage and frontend display
frontendPath := indexPath
// Check if path exists on filesystem
pathExists := utils.CheckPathExists(filepath.Join(sourcePath, indexPath))
// Convert AccessRule to FrontendAccessRule
frontendRules[frontendPath] = FrontendAccessRule{
DenyAll: rule.DenyAll,
SourceDenyDefault: sourceDenyDefault,
PathExists: pathExists,
Deny: FrontendRuleSet{
Users: utils.NonNilSlice(slices.Collect(maps.Keys(rule.Deny.Users))),
Groups: utils.NonNilSlice(slices.Collect(maps.Keys(rule.Deny.Groups))),
},
Allow: FrontendRuleSet{
Users: utils.NonNilSlice(slices.Collect(maps.Keys(rule.Allow.Users))),
Groups: utils.NonNilSlice(slices.Collect(maps.Keys(rule.Allow.Groups))),
},
}
}
// cache responses
rulesCache.Set(accessChangedKey+sourcePath, frontendRules)
return frontendRules, nil
}
// AddUserToGroup adds a username to a group.
func (s *Storage) AddUserToGroup(group, username string) error {
s.mux.Lock()
defer s.mux.Unlock()
if _, ok := s.Groups[group]; !ok {
s.Groups[group] = make(StringSet)
}
if _, ok := s.Groups[group][username]; ok {
return nil
}
s.Groups[group][username] = struct{}{}
s.persistGroupSQLNL(group)
s.clearAllCaches()
return nil
}
// GetAllGroups returns all group names.
func (s *Storage) GetAllGroups() []string {
s.mux.RLock()
defer s.mux.RUnlock()
groups := make([]string, 0, len(s.Groups))
for group := range s.Groups {
groups = append(groups, group)
}
sort.Strings(groups)
return groups
}
// GetUserGroups returns all groups for a specific user.
func (s *Storage) GetUserGroups(username string) []string {
s.mux.RLock()
defer s.mux.RUnlock()
var groups []string
for group, users := range s.Groups {
if _, ok := users[username]; ok {
groups = append(groups, group)
}
}
return utils.NonNilSlice(groups)
}
// SyncUserGroups updates a user's group memberships.
// It removes the user from groups not in the new list and adds them to new ones.
// Changes are write-through to SQL when a sqlStore is configured.
func (s *Storage) SyncUserGroups(username string, newGroups []string) error {
s.mux.Lock()
defer s.mux.Unlock()
affected := make(map[string]struct{})
// Create a set of new groups for efficient lookup
newGroupsSet := make(StringSet, len(newGroups))
for _, g := range newGroups {
if g == "" {
continue
}
newGroupsSet[g] = struct{}{}
}
// Iterate over all existing groups to find the user's current memberships
for group, members := range s.Groups {
_, userIsInGroup := members[username]
_, groupIsInNewSet := newGroupsSet[group]
// If user is in a group that is not in their new set of groups, remove them.
if userIsInGroup && !groupIsInNewSet {
delete(s.Groups[group], username)
affected[group] = struct{}{}
}
}
// Add user to new groups
for group := range newGroupsSet {
if _, ok := s.Groups[group]; !ok {
s.Groups[group] = make(StringSet)
}
if _, ok := s.Groups[group][username]; !ok {
s.Groups[group][username] = struct{}{}
affected[group] = struct{}{}
}
}
for group := range affected {
s.persistGroupSQLNL(group)
}
if len(affected) > 0 {
s.clearAllCaches()
}
return nil
}
// RemoveUserFromGroup removes a username from a group.
func (s *Storage) RemoveUserFromGroup(group, username string) error {
s.mux.Lock()
defer s.mux.Unlock()
members, ok := s.Groups[group]
if !ok {
return nil
}
if _, ok := members[username]; !ok {
return nil
}
delete(members, username)
s.persistGroupSQLNL(group)
s.clearAllCaches()
return nil
}
// RemoveAllowUser removes a user from the allow list for a given source and index path.
func (s *Storage) RemoveAllowUser(sourcePath string, indexPath utils.IndexPath, username string) (bool, error) {
s.mux.Lock()
defer s.mux.Unlock()
normalizedPath := ruleKey(indexPath)
rule, ok := s.AllRules[sourcePath][normalizedPath]
if !ok {
return false, nil
}
_, exists := rule.Allow.Users[username]
if exists {
delete(rule.Allow.Users, username)
}
removed := exists
// If rule is now empty, remove it
if len(rule.Allow.Users) == 0 && len(rule.Allow.Groups) == 0 && len(rule.Deny.Users) == 0 && len(rule.Deny.Groups) == 0 {
delete(s.AllRules[sourcePath], normalizedPath)
if len(s.AllRules[sourcePath]) == 0 {
delete(s.AllRules, sourcePath)
}
}
if removed {
s.clearAllCaches()
s.persistRuleSQLNL(sourcePath, normalizedPath)
return exists, nil
}
return false, nil
}
// RemoveAllowGroup removes a group from the allow list for a given source and index path.
func (s *Storage) RemoveAllowGroup(sourcePath string, indexPath utils.IndexPath, groupname string) (bool, error) {
s.mux.Lock()
defer s.mux.Unlock()
normalizedPath := ruleKey(indexPath)
rule, ok := s.AllRules[sourcePath][normalizedPath]
if !ok {
return false, nil
}
_, exists := rule.Allow.Groups[groupname]
if exists {
delete(rule.Allow.Groups, groupname)
}
removed := exists
// If rule is now empty, remove it
if len(rule.Allow.Users) == 0 && len(rule.Allow.Groups) == 0 && len(rule.Deny.Users) == 0 && len(rule.Deny.Groups) == 0 {
delete(s.AllRules[sourcePath], normalizedPath)
if len(s.AllRules[sourcePath]) == 0 {
delete(s.AllRules, sourcePath)
}
}
if removed {
s.clearAllCaches()
s.persistRuleSQLNL(sourcePath, normalizedPath)
return exists, nil
}
return false, nil
}
// RemoveDenyUser removes a user from the deny list for a given source and index path.
func (s *Storage) RemoveDenyUser(sourcePath string, indexPath utils.IndexPath, username string) (bool, error) {
s.mux.Lock()
defer s.mux.Unlock()
normalizedPath := ruleKey(indexPath)
rule, ok := s.AllRules[sourcePath][normalizedPath]
if !ok {
return false, nil
}
_, exists := rule.Deny.Users[username]
if exists {
delete(rule.Deny.Users, username)
}
removed := exists
// If rule is now empty, remove it
if len(rule.Allow.Users) == 0 && len(rule.Allow.Groups) == 0 && len(rule.Deny.Users) == 0 && len(rule.Deny.Groups) == 0 {
delete(s.AllRules[sourcePath], normalizedPath)
if len(s.AllRules[sourcePath]) == 0 {
delete(s.AllRules, sourcePath)
}
}
if removed {
s.clearAllCaches()
s.persistRuleSQLNL(sourcePath, normalizedPath)
return exists, nil
}
return false, nil
}
// RemoveDenyGroup removes a group from the deny list for a given source and index path.
func (s *Storage) RemoveDenyGroup(sourcePath string, indexPath utils.IndexPath, groupname string) (bool, error) {
s.mux.Lock()
defer s.mux.Unlock()
normalizedPath := ruleKey(indexPath)
rule, ok := s.AllRules[sourcePath][normalizedPath]
if !ok {
return false, nil
}
_, exists := rule.Deny.Groups[groupname]
if exists {
delete(rule.Deny.Groups, groupname)
}
removed := exists
// If rule is now empty, remove it
if len(rule.Allow.Users) == 0 && len(rule.Allow.Groups) == 0 && len(rule.Deny.Users) == 0 && len(rule.Deny.Groups) == 0 {
delete(s.AllRules[sourcePath], normalizedPath)
if len(s.AllRules[sourcePath]) == 0 {
delete(s.AllRules, sourcePath)
}
}
if removed {
s.clearAllCaches()
s.persistRuleSQLNL(sourcePath, normalizedPath)
return exists, nil
}
return false, nil
}
// RemoveDenyAll removes the deny all rule for a given source and index path.
func (s *Storage) RemoveDenyAll(sourcePath string, indexPath utils.IndexPath) (bool, error) {
s.mux.Lock()
defer s.mux.Unlock()
normalizedPath := ruleKey(indexPath)
rule, ok := s.AllRules[sourcePath][normalizedPath]
if !ok {
return false, nil
}
removed := false
if rule.DenyAll {
rule.DenyAll = false
removed = true
}
// If rule is now empty, remove it
if len(rule.Allow.Users) == 0 && len(rule.Allow.Groups) == 0 && len(rule.Deny.Users) == 0 && len(rule.Deny.Groups) == 0 {
delete(s.AllRules[sourcePath], normalizedPath)
if len(s.AllRules[sourcePath]) == 0 {
delete(s.AllRules, sourcePath)
}
}
if removed {
s.clearAllCaches()
s.persistRuleSQLNL(sourcePath, normalizedPath)
return true, nil
}
return false, nil
}
// RemoveAllRulesForUser removes a user from all allow and deny lists.
func (s *Storage) RemoveAllRulesForUser(username string) error {
s.mux.Lock()
defer s.mux.Unlock()
changed := false
dirty := make(map[string]map[string]struct{})
touch := func(sp, ip string) {
if dirty[sp] == nil {
dirty[sp] = make(map[string]struct{})
}
dirty[sp][ip] = struct{}{}
}
for sourcePath, rulesBySource := range s.AllRules {
for indexPath, rule := range rulesBySource {
if _, exists := rule.Allow.Users[username]; exists {
delete(rule.Allow.Users, username)
touch(sourcePath, indexPath)
changed = true
}
if _, exists := rule.Deny.Users[username]; exists {
delete(rule.Deny.Users, username)
touch(sourcePath, indexPath)
changed = true
}
if len(rule.Allow.Users) == 0 && len(rule.Allow.Groups) == 0 && len(rule.Deny.Users) == 0 && len(rule.Deny.Groups) == 0 {
delete(s.AllRules[sourcePath], indexPath)
if len(s.AllRules[sourcePath]) == 0 {
delete(s.AllRules, sourcePath)
}
touch(sourcePath, indexPath)
}
}
}
if changed {
s.clearAllCaches()
for sp, paths := range dirty {
for ip := range paths {
s.persistRuleSQLNL(sp, ip)
}
}
}
return nil
}
// RemoveAllRulesForGroup removes a group from all allow and deny lists.
func (s *Storage) RemoveAllRulesForGroup(groupname string) error {
s.mux.Lock()
defer s.mux.Unlock()
changed := false
dirty := make(map[string]map[string]struct{})
touch := func(sp, ip string) {
if dirty[sp] == nil {
dirty[sp] = make(map[string]struct{})
}
dirty[sp][ip] = struct{}{}
}
for sourcePath, rulesBySource := range s.AllRules {
for indexPath, rule := range rulesBySource {
if _, exists := rule.Allow.Groups[groupname]; exists {
delete(rule.Allow.Groups, groupname)
touch(sourcePath, indexPath)
changed = true
}
if _, exists := rule.Deny.Groups[groupname]; exists {
delete(rule.Deny.Groups, groupname)
touch(sourcePath, indexPath)
changed = true
}
if len(rule.Allow.Users) == 0 && len(rule.Allow.Groups) == 0 && len(rule.Deny.Users) == 0 && len(rule.Deny.Groups) == 0 {
delete(s.AllRules[sourcePath], indexPath)
if len(s.AllRules[sourcePath]) == 0 {
delete(s.AllRules, sourcePath)
}
touch(sourcePath, indexPath)
}
}
}
if changed {
s.clearAllCaches()
for sp, paths := range dirty {
for ip := range paths {
s.persistRuleSQLNL(sp, ip)
}
}
}
return nil
}
// GetRulesForUser returns all rules for a specific user for a given sourcePath.
func (s *Storage) GetRulesForUser(sourcePath, username string) map[string]FrontendAccessRule {
s.mux.RLock()
defer s.mux.RUnlock()
// Get source configuration
sourceDenyDefault := false
sourceInfo, sourceExists := settings.Config.Server.SourceMap[sourcePath]
if sourceExists {
sourceDenyDefault = sourceInfo.Config.DenyByDefault
}
userRules := make(map[string]FrontendAccessRule)
rulesBySource, ok := s.AllRules[sourcePath]
if !ok {
return userRules
}
for indexPath, rule := range rulesBySource {
userHasRule := false
if _, ok := rule.Allow.Users[username]; ok {
userHasRule = true
}
if !userHasRule {
if _, ok := rule.Deny.Users[username]; ok {
userHasRule = true
}
}
if userHasRule {
userRules[indexPath] = FrontendAccessRule{
DenyAll: rule.DenyAll,
SourceDenyDefault: sourceDenyDefault,
Deny: FrontendRuleSet{
Users: utils.NonNilSlice(slices.Collect(maps.Keys(rule.Deny.Users))),
Groups: utils.NonNilSlice(slices.Collect(maps.Keys(rule.Deny.Groups))),
},
Allow: FrontendRuleSet{
Users: utils.NonNilSlice(slices.Collect(maps.Keys(rule.Allow.Users))),
Groups: utils.NonNilSlice(slices.Collect(maps.Keys(rule.Allow.Groups))),
},
}
}
}
return userRules
}
// GetRulesForGroup returns all rules for a specific group for a given sourcePath.
func (s *Storage) GetRulesForGroup(sourcePath, groupname string) map[string]FrontendAccessRule {
s.mux.RLock()
defer s.mux.RUnlock()
// Get source configuration
sourceDenyDefault := false
sourceInfo, sourceExists := settings.Config.Server.SourceMap[sourcePath]
if sourceExists {
sourceDenyDefault = sourceInfo.Config.DenyByDefault
}
groupRules := make(map[string]FrontendAccessRule)
rulesBySource, ok := s.AllRules[sourcePath]
if !ok {
return groupRules
}
for indexPath, rule := range rulesBySource {
groupHasRule := false
if _, ok := rule.Allow.Groups[groupname]; ok {
groupHasRule = true
}
if !groupHasRule {
if _, ok := rule.Deny.Groups[groupname]; ok {
groupHasRule = true
}
}
if groupHasRule {
groupRules[indexPath] = FrontendAccessRule{
DenyAll: rule.DenyAll,
SourceDenyDefault: sourceDenyDefault,
Deny: FrontendRuleSet{
Users: utils.NonNilSlice(slices.Collect(maps.Keys(rule.Deny.Users))),
Groups: utils.NonNilSlice(slices.Collect(maps.Keys(rule.Deny.Groups))),
},
Allow: FrontendRuleSet{
Users: utils.NonNilSlice(slices.Collect(maps.Keys(rule.Allow.Users))),
Groups: utils.NonNilSlice(slices.Collect(maps.Keys(rule.Allow.Groups))),
},
}
}
}
return groupRules
}
// GetAllRulesByUsers returns a map of usernames to their rules for a given sourcePath.
func (s *Storage) GetAllRulesByUsers(sourcePath string) map[string]map[string]FrontendAccessRule {
s.mux.RLock()
defer s.mux.RUnlock()
// Get source configuration
sourceDenyDefault := false
sourceInfo, sourceExists := settings.Config.Server.SourceMap[sourcePath]
if sourceExists {
sourceDenyDefault = sourceInfo.Config.DenyByDefault
}
allUserRules := make(map[string]map[string]FrontendAccessRule)
rulesBySource, ok := s.AllRules[sourcePath]
if !ok {
return allUserRules
}
for indexPath, rule := range rulesBySource {
hasAllowUsers := len(rule.Allow.Users) > 0
hasDenyUsers := len(rule.Deny.Users) > 0
if !hasAllowUsers && !hasDenyUsers {
continue
}
// Use the internal path as the frontend path (with trailing slash)
// This ensures consistency between internal storage and frontend display
frontendPath := indexPath
frontendRule := FrontendAccessRule{
DenyAll: rule.DenyAll,
SourceDenyDefault: sourceDenyDefault,
Deny: FrontendRuleSet{
Users: utils.NonNilSlice(slices.Collect(maps.Keys(rule.Deny.Users))),
Groups: utils.NonNilSlice(slices.Collect(maps.Keys(rule.Deny.Groups))),
},
Allow: FrontendRuleSet{
Users: utils.NonNilSlice(slices.Collect(maps.Keys(rule.Allow.Users))),
Groups: utils.NonNilSlice(slices.Collect(maps.Keys(rule.Allow.Groups))),
},
}
for user := range rule.Allow.Users {
if _, ok := allUserRules[user]; !ok {
allUserRules[user] = make(map[string]FrontendAccessRule)
}
allUserRules[user][frontendPath] = frontendRule
}
for user := range rule.Deny.Users {
if _, ok := allUserRules[user]; !ok {
allUserRules[user] = make(map[string]FrontendAccessRule)
}
allUserRules[user][frontendPath] = frontendRule
}
}
return allUserRules
}
// GetAllRulesByGroups returns a map of groupnames to their rules for a given sourcePath.
func (s *Storage) GetAllRulesByGroups(sourcePath string) map[string]map[string]FrontendAccessRule {
s.mux.RLock()
defer s.mux.RUnlock()
// Get source configuration
sourceDenyDefault := false
sourceInfo, sourceExists := settings.Config.Server.SourceMap[sourcePath]
if sourceExists {
sourceDenyDefault = sourceInfo.Config.DenyByDefault
}
allGroupRules := make(map[string]map[string]FrontendAccessRule)
rulesBySource, ok := s.AllRules[sourcePath]
if !ok {
return allGroupRules
}
for indexPath, rule := range rulesBySource {
hasAllowGroups := len(rule.Allow.Groups) > 0
hasDenyGroups := len(rule.Deny.Groups) > 0
if !hasAllowGroups && !hasDenyGroups {
continue
}
// Use the internal path as the frontend path (with trailing slash)
// This ensures consistency between internal storage and frontend display
frontendPath := indexPath
frontendRule := FrontendAccessRule{
DenyAll: rule.DenyAll,
SourceDenyDefault: sourceDenyDefault,
Deny: FrontendRuleSet{
Users: utils.NonNilSlice(slices.Collect(maps.Keys(rule.Deny.Users))),
Groups: utils.NonNilSlice(slices.Collect(maps.Keys(rule.Deny.Groups))),
},
Allow: FrontendRuleSet{
Users: utils.NonNilSlice(slices.Collect(maps.Keys(rule.Allow.Users))),
Groups: utils.NonNilSlice(slices.Collect(maps.Keys(rule.Allow.Groups))),
},
}
for group := range rule.Allow.Groups {
if _, ok := allGroupRules[group]; !ok {
allGroupRules[group] = make(map[string]FrontendAccessRule)
}
allGroupRules[group][frontendPath] = frontendRule
}
for group := range rule.Deny.Groups {
if _, ok := allGroupRules[group]; !ok {
allGroupRules[group] = make(map[string]FrontendAccessRule)
}
allGroupRules[group][frontendPath] = frontendRule
}
}
return allGroupRules
}
// HasAnyVisibleItems checks if a user has access to any items in a given parent path.
// This is used to determine if a user should see a folder's contents even when
// they don't have direct access to the parent folder.
func (s *Storage) HasAnyVisibleItems(sourcePath string, parentPath utils.IndexPath, itemNames []string, username string) bool {
parent := checkPath(parentPath)
for _, itemName := range itemNames {
child := parent.Join(itemName, true)
if s.Permitted(sourcePath, child, username) {
return true
}
}
return false
}
// RemoveUserCascade removes a user from either the allow or deny list for a given path and all its subpaths.
// This is used for cascade delete operations when deleting user access from a directory tree.
// The allow parameter determines which list to remove from: true for allow list, false for deny list.
func (s *Storage) RemoveUserCascade(sourcePath string, indexPath utils.IndexPath, username string, allow bool) (int, error) {
s.mux.Lock()
defer s.mux.Unlock()
normalizedPath := ruleKey(indexPath)
rulesBySource, ok := s.AllRules[sourcePath]
if !ok {
return 0, nil
}
changed := false
removedCount := 0
touchedPaths := make(map[string]struct{})
// Iterate through all rules for this source
for rulePath, rule := range rulesBySource {
// Check if this rule path matches or is a subpath of the target path
if rulePath == normalizedPath || strings.HasPrefix(rulePath, normalizedPath) {
pathChanged := false
if allow {
// Remove user from allow list only
if _, exists := rule.Allow.Users[username]; exists {
delete(rule.Allow.Users, username)
changed = true
removedCount++
pathChanged = true
}
} else {
// Remove user from deny list only
if _, exists := rule.Deny.Users[username]; exists {
delete(rule.Deny.Users, username)
changed = true
removedCount++
pathChanged = true
}
}
// If rule is now empty, mark it for deletion
if len(rule.Allow.Users) == 0 && len(rule.Allow.Groups) == 0 &&
len(rule.Deny.Users) == 0 && len(rule.Deny.Groups) == 0 && !rule.DenyAll {
delete(s.AllRules[sourcePath], rulePath)
pathChanged = true
}
if pathChanged {
touchedPaths[rulePath] = struct{}{}
}
}
}
// If no rules left for this source, remove the source entry
if len(s.AllRules[sourcePath]) == 0 {
delete(s.AllRules, sourcePath)
}
if changed {
s.clearAllCaches()
for rp := range touchedPaths {
s.persistRuleSQLNL(sourcePath, rp)
}
return removedCount, nil
}
return 0, nil
}
// RemoveGroupCascade removes a group from either the allow or deny list for a given path and all its subpaths.
// This is used for cascade delete operations when deleting group access from a directory tree.
// The allow parameter determines which list to remove from: true for allow list, false for deny list.
func (s *Storage) RemoveGroupCascade(sourcePath string, indexPath utils.IndexPath, groupname string, allow bool) (int, error) {
s.mux.Lock()
defer s.mux.Unlock()
normalizedPath := ruleKey(indexPath)
rulesBySource, ok := s.AllRules[sourcePath]
if !ok {
return 0, nil
}
changed := false
removedCount := 0
touchedPaths := make(map[string]struct{})
// Iterate through all rules for this source
for rulePath, rule := range rulesBySource {
// Check if this rule path matches or is a subpath of the target path
if rulePath == normalizedPath || strings.HasPrefix(rulePath, normalizedPath) {
pathChanged := false
if allow {
// Remove group from allow list only
if _, exists := rule.Allow.Groups[groupname]; exists {
delete(rule.Allow.Groups, groupname)
changed = true
removedCount++
pathChanged = true
}
} else {
// Remove group from deny list only
if _, exists := rule.Deny.Groups[groupname]; exists {
delete(rule.Deny.Groups, groupname)
changed = true
removedCount++
pathChanged = true
}
}
// If rule is now empty, mark it for deletion
if len(rule.Allow.Users) == 0 && len(rule.Allow.Groups) == 0 &&
len(rule.Deny.Users) == 0 && len(rule.Deny.Groups) == 0 && !rule.DenyAll {
delete(s.AllRules[sourcePath], rulePath)
pathChanged = true
}
if pathChanged {
touchedPaths[rulePath] = struct{}{}
}
}
}
// If no rules left for this source, remove the source entry
if len(s.AllRules[sourcePath]) == 0 {
delete(s.AllRules, sourcePath)
}
if changed {
s.clearAllCaches()
for rp := range touchedPaths {
s.persistRuleSQLNL(sourcePath, rp)
}
return removedCount, nil
}
return 0, nil
}
// UpdateRules updates all access rules that match oldPath to point to newPath.
// Handles both exact matches and subdirectories. Similar to share.Storage.UpdateShares.
func (s *Storage) UpdateRules(sourcePath string, oldPath, newPath utils.IndexPath) (int, error) {
s.mux.Lock()
defer s.mux.Unlock()
rulesBySource, ok := s.AllRules[sourcePath]
if !ok {
return 0, nil // No rules for this source, not an error
}
oldKey := ruleKey(oldPath)
newKey := ruleKey(newPath)
updated := 0
rulesToUpdate := make(map[string]string) // old path -> new path
// Find all rules that need to be updated
for rulePath := range rulesBySource {
if rulePath == oldKey {
rulesToUpdate[rulePath] = newKey
} else if strings.HasPrefix(rulePath, oldKey) {
newRulePath := newKey + strings.TrimPrefix(rulePath, oldKey)
rulesToUpdate[rulePath] = newRulePath
}
}
// Update all matched rules
for oldRulePath, newRulePath := range rulesToUpdate {
rule := rulesBySource[oldRulePath]
delete(rulesBySource, oldRulePath)
rulesBySource[newRulePath] = rule
logger.Info("access rule updated", "source", sourcePath, "fromPath", oldRulePath, "toPath", newRulePath)
updated++
}
if updated > 0 {
s.clearAllCaches()
for oldRulePath := range rulesToUpdate {
if s.sqlStore != nil {
_ = s.sqlStore.DeleteAccessRule(sourcePath, oldRulePath)
}
}
for _, newRulePath := range rulesToUpdate {
s.persistRuleSQLNL(sourcePath, newRulePath)
}
}
return updated, nil
}
// UpdateRulePath updates the path for a specific access rule (used by PATCH API endpoint).
func (s *Storage) UpdateRulePath(sourcePath string, oldPath, newPath utils.IndexPath) error {
s.mux.Lock()
defer s.mux.Unlock()
oldKey := ruleKey(oldPath)
newKey := ruleKey(newPath)
rulesBySource, ok := s.AllRules[sourcePath]
if !ok {
return fmt.Errorf("no rules found for source: %s", sourcePath)
}
rule, ok := rulesBySource[oldKey]
if !ok {
return fmt.Errorf("no rule found for path: %s", oldKey)
}
delete(rulesBySource, oldKey)
rulesBySource[newKey] = rule
s.clearAllCaches()
if s.sqlStore != nil {
_ = s.sqlStore.DeleteAccessRule(sourcePath, oldKey)
}
s.persistRuleSQLNL(sourcePath, newKey)
logger.Debugf("access rule path updated: source=%s, fromPath=%s, toPath=%s", sourcePath, oldKey, newKey)
return nil
}
// RevokeToken adds a token hash to the revoked list and persists to DB.
func (s *Storage) RevokeToken(tokenHash string) error {
tokenHash = utils.HashSHA256(tokenHash)
s.mux.Lock()
s.RevokedTokens[tokenHash] = struct{}{}
delete(s.HashedTokens, tokenHash)
sqlStore := s.sqlStore
s.mux.Unlock()
if sqlStore != nil {
_ = sqlStore.DeleteHashedToken(tokenHash)
_ = sqlStore.SaveRevokedToken(tokenHash)
}
return nil
}
// IsTokenRevoked checks if a token hash is in the revoked list (memory-only read).
func (s *Storage) IsTokenRevoked(tokenHash string) bool {
s.mux.RLock()
defer s.mux.RUnlock()
tokenHash = utils.HashSHA256(tokenHash)
_, exists := s.RevokedTokens[tokenHash]
return exists
}
// AddApiToken maps a token string hash to an owner user id (for minimal JWTs).
func (s *Storage) AddApiToken(tokenString string, userID uint64) error {
tokenHash := utils.HashSHA256(tokenString)
s.mux.Lock()
s.HashedTokens[tokenHash] = userID
sqlStore := s.sqlStore
s.mux.Unlock()
if sqlStore != nil {
return sqlStore.SaveHashedToken(tokenHash, userID)
}
return nil
}
// GetUserIDFromToken retrieves the owner user id for a given token string (memory read; SQL populated at startup).
func (s *Storage) GetUserIDFromToken(tokenString string) (uint64, bool) {
s.mux.RLock()
defer s.mux.RUnlock()
tokenHash := utils.HashSHA256(tokenString)
uid, exists := s.HashedTokens[tokenHash]
return uid, exists
}
// GetRevokedTokens returns a copy of all revoked token hashes.
func (s *Storage) GetRevokedTokens() map[string]struct{} {
s.mux.RLock()
defer s.mux.RUnlock()
// Return a copy to prevent external modification
result := make(map[string]struct{}, len(s.RevokedTokens))
for k := range s.RevokedTokens {
result[k] = struct{}{}
}
return result
}
// RemoveApiToken removes a token hash mapping (used when deleting API keys).
func (s *Storage) RemoveApiToken(tokenString string) error {
tokenHash := utils.HashSHA256(tokenString)
s.mux.Lock()
delete(s.HashedTokens, tokenHash)
sqlStore := s.sqlStore
s.mux.Unlock()
if sqlStore != nil {
return sqlStore.DeleteHashedToken(tokenHash)
}
return nil
}
// RemoveHashedTokensForUser removes every minimal-JWT hash → user id mapping for that owner.
// Call when deleting a user so recycled usernames never resolve leftover token hashes to a new id.
func (s *Storage) RemoveHashedTokensForUser(userID uint64) error {
if userID == 0 {
return nil
}
s.mux.Lock()
for hash, uid := range s.HashedTokens {
if uid == userID {
delete(s.HashedTokens, hash)
}
}
sqlStore := s.sqlStore
s.mux.Unlock()
if sqlStore != nil {
return sqlStore.DeleteHashedTokensByUserID(userID)
}
return nil
}