Parcourir la source

Persist attestation format provenance

Josh Drake il y a 3 mois
Parent
commit
adb7b880df

+ 13 - 10
acme/authorization.go

@@ -8,16 +8,19 @@ import (
 
 // Authorization representst an ACME Authorization.
 type Authorization struct {
-	ID          string       `json:"-"`
-	AccountID   string       `json:"-"`
-	Token       string       `json:"-"`
-	Fingerprint string       `json:"-"`
-	Identifier  Identifier   `json:"identifier"`
-	Status      Status       `json:"status"`
-	Challenges  []*Challenge `json:"challenges"`
-	Wildcard    bool         `json:"wildcard"`
-	ExpiresAt   time.Time    `json:"expires"`
-	Error       *Error       `json:"error,omitempty"`
+	ID          string `json:"-"`
+	AccountID   string `json:"-"`
+	Token       string `json:"-"`
+	Fingerprint string `json:"-"`
+	// AttestationFormat records the validated device-attest-01 format. It is
+	// internal authorization state and is not exposed in the ACME response.
+	AttestationFormat string       `json:"-"`
+	Identifier        Identifier   `json:"identifier"`
+	Status            Status       `json:"status"`
+	Challenges        []*Challenge `json:"challenges"`
+	Wildcard          bool         `json:"wildcard"`
+	ExpiresAt         time.Time    `json:"expires"`
+	Error             *Error       `json:"error,omitempty"`
 }
 
 // ToLog enables response logging.

+ 2 - 1
acme/challenge.go

@@ -975,6 +975,7 @@ func deviceAttest01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose
 	default:
 		return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "unsupported attestation object format %q", format))
 	}
+	az.AttestationFormat = format
 
 	// Update and store the challenge.
 	ch.Status = StatusValid
@@ -985,7 +986,7 @@ func deviceAttest01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose
 	// Store the fingerprint in the authorization.
 	//
 	// TODO: add method to update authorization and challenge atomically.
-	if az.Fingerprint != "" {
+	if az.Fingerprint != "" || az.AttestationFormat != "" {
 		if err := db.UpdateAuthorization(ctx, az); err != nil {
 			return WrapErrorISE(err, "error updating authorization")
 		}

+ 49 - 1
acme/challenge_test.go

@@ -4486,6 +4486,45 @@ func Test_deviceAttest01Validate(t *testing.T) {
 				wantErr: nil,
 			}
 		},
+		"ok/doAppleAttestationFormat": func(t *testing.T) test {
+			jwk, _ := mustAccountAndKeyAuthorization(t, "nonce")
+			payload, leaf, root := mustAttestApple(t, "nonce")
+			caRoot := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: root.Raw})
+			ctx := NewProvisionerContext(context.Background(), mustAttestationProvisioner(t, caRoot))
+
+			return test{
+				args: args{
+					ctx: ctx,
+					jwk: jwk,
+					ch: &Challenge{
+						ID:              "chID",
+						AuthorizationID: "azID",
+						Token:           "nonce",
+						Type:            "device-attest-01",
+						Status:          StatusPending,
+						Value:           "serial-number",
+					},
+					payload: payload,
+					db: &MockDB{
+						MockGetAuthorization: func(context.Context, string) (*Authorization, error) {
+							return &Authorization{ID: "azID"}, nil
+						},
+						MockUpdateAuthorization: func(_ context.Context, az *Authorization) error {
+							fingerprint, err := keyutil.Fingerprint(leaf.PublicKey)
+							assert.NoError(t, err)
+							assert.Equal(t, fingerprint, az.Fingerprint)
+							assert.Equal(t, "apple", az.AttestationFormat)
+							return nil
+						},
+						MockUpdateChallenge: func(_ context.Context, ch *Challenge) error {
+							assert.Equal(t, StatusValid, ch.Status)
+							assert.Equal(t, "apple", ch.PayloadFormat)
+							return nil
+						},
+					},
+				},
+			}
+		},
 		"ok/doAppleAttestationFormat-non-matching-nonce": func(t *testing.T) test {
 			jwk, _ := mustAccountAndKeyAuthorization(t, "token")
 			payload, _, root := mustAttestApple(t, "bad-nonce")
@@ -4590,7 +4629,7 @@ func Test_deviceAttest01Validate(t *testing.T) {
 		},
 		"ok/doAndroidAttestationFormat": func(t *testing.T) test {
 			jwk, keyAuth := mustAccountAndKeyAuthorization(t, "token")
-			payload, _, root := mustAttestAndroid(t, keyAuth)
+			payload, leaf, root := mustAttestAndroid(t, keyAuth)
 
 			caRoot := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: root.Raw})
 			ctx := NewProvisionerContext(context.Background(), mustAndroidAttestationProvisioner(t, caRoot, nil))
