order.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. package acme
  2. import (
  3. "context"
  4. "crypto/x509"
  5. "encoding/json"
  6. "reflect"
  7. "time"
  8. "github.com/pkg/errors"
  9. "github.com/smallstep/certificates/authority/provisioner"
  10. "github.com/smallstep/nosql"
  11. )
  12. var defaultOrderExpiry = time.Hour * 24
  13. // Order contains order metadata for the ACME protocol order type.
  14. type Order struct {
  15. Status string `json:"status"`
  16. Expires string `json:"expires,omitempty"`
  17. Identifiers []Identifier `json:"identifiers"`
  18. NotBefore string `json:"notBefore,omitempty"`
  19. NotAfter string `json:"notAfter,omitempty"`
  20. Error interface{} `json:"error,omitempty"`
  21. Authorizations []string `json:"authorizations"`
  22. Finalize string `json:"finalize"`
  23. Certificate string `json:"certificate,omitempty"`
  24. ID string `json:"-"`
  25. }
  26. // ToLog enables response logging.
  27. func (o *Order) ToLog() (interface{}, error) {
  28. b, err := json.Marshal(o)
  29. if err != nil {
  30. return nil, ServerInternalErr(errors.Wrap(err, "error marshaling order for logging"))
  31. }
  32. return string(b), nil
  33. }
  34. // GetID returns the Order ID.
  35. func (o *Order) GetID() string {
  36. return o.ID
  37. }
  38. // OrderOptions options with which to create a new Order.
  39. type OrderOptions struct {
  40. AccountID string `json:"accID"`
  41. Identifiers []Identifier `json:"identifiers"`
  42. NotBefore time.Time `json:"notBefore"`
  43. NotAfter time.Time `json:"notAfter"`
  44. }
  45. type order struct {
  46. ID string `json:"id"`
  47. AccountID string `json:"accountID"`
  48. Created time.Time `json:"created"`
  49. Expires time.Time `json:"expires,omitempty"`
  50. Status string `json:"status"`
  51. Identifiers []Identifier `json:"identifiers"`
  52. NotBefore time.Time `json:"notBefore,omitempty"`
  53. NotAfter time.Time `json:"notAfter,omitempty"`
  54. Error *Error `json:"error,omitempty"`
  55. Authorizations []string `json:"authorizations"`
  56. Certificate string `json:"certificate,omitempty"`
  57. }
  58. // newOrder returns a new Order type.
  59. func newOrder(db nosql.DB, ops OrderOptions) (*order, error) {
  60. id, err := randID()
  61. if err != nil {
  62. return nil, err
  63. }
  64. authzs := make([]string, len(ops.Identifiers))
  65. for i, identifier := range ops.Identifiers {
  66. az, err := newAuthz(db, ops.AccountID, identifier)
  67. if err != nil {
  68. return nil, err
  69. }
  70. authzs[i] = az.getID()
  71. }
  72. now := clock.Now()
  73. o := &order{
  74. ID: id,
  75. AccountID: ops.AccountID,
  76. Created: now,
  77. Status: StatusPending,
  78. Expires: now.Add(defaultOrderExpiry),
  79. Identifiers: ops.Identifiers,
  80. NotBefore: ops.NotBefore,
  81. NotAfter: ops.NotAfter,
  82. Authorizations: authzs,
  83. }
  84. if err := o.save(db, nil); err != nil {
  85. return nil, err
  86. }
  87. // Update the "order IDs by account ID" index //
  88. oids, err := getOrderIDsByAccount(db, ops.AccountID)
  89. if err != nil {
  90. return nil, err
  91. }
  92. newOids := append(oids, o.ID)
  93. if err = orderIDs(newOids).save(db, oids, o.AccountID); err != nil {
  94. db.Del(orderTable, []byte(o.ID))
  95. return nil, err
  96. }
  97. return o, nil
  98. }
  99. type orderIDs []string
  100. func (oids orderIDs) save(db nosql.DB, old orderIDs, accID string) error {
  101. var (
  102. err error
  103. oldb []byte
  104. )
  105. if len(old) == 0 {
  106. oldb = nil
  107. } else {
  108. oldb, err = json.Marshal(old)
  109. if err != nil {
  110. return ServerInternalErr(errors.Wrap(err, "error marshaling old order IDs slice"))
  111. }
  112. }
  113. newb, err := json.Marshal(oids)
  114. if err != nil {
  115. return ServerInternalErr(errors.Wrap(err, "error marshaling new order IDs slice"))
  116. }
  117. _, swapped, err := db.CmpAndSwap(ordersByAccountIDTable, []byte(accID), oldb, newb)
  118. switch {
  119. case err != nil:
  120. return ServerInternalErr(errors.Wrapf(err, "error storing order IDs for account %s", accID))
  121. case !swapped:
  122. return ServerInternalErr(errors.Errorf("error storing order IDs "+
  123. "for account %s; order IDs changed since last read", accID))
  124. default:
  125. return nil
  126. }
  127. }
  128. func (o *order) save(db nosql.DB, old *order) error {
  129. var (
  130. err error
  131. oldB []byte
  132. )
  133. if old == nil {
  134. oldB = nil
  135. } else {
  136. if oldB, err = json.Marshal(old); err != nil {
  137. return ServerInternalErr(errors.Wrap(err, "error marshaling old acme order"))
  138. }
  139. }
  140. newB, err := json.Marshal(o)
  141. if err != nil {
  142. return ServerInternalErr(errors.Wrap(err, "error marshaling new acme order"))
  143. }
  144. _, swapped, err := db.CmpAndSwap(orderTable, []byte(o.ID), oldB, newB)
  145. switch {
  146. case err != nil:
  147. return ServerInternalErr(errors.Wrap(err, "error storing order"))
  148. case !swapped:
  149. return ServerInternalErr(errors.New("error storing order; " +
  150. "value has changed since last read"))
  151. default:
  152. return nil
  153. }
  154. }
  155. // updateStatus updates order status if necessary.
  156. func (o *order) updateStatus(db nosql.DB) (*order, error) {
  157. _newOrder := *o
  158. newOrder := &_newOrder
  159. now := time.Now().UTC()
  160. switch o.Status {
  161. case StatusInvalid:
  162. return o, nil
  163. case StatusValid:
  164. return o, nil
  165. case StatusReady:
  166. // check expiry
  167. if now.After(o.Expires) {
  168. newOrder.Status = StatusInvalid
  169. newOrder.Error = MalformedErr(errors.New("order has expired"))
  170. break
  171. }
  172. return o, nil
  173. case StatusPending:
  174. // check expiry
  175. if now.After(o.Expires) {
  176. newOrder.Status = StatusInvalid
  177. newOrder.Error = MalformedErr(errors.New("order has expired"))
  178. break
  179. }
  180. var count = map[string]int{
  181. StatusValid: 0,
  182. StatusInvalid: 0,
  183. StatusPending: 0,
  184. }
  185. for _, azID := range o.Authorizations {
  186. az, err := getAuthz(db, azID)
  187. if err != nil {
  188. return nil, err
  189. }
  190. if az, err = az.updateStatus(db); err != nil {
  191. return nil, err
  192. }
  193. st := az.getStatus()
  194. count[st]++
  195. }
  196. switch {
  197. case count[StatusInvalid] > 0:
  198. newOrder.Status = StatusInvalid
  199. case count[StatusPending] > 0:
  200. break
  201. case count[StatusValid] == len(o.Authorizations):
  202. newOrder.Status = StatusReady
  203. default:
  204. return nil, ServerInternalErr(errors.New("unexpected authz status"))
  205. }
  206. default:
  207. return nil, ServerInternalErr(errors.Errorf("unrecognized order status: %s", o.Status))
  208. }
  209. if err := newOrder.save(db, o); err != nil {
  210. return nil, err
  211. }
  212. return newOrder, nil
  213. }
  214. // finalize signs a certificate if the necessary conditions for Order completion
  215. // have been met.
  216. func (o *order) finalize(db nosql.DB, csr *x509.CertificateRequest, auth SignAuthority, p provisioner.Interface) (*order, error) {
  217. var err error
  218. if o, err = o.updateStatus(db); err != nil {
  219. return nil, err
  220. }
  221. switch o.Status {
  222. case StatusInvalid:
  223. return nil, OrderNotReadyErr(errors.Errorf("order %s has been abandoned", o.ID))
  224. case StatusValid:
  225. return o, nil
  226. case StatusPending:
  227. return nil, OrderNotReadyErr(errors.Errorf("order %s is not ready", o.ID))
  228. case StatusReady:
  229. break
  230. default:
  231. return nil, ServerInternalErr(errors.Errorf("unexpected status %s for order %s", o.Status, o.ID))
  232. }
  233. // Validate identifier names against CSR alternative names //
  234. csrNames := make(map[string]int)
  235. for _, n := range csr.DNSNames {
  236. csrNames[n] = 1
  237. }
  238. orderNames := make(map[string]int)
  239. for _, n := range o.Identifiers {
  240. orderNames[n.Value] = 1
  241. }
  242. if !reflect.DeepEqual(csrNames, orderNames) {
  243. return nil, BadCSRErr(errors.Errorf("CSR names do not match identifiers exactly"))
  244. }
  245. // Get authorizations from the ACME provisioner.
  246. ctx := provisioner.NewContextWithMethod(context.Background(), provisioner.SignMethod)
  247. signOps, err := p.AuthorizeSign(ctx, "")
  248. if err != nil {
  249. return nil, ServerInternalErr(errors.Wrapf(err, "error retrieving authorization options from ACME provisioner"))
  250. }
  251. // Create and store a new certificate.
  252. leaf, inter, err := auth.Sign(csr, provisioner.Options{
  253. NotBefore: provisioner.NewTimeDuration(o.NotBefore),
  254. NotAfter: provisioner.NewTimeDuration(o.NotAfter),
  255. }, signOps...)
  256. if err != nil {
  257. return nil, ServerInternalErr(errors.Wrapf(err, "error generating certificate for order %s", o.ID))
  258. }
  259. cert, err := newCert(db, CertOptions{
  260. AccountID: o.AccountID,
  261. OrderID: o.ID,
  262. Leaf: leaf,
  263. Intermediates: []*x509.Certificate{inter},
  264. })
  265. if err != nil {
  266. return nil, err
  267. }
  268. _newOrder := *o
  269. newOrder := &_newOrder
  270. newOrder.Certificate = cert.ID
  271. newOrder.Status = StatusValid
  272. if err := newOrder.save(db, o); err != nil {
  273. return nil, err
  274. }
  275. return newOrder, nil
  276. }
  277. // getOrder retrieves and unmarshals an ACME Order type from the database.
  278. func getOrder(db nosql.DB, id string) (*order, error) {
  279. b, err := db.Get(orderTable, []byte(id))
  280. if nosql.IsErrNotFound(err) {
  281. return nil, MalformedErr(errors.Wrapf(err, "order %s not found", id))
  282. } else if err != nil {
  283. return nil, ServerInternalErr(errors.Wrapf(err, "error loading order %s", id))
  284. }
  285. var o order
  286. if err := json.Unmarshal(b, &o); err != nil {
  287. return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling order"))
  288. }
  289. return &o, nil
  290. }
  291. // toACME converts the internal Order type into the public acmeOrder type for
  292. // presentation in the ACME protocol.
  293. func (o *order) toACME(db nosql.DB, dir *directory, p provisioner.Interface) (*Order, error) {
  294. azs := make([]string, len(o.Authorizations))
  295. for i, aid := range o.Authorizations {
  296. azs[i] = dir.getLink(AuthzLink, URLSafeProvisionerName(p), true, aid)
  297. }
  298. ao := &Order{
  299. Status: o.Status,
  300. Expires: o.Expires.Format(time.RFC3339),
  301. Identifiers: o.Identifiers,
  302. NotBefore: o.NotBefore.Format(time.RFC3339),
  303. NotAfter: o.NotAfter.Format(time.RFC3339),
  304. Authorizations: azs,
  305. Finalize: dir.getLink(FinalizeLink, URLSafeProvisionerName(p), true, o.ID),
  306. ID: o.ID,
  307. }
  308. if o.Certificate != "" {
  309. ao.Certificate = dir.getLink(CertificateLink, URLSafeProvisionerName(p), true, o.Certificate)
  310. }
  311. return ao, nil
  312. }