collection.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. package administrator
  2. import (
  3. "sort"
  4. "sync"
  5. "github.com/pkg/errors"
  6. "github.com/smallstep/certificates/authority/admin"
  7. "github.com/smallstep/certificates/authority/provisioner"
  8. "go.step.sm/linkedca"
  9. )
  10. // DefaultAdminLimit is the default limit for listing provisioners.
  11. const DefaultAdminLimit = 20
  12. // DefaultAdminMax is the maximum limit for listing provisioners.
  13. const DefaultAdminMax = 100
  14. type adminSlice []*linkedca.Admin
  15. func (p adminSlice) Len() int { return len(p) }
  16. func (p adminSlice) Less(i, j int) bool { return p[i].Id < p[j].Id }
  17. func (p adminSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  18. // Collection is a memory map of admins.
  19. type Collection struct {
  20. byID *sync.Map
  21. bySubProv *sync.Map
  22. byProv *sync.Map
  23. sorted adminSlice
  24. provisioners *provisioner.Collection
  25. superCount int
  26. superCountByProvisioner map[string]int
  27. }
  28. // NewCollection initializes a collection of provisioners. The given list of
  29. // audiences are the audiences used by the JWT provisioner.
  30. func NewCollection(provisioners *provisioner.Collection) *Collection {
  31. return &Collection{
  32. byID: new(sync.Map),
  33. byProv: new(sync.Map),
  34. bySubProv: new(sync.Map),
  35. superCountByProvisioner: map[string]int{},
  36. provisioners: provisioners,
  37. }
  38. }
  39. // LoadByID a admin by the ID.
  40. func (c *Collection) LoadByID(id string) (*linkedca.Admin, bool) {
  41. return loadAdmin(c.byID, id)
  42. }
  43. type subProv struct {
  44. subject string
  45. provisioner string
  46. }
  47. func newSubProv(subject, provisioner string) subProv {
  48. return subProv{subject, provisioner}
  49. }
  50. // LoadBySubProv a admin by the subject and provisioner name.
  51. func (c *Collection) LoadBySubProv(sub, provName string) (*linkedca.Admin, bool) {
  52. return loadAdmin(c.bySubProv, newSubProv(sub, provName))
  53. }
  54. // LoadByProvisioner a admin by the subject and provisioner name.
  55. func (c *Collection) LoadByProvisioner(provName string) ([]*linkedca.Admin, bool) {
  56. val, ok := c.byProv.Load(provName)
  57. if !ok {
  58. return nil, false
  59. }
  60. admins, ok := val.([]*linkedca.Admin)
  61. if !ok {
  62. return nil, false
  63. }
  64. return admins, true
  65. }
  66. // Store adds an admin to the collection and enforces the uniqueness of
  67. // admin IDs and amdin subject <-> provisioner name combos.
  68. func (c *Collection) Store(adm *linkedca.Admin, prov provisioner.Interface) error {
  69. // Input validation.
  70. if adm.ProvisionerId != prov.GetID() {
  71. return admin.NewErrorISE("admin.provisionerId does not match provisioner argument")
  72. }
  73. // Store admin always in byID. ID must be unique.
  74. if _, loaded := c.byID.LoadOrStore(adm.Id, adm); loaded {
  75. return errors.New("cannot add multiple admins with the same id")
  76. }
  77. provName := prov.GetName()
  78. // Store admin always in bySubProv. Subject <-> ProvisionerName must be unique.
  79. if _, loaded := c.bySubProv.LoadOrStore(newSubProv(adm.Subject, provName), adm); loaded {
  80. c.byID.Delete(adm.Id)
  81. return errors.New("cannot add multiple admins with the same subject and provisioner")
  82. }
  83. var isSuper = (adm.Type == linkedca.Admin_SUPER_ADMIN)
  84. if admins, ok := c.LoadByProvisioner(provName); ok {
  85. c.byProv.Store(provName, append(admins, adm))
  86. if isSuper {
  87. c.superCountByProvisioner[provName]++
  88. }
  89. } else {
  90. c.byProv.Store(provName, []*linkedca.Admin{adm})
  91. if isSuper {
  92. c.superCountByProvisioner[provName] = 1
  93. }
  94. }
  95. if isSuper {
  96. c.superCount++
  97. }
  98. c.sorted = append(c.sorted, adm)
  99. sort.Sort(c.sorted)
  100. return nil
  101. }
  102. // Remove deletes an admin from all associated collections and lists.
  103. func (c *Collection) Remove(id string) error {
  104. adm, ok := c.LoadByID(id)
  105. if !ok {
  106. return admin.NewError(admin.ErrorNotFoundType, "admin %s not found", id)
  107. }
  108. if adm.Type == linkedca.Admin_SUPER_ADMIN && c.SuperCount() == 1 {
  109. return admin.NewError(admin.ErrorBadRequestType, "cannot remove the last super admin")
  110. }
  111. prov, ok := c.provisioners.Load(adm.ProvisionerId)
  112. if !ok {
  113. return admin.NewError(admin.ErrorNotFoundType,
  114. "provisioner %s for admin %s not found", adm.ProvisionerId, id)
  115. }
  116. provName := prov.GetName()
  117. adminsByProv, ok := c.LoadByProvisioner(provName)
  118. if !ok {
  119. return admin.NewError(admin.ErrorNotFoundType,
  120. "admins not found for provisioner %s", provName)
  121. }
  122. // Find index in sorted list.
  123. sortedIndex := sort.Search(c.sorted.Len(), func(i int) bool { return c.sorted[i].Id >= adm.Id })
  124. if c.sorted[sortedIndex].Id != adm.Id {
  125. return admin.NewError(admin.ErrorNotFoundType,
  126. "admin %s not found in sorted list", adm.Id)
  127. }
  128. var found bool
  129. for i, a := range adminsByProv {
  130. if a.Id == adm.Id {
  131. // Remove admin from list. https://stackoverflow.com/questions/37334119/how-to-delete-an-element-from-a-slice-in-golang
  132. // Order does not matter.
  133. adminsByProv[i] = adminsByProv[len(adminsByProv)-1]
  134. c.byProv.Store(provName, adminsByProv[:len(adminsByProv)-1])
  135. found = true
  136. }
  137. }
  138. if !found {
  139. return admin.NewError(admin.ErrorNotFoundType,
  140. "admin %s not found in adminsByProvisioner list", adm.Id)
  141. }
  142. // Remove index in sorted list
  143. copy(c.sorted[sortedIndex:], c.sorted[sortedIndex+1:]) // Shift a[i+1:] left one index.
  144. c.sorted[len(c.sorted)-1] = nil // Erase last element (write zero value).
  145. c.sorted = c.sorted[:len(c.sorted)-1] // Truncate slice.
  146. c.byID.Delete(adm.Id)
  147. c.bySubProv.Delete(newSubProv(adm.Subject, provName))
  148. if adm.Type == linkedca.Admin_SUPER_ADMIN {
  149. c.superCount--
  150. c.superCountByProvisioner[provName]--
  151. }
  152. return nil
  153. }
  154. // Update updates the given admin in all related lists and collections.
  155. func (c *Collection) Update(id string, nu *linkedca.Admin) (*linkedca.Admin, error) {
  156. adm, ok := c.LoadByID(id)
  157. if !ok {
  158. return nil, admin.NewError(admin.ErrorNotFoundType, "admin %s not found", adm.Id)
  159. }
  160. if adm.Type == nu.Type {
  161. return adm, nil
  162. }
  163. if adm.Type == linkedca.Admin_SUPER_ADMIN && c.SuperCount() == 1 {
  164. return nil, admin.NewError(admin.ErrorBadRequestType, "cannot change role of last super admin")
  165. }
  166. adm.Type = nu.Type
  167. return adm, nil
  168. }
  169. // SuperCount returns the total number of admins.
  170. func (c *Collection) SuperCount() int {
  171. return c.superCount
  172. }
  173. // SuperCountByProvisioner returns the total number of admins.
  174. func (c *Collection) SuperCountByProvisioner(provName string) int {
  175. if cnt, ok := c.superCountByProvisioner[provName]; ok {
  176. return cnt
  177. }
  178. return 0
  179. }
  180. // Find implements pagination on a list of sorted admins.
  181. func (c *Collection) Find(cursor string, limit int) ([]*linkedca.Admin, string) {
  182. switch {
  183. case limit <= 0:
  184. limit = DefaultAdminLimit
  185. case limit > DefaultAdminMax:
  186. limit = DefaultAdminMax
  187. }
  188. n := c.sorted.Len()
  189. i := sort.Search(n, func(i int) bool { return c.sorted[i].Id >= cursor })
  190. slice := []*linkedca.Admin{}
  191. for ; i < n && len(slice) < limit; i++ {
  192. slice = append(slice, c.sorted[i])
  193. }
  194. if i < n {
  195. return slice, c.sorted[i].Id
  196. }
  197. return slice, ""
  198. }
  199. func loadAdmin(m *sync.Map, key interface{}) (*linkedca.Admin, bool) {
  200. val, ok := m.Load(key)
  201. if !ok {
  202. return nil, false
  203. }
  204. adm, ok := val.(*linkedca.Admin)
  205. if !ok {
  206. return nil, false
  207. }
  208. return adm, true
  209. }