store.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. package access
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "os"
  7. "path/filepath"
  8. "sync"
  9. )
  10. const storeVersion = 1
  11. // storeFile is the layout of the rule file on disk
  12. type storeFile struct {
  13. Version int `json:"version"`
  14. Drives map[string]Rule `json:"drives"`
  15. }
  16. /*
  17. Store keeps the rules of the drives of this host in one JSON file. Only drives
  18. whose rule was changed appear in it; every other drive has its DefaultRule.
  19. A rule file that cannot be read must not quietly reopen drives an admin closed,
  20. so such a store answers None for every drive and refuses writes, which would
  21. overwrite the rules still in the file, until the file is repaired or removed.
  22. Admins keep their access through the rules in Explain.
  23. */
  24. type Store struct {
  25. filename string
  26. mu sync.RWMutex
  27. drives map[string]Rule
  28. loadErr error
  29. }
  30. // NewStore opens the rule file. A file that does not exist yet is an empty
  31. // store; check Err for one that could not be read.
  32. func NewStore(filename string) *Store {
  33. s := &Store{filename: filename, drives: map[string]Rule{}}
  34. content, err := os.ReadFile(filename)
  35. if errors.Is(err, os.ErrNotExist) {
  36. return s
  37. }
  38. if err != nil {
  39. s.loadErr = err
  40. return s
  41. }
  42. loaded := storeFile{}
  43. if err := json.Unmarshal(content, &loaded); err != nil {
  44. s.loadErr = err
  45. return s
  46. }
  47. if loaded.Version > storeVersion {
  48. s.loadErr = fmt.Errorf("rule file version %d is newer than this build", loaded.Version)
  49. return s
  50. }
  51. for uuid, rule := range loaded.Drives {
  52. if err := rule.Validate(); err != nil {
  53. s.loadErr = fmt.Errorf("rule of drive %s: %w", uuid, err)
  54. return s
  55. }
  56. s.drives[uuid] = rule
  57. }
  58. return s
  59. }
  60. // Err returns why the rule file could not be read, or nil
  61. func (s *Store) Err() error {
  62. s.mu.RLock()
  63. defer s.mu.RUnlock()
  64. return s.loadErr
  65. }
  66. // Rule implements Source
  67. func (s *Store) Rule(uuid string) (Rule, bool) {
  68. s.mu.RLock()
  69. defer s.mu.RUnlock()
  70. if s.loadErr != nil {
  71. return Rule{Other: None}, true
  72. }
  73. rule, ok := s.drives[uuid]
  74. if !ok {
  75. return Rule{}, false
  76. }
  77. return rule.Clone(), true
  78. }
  79. // Set saves the rule of a drive
  80. func (s *Store) Set(uuid string, rule Rule) error {
  81. if uuid == "" {
  82. return errors.New("drive id is empty")
  83. }
  84. if IsFixed(uuid) {
  85. return errors.New(uuid + ":/ is open to everyone and has no access list")
  86. }
  87. if err := rule.Validate(); err != nil {
  88. return err
  89. }
  90. s.mu.Lock()
  91. defer s.mu.Unlock()
  92. return s.update(func(drives map[string]Rule) {
  93. drives[uuid] = rule.Clone()
  94. })
  95. }
  96. // Remove forgets the rule of a drive, which goes back to its default
  97. func (s *Store) Remove(uuid string) error {
  98. s.mu.Lock()
  99. defer s.mu.Unlock()
  100. if _, ok := s.drives[uuid]; !ok {
  101. return nil
  102. }
  103. return s.update(func(drives map[string]Rule) {
  104. delete(drives, uuid)
  105. })
  106. }
  107. // RemoveGroup drops the rows of a deleted group, so that a new group of the
  108. // same name does not inherit them
  109. func (s *Store) RemoveGroup(group string) error {
  110. s.mu.Lock()
  111. defer s.mu.Unlock()
  112. return s.update(func(drives map[string]Rule) {
  113. for uuid, rule := range drives {
  114. if _, ok := rule.Groups[group]; !ok {
  115. continue
  116. }
  117. rule = rule.Clone()
  118. delete(rule.Groups, group)
  119. drives[uuid] = rule
  120. }
  121. })
  122. }
  123. // update applies a change to a copy of the rules and only keeps it once it
  124. // is on disk. The caller holds the lock.
  125. func (s *Store) update(change func(drives map[string]Rule)) error {
  126. if s.loadErr != nil {
  127. return fmt.Errorf("the rule file could not be read, repair or remove %s first: %w", s.filename, s.loadErr)
  128. }
  129. next := make(map[string]Rule, len(s.drives)+1)
  130. for uuid, rule := range s.drives {
  131. next[uuid] = rule
  132. }
  133. change(next)
  134. if err := s.write(next); err != nil {
  135. return err
  136. }
  137. s.drives = next
  138. return nil
  139. }
  140. // write replaces the rule file in one step, so a crash leaves the old or the
  141. // new file and never half of one
  142. func (s *Store) write(drives map[string]Rule) error {
  143. content, err := json.MarshalIndent(storeFile{Version: storeVersion, Drives: drives}, "", " ")
  144. if err != nil {
  145. return err
  146. }
  147. dir := filepath.Dir(s.filename)
  148. if err := os.MkdirAll(dir, 0775); err != nil {
  149. return err
  150. }
  151. tmp, err := os.CreateTemp(dir, filepath.Base(s.filename)+".*.tmp")
  152. if err != nil {
  153. return err
  154. }
  155. defer os.Remove(tmp.Name())
  156. if _, err := tmp.Write(content); err != nil {
  157. tmp.Close()
  158. return err
  159. }
  160. if err := tmp.Close(); err != nil {
  161. return err
  162. }
  163. return os.Rename(tmp.Name(), s.filename)
  164. }
  165. // bridgeRecord is one entry of the bridge file earlier builds kept
  166. type bridgeRecord struct {
  167. FSHUUID string
  168. SPOwner string
  169. }
  170. /*
  171. MigrateBridges turns the records of the old bridge file into rows and renames
  172. the file, which keeps a backup and stops this from running twice. A drive that
  173. was bridged into a pool gets a row with the access that pool's members had. The
  174. system pool has no members, bridging into it gave the drive to every user, so
  175. there the default access level is raised instead.
  176. homeOf returns the home group of a drive and whether the drive is known at all;
  177. a bridged drive that cannot be found is treated as a group pool drive, so it is
  178. not opened to anybody the record does not name.
  179. It returns how many records were converted. A file that does not exist is not
  180. an error.
  181. */
  182. func (s *Store) MigrateBridges(bridgeFile string, homeOf func(uuid string) (home string, known bool)) (int, error) {
  183. content, err := os.ReadFile(bridgeFile)
  184. if errors.Is(err, os.ErrNotExist) {
  185. return 0, nil
  186. }
  187. if err != nil {
  188. return 0, err
  189. }
  190. records := []bridgeRecord{}
  191. if err := json.Unmarshal(content, &records); err != nil {
  192. return 0, err
  193. }
  194. s.mu.Lock()
  195. err = s.update(func(drives map[string]Rule) {
  196. for _, record := range records {
  197. if record.FSHUUID == "" || record.SPOwner == "" || IsBuiltin(record.FSHUUID) {
  198. continue
  199. }
  200. rule, ok := drives[record.FSHUUID]
  201. if ok {
  202. rule = rule.Clone()
  203. } else {
  204. home, known := homeOf(record.FSHUUID)
  205. if !known {
  206. home = record.SPOwner
  207. }
  208. rule = DefaultRule(record.FSHUUID, home)
  209. }
  210. if record.SPOwner == "system" {
  211. rule.Other = ReadWrite
  212. } else {
  213. if rule.Groups == nil {
  214. rule.Groups = map[string]string{}
  215. }
  216. rule.Groups[record.SPOwner] = ReadWrite
  217. }
  218. drives[record.FSHUUID] = rule
  219. }
  220. })
  221. s.mu.Unlock()
  222. if err != nil {
  223. return 0, err
  224. }
  225. return len(records), os.Rename(bridgeFile, bridgeFile+".migrated")
  226. }