eab.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. package nosql
  2. import (
  3. "context"
  4. "crypto/rand"
  5. "encoding/json"
  6. "sync"
  7. "time"
  8. "github.com/pkg/errors"
  9. "github.com/smallstep/certificates/acme"
  10. nosqlDB "github.com/smallstep/nosql"
  11. )
  12. // externalAccountKeyMutex for read/write locking of EAK operations.
  13. var externalAccountKeyMutex sync.RWMutex
  14. // referencesByProvisionerIndexMutex for locking referencesByProvisioner index operations.
  15. var referencesByProvisionerIndexMutex sync.Mutex
  16. type dbExternalAccountKey struct {
  17. ID string `json:"id"`
  18. ProvisionerID string `json:"provisionerID"`
  19. Reference string `json:"reference"`
  20. AccountID string `json:"accountID,omitempty"`
  21. KeyBytes []byte `json:"key"`
  22. CreatedAt time.Time `json:"createdAt"`
  23. BoundAt time.Time `json:"boundAt"`
  24. }
  25. type dbExternalAccountKeyReference struct {
  26. Reference string `json:"reference"`
  27. ExternalAccountKeyID string `json:"externalAccountKeyID"`
  28. }
  29. // getDBExternalAccountKey retrieves and unmarshals dbExternalAccountKey.
  30. func (db *DB) getDBExternalAccountKey(ctx context.Context, id string) (*dbExternalAccountKey, error) {
  31. data, err := db.db.Get(externalAccountKeyTable, []byte(id))
  32. if err != nil {
  33. if nosqlDB.IsErrNotFound(err) {
  34. return nil, acme.ErrNotFound
  35. }
  36. return nil, errors.Wrapf(err, "error loading external account key %s", id)
  37. }
  38. dbeak := new(dbExternalAccountKey)
  39. if err = json.Unmarshal(data, dbeak); err != nil {
  40. return nil, errors.Wrapf(err, "error unmarshaling external account key %s into dbExternalAccountKey", id)
  41. }
  42. return dbeak, nil
  43. }
  44. // CreateExternalAccountKey creates a new External Account Binding key with a name
  45. func (db *DB) CreateExternalAccountKey(ctx context.Context, provisionerID, reference string) (*acme.ExternalAccountKey, error) {
  46. externalAccountKeyMutex.Lock()
  47. defer externalAccountKeyMutex.Unlock()
  48. keyID, err := randID()
  49. if err != nil {
  50. return nil, err
  51. }
  52. random := make([]byte, 32)
  53. _, err = rand.Read(random)
  54. if err != nil {
  55. return nil, err
  56. }
  57. dbeak := &dbExternalAccountKey{
  58. ID: keyID,
  59. ProvisionerID: provisionerID,
  60. Reference: reference,
  61. KeyBytes: random,
  62. CreatedAt: clock.Now(),
  63. }
  64. if err := db.save(ctx, keyID, dbeak, nil, "external_account_key", externalAccountKeyTable); err != nil {
  65. return nil, err
  66. }
  67. if err := db.addEAKID(ctx, provisionerID, dbeak.ID); err != nil {
  68. return nil, err
  69. }
  70. if dbeak.Reference != "" {
  71. dbExternalAccountKeyReference := &dbExternalAccountKeyReference{
  72. Reference: dbeak.Reference,
  73. ExternalAccountKeyID: dbeak.ID,
  74. }
  75. if err := db.save(ctx, referenceKey(provisionerID, dbeak.Reference), dbExternalAccountKeyReference, nil, "external_account_key_reference", externalAccountKeyIDsByReferenceTable); err != nil {
  76. return nil, err
  77. }
  78. }
  79. return &acme.ExternalAccountKey{
  80. ID: dbeak.ID,
  81. ProvisionerID: dbeak.ProvisionerID,
  82. Reference: dbeak.Reference,
  83. AccountID: dbeak.AccountID,
  84. KeyBytes: dbeak.KeyBytes,
  85. CreatedAt: dbeak.CreatedAt,
  86. BoundAt: dbeak.BoundAt,
  87. }, nil
  88. }
  89. // GetExternalAccountKey retrieves an External Account Binding key by KeyID
  90. func (db *DB) GetExternalAccountKey(ctx context.Context, provisionerID, keyID string) (*acme.ExternalAccountKey, error) {
  91. externalAccountKeyMutex.RLock()
  92. defer externalAccountKeyMutex.RUnlock()
  93. dbeak, err := db.getDBExternalAccountKey(ctx, keyID)
  94. if err != nil {
  95. return nil, err
  96. }
  97. if dbeak.ProvisionerID != provisionerID {
  98. return nil, acme.NewError(acme.ErrorUnauthorizedType, "provisioner does not match provisioner for which the EAB key was created")
  99. }
  100. return &acme.ExternalAccountKey{
  101. ID: dbeak.ID,
  102. ProvisionerID: dbeak.ProvisionerID,
  103. Reference: dbeak.Reference,
  104. AccountID: dbeak.AccountID,
  105. KeyBytes: dbeak.KeyBytes,
  106. CreatedAt: dbeak.CreatedAt,
  107. BoundAt: dbeak.BoundAt,
  108. }, nil
  109. }
  110. func (db *DB) DeleteExternalAccountKey(ctx context.Context, provisionerID, keyID string) error {
  111. externalAccountKeyMutex.Lock()
  112. defer externalAccountKeyMutex.Unlock()
  113. dbeak, err := db.getDBExternalAccountKey(ctx, keyID)
  114. if err != nil {
  115. return errors.Wrapf(err, "error loading ACME EAB Key with Key ID %s", keyID)
  116. }
  117. if dbeak.ProvisionerID != provisionerID {
  118. return errors.New("provisioner does not match provisioner for which the EAB key was created")
  119. }
  120. if dbeak.Reference != "" {
  121. if err := db.db.Del(externalAccountKeyIDsByReferenceTable, []byte(referenceKey(provisionerID, dbeak.Reference))); err != nil {
  122. return errors.Wrapf(err, "error deleting ACME EAB Key reference with Key ID %s and reference %s", keyID, dbeak.Reference)
  123. }
  124. }
  125. if err := db.db.Del(externalAccountKeyTable, []byte(keyID)); err != nil {
  126. return errors.Wrapf(err, "error deleting ACME EAB Key with Key ID %s", keyID)
  127. }
  128. if err := db.deleteEAKID(ctx, provisionerID, keyID); err != nil {
  129. return errors.Wrapf(err, "error removing ACME EAB Key ID %s", keyID)
  130. }
  131. return nil
  132. }
  133. // GetExternalAccountKeys retrieves all External Account Binding keys for a provisioner
  134. func (db *DB) GetExternalAccountKeys(ctx context.Context, provisionerID, cursor string, limit int) ([]*acme.ExternalAccountKey, string, error) {
  135. externalAccountKeyMutex.RLock()
  136. defer externalAccountKeyMutex.RUnlock()
  137. // cursor and limit are ignored in open source, at least for now.
  138. var eakIDs []string
  139. r, err := db.db.Get(externalAccountKeyIDsByProvisionerIDTable, []byte(provisionerID))
  140. if err != nil {
  141. if !nosqlDB.IsErrNotFound(err) {
  142. return nil, "", errors.Wrapf(err, "error loading ACME EAB Key IDs for provisioner %s", provisionerID)
  143. }
  144. // it may happen that no record is found; we'll continue with an empty slice
  145. } else {
  146. if err := json.Unmarshal(r, &eakIDs); err != nil {
  147. return nil, "", errors.Wrapf(err, "error unmarshaling ACME EAB Key IDs for provisioner %s", provisionerID)
  148. }
  149. }
  150. keys := []*acme.ExternalAccountKey{}
  151. for _, eakID := range eakIDs {
  152. if eakID == "" {
  153. continue // shouldn't happen; just in case
  154. }
  155. eak, err := db.getDBExternalAccountKey(ctx, eakID)
  156. if err != nil {
  157. if !nosqlDB.IsErrNotFound(err) {
  158. return nil, "", errors.Wrapf(err, "error retrieving ACME EAB Key for provisioner %s and keyID %s", provisionerID, eakID)
  159. }
  160. }
  161. keys = append(keys, &acme.ExternalAccountKey{
  162. ID: eak.ID,
  163. KeyBytes: eak.KeyBytes,
  164. ProvisionerID: eak.ProvisionerID,
  165. Reference: eak.Reference,
  166. AccountID: eak.AccountID,
  167. CreatedAt: eak.CreatedAt,
  168. BoundAt: eak.BoundAt,
  169. })
  170. }
  171. return keys, "", nil
  172. }
  173. // GetExternalAccountKeyByReference retrieves an External Account Binding key with unique reference
  174. func (db *DB) GetExternalAccountKeyByReference(ctx context.Context, provisionerID, reference string) (*acme.ExternalAccountKey, error) {
  175. externalAccountKeyMutex.RLock()
  176. defer externalAccountKeyMutex.RUnlock()
  177. if reference == "" {
  178. return nil, nil
  179. }
  180. k, err := db.db.Get(externalAccountKeyIDsByReferenceTable, []byte(referenceKey(provisionerID, reference)))
  181. if nosqlDB.IsErrNotFound(err) {
  182. return nil, acme.ErrNotFound
  183. } else if err != nil {
  184. return nil, errors.Wrapf(err, "error loading ACME EAB key for reference %s", reference)
  185. }
  186. dbExternalAccountKeyReference := new(dbExternalAccountKeyReference)
  187. if err := json.Unmarshal(k, dbExternalAccountKeyReference); err != nil {
  188. return nil, errors.Wrapf(err, "error unmarshaling ACME EAB key for reference %s", reference)
  189. }
  190. return db.GetExternalAccountKey(ctx, provisionerID, dbExternalAccountKeyReference.ExternalAccountKeyID)
  191. }
  192. func (db *DB) UpdateExternalAccountKey(ctx context.Context, provisionerID string, eak *acme.ExternalAccountKey) error {
  193. externalAccountKeyMutex.Lock()
  194. defer externalAccountKeyMutex.Unlock()
  195. old, err := db.getDBExternalAccountKey(ctx, eak.ID)
  196. if err != nil {
  197. return err
  198. }
  199. if old.ProvisionerID != provisionerID {
  200. return errors.New("provisioner does not match provisioner for which the EAB key was created")
  201. }
  202. if old.ProvisionerID != eak.ProvisionerID {
  203. return errors.New("cannot change provisioner for an existing ACME EAB Key")
  204. }
  205. if old.Reference != eak.Reference {
  206. return errors.New("cannot change reference for an existing ACME EAB Key")
  207. }
  208. nu := dbExternalAccountKey{
  209. ID: eak.ID,
  210. ProvisionerID: eak.ProvisionerID,
  211. Reference: eak.Reference,
  212. AccountID: eak.AccountID,
  213. KeyBytes: eak.KeyBytes,
  214. CreatedAt: eak.CreatedAt,
  215. BoundAt: eak.BoundAt,
  216. }
  217. return db.save(ctx, nu.ID, nu, old, "external_account_key", externalAccountKeyTable)
  218. }
  219. func (db *DB) addEAKID(ctx context.Context, provisionerID, eakID string) error {
  220. referencesByProvisionerIndexMutex.Lock()
  221. defer referencesByProvisionerIndexMutex.Unlock()
  222. if eakID == "" {
  223. return errors.Errorf("can't add empty eakID for provisioner %s", provisionerID)
  224. }
  225. var eakIDs []string
  226. b, err := db.db.Get(externalAccountKeyIDsByProvisionerIDTable, []byte(provisionerID))
  227. if err != nil {
  228. if !nosqlDB.IsErrNotFound(err) {
  229. return errors.Wrapf(err, "error loading eakIDs for provisioner %s", provisionerID)
  230. }
  231. // it may happen that no record is found; we'll continue with an empty slice
  232. } else {
  233. if err := json.Unmarshal(b, &eakIDs); err != nil {
  234. return errors.Wrapf(err, "error unmarshaling eakIDs for provisioner %s", provisionerID)
  235. }
  236. }
  237. for _, id := range eakIDs {
  238. if id == eakID {
  239. // return an error when a duplicate ID is found
  240. return errors.Errorf("eakID %s already exists for provisioner %s", eakID, provisionerID)
  241. }
  242. }
  243. var newEAKIDs []string
  244. newEAKIDs = append(newEAKIDs, eakIDs...)
  245. newEAKIDs = append(newEAKIDs, eakID)
  246. var (
  247. _old interface{} = eakIDs
  248. _new interface{} = newEAKIDs
  249. )
  250. // ensure that the DB gets the expected value when the slice is empty; otherwise
  251. // it'll return with an error that indicates that the DBs view of the data is
  252. // different from the last read (i.e. _old is different from what the DB has).
  253. if len(eakIDs) == 0 {
  254. _old = nil
  255. }
  256. if err = db.save(ctx, provisionerID, _new, _old, "externalAccountKeyIDsByProvisionerID", externalAccountKeyIDsByProvisionerIDTable); err != nil {
  257. return errors.Wrapf(err, "error saving eakIDs index for provisioner %s", provisionerID)
  258. }
  259. return nil
  260. }
  261. func (db *DB) deleteEAKID(ctx context.Context, provisionerID, eakID string) error {
  262. referencesByProvisionerIndexMutex.Lock()
  263. defer referencesByProvisionerIndexMutex.Unlock()
  264. var eakIDs []string
  265. b, err := db.db.Get(externalAccountKeyIDsByProvisionerIDTable, []byte(provisionerID))
  266. if err != nil {
  267. if !nosqlDB.IsErrNotFound(err) {
  268. return errors.Wrapf(err, "error loading eakIDs for provisioner %s", provisionerID)
  269. }
  270. // it may happen that no record is found; we'll continue with an empty slice
  271. } else {
  272. if err := json.Unmarshal(b, &eakIDs); err != nil {
  273. return errors.Wrapf(err, "error unmarshaling eakIDs for provisioner %s", provisionerID)
  274. }
  275. }
  276. newEAKIDs := removeElement(eakIDs, eakID)
  277. var (
  278. _old interface{} = eakIDs
  279. _new interface{} = newEAKIDs
  280. )
  281. // ensure that the DB gets the expected value when the slice is empty; otherwise
  282. // it'll return with an error that indicates that the DBs view of the data is
  283. // different from the last read (i.e. _old is different from what the DB has).
  284. if len(eakIDs) == 0 {
  285. _old = nil
  286. }
  287. if err = db.save(ctx, provisionerID, _new, _old, "externalAccountKeyIDsByProvisionerID", externalAccountKeyIDsByProvisionerIDTable); err != nil {
  288. return errors.Wrapf(err, "error saving eakIDs index for provisioner %s", provisionerID)
  289. }
  290. return nil
  291. }
  292. // referenceKey returns a unique key for a reference per provisioner
  293. func referenceKey(provisionerID, reference string) string {
  294. return provisionerID + "." + reference
  295. }
  296. // sliceIndex finds the index of item in slice
  297. func sliceIndex(slice []string, item string) int {
  298. for i := range slice {
  299. if slice[i] == item {
  300. return i
  301. }
  302. }
  303. return -1
  304. }
  305. // removeElement deletes the item if it exists in the
  306. // slice. It returns a new slice, keeping the old one intact.
  307. func removeElement(slice []string, item string) []string {
  308. newSlice := make([]string, 0)
  309. index := sliceIndex(slice, item)
  310. if index < 0 {
  311. newSlice = append(newSlice, slice...)
  312. return newSlice
  313. }
  314. newSlice = append(newSlice, slice[:index]...)
  315. return append(newSlice, slice[index+1:]...)
  316. }