eab.go 12 KB

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