eab.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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. HmacKey []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(_ 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. HmacKey: 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. HmacKey: dbeak.HmacKey,
  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. HmacKey: dbeak.HmacKey,
  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. _, _ = cursor, limit // unused input
  136. externalAccountKeyMutex.RLock()
  137. defer externalAccountKeyMutex.RUnlock()
  138. // cursor and limit are ignored in open source, at least for now.
  139. var eakIDs []string
  140. r, err := db.db.Get(externalAccountKeyIDsByProvisionerIDTable, []byte(provisionerID))
  141. if err != nil {
  142. if !nosqlDB.IsErrNotFound(err) {
  143. return nil, "", errors.Wrapf(err, "error loading ACME EAB Key IDs for provisioner %s", provisionerID)
  144. }
  145. // it may happen that no record is found; we'll continue with an empty slice
  146. } else {
  147. if err := json.Unmarshal(r, &eakIDs); err != nil {
  148. return nil, "", errors.Wrapf(err, "error unmarshaling ACME EAB Key IDs for provisioner %s", provisionerID)
  149. }
  150. }
  151. keys := []*acme.ExternalAccountKey{}
  152. for _, eakID := range eakIDs {
  153. if eakID == "" {
  154. continue // shouldn't happen; just in case
  155. }
  156. eak, err := db.getDBExternalAccountKey(ctx, eakID)
  157. if err != nil {
  158. if !nosqlDB.IsErrNotFound(err) {
  159. return nil, "", errors.Wrapf(err, "error retrieving ACME EAB Key for provisioner %s and keyID %s", provisionerID, eakID)
  160. }
  161. }
  162. keys = append(keys, &acme.ExternalAccountKey{
  163. ID: eak.ID,
  164. HmacKey: eak.HmacKey,
  165. ProvisionerID: eak.ProvisionerID,
  166. Reference: eak.Reference,
  167. AccountID: eak.AccountID,
  168. CreatedAt: eak.CreatedAt,
  169. BoundAt: eak.BoundAt,
  170. })
  171. }
  172. return keys, "", nil
  173. }
  174. // GetExternalAccountKeyByReference retrieves an External Account Binding key with unique reference
  175. func (db *DB) GetExternalAccountKeyByReference(ctx context.Context, provisionerID, reference string) (*acme.ExternalAccountKey, error) {
  176. externalAccountKeyMutex.RLock()
  177. defer externalAccountKeyMutex.RUnlock()
  178. if reference == "" {
  179. //nolint:nilnil // legacy
  180. return nil, nil
  181. }
  182. k, err := db.db.Get(externalAccountKeyIDsByReferenceTable, []byte(referenceKey(provisionerID, reference)))
  183. if nosqlDB.IsErrNotFound(err) {
  184. return nil, acme.ErrNotFound
  185. } else if err != nil {
  186. return nil, errors.Wrapf(err, "error loading ACME EAB key for reference %s", reference)
  187. }
  188. dbExternalAccountKeyReference := new(dbExternalAccountKeyReference)
  189. if err := json.Unmarshal(k, dbExternalAccountKeyReference); err != nil {
  190. return nil, errors.Wrapf(err, "error unmarshaling ACME EAB key for reference %s", reference)
  191. }
  192. return db.GetExternalAccountKey(ctx, provisionerID, dbExternalAccountKeyReference.ExternalAccountKeyID)
  193. }
  194. func (db *DB) GetExternalAccountKeyByAccountID(context.Context, string, string) (*acme.ExternalAccountKey, error) {
  195. //nolint:nilnil // legacy
  196. return nil, nil
  197. }
  198. func (db *DB) UpdateExternalAccountKey(ctx context.Context, provisionerID string, eak *acme.ExternalAccountKey) error {
  199. externalAccountKeyMutex.Lock()
  200. defer externalAccountKeyMutex.Unlock()
  201. old, err := db.getDBExternalAccountKey(ctx, eak.ID)
  202. if err != nil {
  203. return err
  204. }
  205. if old.ProvisionerID != provisionerID {
  206. return errors.New("provisioner does not match provisioner for which the EAB key was created")
  207. }
  208. if old.ProvisionerID != eak.ProvisionerID {
  209. return errors.New("cannot change provisioner for an existing ACME EAB Key")
  210. }
  211. if old.Reference != eak.Reference {
  212. return errors.New("cannot change reference for an existing ACME EAB Key")
  213. }
  214. nu := dbExternalAccountKey{
  215. ID: eak.ID,
  216. ProvisionerID: eak.ProvisionerID,
  217. Reference: eak.Reference,
  218. AccountID: eak.AccountID,
  219. HmacKey: eak.HmacKey,
  220. CreatedAt: eak.CreatedAt,
  221. BoundAt: eak.BoundAt,
  222. }
  223. return db.save(ctx, nu.ID, nu, old, "external_account_key", externalAccountKeyTable)
  224. }
  225. func (db *DB) addEAKID(ctx context.Context, provisionerID, eakID string) error {
  226. referencesByProvisionerIndexMutex.Lock()
  227. defer referencesByProvisionerIndexMutex.Unlock()
  228. if eakID == "" {
  229. return errors.Errorf("can't add empty eakID for provisioner %s", provisionerID)
  230. }
  231. var eakIDs []string
  232. b, err := db.db.Get(externalAccountKeyIDsByProvisionerIDTable, []byte(provisionerID))
  233. if err != nil {
  234. if !nosqlDB.IsErrNotFound(err) {
  235. return errors.Wrapf(err, "error loading eakIDs for provisioner %s", provisionerID)
  236. }
  237. // it may happen that no record is found; we'll continue with an empty slice
  238. } else {
  239. if err := json.Unmarshal(b, &eakIDs); err != nil {
  240. return errors.Wrapf(err, "error unmarshaling eakIDs for provisioner %s", provisionerID)
  241. }
  242. }
  243. for _, id := range eakIDs {
  244. if id == eakID {
  245. // return an error when a duplicate ID is found
  246. return errors.Errorf("eakID %s already exists for provisioner %s", eakID, provisionerID)
  247. }
  248. }
  249. var newEAKIDs []string
  250. newEAKIDs = append(newEAKIDs, eakIDs...)
  251. newEAKIDs = append(newEAKIDs, eakID)
  252. var (
  253. _old interface{} = eakIDs
  254. _new interface{} = newEAKIDs
  255. )
  256. // ensure that the DB gets the expected value when the slice is empty; otherwise
  257. // it'll return with an error that indicates that the DBs view of the data is
  258. // different from the last read (i.e. _old is different from what the DB has).
  259. if len(eakIDs) == 0 {
  260. _old = nil
  261. }
  262. if err = db.save(ctx, provisionerID, _new, _old, "externalAccountKeyIDsByProvisionerID", externalAccountKeyIDsByProvisionerIDTable); err != nil {
  263. return errors.Wrapf(err, "error saving eakIDs index for provisioner %s", provisionerID)
  264. }
  265. return nil
  266. }
  267. func (db *DB) deleteEAKID(ctx context.Context, provisionerID, eakID string) error {
  268. referencesByProvisionerIndexMutex.Lock()
  269. defer referencesByProvisionerIndexMutex.Unlock()
  270. var eakIDs []string
  271. b, err := db.db.Get(externalAccountKeyIDsByProvisionerIDTable, []byte(provisionerID))
  272. if err != nil {
  273. if !nosqlDB.IsErrNotFound(err) {
  274. return errors.Wrapf(err, "error loading eakIDs for provisioner %s", provisionerID)
  275. }
  276. // it may happen that no record is found; we'll continue with an empty slice
  277. } else {
  278. if err := json.Unmarshal(b, &eakIDs); err != nil {
  279. return errors.Wrapf(err, "error unmarshaling eakIDs for provisioner %s", provisionerID)
  280. }
  281. }
  282. newEAKIDs := removeElement(eakIDs, eakID)
  283. var (
  284. _old interface{} = eakIDs
  285. _new interface{} = newEAKIDs
  286. )
  287. // ensure that the DB gets the expected value when the slice is empty; otherwise
  288. // it'll return with an error that indicates that the DBs view of the data is
  289. // different from the last read (i.e. _old is different from what the DB has).
  290. if len(eakIDs) == 0 {
  291. _old = nil
  292. }
  293. if err = db.save(ctx, provisionerID, _new, _old, "externalAccountKeyIDsByProvisionerID", externalAccountKeyIDsByProvisionerIDTable); err != nil {
  294. return errors.Wrapf(err, "error saving eakIDs index for provisioner %s", provisionerID)
  295. }
  296. return nil
  297. }
  298. // referenceKey returns a unique key for a reference per provisioner
  299. func referenceKey(provisionerID, reference string) string {
  300. return provisionerID + "." + reference
  301. }
  302. // sliceIndex finds the index of item in slice
  303. func sliceIndex(slice []string, item string) int {
  304. for i := range slice {
  305. if slice[i] == item {
  306. return i
  307. }
  308. }
  309. return -1
  310. }
  311. // removeElement deletes the item if it exists in the
  312. // slice. It returns a new slice, keeping the old one intact.
  313. func removeElement(slice []string, item string) []string {
  314. newSlice := make([]string, 0)
  315. index := sliceIndex(slice, item)
  316. if index < 0 {
  317. newSlice = append(newSlice, slice...)
  318. return newSlice
  319. }
  320. newSlice = append(newSlice, slice[:index]...)
  321. return append(newSlice, slice[index+1:]...)
  322. }