eab.go 12 KB

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