@@ -4612,6 +4651,13 @@ func Test_deviceAttest01Validate(t *testing.T) {
 							assert.Equal(t, "azID", id)
 							return &Authorization{ID: "azID"}, nil
 						},
+						MockUpdateAuthorization: func(_ context.Context, az *Authorization) error {
+							fingerprint, err := keyutil.Fingerprint(leaf.PublicKey)
+							assert.NoError(t, err)
+							assert.Equal(t, fingerprint, az.Fingerprint)
+							assert.Equal(t, "android-key", az.AttestationFormat)
+							return nil
+						},
 						MockUpdateChallenge: func(ctx context.Context, updch *Challenge) error {
 							assert.Equal(t, "chID", updch.ID)
 							assert.Equal(t, "token", updch.Token)
@@ -4973,6 +5019,7 @@ func Test_deviceAttest01Validate(t *testing.T) {
 							assert.NoError(t, err)
 							assert.Equal(t, "azID", az.ID)
 							assert.Equal(t, fingerprint, az.Fingerprint)
+							assert.Equal(t, "step", az.AttestationFormat)
 							return nil
 						},
 						MockUpdateChallenge: func(ctx context.Context, updch *Challenge) error {
@@ -5021,6 +5068,7 @@ func Test_deviceAttest01Validate(t *testing.T) {
 							assert.NoError(t, err)
 							assert.Equal(t, "azID", az.ID)
 							assert.Equal(t, fingerprint, az.Fingerprint)
+							assert.Equal(t, "step", az.AttestationFormat)
 							return nil
 						},
 						MockUpdateChallenge: func(ctx context.Context, updch *Challenge) error {

+ 2 - 0
acme/challenge_tpmsimulator_test.go

@@ -329,6 +329,7 @@ func Test_deviceAttest01ValidateWithTPMSimulator(t *testing.T) {
 							assert.NoError(t, err)
 							assert.Equal(t, "azID", az.ID)
 							assert.Equal(t, fingerprint, az.Fingerprint)
+							assert.Equal(t, "tpm", az.AttestationFormat)
 							return nil
 						},
 						MockUpdateChallenge: func(ctx context.Context, updch *Challenge) error {
@@ -372,6 +373,7 @@ func Test_deviceAttest01ValidateWithTPMSimulator(t *testing.T) {
 							assert.NoError(t, err)
 							assert.Equal(t, "azID", az.ID)
 							assert.Equal(t, fingerprint, az.Fingerprint)
+							assert.Equal(t, "tpm", az.AttestationFormat)
 							return nil
 						},
 						MockUpdateChallenge: func(ctx context.Context, updch *Challenge) error {

+ 46 - 41
acme/db/nosql/authz.go

@@ -12,17 +12,18 @@ import (
 
 // dbAuthz is the base authz type that others build from.
 type dbAuthz struct {
-	ID           string          `json:"id"`
-	AccountID    string          `json:"accountID"`
-	Identifier   acme.Identifier `json:"identifier"`
-	Status       acme.Status     `json:"status"`
-	Token        string          `json:"token"`
-	Fingerprint  string          `json:"fingerprint,omitempty"`
-	ChallengeIDs []string        `json:"challengeIDs"`
-	Wildcard     bool            `json:"wildcard"`
-	CreatedAt    time.Time       `json:"createdAt"`
-	ExpiresAt    time.Time       `json:"expiresAt"`
-	Error        *acme.Error     `json:"error"`
+	ID                string          `json:"id"`
+	AccountID         string          `json:"accountID"`
+	Identifier        acme.Identifier `json:"identifier"`
+	Status            acme.Status     `json:"status"`
+	Token             string          `json:"token"`
+	Fingerprint       string          `json:"fingerprint,omitempty"`
+	AttestationFormat string          `json:"attestationFormat,omitempty"`
+	ChallengeIDs      []string        `json:"challengeIDs"`
+	Wildcard          bool            `json:"wildcard"`
+	CreatedAt         time.Time       `json:"createdAt"`
+	ExpiresAt         time.Time       `json:"expiresAt"`
+	Error             *acme.Error     `json:"error"`
 }
 
 func (ba *dbAuthz) clone() *dbAuthz {
@@ -62,16 +63,17 @@ func (db *DB) GetAuthorization(ctx context.Context, id string) (*acme.Authorizat
 		}
 	}
 	return &acme.Authorization{
-		ID:          dbaz.ID,
-		AccountID:   dbaz.AccountID,
-		Identifier:  dbaz.Identifier,
-		Status:      dbaz.Status,
-		Challenges:  chs,
-		Wildcard:    dbaz.Wildcard,
-		ExpiresAt:   dbaz.ExpiresAt,
-		Token:       dbaz.Token,
-		Fingerprint: dbaz.Fingerprint,
-		Error:       dbaz.Error,
+		ID:                dbaz.ID,
+		AccountID:         dbaz.AccountID,
+		Identifier:        dbaz.Identifier,
+		Status:            dbaz.Status,
+		Challenges:        chs,
+		Wildcard:          dbaz.Wildcard,
+		ExpiresAt:         dbaz.ExpiresAt,
+		Token:             dbaz.Token,
+		Fingerprint:       dbaz.Fingerprint,
+		AttestationFormat: dbaz.AttestationFormat,
+		Error:             dbaz.Error,
 	}, nil
 }
 
@@ -91,16 +93,17 @@ func (db *DB) CreateAuthorization(ctx context.Context, az *acme.Authorization) e
 
 	now := clock.Now()
 	dbaz := &dbAuthz{
-		ID:           az.ID,
-		AccountID:    az.AccountID,
-		Status:       az.Status,
-		CreatedAt:    now,
-		ExpiresAt:    az.ExpiresAt,
-		Identifier:   az.Identifier,
-		ChallengeIDs: chIDs,
-		Token:        az.Token,
-		Fingerprint:  az.Fingerprint,
-		Wildcard:     az.Wildcard,
+		ID:                az.ID,
+		AccountID:         az.AccountID,
+		Status:            az.Status,
+		CreatedAt:         now,
+		ExpiresAt:         az.ExpiresAt,
+		Identifier:        az.Identifier,
+		ChallengeIDs:      chIDs,
+		Token:             az.Token,
+		Fingerprint:       az.Fingerprint,
+		AttestationFormat: az.AttestationFormat,
+		Wildcard:          az.Wildcard,
 	}
 
 	return db.save(ctx, az.ID, dbaz, nil, "authz", authzTable)
@@ -116,6 +119,7 @@ func (db *DB) UpdateAuthorization(ctx context.Context, az *acme.Authorization) e
 	nu := old.clone()
 	nu.Status = az.Status
 	nu.Fingerprint = az.Fingerprint
+	nu.AttestationFormat = az.AttestationFormat
 	nu.Error = az.Error
 	return db.save(ctx, old.ID, nu, old, "authz", authzTable)
 }
@@ -139,16 +143,17 @@ func (db *DB) GetAuthorizationsByAccountID(_ context.Context, accountID string)
 			continue
 		}
 		authzs = append(authzs, &acme.Authorization{
-			ID:          dbaz.ID,
-			AccountID:   dbaz.AccountID,
-			Identifier:  dbaz.Identifier,
-			Status:      dbaz.Status,
-			Challenges:  nil, // challenges not required for current use case
-			Wildcard:    dbaz.Wildcard,
-			ExpiresAt:   dbaz.ExpiresAt,
-			Token:       dbaz.Token,
-			Fingerprint: dbaz.Fingerprint,
-			Error:       dbaz.Error,
+			ID:                dbaz.ID,
+			AccountID:         dbaz.AccountID,
+			Identifier:        dbaz.Identifier,
+			Status:            dbaz.Status,
+			Challenges:        nil, // challenges not required for current use case
+			Wildcard:          dbaz.Wildcard,
+			ExpiresAt:         dbaz.ExpiresAt,
+			Token:             dbaz.Token,
+			Fingerprint:       dbaz.Fingerprint,
+			AttestationFormat: dbaz.AttestationFormat,
+			Error:             dbaz.Error,
 		})
 	}
 

+ 68 - 43
acme/db/nosql/authz_test.go

@@ -73,13 +73,14 @@ func TestDB_getDBAuthz(t *testing.T) {
 					Type:  "dns",
 					Value: "test.ca.smallstep.com",
 				},
-				Status:       acme.StatusPending,
-				Token:        "token",
-				CreatedAt:    now,
-				ExpiresAt:    now.Add(5 * time.Minute),
-				Error:        acme.NewErrorISE("The server experienced an internal error"),
-				ChallengeIDs: []string{"foo", "bar"},
-				Wildcard:     true,
+				Status:            acme.StatusPending,
+				Token:             "token",
+				CreatedAt:         now,
+				ExpiresAt:         now.Add(5 * time.Minute),
+				Error:             acme.NewErrorISE("The server experienced an internal error"),
+				ChallengeIDs:      []string{"foo", "bar"},
+				Wildcard:          true,
+				AttestationFormat: "apple",
 			}
 			b, err := json.Marshal(dbaz)
 			assert.FatalError(t, err)
@@ -125,11 +126,26 @@ func TestDB_getDBAuthz(t *testing.T) {
 				assert.Equals(t, dbaz.ExpiresAt, tc.dbaz.ExpiresAt)
 				assert.Equals(t, dbaz.Error.Error(), tc.dbaz.Error.Error())
 				assert.Equals(t, dbaz.Wildcard, tc.dbaz.Wildcard)
+				assert.Equals(t, dbaz.AttestationFormat, tc.dbaz.AttestationFormat)
 			}
 		})
 	}
 }
 
