acl.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284
  1. /*
  2. * Public Domain Software
  3. *
  4. * I (Matthias Ladkau) am the author of the source code in this file.
  5. * I have placed the source code in this file in the public domain.
  6. *
  7. * For further information see: http://creativecommons.org/publicdomain/zero/1.0/
  8. */
  9. /*
  10. Package access contains access control code for webservers.
  11. Users (subjects) get rights to resources (objects) via groups. A group is
  12. a collection of access rights. Users are members of groups. Access is denied
  13. unless explicitly granted.
  14. */
  15. package access
  16. import (
  17. "bytes"
  18. "crypto/sha256"
  19. "encoding/json"
  20. "errors"
  21. "fmt"
  22. "io"
  23. "io/ioutil"
  24. "os"
  25. "sort"
  26. "strings"
  27. "sync"
  28. "time"
  29. "devt.de/krotik/common/datautil"
  30. "devt.de/krotik/common/errorutil"
  31. "devt.de/krotik/common/stringutil"
  32. )
  33. /*
  34. ACLTable is a management object which can be used to define and enforce users rights.
  35. */
  36. type ACLTable interface {
  37. /*
  38. Close closes this table.
  39. */
  40. Close() error
  41. /*
  42. GroupNames returns a list of all known groups.
  43. */
  44. GroupNames() ([]string, error)
  45. /*
  46. UserNames returns a list of all known users.
  47. */
  48. UserNames() ([]string, error)
  49. /*
  50. GroupsOfUser for user returns the list of groups for a specific user.
  51. */
  52. GroupsOfUser(name string) ([]string, error)
  53. /*
  54. AddPermission adds a new resource permission.
  55. */
  56. AddPermission(group, resource string, permission *Rights) error
  57. /*
  58. Permissions returns all permissions of a group.
  59. */
  60. Permissions(group string) (map[string]string, error)
  61. /*
  62. ClearPermissions removes all permissions of a group.
  63. */
  64. ClearPermissions(group string) error
  65. /*
  66. IsPermitted checks if a user has a certain permission. If the
  67. permission is given it also returns the rule which granted permission.
  68. */
  69. IsPermitted(user, resource string, request *Rights) (bool, string, error)
  70. /*
  71. AddGroup creates a new group.
  72. */
  73. AddGroup(name string) error
  74. /*
  75. RemoveGroup removes a group.
  76. */
  77. RemoveGroup(name string) error
  78. /*
  79. AddUserToGroup adds a user to a group.
  80. */
  81. AddUserToGroup(name string, group string) error
  82. /*
  83. RemoveUserFromGroup removes a user from a group.
  84. */
  85. RemoveUserFromGroup(name string, group string) error
  86. /*
  87. GetConfig returns a data structure which contains the whole config of this
  88. ACLTable. The data structure can be easily converted into JSON.
  89. */
  90. GetConfig() (map[string]interface{}, error)
  91. /*
  92. String returns a string representation of this ACL table.
  93. */
  94. String() string
  95. }
  96. /*
  97. Group is a collection of access rights.
  98. */
  99. type Group struct {
  100. Name string
  101. ResourceAccessAbs map[string]*Rights // Map from resource to access rights
  102. ResourceAccessPre map[string]*Rights // Map from resource prefix to access rights
  103. }
  104. /*
  105. ClearResourceAccess removes all resource access rights from this group.
  106. */
  107. func (g *Group) ClearResourceAccess() {
  108. g.ResourceAccessAbs = make(map[string]*Rights)
  109. g.ResourceAccessPre = make(map[string]*Rights)
  110. }
  111. /*
  112. AddResourceAccess adds a new resource access right. A * as the resource
  113. string suffix will grant access to all resources which start with the
  114. resource string.
  115. */
  116. func (g *Group) AddResourceAccess(res string, r *Rights) error {
  117. if strings.HasSuffix(res, "*") {
  118. pre := res[:len(res)-1]
  119. if _, ok := g.ResourceAccessPre[pre]; ok {
  120. return fmt.Errorf("Resource access wildcard for %v registered twice", res)
  121. }
  122. g.ResourceAccessPre[pre] = r
  123. } else {
  124. if _, ok := g.ResourceAccessAbs[res]; ok {
  125. return fmt.Errorf("Resource access for %v registered twice", res)
  126. }
  127. g.ResourceAccessAbs[res] = r
  128. }
  129. return nil
  130. }
  131. /*
  132. IsPermitted checks if this group has access to a certain resource. Returns
  133. also the rule which gives permission.
  134. */
  135. func (g *Group) IsPermitted(resource string, request *Rights) (bool, string) {
  136. // First check direct match
  137. if r, ok := g.ResourceAccessAbs[resource]; ok {
  138. if r.IsAllowed(request) {
  139. return true, fmt.Sprintf("Group %v has specific access to %v with %v", g.Name, resource, r.String())
  140. }
  141. }
  142. // Go through prefixes
  143. for pre, r := range g.ResourceAccessPre {
  144. if strings.HasPrefix(resource, pre) && r.IsAllowed(request) {
  145. return true, fmt.Sprintf("Group %v has general access to %v with %v", g.Name, pre, r.String())
  146. }
  147. }
  148. return false, ""
  149. }
  150. /*
  151. String returns the access rights of this group as a string table.
  152. */
  153. func (g *Group) String() string {
  154. var buf bytes.Buffer
  155. buf.WriteString(fmt.Sprintf("Group: %v\n====\n", g.Name))
  156. // Find out the longest name
  157. longest := 0
  158. for n := range g.ResourceAccessAbs {
  159. if len(n) > longest {
  160. longest = len(n)
  161. }
  162. }
  163. for n := range g.ResourceAccessPre {
  164. if len(n) > longest {
  165. longest = len(n)
  166. }
  167. }
  168. addResourceMap := func(m map[string]*Rights) {
  169. res := make([]string, 0, len(m))
  170. for n := range m {
  171. res = append(res, n)
  172. }
  173. sort.Strings(res)
  174. for _, n := range res {
  175. buf.WriteString(fmt.Sprintf("%-"+fmt.Sprint(longest)+"v : %v\n",
  176. n, m[n]))
  177. }
  178. }
  179. addResourceMap(g.ResourceAccessAbs)
  180. addResourceMap(g.ResourceAccessPre)
  181. return buf.String()
  182. }
  183. /*
  184. Rights is an atomic permission of access.
  185. */
  186. type Rights struct {
  187. Create bool // Create requests can be processed
  188. Read bool // Read requests can be processed
  189. Update bool // Update requests can be processed
  190. Delete bool // Delete requests can be processed
  191. }
  192. /*
  193. RightsFromString creates a new Rights object from a given rights string. A rights
  194. string defines the access rights (c)reate, (r)ead, (u)pdate and (d)elete. Missing
  195. rights are defined with a '-' sign. For example: read-only access would be '-r--',
  196. full access would be 'crud'. REST APIs typically associate request types with these
  197. rights: (c) POST, (r) GET, (u) PATCH, (d) DELETE.
  198. */
  199. func RightsFromString(rights string) (*Rights, error) {
  200. var ret *Rights
  201. var c, r, u, d bool
  202. var err error
  203. if len(rights) != 4 {
  204. return nil, fmt.Errorf("Rigths string must be 4 characters")
  205. }
  206. rights = strings.ToLower(rights)
  207. parseChar := func(got byte, positive, desc string) (bool, error) {
  208. if string(got) == positive {
  209. return true, nil
  210. } else if string(got) == "-" {
  211. return false, nil
  212. }
  213. return false, fmt.Errorf("%v permission in rights string must be either '%v' or '-'", desc, positive)
  214. }
  215. if c, err = parseChar(rights[0], "c", "Create"); err == nil {
  216. if r, err = parseChar(rights[1], "r", "Read"); err == nil {
  217. if u, err = parseChar(rights[2], "u", "Update"); err == nil {
  218. d, err = parseChar(rights[3], "d", "Delete")
  219. }
  220. }
  221. }
  222. if err == nil {
  223. ret = &Rights{Create: c, Read: r, Update: u, Delete: d}
  224. }
  225. return ret, err
  226. }
  227. /*
  228. IsAllowed checks if a given set of access requests is allowed by this set
  229. of access permissions.
  230. */
  231. func (r *Rights) IsAllowed(request *Rights) bool {
  232. if request.Create && request.Create != r.Create {
  233. return false
  234. } else if request.Read && request.Read != r.Read {
  235. return false
  236. } else if request.Update && request.Update != r.Update {
  237. return false
  238. } else if request.Delete && request.Delete != r.Delete {
  239. return false
  240. }
  241. return true
  242. }
  243. /*
  244. String returns a string representation of this rights atom.
  245. */
  246. func (r *Rights) String() string {
  247. ret := []string{"-", "-", "-", "-"}
  248. if r.Create {
  249. ret[0] = "C"
  250. }
  251. if r.Read {
  252. ret[1] = "R"
  253. }
  254. if r.Update {
  255. ret[2] = "U"
  256. }
  257. if r.Delete {
  258. ret[3] = "D"
  259. }
  260. return strings.Join(ret, "")
  261. }
  262. /*
  263. MemoryACLTable is the main ACL table implementation. It stores permission
  264. and group information in memory.
  265. */
  266. type MemoryACLTable struct {
  267. PermissionCache *datautil.MapCache // Cache for permission checks
  268. Users map[string]map[string]*Group // Mapping from users to groups
  269. Groups map[string]*Group // Table of groups
  270. }
  271. /*
  272. NewMemoryACLTable returns a new empty basic ACL table.
  273. */
  274. func NewMemoryACLTable() ACLTable {
  275. return &MemoryACLTable{datautil.NewMapCache(300, 0),
  276. make(map[string]map[string]*Group), make(map[string]*Group)}
  277. }
  278. /*
  279. NewMemoryACLTableFromConfig builds an ACL table from a given data structure which
  280. was previously produced by GetConfig.
  281. */
  282. func NewMemoryACLTableFromConfig(config map[string]interface{}) (ACLTable, error) {
  283. // Normalise the config object to avoid fighting the type system
  284. v, err := json.Marshal(config)
  285. if err == nil {
  286. err = json.Unmarshal(v, &config)
  287. if err == nil {
  288. usersData, ok := config["users"]
  289. if !ok {
  290. return nil, fmt.Errorf("Entry 'users' is missing from ACL table config")
  291. }
  292. users, ok := usersData.(map[string]interface{})
  293. if !ok {
  294. return nil, fmt.Errorf("Entry 'users' is not of the expected format")
  295. }
  296. groupsData, ok := config["groups"]
  297. if !ok {
  298. return nil, fmt.Errorf("Entry 'groups' is missing from ACL table config")
  299. }
  300. groups, ok := groupsData.(map[string]interface{})
  301. if !ok {
  302. return nil, fmt.Errorf("Entry 'groups' is not of the expected format")
  303. }
  304. tab := NewMemoryACLTable()
  305. // Create groups and their permissions to resources
  306. for g, res := range groups {
  307. err = tab.AddGroup(g)
  308. if _, ok := res.(map[string]interface{}); !ok {
  309. return nil, fmt.Errorf("Entries in 'groups' are not of the expected format")
  310. }
  311. for r, p := range res.(map[string]interface{}) {
  312. var rights *Rights
  313. rights, err = RightsFromString(fmt.Sprint(p))
  314. if err == nil {
  315. err = tab.AddPermission(g, r, rights)
  316. }
  317. if err != nil {
  318. err = fmt.Errorf("Error adding resource %v of group %v: %v",
  319. r, g, err.Error())
  320. break
  321. }
  322. }
  323. if err != nil {
  324. break
  325. }
  326. }
  327. // Add users to groups
  328. if err == nil {
  329. for u, gs := range users {
  330. if _, ok := gs.([]interface{}); !ok {
  331. return nil, fmt.Errorf("Entries in 'users' are not of the expected format")
  332. }
  333. for _, g := range gs.([]interface{}) {
  334. if err = tab.AddUserToGroup(u, fmt.Sprint(g)); err != nil {
  335. err = fmt.Errorf("Error adding user %v to group %v: %v",
  336. u, g, err.Error())
  337. break
  338. }
  339. }
  340. if err != nil {
  341. break
  342. }
  343. }
  344. }
  345. if err == nil {
  346. return tab, nil
  347. }
  348. }
  349. }
  350. return nil, err
  351. }
  352. /*
  353. Close closes this table.
  354. */
  355. func (t *MemoryACLTable) Close() error {
  356. // Nothing to do for the memory ACL table.
  357. return nil
  358. }
  359. /*
  360. GroupNames returns a list of all known groups.
  361. */
  362. func (t *MemoryACLTable) GroupNames() ([]string, error) {
  363. var ret []string
  364. if t != nil {
  365. for n := range t.Groups {
  366. ret = append(ret, n)
  367. }
  368. sort.Strings(ret)
  369. }
  370. return ret, nil
  371. }
  372. /*
  373. UserNames returns a list of all known users.
  374. */
  375. func (t *MemoryACLTable) UserNames() ([]string, error) {
  376. var ret []string
  377. if t != nil {
  378. for n := range t.Users {
  379. ret = append(ret, n)
  380. }
  381. sort.Strings(ret)
  382. }
  383. return ret, nil
  384. }
  385. /*
  386. GroupsOfUser for user returns the list of groups for a specific user.
  387. */
  388. func (t *MemoryACLTable) GroupsOfUser(name string) ([]string, error) {
  389. var ret []string
  390. var err error
  391. if ug, ok := t.Users[name]; ok {
  392. for n := range ug {
  393. ret = append(ret, n)
  394. }
  395. sort.Strings(ret)
  396. } else {
  397. err = fmt.Errorf("Unknown user: %v", name)
  398. }
  399. return ret, err
  400. }
  401. /*
  402. AddPermission adds a new resource permission.
  403. */
  404. func (t *MemoryACLTable) AddPermission(group, resource string, permission *Rights) error {
  405. g, ok := t.Groups[group]
  406. if !ok {
  407. return fmt.Errorf("Group %v does not exist", group)
  408. }
  409. t.invalidatePermCache()
  410. return g.AddResourceAccess(resource, permission)
  411. }
  412. /*
  413. Permissions returns all permissions of a group.
  414. */
  415. func (t *MemoryACLTable) Permissions(group string) (map[string]string, error) {
  416. if _, ok := t.Groups[group]; !ok {
  417. return nil, fmt.Errorf("Group %v does not exist", group)
  418. }
  419. c, _ := t.GetConfig()
  420. return c["groups"].(map[string]map[string]string)[group], nil
  421. }
  422. /*
  423. ClearPermissions removes all permissions of a group.
  424. */
  425. func (t *MemoryACLTable) ClearPermissions(group string) error {
  426. g, ok := t.Groups[group]
  427. if !ok {
  428. return fmt.Errorf("Group %v does not exist", group)
  429. }
  430. t.invalidatePermCache()
  431. g.ClearResourceAccess()
  432. return nil
  433. }
  434. /*
  435. invalidatePermCache invalidates the permission cache. This should be called before
  436. any write operation.
  437. */
  438. func (t *MemoryACLTable) invalidatePermCache() {
  439. t.PermissionCache.Clear()
  440. }
  441. /*
  442. IsPermitted checks if a user has a certain permission. If the
  443. permission is given it also returns the rule which granted permission.
  444. */
  445. func (t *MemoryACLTable) IsPermitted(user, resource string, request *Rights) (bool, string, error) {
  446. var res bool
  447. var err error
  448. var reason string
  449. // Check from permission cache
  450. if res, ok := t.PermissionCache.Get(fmt.Sprint([]string{user, resource, request.String()})); ok {
  451. return res.(bool), "Permission was stored in the cache", err
  452. }
  453. if ug, ok := t.Users[user]; ok {
  454. // Check if one of the user's groups is permitted to access the resource
  455. for _, g := range ug {
  456. if ok, okReason := g.IsPermitted(resource, request); ok {
  457. res = true
  458. reason = okReason
  459. break
  460. }
  461. }
  462. // Store the result in the permission cache
  463. t.PermissionCache.Put(fmt.Sprint([]string{user, resource, request.String()}), res)
  464. } else {
  465. err = fmt.Errorf("Unknown user: %v", user)
  466. }
  467. return res, reason, err
  468. }
  469. /*
  470. AddGroup creates a new group.
  471. */
  472. func (t *MemoryACLTable) AddGroup(name string) error {
  473. if _, ok := t.Groups[name]; ok {
  474. return fmt.Errorf("Group %v added twice", name)
  475. }
  476. t.invalidatePermCache()
  477. g := &Group{name, make(map[string]*Rights), make(map[string]*Rights)}
  478. t.Groups[g.Name] = g
  479. return nil
  480. }
  481. /*
  482. RemoveGroup removes a group.
  483. */
  484. func (t *MemoryACLTable) RemoveGroup(name string) error {
  485. if _, ok := t.Groups[name]; !ok {
  486. return fmt.Errorf("Group %v does not exist", name)
  487. }
  488. t.invalidatePermCache()
  489. delete(t.Groups, name)
  490. for gname, gm := range t.Users {
  491. delete(gm, name)
  492. if len(gm) == 0 {
  493. // Users without any groups are removed
  494. delete(t.Users, gname)
  495. }
  496. }
  497. return nil
  498. }
  499. /*
  500. AddUserToGroup adds a user to a group.
  501. */
  502. func (t *MemoryACLTable) AddUserToGroup(name string, group string) error {
  503. g, ok := t.Groups[group]
  504. if !ok {
  505. return fmt.Errorf("Group %v does not exist", group)
  506. }
  507. t.invalidatePermCache()
  508. if l, ok := t.Users[name]; ok {
  509. if _, ok := l[group]; !ok {
  510. l[group] = g
  511. }
  512. } else {
  513. t.Users[name] = map[string]*Group{
  514. group: g,
  515. }
  516. }
  517. return nil
  518. }
  519. /*
  520. RemoveUserFromGroup removes a user from a group.
  521. */
  522. func (t *MemoryACLTable) RemoveUserFromGroup(name string, group string) error {
  523. var err error
  524. u, ok := t.Users[name]
  525. if !ok {
  526. return fmt.Errorf("User %v does not exist", name)
  527. }
  528. t.invalidatePermCache()
  529. if _, ok := u[group]; ok {
  530. delete(u, group)
  531. } else {
  532. err = fmt.Errorf("User %v is not in group %v", name, group)
  533. }
  534. return err
  535. }
  536. /*
  537. String returns a string representation of this ACL table.
  538. */
  539. func (t *MemoryACLTable) String() string {
  540. var buf bytes.Buffer
  541. buf.WriteString("ACLTable\n")
  542. buf.WriteString("========\n")
  543. buf.WriteString("Users:\n")
  544. usernames, _ := t.UserNames()
  545. for _, u := range usernames {
  546. g, err := t.GroupsOfUser(u)
  547. errorutil.AssertOk(err)
  548. buf.WriteString(fmt.Sprintf("%v : %v\n", u, strings.Join(g, ", ")))
  549. }
  550. groupnames, _ := t.GroupNames()
  551. for _, g := range groupnames {
  552. buf.WriteString("\n")
  553. buf.WriteString(t.Groups[g].String())
  554. }
  555. return buf.String()
  556. }
  557. /*
  558. GetConfig returns a data structure which contains the whole config of this
  559. ACLTable. The data structure can be easily converted into JSON.
  560. */
  561. func (t *MemoryACLTable) GetConfig() (map[string]interface{}, error) {
  562. data := make(map[string]interface{})
  563. users := make(map[string][]string)
  564. data["users"] = users
  565. usernames, _ := t.UserNames()
  566. for _, u := range usernames {
  567. g, err := t.GroupsOfUser(u)
  568. errorutil.AssertOk(err)
  569. users[u] = g
  570. }
  571. groups := make(map[string]map[string]string)
  572. data["groups"] = groups
  573. groupnames, _ := t.GroupNames()
  574. for _, g := range groupnames {
  575. group := t.Groups[g]
  576. resources := make(map[string]string)
  577. groups[g] = resources
  578. for res, rights := range group.ResourceAccessAbs {
  579. resources[res] = rights.String()
  580. }
  581. for res, rights := range group.ResourceAccessPre {
  582. resources[res+"*"] = rights.String()
  583. }
  584. }
  585. return data, nil
  586. }
  587. /*
  588. PersistedACLTableErrRetries is the number of times the code will try to
  589. read the disk configuration before overwriting it with the current
  590. (working) configuration. Set to -1 if it should never attempt to overwrite.
  591. */
  592. var PersistedACLTableErrRetries = 10
  593. /*
  594. watchSleep is the sleep which is used by the watch thread
  595. */
  596. var watchSleep = time.Sleep
  597. /*
  598. Defined error codes for PersistedACLTable
  599. */
  600. var (
  601. ErrClosed = errors.New("ACL table was closed")
  602. )
  603. /*
  604. PersistedACLTable is an ACL table whose state is persisted in a file and
  605. in memory. The table in memory and the file on disk are kept automatically
  606. in sync. This object is thread-safe. A persistent synchronization error between
  607. file and memory table will lock this object down.
  608. */
  609. type PersistedACLTable struct {
  610. table ACLTable // Internal in memory ACL Table
  611. tableLock *sync.RWMutex // Lock for ACL table
  612. interval time.Duration // Interval with which the file should be watched
  613. filename string // File which stores the ACL table
  614. SyncError error // Synchronization errors
  615. shutdown chan bool // Signal channel for thread shutdown
  616. }
  617. /*
  618. NewPersistedACLTable returns a new file-persisted ACL table.
  619. */
  620. func NewPersistedACLTable(filename string, interval time.Duration) (ACLTable, error) {
  621. var ret *PersistedACLTable
  622. ptable := &PersistedACLTable{nil, &sync.RWMutex{}, interval, filename, nil, nil}
  623. err := ptable.start()
  624. if err == nil {
  625. ret = ptable
  626. }
  627. return ret, err
  628. }
  629. /*
  630. start kicks off the file watcher background thread.
  631. */
  632. func (t *PersistedACLTable) start() error {
  633. // Sync from file - if the file exists. No need to hold a lock since
  634. // we are in the startup
  635. err := t.sync(true)
  636. if err == nil {
  637. // Kick off watcher
  638. t.shutdown = make(chan bool)
  639. go t.watch()
  640. }
  641. return err
  642. }
  643. /*
  644. watch is the internal file watch goroutine function.
  645. */
  646. func (t *PersistedACLTable) watch() {
  647. err := t.SyncError
  648. errCnt := 0
  649. defer func() {
  650. t.shutdown <- true
  651. }()
  652. for t.SyncError != ErrClosed {
  653. // Wakeup every interval
  654. watchSleep(t.interval)
  655. // Run the sync
  656. t.tableLock.Lock()
  657. // Sync from file
  658. if err = t.sync(true); err != nil && t.SyncError != ErrClosed {
  659. // Increase the error count
  660. err = fmt.Errorf("Could not sync ACL table config from disk: %v",
  661. err.Error())
  662. errCnt++
  663. } else {
  664. // Reset the error count
  665. errCnt = 0
  666. }
  667. // Update the sync error
  668. if t.SyncError != ErrClosed {
  669. t.SyncError = err
  670. }
  671. if errCnt == PersistedACLTableErrRetries {
  672. // We can't read the disk configuration after
  673. // PersistedACLTableErrRetries attempts - try to overwrite
  674. // it with the working memory configuration
  675. t.sync(false)
  676. }
  677. t.tableLock.Unlock()
  678. }
  679. }
  680. /*
  681. Close closes this table.
  682. */
  683. func (t *PersistedACLTable) Close() error {
  684. var err error
  685. t.tableLock.Lock()
  686. if t.SyncError != nil {
  687. // Preserve any old error
  688. err = t.SyncError
  689. }
  690. // Set the table into the closed state
  691. t.SyncError = ErrClosed
  692. t.tableLock.Unlock()
  693. // Wait for watcher shutdown if it was started
  694. if t.shutdown != nil {
  695. <-t.shutdown
  696. t.shutdown = nil
  697. }
  698. return err
  699. }
  700. /*
  701. Attempt to synchronize the memory table with the file. Depending on the
  702. checkFile flag either the file (true) or the memory table (false) is
  703. regarded as up-to-date.
  704. It is assumed that the tableLock (write) is held before calling this
  705. function.
  706. The table is in an undefined state if an error is returned.
  707. */
  708. func (t *PersistedACLTable) sync(checkFile bool) error {
  709. var checksumFile, checksumMemory string
  710. stringMemoryTable := func() ([]byte, error) {
  711. tableconfig, _ := t.table.GetConfig()
  712. return json.MarshalIndent(tableconfig, "", " ")
  713. }
  714. writeMemoryTable := func() error {
  715. res, err := stringMemoryTable()
  716. if err == nil {
  717. err = ioutil.WriteFile(t.filename, res, 0666)
  718. }
  719. return err
  720. }
  721. readMemoryTable := func() (map[string]interface{}, error) {
  722. var conf map[string]interface{}
  723. res, err := ioutil.ReadFile(t.filename)
  724. if err == nil {
  725. err = json.Unmarshal(stringutil.StripCStyleComments(res), &conf)
  726. }
  727. return conf, err
  728. }
  729. // Check if the file can be opened
  730. file, err := os.OpenFile(t.filename, os.O_RDONLY, 0660)
  731. if err != nil {
  732. if os.IsNotExist(err) {
  733. // Just ignore not found errors
  734. err = nil
  735. }
  736. // File does not exist - no checksum
  737. checksumFile = ""
  738. } else {
  739. hashFactory := sha256.New()
  740. if _, err = io.Copy(hashFactory, file); err == nil {
  741. // Create the checksum of the present file
  742. checksumFile = fmt.Sprintf("%x", hashFactory.Sum(nil))
  743. }
  744. file.Close()
  745. }
  746. if err == nil {
  747. // At this point we know everything about the file now check
  748. // the memory table
  749. if t.table != nil {
  750. var mtString []byte
  751. if mtString, err = stringMemoryTable(); err == nil {
  752. hashFactory := sha256.New()
  753. hashFactory.Write(mtString)
  754. checksumMemory = fmt.Sprintf("%x", hashFactory.Sum(nil))
  755. }
  756. } else {
  757. checksumMemory = ""
  758. }
  759. }
  760. if err == nil {
  761. // At this point we also know everything about the memory table
  762. if checkFile {
  763. // File is up-to-date - we should build the memory table
  764. if checksumFile == "" {
  765. // No file on disk just create an empty table and write it
  766. t.table = NewMemoryACLTable()
  767. err = writeMemoryTable()
  768. } else if checksumFile != checksumMemory {
  769. var conf map[string]interface{}
  770. if conf, err = readMemoryTable(); err == nil {
  771. t.table, err = NewMemoryACLTableFromConfig(conf)
  772. }
  773. }
  774. } else {
  775. // Memory is up-to-date - we should write a new file
  776. if checksumMemory == "" {
  777. // No data in memory just create an empty table and write it
  778. t.table = NewMemoryACLTable()
  779. err = writeMemoryTable()
  780. } else if checksumFile != checksumMemory {
  781. err = writeMemoryTable()
  782. }
  783. }
  784. }
  785. return err
  786. }
  787. /*
  788. GroupNames returns a list of all known groups.
  789. */
  790. func (t *PersistedACLTable) GroupNames() ([]string, error) {
  791. t.tableLock.RLock()
  792. defer t.tableLock.RUnlock()
  793. if t.SyncError != nil {
  794. return nil, t.SyncError
  795. }
  796. return t.table.GroupNames()
  797. }
  798. /*
  799. UserNames returns a list of all known users.
  800. */
  801. func (t *PersistedACLTable) UserNames() ([]string, error) {
  802. t.tableLock.RLock()
  803. defer t.tableLock.RUnlock()
  804. if t.SyncError != nil {
  805. return nil, t.SyncError
  806. }
  807. return t.table.UserNames()
  808. }
  809. /*
  810. GroupsOfUser for user returns the list of groups for a specific user.
  811. */
  812. func (t *PersistedACLTable) GroupsOfUser(name string) ([]string, error) {
  813. t.tableLock.RLock()
  814. defer t.tableLock.RUnlock()
  815. if t.SyncError != nil {
  816. return nil, t.SyncError
  817. }
  818. return t.table.GroupsOfUser(name)
  819. }
  820. /*
  821. AddPermission adds a new resource permission.
  822. */
  823. func (t *PersistedACLTable) AddPermission(group, resource string, permission *Rights) error {
  824. t.tableLock.Lock()
  825. defer t.tableLock.Unlock()
  826. if t.SyncError != nil {
  827. return t.SyncError
  828. }
  829. err := t.table.AddPermission(group, resource, permission)
  830. if err == nil {
  831. // Sync change to disk
  832. err = t.sync(false)
  833. }
  834. return err
  835. }
  836. /*
  837. Permissions returns all permissions of a group.
  838. */
  839. func (t *PersistedACLTable) Permissions(group string) (map[string]string, error) {
  840. t.tableLock.RLock()
  841. defer t.tableLock.RUnlock()
  842. if t.SyncError != nil {
  843. return nil, t.SyncError
  844. }
  845. return t.table.Permissions(group)
  846. }
  847. /*
  848. ClearPermissions removes all permissions of a group.
  849. */
  850. func (t *PersistedACLTable) ClearPermissions(group string) error {
  851. t.tableLock.Lock()
  852. defer t.tableLock.Unlock()
  853. if t.SyncError != nil {
  854. return t.SyncError
  855. }
  856. t.table.ClearPermissions(group)
  857. return t.sync(false)
  858. }
  859. /*
  860. IsPermitted checks if a user has a certain permission. If the
  861. permission is given it also returns the rule which granted permission.
  862. */
  863. func (t *PersistedACLTable) IsPermitted(user, resource string, request *Rights) (bool, string, error) {
  864. t.tableLock.RLock()
  865. defer t.tableLock.RUnlock()
  866. if t.SyncError != nil {
  867. return false, "", t.SyncError
  868. }
  869. return t.table.IsPermitted(user, resource, request)
  870. }
  871. /*
  872. AddGroup creates a new group.
  873. */
  874. func (t *PersistedACLTable) AddGroup(name string) error {
  875. t.tableLock.Lock()
  876. defer t.tableLock.Unlock()
  877. if t.SyncError != nil {
  878. return t.SyncError
  879. }
  880. err := t.table.AddGroup(name)
  881. if err == nil {
  882. // Sync change to disk
  883. err = t.sync(false)
  884. }
  885. return err
  886. }
  887. /*
  888. RemoveGroup removes a group.
  889. */
  890. func (t *PersistedACLTable) RemoveGroup(name string) error {
  891. t.tableLock.Lock()
  892. defer t.tableLock.Unlock()
  893. if t.SyncError != nil {
  894. return t.SyncError
  895. }
  896. err := t.table.RemoveGroup(name)
  897. if err == nil {
  898. // Sync change to disk
  899. err = t.sync(false)
  900. }
  901. return err
  902. }
  903. /*
  904. AddUserToGroup adds a user to a group.
  905. */
  906. func (t *PersistedACLTable) AddUserToGroup(name string, group string) error {
  907. t.tableLock.Lock()
  908. defer t.tableLock.Unlock()
  909. if t.SyncError != nil {
  910. return t.SyncError
  911. }
  912. err := t.table.AddUserToGroup(name, group)
  913. if err == nil {
  914. // Sync change to disk
  915. err = t.sync(false)
  916. }
  917. return err
  918. }
  919. /*
  920. RemoveUserFromGroup removes a user from a group.
  921. */
  922. func (t *PersistedACLTable) RemoveUserFromGroup(name string, group string) error {
  923. t.tableLock.Lock()
  924. defer t.tableLock.Unlock()
  925. if t.SyncError != nil {
  926. return t.SyncError
  927. }
  928. err := t.table.RemoveUserFromGroup(name, group)
  929. if err == nil {
  930. // Sync change to disk
  931. err = t.sync(false)
  932. }
  933. return err
  934. }
  935. /*
  936. GetConfig returns a data structure which contains the whole config of this
  937. ACLTable. The data structure can be easily converted into JSON.
  938. */
  939. func (t *PersistedACLTable) GetConfig() (map[string]interface{}, error) {
  940. t.tableLock.RLock()
  941. defer t.tableLock.RUnlock()
  942. if t.SyncError != nil {
  943. return nil, t.SyncError
  944. }
  945. return t.table.GetConfig()
  946. }
  947. /*
  948. String returns a string representation of this ACL table.
  949. */
  950. func (t *PersistedACLTable) String() string {
  951. t.tableLock.RLock()
  952. defer t.tableLock.RUnlock()
  953. return t.table.String()
  954. }