diff --git a/handlers.go b/handlers.go index 93f676b..d54a288 100644 --- a/handlers.go +++ b/handlers.go @@ -472,6 +472,13 @@ func (ca *CA) handleAuthorization(w http.ResponseWriter, r *http.Request) { // pending orders. ca.updateAuthorizationStatus(ctx, authz) + // The composed challenge copies carry the stored status; a processing + // challenge whose reservation lapsed reads as pending, as + // handleChallenge presents it. + for i := range authz.Challenges { + authz.Challenges[i].presentLapsed(ca.reservationLease) + } + if postData.postAsGet { ca.writeJSONResponseWithNonce(ctx, w, http.StatusOK, authz) } else { @@ -601,9 +608,9 @@ func (ca *CA) handleCertificate(w http.ResponseWriter, r *http.Request) { } } -// scrubStorageState strips storage-internal state — the reservation and the -// stored attestation object — from a client-facing copy; the ACME wire -// format has neither field. +// scrubStorageState strips storage-internal state, the reservation, the +// stored attestation object, and the challenge ID list, from a +// client-facing copy; the ACME wire format has none of these fields. func scrubStorageState(data any) any { switch v := data.(type) { case *Order: @@ -617,6 +624,7 @@ func scrubStorageState(data any) any { return &scrubbed case *Authorization: scrubbed := *v + scrubbed.ChallengeIDs = nil scrubbed.Challenges = slices.Clone(v.Challenges) for i := range scrubbed.Challenges { scrubbed.Challenges[i].Reservation = nil @@ -740,6 +748,8 @@ func (ca *CA) createOrder(ctx context.Context, accountID string, orderReq OrderR orderID := ca.generateOrderID() var authzURLs []string + var authzs []*Authorization + var challenges []*Challenge for _, identifier := range orderReq.Identifiers { authzID := ca.generateAuthorizationID() @@ -754,13 +764,12 @@ func (ca *CA) createOrder(ctx context.Context, accountID string, orderReq OrderR Identifier: identifier, Status: "pending", Expires: &expires, - Challenges: []Challenge{}, CreatedAt: time.Now(), } if identifier.Type == "permanent-identifier" || identifier.Type == "hardware-module" { challengeID := ca.generateChallengeID() - challenge := Challenge{ + challenge := &Challenge{ ID: challengeID, AuthzID: authzID, Type: "device-attest-01", @@ -769,15 +778,11 @@ func (ca *CA) createOrder(ctx context.Context, accountID string, orderReq OrderR URL: ca.url(fmt.Sprintf("/challenge/%s", challengeID)), } - if err := ca.storage.CreateChallenge(ctx, &challenge); err != nil { - return nil, fmt.Errorf("failed to create challenge: %w", err) - } - authz.Challenges = append(authz.Challenges, challenge) + challenges = append(challenges, challenge) + authz.ChallengeIDs = append(authz.ChallengeIDs, challengeID) } - if err := ca.storage.CreateAuthorization(ctx, authz); err != nil { - return nil, fmt.Errorf("failed to create authorization: %w", err) - } + authzs = append(authzs, authz) } order := &Order{ @@ -790,7 +795,7 @@ func (ca *CA) createOrder(ctx context.Context, accountID string, orderReq OrderR CreatedAt: time.Now(), } - if err := ca.storage.CreateOrder(ctx, order); err != nil { + if err := ca.storage.CreateOrder(ctx, order, authzs, challenges); err != nil { return nil, fmt.Errorf("failed to create order: %w", err) } return order, nil @@ -1007,8 +1012,7 @@ func (ca *CA) updateOrderStatus(ctx context.Context, order *Order) { } // updateAuthorizationStatus settles a pending authorization once its -// challenges settle, refreshing the embedded challenge copies with the -// transition. The pending-only guard — enforced again by +// challenges settle. The pending-only guard — enforced again by // SettleAuthorization against the stored record — keeps a recompute from // stale reads from overwriting a settlement another request has since // written; a recompute that settles nothing writes nothing. @@ -1018,11 +1022,11 @@ func (ca *CA) updateAuthorizationStatus(ctx context.Context, authz *Authorizatio } // An authorization with no challenges must not count as valid. - allValid := len(authz.Challenges) > 0 + allValid := len(authz.ChallengeIDs) > 0 anyInvalid := false - for i, challenge := range authz.Challenges { - currentChallenge, err := ca.storage.GetChallenge(ctx, challenge.ID) + for _, challengeID := range authz.ChallengeIDs { + challenge, err := ca.storage.GetChallenge(ctx, challengeID) if err != nil { allValid = false continue @@ -1032,19 +1036,13 @@ func (ca *CA) updateAuthorizationStatus(ctx context.Context, authz *Authorizatio // here for the same reason handleChallenge presents it that way: an // RFC 8555 Section 7.5.1 client polls the authorization object, and // a challenge shown as processing forever would never be re-POSTed. - currentChallenge.presentLapsed(ca.reservationLease) - - // Reservations and attestation blobs belong to the challenge - // record, not embedded copies. - currentChallenge.Reservation = nil - currentChallenge.Attestation = nil - authz.Challenges[i] = *currentChallenge + challenge.presentLapsed(ca.reservationLease) - if currentChallenge.Status == "invalid" { + if challenge.Status == ChallengeStatusInvalid { anyInvalid = true break } - if currentChallenge.Status != "valid" { + if challenge.Status != ChallengeStatusValid { allValid = false } } @@ -1185,13 +1183,14 @@ func (ca *CA) finalizeCertificate(ctx context.Context, orderID, accountID string return order, nil } -// issueForOrder issues the certificate for a reserved order and commits it -// atomically with the order's valid transition. Nothing is persisted until -// that commit, so a failure releases the reservation and discards the -// signed certificate — a retry issues a fresh certificate for the CSR it -// actually carries, so a stored certificate never predates the CSR that -// finalized the order — and a crash leaves the order processing until the -// lease lapses and a retry reclaims it. +// issueForOrder issues the certificate for a reserved order under a fresh +// per-attempt ID and commits it by transitioning the order to valid. The +// token-gated order write is the commit point: a failure releases the +// reservation and leaves the signed certificate stored but referenced by +// no order, so it is never served. A retry issues a fresh certificate for +// the CSR it actually carries, so a served certificate never predates the +// CSR that finalized the order, and a crash leaves the order processing +// until the lease lapses and a retry reclaims it. func (ca *CA) issueForOrder(ctx context.Context, order *Order, csr *x509.CertificateRequest, token string) (*Certificate, []*DeviceInfo, error) { deviceInfos, err := ca.deviceInfosForOrder(ctx, order) if err != nil { @@ -1202,13 +1201,13 @@ func (ca *CA) issueForOrder(ctx context.Context, order *Order, csr *x509.Certifi if err != nil { return nil, nil, ca.failOrder(ctx, order.ID, token, fmt.Errorf("failed to issue certificate: %w", err)) } - cert.ID = order.ID + cert.ID = randomID(16) order.Status = OrderStatusValid order.Certificate = ca.url(fmt.Sprintf("/certificate/%s", cert.ID)) order.Reservation = nil if err := ca.storage.CompleteOrder(ctx, order, cert, token); err != nil { - ca.logger.ErrorContext(ctx, "Discarding signed certificate after failed completion", "serial_number", cert.SerialNumber, "error", err) + ca.logger.ErrorContext(ctx, "Leaving signed certificate unreferenced after failed completion", "serial_number", cert.SerialNumber, "error", err) // A lost race means the lease lapsed and another finalize // reclaimed the order; its outcome stands and there is no // reservation left to release. That is a client-state condition @@ -1266,15 +1265,15 @@ func (ca *CA) deviceInfosForOrder(ctx context.Context, order *Order) ([]*DeviceI continue } - for _, challenge := range authz.Challenges { - if challenge.Status != ChallengeStatusValid { - continue - } - challengeObj, err := ca.storage.GetChallenge(ctx, challenge.ID) + for _, challengeID := range authz.ChallengeIDs { + challenge, err := ca.storage.GetChallenge(ctx, challengeID) if err != nil { return nil, fmt.Errorf("failed to get challenge: %w", err) } - deviceInfo, err := ca.extractDeviceInfoFromChallenge(ctx, challengeObj) + if challenge.Status != ChallengeStatusValid { + continue + } + deviceInfo, err := ca.extractDeviceInfoFromChallenge(ctx, challenge) if err != nil { return nil, fmt.Errorf("failed to extract device info: %w", err) } diff --git a/handlers_internal_test.go b/handlers_internal_test.go index 2846495..2c07184 100644 --- a/handlers_internal_test.go +++ b/handlers_internal_test.go @@ -49,7 +49,7 @@ func TestWriteJSONResponseScrubsStorageState(t *testing.T) { order := &Order{ID: "o1", Status: OrderStatusProcessing, Reservation: reservation()} challenge := &Challenge{ID: "c1", Status: ChallengeStatusValid, Attestation: attestation, Reservation: reservation()} - authz := &Authorization{ID: "a1", Challenges: []Challenge{{ID: "c1", Attestation: attestation, Reservation: reservation()}}} + authz := &Authorization{ID: "a1", ChallengeIDs: []string{"c1"}, Challenges: []Challenge{{ID: "c1", Attestation: attestation, Reservation: reservation()}}} for name, data := range map[string]any{ "order": order, @@ -58,7 +58,7 @@ func TestWriteJSONResponseScrubsStorageState(t *testing.T) { } { rec := httptest.NewRecorder() ca.writeJSONResponse(t.Context(), rec, http.StatusOK, data, "") - for _, field := range []string{"reservation", "attestation"} { + for _, field := range []string{"reservation", "attestation", "challengeIds"} { if body := rec.Body.String(); strings.Contains(body, field) { t.Errorf("%s response leaks %s state:\n%s", name, field, body) } diff --git a/handlers_storage_test.go b/handlers_storage_test.go index 938364a..621d976 100644 --- a/handlers_storage_test.go +++ b/handlers_storage_test.go @@ -63,7 +63,7 @@ type orderCreateFailingStorage struct { nanoca.Storage } -func (orderCreateFailingStorage) CreateOrder(context.Context, *nanoca.Order) error { +func (orderCreateFailingStorage) CreateOrder(context.Context, *nanoca.Order, []*nanoca.Authorization, []*nanoca.Challenge) error { return errors.New("backend unavailable") } @@ -71,7 +71,7 @@ type orderCreateNotFoundStorage struct { nanoca.Storage } -func (orderCreateNotFoundStorage) CreateOrder(context.Context, *nanoca.Order) error { +func (orderCreateNotFoundStorage) CreateOrder(context.Context, *nanoca.Order, []*nanoca.Authorization, []*nanoca.Challenge) error { return fmt.Errorf("parent record missing: %w", nanoca.ErrNotFound) } @@ -128,8 +128,8 @@ func (s *authzLookupFailingStorage) GetAuthorization(ctx context.Context, id str return s.Storage.GetAuthorization(ctx, id) } -// completeOrderFailingOnceStorage fails the first atomic completion, after -// the certificate has been signed but before anything is persisted. +// completeOrderFailingOnceStorage fails the first completion, after the +// certificate has been signed but before the order commits. type completeOrderFailingOnceStorage struct { nanoca.Storage mu sync.Mutex @@ -147,6 +147,32 @@ func (s *completeOrderFailingOnceStorage) CompleteOrder(ctx context.Context, ord return s.Storage.CompleteOrder(ctx, order, cert, token) } +// completeOrderStaleTokenStorage passes a stale token to the first +// completion, as when another finalize reclaims a lapsed reservation: the +// certificate write lands but the order commit is refused. It records the +// ID of the certificate left behind. +type completeOrderStaleTokenStorage struct { + nanoca.Storage + mu sync.Mutex + certID string +} + +func (s *completeOrderStaleTokenStorage) CompleteOrder(ctx context.Context, order *nanoca.Order, cert *nanoca.Certificate, token string) error { + s.mu.Lock() + if s.certID == "" { + s.certID = cert.ID + token = "stale-" + token + } + s.mu.Unlock() + return s.Storage.CompleteOrder(ctx, order, cert, token) +} + +func (s *completeOrderStaleTokenStorage) unreferencedCertID() string { + s.mu.Lock() + defer s.mu.Unlock() + return s.certID +} + type selfSignedIssuer struct{} func (selfSignedIssuer) IssueCertificate(_ context.Context, csr *x509.CertificateRequest, _ []*nanoca.DeviceInfo) (*nanoca.Certificate, error) { @@ -388,11 +414,11 @@ func TestFinalizeDeviceInfoStorageFailure(t *testing.T) { wantServerInternal(t, err) } -// A failed completion persists nothing: the signed certificate is discarded -// and the order stays ready, so a retry — even with a regenerated key — -// gets a fresh certificate for the CSR it actually carries. Once the order -// is valid, further finalizes are refused per RFC 8555 Section 7.4 rather -// than answered with the stored certificate. +// A failed completion never becomes servable: the signed certificate is +// left unreferenced and the order stays ready, so a retry, even with a +// regenerated key, gets a fresh certificate for the CSR it actually +// carries. Once the order is valid, further finalizes are refused per +// RFC 8555 Section 7.4 rather than answered with the stored certificate. func TestFinalizeRetryAfterCompletionFailure(t *testing.T) { t.Parallel() @@ -437,6 +463,40 @@ func TestFinalizeRetryAfterCompletionFailure(t *testing.T) { } } +// A completion that loses the token-gated order write leaves its +// certificate stored but referenced by no order, so fetching it is refused +// even for the account that finalized. +func TestUnreferencedCertificateNotServed(t *testing.T) { + t.Parallel() + + storage := &completeOrderStaleTokenStorage{Storage: newTestStorage(t)} + ts := newStorageTestServer(t, storage, selfSignedIssuer{}) + + client := newACMEClient(t, ts) + order, chal := pendingChallenge(t, client, "unreferenced-device") + if err := submitAttObj(t, client, chal, nullAttObj(t)); err != nil { + t.Fatalf("failed to satisfy challenge: %v", err) + } + + if _, _, err := client.CreateOrderCert(t.Context(), order.FinalizeURL, newCSR(t), true); err == nil { + t.Fatal("finalize with a lost order write error = nil, want error") + } + + certID := storage.unreferencedCertID() + if certID == "" { + t.Fatal("no completion was attempted") + } + if _, err := storage.GetCertificate(t.Context(), certID); err != nil { + t.Fatalf("GetCertificate() error = %v, want the unreferenced certificate stored", err) + } + + _, err := client.FetchCert(t.Context(), ts.URL+"/certificate/"+certID, true) + var ae *acme.Error + if !errors.As(err, &ae) || ae.ProblemType != "urn:ietf:params:acme:error:unauthorized" { + t.Errorf("FetchCert(unreferenced certificate) error = %v, want unauthorized", err) + } +} + // A nonce-storage failure must surface as serverInternal, not badNonce: // clients respond to badNonce by retrying immediately with a fresh nonce, // hammering a backend that is already down. @@ -1233,19 +1293,17 @@ func TestFinalizeRefusesOrderWithoutValidAuthz(t *testing.T) { t.Error("finalize issued a certificate without the attested identifiers") } -// The attestation blob belongs to the challenge record: finalize re-reads it -// through GetChallenge and responses scrub it, so nothing ever reads a copy -// embedded in the authorization. Persisting one there duplicates a -// multi-kilobyte CBOR object into every settled authorization and pays its -// (de)serialization on every authz poll, order recompute, and finalize. -func TestSettledAuthorizationOmitsAttestation(t *testing.T) { +// The stored authorization names its challenges by ID and reads compose the +// wire-format challenges from the challenge records, so a settled +// authorization always reflects the live challenge state. +func TestSettledAuthorizationComposesChallenges(t *testing.T) { t.Parallel() storage := newTestStorage(t) ts := newStorageTestServer(t, storage, nil) client := newACMEClient(t, ts) - order, chal := pendingChallenge(t, client, "embedded-blob-device") + order, chal := pendingChallenge(t, client, "composed-device") if err := submitAttObj(t, client, chal, nullAttObj(t)); err != nil { t.Fatalf("failed to satisfy challenge: %v", err) } @@ -1257,10 +1315,14 @@ func TestSettledAuthorizationOmitsAttestation(t *testing.T) { if authz.Status != nanoca.AuthzStatusValid { t.Fatalf("authorization status = %q, want %q", authz.Status, nanoca.AuthzStatusValid) } - for _, challenge := range authz.Challenges { - if len(challenge.Attestation) > 0 { - t.Errorf("settled authorization embeds a %d-byte attestation for challenge %s", len(challenge.Attestation), challenge.ID) - } + if len(authz.ChallengeIDs) != 1 { + t.Fatalf("authorization challenge IDs = %v, want one", authz.ChallengeIDs) + } + if len(authz.Challenges) != 1 { + t.Fatalf("composed challenges = %d, want 1", len(authz.Challenges)) + } + if got := authz.Challenges[0]; got.ID != authz.ChallengeIDs[0] || got.Status != nanoca.ChallengeStatusValid { + t.Errorf("composed challenge = %q status %q, want %q status %q", got.ID, got.Status, authz.ChallengeIDs[0], nanoca.ChallengeStatusValid) } } diff --git a/storage.go b/storage.go index 5d6c0b8..bfc372d 100644 --- a/storage.go +++ b/storage.go @@ -55,7 +55,11 @@ type Storage interface { GetAccountByKey(ctx context.Context, keyThumbprint string) (*Account, error) UpdateAccount(ctx context.Context, account *Account) error - CreateOrder(ctx context.Context, order *Order) error + // CreateOrder stores a new order together with its authorizations and + // challenges, preferably atomically; a backend without multi-record + // atomicity must write challenges, then authorizations, then the order, + // so a readable record never references a missing one. + CreateOrder(ctx context.Context, order *Order, authzs []*Authorization, challenges []*Challenge) error GetOrder(ctx context.Context, id string) (*Order, error) // SetOrderStatus transitions an order from one status to the next only // if it is still in the expected preceding status, so a stale caller @@ -77,17 +81,17 @@ type Storage interface { ReleaseOrderFinalize(ctx context.Context, id, token, to string) error GetOrdersByAccount(ctx context.Context, accountID string) ([]*Order, error) - CreateAuthorization(ctx context.Context, authz *Authorization) error + // GetAuthorization loads an authorization, composing the wire-format + // Challenges from the challenge records named by ChallengeIDs; the + // stored record carries only the IDs. GetAuthorization(ctx context.Context, id string) (*Authorization, error) // SettleAuthorization transitions a pending authorization to - // authz.Status — valid or invalid — writing the full record so the - // refreshed embedded challenge copies land with the transition. It + // authz.Status, valid or invalid; only the status is written. It // returns ErrStatusMismatch, atomically with the write, when the stored // authorization is no longer pending, so a recompute from stale reads // cannot overwrite a settlement another request has since written. SettleAuthorization(ctx context.Context, authz *Authorization) error - CreateChallenge(ctx context.Context, challenge *Challenge) error GetChallenge(ctx context.Context, id string) (*Challenge, error) // ReserveChallengeValidation takes the exclusive right to validate a // challenge, with the same contract as ReserveOrderFinalize: pending to @@ -103,13 +107,15 @@ type Storage interface { // after a transient failure. SettleChallenge(ctx context.Context, challenge *Challenge, reservationToken string) error - // CompleteOrder atomically stores the certificate under Certificate.ID - // — the identifier GetCertificate looks up — and transitions the order - // from processing to valid, clearing its reservation; the write + // CompleteOrder stores the certificate under Certificate.ID, the + // identifier GetCertificate looks up, and transitions the order from + // processing to valid, clearing its reservation. The order write // requires the matching token, so a finalize whose reservation was - // reclaimed cannot persist a certificate for a stale CSR. On error - // neither write is persisted, so a stored certificate always belongs - // to a valid order. + // reclaimed cannot make its certificate reachable for a stale CSR. + // The certificate write is unconditional and lands before the order + // write, so a failed completion can leave a certificate stored but + // referenced by no order; a certificate is served only through an + // order whose Certificate URL names it. CompleteOrder(ctx context.Context, order *Order, cert *Certificate, token string) error GetCertificate(ctx context.Context, id string) (*Certificate, error) diff --git a/storage/badger/errors_test.go b/storage/badger/errors_test.go index 45629f0..4c1bf3a 100644 --- a/storage/badger/errors_test.go +++ b/storage/badger/errors_test.go @@ -103,9 +103,7 @@ func TestChallengeStatusMismatch(t *testing.T) { s := newTestStore(t) ctx := t.Context() - if err := s.CreateChallenge(ctx, &nanoca.Challenge{ID: "c1", Status: nanoca.ChallengeStatusValid}); err != nil { - t.Fatalf("CreateChallenge() error = %v", err) - } + createChallenge(t, s, &nanoca.Challenge{ID: "c1", Status: nanoca.ChallengeStatusValid}) if err := s.ReserveChallengeValidation(ctx, "c1", "token", time.Minute); !errors.Is(err, nanoca.ErrStatusMismatch) { t.Errorf("ReserveChallengeValidation(valid challenge) error = %v, want ErrStatusMismatch", err) } @@ -117,7 +115,7 @@ func TestSetOrderStatus(t *testing.T) { s := newTestStore(t) ctx := t.Context() - if err := s.CreateOrder(ctx, &nanoca.Order{ID: "o1", Status: nanoca.OrderStatusPending}); err != nil { + if err := s.CreateOrder(ctx, &nanoca.Order{ID: "o1", Status: nanoca.OrderStatusPending}, nil, nil); err != nil { t.Fatalf("CreateOrder() error = %v", err) } if err := s.SetOrderStatus(ctx, "o1", nanoca.OrderStatusPending, nanoca.OrderStatusReady); err != nil { diff --git a/storage/badger/storage.go b/storage/badger/storage.go index 82f80ab..d4723f8 100644 --- a/storage/badger/storage.go +++ b/storage/badger/storage.go @@ -290,14 +290,23 @@ func (s *Storage) UpdateAccount(_ context.Context, account *nanoca.Account) erro }) } -func (s *Storage) CreateOrder(_ context.Context, order *nanoca.Order) error { - data, err := json.Marshal(order) - if err != nil { - return fmt.Errorf("failed to marshal order: %w", err) - } - +func (s *Storage) CreateOrder(_ context.Context, order *nanoca.Order, authzs []*nanoca.Authorization, challenges []*nanoca.Challenge) error { return s.db.Update(func(txn *badger.Txn) error { - return txn.Set(orderKey(order.ID), data) + for _, challenge := range challenges { + if err := setJSON(txn, challengeKey(challenge.ID), "challenge", challenge); err != nil { + return err + } + } + for _, authz := range authzs { + // The composed challenge copies are never persisted; the + // stored record names its challenges by ID. + stored := *authz + stored.Challenges = nil + if err := setJSON(txn, authzKey(authz.ID), "authorization", &stored); err != nil { + return err + } + } + return setJSON(txn, orderKey(order.ID), "order", order) }) } @@ -393,22 +402,23 @@ func (s *Storage) GetOrdersByAccount(_ context.Context, accountID string) ([]*na return orders, nil } -func (s *Storage) CreateAuthorization(_ context.Context, authz *nanoca.Authorization) error { - data, err := json.Marshal(authz) - if err != nil { - return fmt.Errorf("failed to marshal authorization: %w", err) - } - - return s.db.Update(func(txn *badger.Txn) error { - return txn.Set(authzKey(authz.ID), data) - }) -} - func (s *Storage) GetAuthorization(_ context.Context, id string) (*nanoca.Authorization, error) { var authz nanoca.Authorization err := s.db.View(func(txn *badger.Txn) error { - return getJSON(txn, authzKey(id), "authorization", &authz) + if err := getJSON(txn, authzKey(id), "authorization", &authz); err != nil { + return err + } + + authz.Challenges = make([]nanoca.Challenge, 0, len(authz.ChallengeIDs)) + for _, challengeID := range authz.ChallengeIDs { + var challenge nanoca.Challenge + if err := getJSON(txn, challengeKey(challengeID), "challenge", &challenge); err != nil { + return err + } + authz.Challenges = append(authz.Challenges, challenge) + } + return nil }) if err != nil { return nil, err @@ -426,18 +436,8 @@ func (s *Storage) SettleAuthorization(_ context.Context, authz *nanoca.Authoriza if stored.Status != nanoca.AuthzStatusPending { return fmt.Errorf("authorization status is %s, not %s: %w", stored.Status, nanoca.AuthzStatusPending, nanoca.ErrStatusMismatch) } - return setJSON(txn, authzKey(authz.ID), "authorization", authz) - }) -} - -func (s *Storage) CreateChallenge(_ context.Context, challenge *nanoca.Challenge) error { - data, err := json.Marshal(challenge) - if err != nil { - return fmt.Errorf("failed to marshal challenge: %w", err) - } - - return s.db.Update(func(txn *badger.Txn) error { - return txn.Set(challengeKey(challenge.ID), data) + stored.Status = authz.Status + return setJSON(txn, authzKey(authz.ID), "authorization", &stored) }) } @@ -484,9 +484,20 @@ func (s *Storage) SettleChallenge(_ context.Context, challenge *nanoca.Challenge } func (s *Storage) CompleteOrder(_ context.Context, order *nanoca.Order, cert *nanoca.Certificate, token string) error { + // The certificate is written first, unconditionally; the token-gated + // order write below is the commit point that makes it reachable. A + // completion that loses the order write leaves the certificate stored + // but referenced by no order. + err := s.db.Update(func(txn *badger.Txn) error { + return setJSON(txn, certificateKey(cert.ID), "certificate", cert) + }) + if err != nil { + return err + } + // CompleteOrder owns the processing-to-valid transition; forcing the - // status here keeps a stored certificate from ever sharing a record - // with a non-valid order, whatever the caller passed. + // status here keeps an order from referencing a certificate without + // turning valid, whatever the caller passed. completed := *order completed.Status = nanoca.OrderStatusValid completed.Reservation = nil @@ -499,11 +510,7 @@ func (s *Storage) CompleteOrder(_ context.Context, order *nanoca.Order, cert *na if err := orderRecord(&stored).consume(token); err != nil { return err } - - if err := setJSON(txn, orderKey(order.ID), "order", &completed); err != nil { - return err - } - return setJSON(txn, certificateKey(cert.ID), "certificate", cert) + return setJSON(txn, orderKey(order.ID), "order", &completed) }) } diff --git a/storage/badger/storage_test.go b/storage/badger/storage_test.go index 1907079..0535a4f 100644 --- a/storage/badger/storage_test.go +++ b/storage/badger/storage_test.go @@ -239,7 +239,7 @@ func TestStorage_OrderOperations(t *testing.T) { Identifiers: []nanoca.Identifier{{Type: "permanent-identifier", Value: "device-123"}}, } - err := storage.CreateOrder(ctx, order) + err := storage.CreateOrder(ctx, order, nil, nil) if err != nil { t.Errorf("CreateOrder() error = %v", err) } @@ -296,9 +296,9 @@ func TestStorage_AuthorizationOperations(t *testing.T) { Identifier: nanoca.Identifier{Type: "permanent-identifier", Value: "device-123"}, } - err := storage.CreateAuthorization(ctx, authz) - if err != nil { - t.Errorf("CreateAuthorization() error = %v", err) + order := &nanoca.Order{ID: "order-for-" + authz.ID, Status: nanoca.OrderStatusPending} + if err := storage.CreateOrder(ctx, order, []*nanoca.Authorization{authz}, nil); err != nil { + t.Errorf("CreateOrder() error = %v", err) } retrieved, err := storage.GetAuthorization(ctx, authz.ID) @@ -342,6 +342,16 @@ func TestStorage_AuthorizationOperations(t *testing.T) { } } +// createChallenge persists a challenge through the batch order create, +// under a throwaway order. +func createChallenge(t *testing.T, s *Storage, challenge *nanoca.Challenge) { + t.Helper() + order := &nanoca.Order{ID: "order-for-" + challenge.ID, Status: nanoca.OrderStatusPending} + if err := s.CreateOrder(t.Context(), order, nil, []*nanoca.Challenge{challenge}); err != nil { + t.Fatalf("CreateOrder() error = %v", err) + } +} + func TestStorage_ChallengeOperations(t *testing.T) { t.Parallel() @@ -358,9 +368,7 @@ func TestStorage_ChallengeOperations(t *testing.T) { Token: "test-token", } - if err := storage.CreateChallenge(ctx, challenge); err != nil { - t.Fatalf("CreateChallenge() error = %v", err) - } + createChallenge(t, storage, challenge) retrieved, err := storage.GetChallenge(ctx, challenge.ID) if err != nil { @@ -391,9 +399,7 @@ func TestStorage_ChallengeOperations(t *testing.T) { Status: "pending", Token: "test-token", } - if err := storage.CreateChallenge(ctx, challenge); err != nil { - t.Fatalf("CreateChallenge() error = %v", err) - } + createChallenge(t, storage, challenge) if err := storage.ReserveChallengeValidation(ctx, challenge.ID, "t1", time.Minute); err != nil { t.Fatalf("ReserveChallengeValidation() error = %v", err) @@ -446,9 +452,7 @@ func TestStorage_ChallengeOperations(t *testing.T) { Status: "pending", Token: "test-token", } - if err := storage.CreateChallenge(ctx, challenge); err != nil { - t.Fatalf("CreateChallenge() error = %v", err) - } + createChallenge(t, storage, challenge) if err := storage.ReserveChallengeValidation(ctx, challenge.ID, "t1", time.Minute); err != nil { t.Fatalf("ReserveChallengeValidation() error = %v", err) } @@ -511,9 +515,7 @@ func TestStorage_ChallengeOperations(t *testing.T) { Status: "pending", Token: "test-token", } - if err := storage.CreateChallenge(ctx, challenge); err != nil { - t.Fatalf("CreateChallenge() error = %v", err) - } + createChallenge(t, storage, challenge) if err := storage.ReserveChallengeValidation(ctx, challenge.ID, "t1", time.Minute); err != nil { t.Fatalf("ReserveChallengeValidation() error = %v", err) } @@ -562,7 +564,7 @@ func storeCertificate(t *testing.T, s *Storage, cert *nanoca.Certificate) { t.Helper() ctx := t.Context() - if err := s.CreateOrder(ctx, &nanoca.Order{ID: cert.ID, Status: nanoca.OrderStatusReady}); err != nil { + if err := s.CreateOrder(ctx, &nanoca.Order{ID: cert.ID, Status: nanoca.OrderStatusReady}, nil, nil); err != nil { t.Fatalf("CreateOrder() error = %v", err) } if err := s.ReserveOrderFinalize(ctx, cert.ID, "token", time.Minute); err != nil { @@ -604,7 +606,7 @@ func TestStorage_CompleteOrder(t *testing.T) { storage := newTestStorage(t) ctx := t.Context() - if err := storage.CreateOrder(ctx, &nanoca.Order{ID: "o1", Status: nanoca.OrderStatusPending}); err != nil { + if err := storage.CreateOrder(ctx, &nanoca.Order{ID: "o1", Status: nanoca.OrderStatusPending}, nil, nil); err != nil { t.Fatalf("CreateOrder() error = %v", err) } // Deliberately not pre-set to valid: CompleteOrder owns the @@ -622,8 +624,13 @@ func TestStorage_CompleteOrder(t *testing.T) { if err := storage.CompleteOrder(ctx, order, cert, "t1"); !errors.Is(err, nanoca.ErrStatusMismatch) { t.Errorf("CompleteOrder(ready, unreserved) error = %v, want ErrStatusMismatch", err) } - if _, err := storage.GetCertificate(ctx, "o1"); !errors.Is(err, nanoca.ErrNotFound) { - t.Errorf("GetCertificate() after failed completion error = %v, want ErrNotFound", err) + // The certificate write is unconditional; a failed completion leaves it + // stored but referenced by no order. + if _, err := storage.GetCertificate(ctx, "o1"); err != nil { + t.Errorf("GetCertificate() after failed completion error = %v", err) + } + if got, err := storage.GetOrder(ctx, "o1"); err != nil || got.Status != nanoca.OrderStatusReady { + t.Errorf("order after failed completion = %+v, %v, want status %q", got, err, nanoca.OrderStatusReady) } if err := storage.ReserveOrderFinalize(ctx, "o1", "t1", time.Minute); err != nil { @@ -661,7 +668,7 @@ func TestReserveOrderFinalize(t *testing.T) { storage := newTestStorage(t) ctx := t.Context() - if err := storage.CreateOrder(ctx, &nanoca.Order{ID: "o1", Status: nanoca.OrderStatusPending}); err != nil { + if err := storage.CreateOrder(ctx, &nanoca.Order{ID: "o1", Status: nanoca.OrderStatusPending}, nil, nil); err != nil { t.Fatalf("CreateOrder() error = %v", err) } if err := storage.ReserveOrderFinalize(ctx, "o1", "t1", time.Minute); !errors.Is(err, nanoca.ErrStatusMismatch) { @@ -710,7 +717,7 @@ func TestReleaseOrderFinalize(t *testing.T) { storage := newTestStorage(t) ctx := t.Context() - if err := storage.CreateOrder(ctx, &nanoca.Order{ID: "o1", Status: nanoca.OrderStatusReady}); err != nil { + if err := storage.CreateOrder(ctx, &nanoca.Order{ID: "o1", Status: nanoca.OrderStatusReady}, nil, nil); err != nil { t.Fatalf("CreateOrder() error = %v", err) } if err := storage.ReleaseOrderFinalize(ctx, "o1", "t1", nanoca.OrderStatusReady); !errors.Is(err, nanoca.ErrStatusMismatch) { @@ -746,9 +753,7 @@ func TestSettleChallengeToPending(t *testing.T) { ctx := t.Context() pending := &nanoca.Challenge{ID: "c1", Status: nanoca.ChallengeStatusPending} - if err := storage.CreateChallenge(ctx, pending); err != nil { - t.Fatalf("CreateChallenge() error = %v", err) - } + createChallenge(t, storage, pending) if err := storage.SettleChallenge(ctx, pending, "t1"); !errors.Is(err, nanoca.ErrStatusMismatch) { t.Errorf("SettleChallenge(pending) error = %v, want ErrStatusMismatch", err) } diff --git a/types.go b/types.go index b131226..d279df1 100644 --- a/types.go +++ b/types.go @@ -54,7 +54,8 @@ type HardwareModule struct { // certificate response is built by ServedChain, which omits the root. type Certificate struct { *x509.Certificate `json:"-"` - // ID is the storage and URL identifier; the CA sets it to the order ID. + // ID is the storage and URL identifier; the CA assigns a fresh random + // ID per finalize attempt. ID string `json:"id"` Raw []byte `json:"raw"` SerialNumber string `json:"serialNumber"` @@ -193,15 +194,20 @@ const ( ) type Authorization struct { - ID string `json:"id"` - Status string `json:"status"` - Expires *time.Time `json:"expires,omitempty"` - Identifier Identifier `json:"identifier"` - Challenges []Challenge `json:"challenges"` - Wildcard bool `json:"wildcard,omitempty"` - AccountID string `json:"accountId"` - OrderID string `json:"orderId"` - CreatedAt time.Time `json:"createdAt"` + ID string `json:"id"` + Status string `json:"status"` + Expires *time.Time `json:"expires,omitempty"` + Identifier Identifier `json:"identifier"` + // ChallengeIDs names the authorization's challenges; the stored record + // carries only the IDs. Challenges is the ACME wire field, composed + // from the challenge records on read and never persisted, so the + // copies cannot drift from the records they mirror. + ChallengeIDs []string `json:"challengeIds,omitempty"` + Challenges []Challenge `json:"challenges"` + Wildcard bool `json:"wildcard,omitempty"` + AccountID string `json:"accountId"` + OrderID string `json:"orderId"` + CreatedAt time.Time `json:"createdAt"` } type Challenge struct {