+func TestDB_getDBAuthzLegacyAttestationFormat(t *testing.T) {
+	d := DB{db: &db.MockNoSQLDB{
+		MGet: func(bucket, key []byte) ([]byte, error) {
+			assert.Equals(t, bucket, authzTable)
+			assert.Equals(t, string(key), "azID")
+			return []byte(`{"id":"azID"}`), nil
+		},
+	}}
+
+	dbaz, err := d.getDBAuthz(context.Background(), "azID")
+	assert.FatalError(t, err)
+	assert.Equals(t, dbaz.AttestationFormat, "")
+}
+
 func TestDB_GetAuthorization(t *testing.T) {
 	azID := "azID"
 	type test struct {
@@ -250,13 +266,14 @@ func TestDB_GetAuthorization(t *testing.T) {
 					Type:  "dns",
 					Value: "test.ca.smallstep.com",
 				},
-				Status:       acme.StatusPending,
-				Token:        "token",
-				CreatedAt:    now,
-				ExpiresAt:    now.Add(5 * time.Minute),
-				Error:        acme.NewErrorISE("The server experienced an internal error"),
-				ChallengeIDs: []string{"foo", "bar"},
-				Wildcard:     true,
+				Status:            acme.StatusPending,
+				Token:             "token",
+				CreatedAt:         now,
+				ExpiresAt:         now.Add(5 * time.Minute),
+				Error:             acme.NewErrorISE("The server experienced an internal error"),
+				ChallengeIDs:      []string{"foo", "bar"},
+				Wildcard:          true,
+				AttestationFormat: "android-key",
 			}
 			b, err := json.Marshal(dbaz)
 			assert.FatalError(t, err)
@@ -317,6 +334,7 @@ func TestDB_GetAuthorization(t *testing.T) {
 				assert.Equals(t, az.Token, tc.dbaz.Token)
 				assert.Equals(t, az.Wildcard, tc.dbaz.Wildcard)
 				assert.Equals(t, az.ExpiresAt, tc.dbaz.ExpiresAt)
+				assert.Equals(t, az.AttestationFormat, tc.dbaz.AttestationFormat)
 				assert.Equals(t, az.Challenges, []*acme.Challenge{
 					{ID: "foo"},
 					{ID: "bar"},
@@ -404,8 +422,9 @@ func TestDB_CreateAuthorization(t *testing.T) {
 						{ID: "foo"},
 						{ID: "bar"},
 					},
-					Wildcard: true,
-					Error:    acme.NewErrorISE("force"),
+					Wildcard:          true,
+					AttestationFormat: "step",
+					Error:             acme.NewErrorISE("force"),
 				}
 			)
 			return test{
@@ -428,6 +447,7 @@ func TestDB_CreateAuthorization(t *testing.T) {
 						assert.Equals(t, dbaz.Token, az.Token)
 						assert.Equals(t, dbaz.ChallengeIDs, []string{"foo", "bar"})
 						assert.Equals(t, dbaz.Wildcard, az.Wildcard)
+						assert.Equals(t, dbaz.AttestationFormat, az.AttestationFormat)
 						assert.Equals(t, dbaz.ExpiresAt, az.ExpiresAt)
 						assert.Nil(t, dbaz.Error)
 						assert.True(t, clock.Now().Add(-time.Minute).Before(dbaz.CreatedAt))
@@ -467,13 +487,14 @@ func TestDB_UpdateAuthorization(t *testing.T) {
 			Type:  "dns",
 			Value: "test.ca.smallstep.com",
 		},
-		Status:       acme.StatusPending,
-		Token:        "token",
-		CreatedAt:    now,
-		ExpiresAt:    now.Add(5 * time.Minute),
-		ChallengeIDs: []string{"foo", "bar"},
-		Wildcard:     true,
-		Fingerprint:  "fingerprint",
+		Status:            acme.StatusPending,
+		Token:             "token",
+		CreatedAt:         now,
+		ExpiresAt:         now.Add(5 * time.Minute),
+		ChallengeIDs:      []string{"foo", "bar"},
+		Wildcard:          true,
+		Fingerprint:       "fingerprint",
+		AttestationFormat: "apple",
 	}
 	b, err := json.Marshal(dbaz)
 	assert.FatalError(t, err)
@@ -550,11 +571,12 @@ func TestDB_UpdateAuthorization(t *testing.T) {
 					{ID: "foo"},
 					{ID: "bar"},
 				},
-				Token:       dbaz.Token,
-				Wildcard:    dbaz.Wildcard,
-				ExpiresAt:   dbaz.ExpiresAt,
-				Fingerprint: "fingerprint",
-				Error:       acme.NewError(acme.ErrorMalformedType, "malformed"),
+				Token:             dbaz.Token,
+				Wildcard:          dbaz.Wildcard,
+				ExpiresAt:         dbaz.ExpiresAt,
+				Fingerprint:       "fingerprint",
+				AttestationFormat: "tpm",
+				Error:             acme.NewError(acme.ErrorMalformedType, "malformed"),
 			}
 			return test{
 				az: updAz,
@@ -585,6 +607,7 @@ func TestDB_UpdateAuthorization(t *testing.T) {
 						assert.Equals(t, dbNew.CreatedAt, dbaz.CreatedAt)
 						assert.Equals(t, dbNew.ExpiresAt, dbaz.ExpiresAt)
 						assert.Equals(t, dbNew.Fingerprint, dbaz.Fingerprint)
+						assert.Equals(t, dbNew.AttestationFormat, "tpm")
 						assert.Equals(t, dbNew.Error.Error(), acme.NewError(acme.ErrorMalformedType, "The request message was malformed").Error())
 						return nu, true, nil
 					},
@@ -669,12 +692,13 @@ func TestDB_GetAuthorizationsByAccountID(t *testing.T) {
 					Type:  "dns",
 					Value: "test.ca.smallstep.com",
 				},
-				Status:       acme.StatusValid,
-				Token:        "token",
-				CreatedAt:    now,
-				ExpiresAt:    now.Add(5 * time.Minute),
-				ChallengeIDs: []string{"foo", "bar"},
-				Wildcard:     true,
+				Status:            acme.StatusValid,
+				Token:             "token",
+				CreatedAt:         now,
+				ExpiresAt:         now.Add(5 * time.Minute),
+				ChallengeIDs:      []string{"foo", "bar"},
+				Wildcard:          true,
+				AttestationFormat: "apple",
 			}
 			b, err := json.Marshal(dbaz)
 			assert.FatalError(t, err)
@@ -694,15 +718,16 @@ func TestDB_GetAuthorizationsByAccountID(t *testing.T) {
 				},
 				authzs: []*acme.Authorization{
 					{
-						ID:         dbaz.ID,
-						AccountID:  dbaz.AccountID,
-						Token:      dbaz.Token,
-						Identifier: dbaz.Identifier,
-						Status:     dbaz.Status,
-						Challenges: nil,
-						Wildcard:   dbaz.Wildcard,
-						ExpiresAt:  dbaz.ExpiresAt,
-						Error:      dbaz.Error,
+						ID:                dbaz.ID,
+						AccountID:         dbaz.AccountID,
+						Token:             dbaz.Token,
+						Identifier:        dbaz.Identifier,
+						Status:            dbaz.Status,
+						Challenges:        nil,
+						Wildcard:          dbaz.Wildcard,
+						ExpiresAt:         dbaz.ExpiresAt,
+						Error:             dbaz.Error,
+						AttestationFormat: dbaz.AttestationFormat,
 					},
 				},
 			}

+ 27 - 0
acme/order.go

@@ -161,6 +161,28 @@ func (o *Order) getAuthorizationFingerprint(ctx context.Context, db DB) (string,
 	return "", nil
 }
 
+// getAuthorizationAttestationFormat returns the validated attestation format
+// recorded by permanent-identifier authorizations. Empty values from legacy
+// authorization records remain unknown. Conflicting nonempty values are
+// rejected instead of choosing one.
+func (o *Order) getAuthorizationAttestationFormat(ctx context.Context, db DB) (string, error) {
+	var format string
+	for _, azID := range o.AuthorizationIDs {
+		az, err := db.GetAuthorization(ctx, azID)
+		if err != nil {
+			return "", WrapErrorISE(err, "error getting authorization %q", azID)
+		}
+		if az.Identifier.Type != PermanentIdentifier || az.AttestationFormat == "" {
+			continue
+		}
+		if format != "" && format != az.AttestationFormat {
+			return "", NewErrorISE("conflicting attestation formats %q and %q for order %s", format, az.AttestationFormat, o.ID)
+		}
+		format = az.AttestationFormat
+	}
+	return format, nil
+}
+
 // Finalize signs a certificate if the necessary conditions for Order completion
 // have been met.
 //
@@ -259,6 +281,10 @@ func (o *Order) Finalize(ctx context.Context, db DB, csr *x509.CertificateReques
 
 	var defaultTemplate string
 	if permanentIdentifier != "" {
+		attestationFormat, err := o.getAuthorizationAttestationFormat(ctx, db)
+		if err != nil {
+			return err
+		}
 		defaultTemplate = x509util.DefaultAttestedLeafTemplate
 		data.SetSubjectAlternativeNames(x509util.SubjectAlternativeName{
 			Type:  x509util.PermanentIdentifierType,
@@ -266,6 +292,7 @@ func (o *Order) Finalize(ctx context.Context, db DB, csr *x509.CertificateReques
 		})
 		extraOptions = append(extraOptions, provisioner.AttestationData{
 			PermanentIdentifier: permanentIdentifier,
+			Format:              attestationFormat,
 		})
 	} else {
 		defaultTemplate = x509util.DefaultLeafTemplate

+ 179 - 0
acme/order_test.go

@@ -11,6 +11,7 @@ import (
 	"net"
 	"net/url"
 	"reflect"
+	"strings"
 	"testing"
 	"time"
 
@@ -2641,3 +2642,181 @@ func TestOrder_getAuthorizationFingerprint(t *testing.T) {
 		})
 	}
 }
+
+func TestOrder_getAuthorizationAttestationFormat(t *testing.T) {
+	ctx := context.Background()
+	tests := []struct {
+		name    string
+		authzs  map[string]*Authorization
+		err     error
+		want    string
+		wantErr string
+	}{
+		{
+			name: "legacy empty format",
+			authzs: map[string]*Authorization{
+				"az1": {ID: "az1", Identifier: Identifier{Type: PermanentIdentifier}},
+			},
+		},
+		{
+			name: "format",
+			authzs: map[string]*Authorization{
+				"az1": {ID: "az1", Identifier: Identifier{Type: PermanentIdentifier}, AttestationFormat: "apple"},
+			},
+			want: "apple",
+		},
+		{
+			name: "matching repeated formats",
+			authzs: map[string]*Authorization{
+				"az1": {ID: "az1", Identifier: Identifier{Type: PermanentIdentifier}, AttestationFormat: "tpm"},
+				"az2": {ID: "az2", Identifier: Identifier{Type: PermanentIdentifier}, AttestationFormat: "tpm"},
+			},
+			want: "tpm",
+		},
+		{
+			name: "known format with legacy empty format",
+			authzs: map[string]*Authorization{
+				"az1": {ID: "az1", Identifier: Identifier{Type: PermanentIdentifier}},
+				"az2": {ID: "az2", Identifier: Identifier{Type: PermanentIdentifier}, AttestationFormat: "step"},
+			},
+			want: "step",
+		},
+		{
+			name: "ignore non-permanent identifier",
+			authzs: map[string]*Authorization{
+				"az1": {ID: "az1", Identifier: Identifier{Type: DNS}, AttestationFormat: "step"},
+				"az2": {ID: "az2", Identifier: Identifier{Type: PermanentIdentifier}, AttestationFormat: "android-key"},
+			},
+			want: "android-key",
+		},
+		{
+			name: "conflicting formats",
+			authzs: map[string]*Authorization{
+				"az1": {ID: "az1", Identifier: Identifier{Type: PermanentIdentifier}, AttestationFormat: "apple"},
+				"az2": {ID: "az2", Identifier: Identifier{Type: PermanentIdentifier}, AttestationFormat: "step"},
+			},
+			wantErr: "conflicting attestation formats",
+		},
+		{
+			name:    "database error",
+			err:     errors.New("force"),
+			wantErr: "error getting authorization \"az1\": force",
+		},
+	}
+
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			o := &Order{AuthorizationIDs: []string{"az1", "az2"}}
+			db := &MockDB{
+				MockGetAuthorization: func(_ context.Context, id string) (*Authorization, error) {
+					if tt.err != nil {
+						return nil, tt.err
+					}
+					if az, ok := tt.authzs[id]; ok {
+						return az, nil
+					}
+					return &Authorization{ID: id, Identifier: Identifier{Type: DNS}}, nil
+				},
+			}
+
+			got, err := o.getAuthorizationAttestationFormat(ctx, db)
+			if tt.wantErr != "" {
+				if assert.Error(t, err) {
+					assert.True(t, strings.Contains(err.Error(), tt.wantErr))
+				}
+				return
+			}
+			assert.FatalError(t, err)
+			assert.Equals(t, got, tt.want)
+		})
+	}
+}
+
+func TestOrder_FinalizeAttestationData(t *testing.T) {
+	for _, format := range []string{"apple", "android-key", "step", "tpm"} {
+		t.Run(format, func(t *testing.T) {
+			signer, err := keyutil.GenerateSigner("EC", "P-256", 0)
+			assert.FatalError(t, err)
+			fingerprint, err := keyutil.Fingerprint(signer.Public())
+			assert.FatalError(t, err)
+
+			o := &Order{
+				ID:               "orderID",
+				AccountID:        "accountID",
+				Status:           StatusReady,
+				ExpiresAt:        clock.Now().Add(time.Minute),
+				AuthorizationIDs: []string{"authzID"},
+				Identifiers:      []Identifier{{Type: PermanentIdentifier, Value: "deviceID"}},
+			}
+			csr := &x509.CertificateRequest{
+				Subject:   pkix.Name{CommonName: "deviceID"},
+				PublicKey: signer.Public(),
+			}
+			db := &MockDB{
+				MockGetAuthorization: func(_ context.Context, id string) (*Authorization, error) {
+					assert.Equals(t, id, "authzID")
+					return &Authorization{
+						ID:                id,
+						Identifier:        Identifier{Type: PermanentIdentifier, Value: "deviceID"},
+						Fingerprint:       fingerprint,
+						AttestationFormat: format,
+					}, nil
+				},
+				MockCreateCertificate: func(_ context.Context, cert *Certificate) error {
+					cert.ID = "certID"
+					return nil
+				},
+				MockUpdateOrder: func(_ context.Context, _ *Order) error { return nil },
+			}
+			ca := &mockSignAuth{
+				signWithContext: func(_ context.Context, _ *x509.CertificateRequest, _ provisioner.SignOptions, opts ...provisioner.SignOption) ([]*x509.Certificate, error) {
+					var got *provisioner.AttestationData
+					for _, opt := range opts {
+						if attestationData, ok := opt.(provisioner.AttestationData); ok {
+							got = &attestationData
+						}
+					}
+					assert.Equals(t, got, &provisioner.AttestationData{
+						PermanentIdentifier: "deviceID",
+						Format:              format,
+					})
+					return []*x509.Certificate{{PublicKey: signer.Public()}}, nil
+				},
+			}
+			prov := &MockProvisioner{
+				MauthorizeSign: func(context.Context, string) ([]provisioner.SignOption, error) { return nil, nil },
+				MgetOptions:    func() *provisioner.Options { return nil },
+			}
+
+			assert.FatalError(t, o.Finalize(context.Background(), db, csr, ca, prov))
+		})
+	}
+}
+
+func TestOrder_FinalizeConflictingAttestationFormats(t *testing.T) {
+	o := &Order{
+		ID:               "orderID",
+		Status:           StatusReady,
+		ExpiresAt:        clock.Now().Add(time.Minute),
+		AuthorizationIDs: []string{"authz1", "authz2"},
+		Identifiers:      []Identifier{{Type: PermanentIdentifier, Value: "deviceID"}},
+	}
+	db := &MockDB{
+		MockGetAuthorization: func(_ context.Context, id string) (*Authorization, error) {
+			format := "apple"
+			if id == "authz2" {
+				format = "tpm"
+			}
+			return &Authorization{
+				ID:                id,
+				Identifier:        Identifier{Type: PermanentIdentifier, Value: "deviceID"},
+				AttestationFormat: format,
+			}, nil
+		},
+	}
+
+	err := o.Finalize(context.Background(), db, &x509.CertificateRequest{}, nil, nil)
+	if assert.Error(t, err) {
+		assert.True(t, strings.Contains(err.Error(), "conflicting attestation formats"))
+	}
+}

+ 1 - 0
authority/provisioner/sign_options.go

@@ -85,6 +85,7 @@ func (fn CertificateEnforcerFunc) Enforce(cert *x509.Certificate) error {
 // sign methods.
 type AttestationData struct {
 	PermanentIdentifier string
+	Format              string
 }
 
 // defaultPublicKeyValidator validates the public key of a certificate request.

+ 2 - 0
authority/tls_test.go

@@ -864,6 +864,7 @@ ZYtQ9Ot36qc=
 					if assert.True(t, ok) {
 						assert.Equal(t, &provisioner.AttestationData{
 							PermanentIdentifier: "1234567890",
+							Format:              "step",
 						}, p.AttestationData())
 					}
 					if assert.Len(t, certs, 2) {
@@ -879,6 +880,7 @@ ZYtQ9Ot36qc=
 				csr:  csr,
 				extraOpts: append(extraOpts, provisioner.AttestationData{
 					PermanentIdentifier: "1234567890",
+					Format:              "step",
 				}),
 				signOpts:        signOpts,
 				notBefore:       signOpts.NotBefore.Time().Truncate(time.Second),