Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 41 additions & 42 deletions handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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:
Expand All @@ -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
Expand Down Expand Up @@ -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()
Expand All @@ -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",
Expand All @@ -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{
Expand All @@ -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
Expand Down Expand Up @@ -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.
Expand All @@ -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
Expand All @@ -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
}
}
Expand Down Expand Up @@ -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 {
Expand All @@ -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
Expand Down Expand Up @@ -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)
}
Expand Down
4 changes: 2 additions & 2 deletions handlers_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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)
}
Expand Down
102 changes: 82 additions & 20 deletions handlers_storage_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,15 +63,15 @@ 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")
}

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)
}

Expand Down Expand Up @@ -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
Expand All @@ -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) {
Expand Down Expand Up @@ -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()

Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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)
}
Expand All @@ -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)
}
}

Expand Down
Loading