Просмотр исходного кода

Merge pull request #1681 from smallstep/herman/fix-wire-extensions

Improve access and dpop token validation
Herman Slatman 2 лет назад
Родитель
Сommit
51d1270541

+ 2 - 2
acme/api/order_test.go

@@ -1729,11 +1729,11 @@ MCowBQYDK2VwAyEA5c+4NKZSNQcR1T8qN6SjwgdPZQ0Ge12Ylx/YeGAJ35k=
 							TokenURL:    "",
 							JWKSURL:     "",
 							UserInfoURL: "",
-							Algorithms:  []string{},
+							Algorithms:  []string{"ES256"},
 						},
 						Config: &wire.Config{
 							ClientID:                   "integration test",
-							SignatureAlgorithms:        []string{},
+							SignatureAlgorithms:        []string{"ES256"},
 							SkipClientIDCheck:          true,
 							SkipExpiryCheck:            true,
 							SkipIssuerCheck:            true,

+ 10 - 6
acme/api/wire_integration_test.go

@@ -85,7 +85,7 @@ func TestWireIntegration(t *testing.T) {
 					"organization": "WireTest",
 					"commonName": {{ toJson .Oidc.name }}
 				},
-				"uris": [{{ toJson .Oidc.handle }}, {{ toJson .Dpop.sub }}],
+				"uris": [{{ toJson .Oidc.preferred_username }}, {{ toJson .Dpop.sub }}],
 				"keyUsage": ["digitalSignature"],
 				"extKeyUsage": ["clientAuth"]
 			}`,
@@ -98,11 +98,11 @@ func TestWireIntegration(t *testing.T) {
 					TokenURL:    "",
 					JWKSURL:     "",
 					UserInfoURL: "",
-					Algorithms:  []string{},
+					Algorithms:  []string{"ES256"},
 				},
 				Config: &wire.Config{
 					ClientID:                   "integration test",
-					SignatureAlgorithms:        []string{},
+					SignatureAlgorithms:        []string{"ES256"},
 					SkipClientIDCheck:          true,
 					SkipExpiryCheck:            true,
 					SkipIssuerCheck:            true,
@@ -306,12 +306,16 @@ func TestWireIntegration(t *testing.T) {
 					jose.Claims
 					Challenge string `json:"chal,omitempty"`
 					Handle    string `json:"handle,omitempty"`
+					Nonce     string `json:"nonce,omitempty"`
+					HTU       string `json:"htu,omitempty"`
 				}{
 					Claims: jose.Claims{
 						Subject: "wireapp://lJGYPz0ZRq2kvc_XpdaDlA!ed416ce8ecdd9fad@example.com",
 					},
 					Challenge: "token",
 					Handle:    "wireapp://%40alice.smith.qa@example.com",
+					Nonce:     "nonce",
+					HTU:       "http://issuer.example.com",
 				})
 				require.NoError(t, err)
 				dpop, err := dpopSigner.Sign(dpopBytes)
@@ -366,6 +370,7 @@ func TestWireIntegration(t *testing.T) {
 					jose.Claims
 					Name              string `json:"name,omitempty"`
 					PreferredUsername string `json:"preferred_username,omitempty"`
+					KeyAuth           string `json:"keyauth"`
 				}{
 					Claims: jose.Claims{
 						Issuer:   "https://issuer.example.com",
@@ -374,6 +379,7 @@ func TestWireIntegration(t *testing.T) {
 					},
 					Name:              "Alice Smith",
 					PreferredUsername: "wireapp://%40alice_wire@wire.com",
+					KeyAuth:           keyAuth,
 				})
 				require.NoError(t, err)
 				signed, err := oidcTokenSigner.Sign(tokenBytes)
@@ -382,10 +388,8 @@ func TestWireIntegration(t *testing.T) {
 				require.NoError(t, err)
 				p, err := json.Marshal(struct {
 					IDToken string `json:"id_token"`
-					KeyAuth string `json:"keyauth"`
 				}{
 					IDToken: idToken,
-					KeyAuth: keyAuth,
 				})
 				require.NoError(t, err)
 				payload = p
@@ -436,7 +440,7 @@ func TestWireIntegration(t *testing.T) {
 			t.Log("updated challenge:", challenge.ID, challenge.Status)
 			switch challenge.Type {
 			case acme.WIREOIDC01:
-				err = db.CreateOidcToken(ctx, order.ID, map[string]any{"name": "Smith, Alice M (QA)", "handle": "wireapp://%40alice.smith.qa@example.com"})
+				err = db.CreateOidcToken(ctx, order.ID, map[string]any{"name": "Smith, Alice M (QA)", "preferred_username": "wireapp://%40alice.smith.qa@example.com"})
 				require.NoError(t, err)
 			case acme.WIREDPOP01:
 				err = db.CreateDpopToken(ctx, order.ID, map[string]any{"sub": "wireapp://lJGYPz0ZRq2kvc_XpdaDlA!ed416ce8ecdd9fad@example.com"})

+ 121 - 28
acme/challenge.go

@@ -355,8 +355,6 @@ func dns01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSONWebK
 type wireOidcPayload struct {
 	// IDToken contains the OIDC identity token
 	IDToken string `json:"id_token"`
-	// KeyAuth ({challenge-token}.{jwk-thumbprint})
-	KeyAuth string `json:"keyauth"`
 }
 
 func wireOIDC01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSONWebKey, payload []byte) error {
@@ -364,6 +362,10 @@ func wireOIDC01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSO
 	if !ok {
 		return NewErrorISE("missing provisioner")
 	}
+	linker, ok := LinkerFromContext(ctx)
+	if !ok {
+		return NewErrorISE("missing linker")
+	}
 
 	var oidcPayload wireOidcPayload
 	err := json.Unmarshal(payload, &oidcPayload)
@@ -381,16 +383,6 @@ func wireOIDC01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSO
 		return WrapErrorISE(err, "failed getting Wire options")
 	}
 
-	// TODO(hs): move this into validation below?
-	expectedKeyAuth, err := KeyAuthorization(ch.Token, jwk)
-	if err != nil {
-		return WrapErrorISE(err, "error determining key authorization")
-	}
-	if expectedKeyAuth != oidcPayload.KeyAuth {
-		return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
-			"keyAuthorization does not match; expected %q, but got %q", expectedKeyAuth, oidcPayload.KeyAuth))
-	}
-
 	oidcOptions := wireOptions.GetOIDCOptions()
 	verifier := oidcOptions.GetProvider(ctx).Verifier(oidcOptions.GetConfig())
 	idToken, err := verifier.Verify(ctx, oidcPayload.IDToken)
@@ -400,17 +392,35 @@ func wireOIDC01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSO
 	}
 
 	var claims struct {
-		Name      string `json:"preferred_username,omitempty"`
-		Handle    string `json:"name"`
-		Issuer    string `json:"iss,omitempty"`
-		GivenName string `json:"given_name,omitempty"`
-		KeyAuth   string `json:"keyauth"` // TODO(hs): use this property instead of the one in the payload after https://github.com/wireapp/rusty-jwt-tools/tree/fix/keyauth is done
+		Name         string `json:"preferred_username,omitempty"`
+		Handle       string `json:"name"`
+		Issuer       string `json:"iss,omitempty"`
+		GivenName    string `json:"given_name,omitempty"`
+		KeyAuth      string `json:"keyauth"`
+		ACMEAudience string `json:"acme_aud,omitempty"`
 	}
 	if err := idToken.Claims(&claims); err != nil {
 		return storeError(ctx, db, ch, true, WrapError(ErrorRejectedIdentifierType, err,
 			"error retrieving claims from ID token"))
 	}
 
+	// TODO(hs): move this into validation below?
+	expectedKeyAuth, err := KeyAuthorization(ch.Token, jwk)
+	if err != nil {
+		return WrapErrorISE(err, "error determining key authorization")
+	}
+	if expectedKeyAuth != claims.KeyAuth {
+		return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
+			"keyAuthorization does not match; expected %q, but got %q", expectedKeyAuth, claims.KeyAuth))
+	}
+
+	// audience is the full URL to the challenge
+	acmeAudience := linker.GetLink(ctx, ChallengeLinkType, ch.AuthorizationID, ch.ID)
+	if claims.ACMEAudience != acmeAudience {
+		return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
+			"invalid 'acme_aud' %q", claims.ACMEAudience))
+	}
+
 	transformedIDToken, err := validateWireOIDCClaims(oidcOptions, idToken, wireID)
 	if err != nil {
 		return storeError(ctx, db, ch, true, WrapError(ErrorRejectedIdentifierType, err, "claims in OIDC ID token don't match"))
@@ -459,12 +469,12 @@ func validateWireOIDCClaims(o *wireprovisioner.OIDCOptions, token *oidc.IDToken,
 		return nil, fmt.Errorf("invalid 'name' %q after transformation", name)
 	}
 
-	handle, ok := transformed["handle"]
+	preferredUsername, ok := transformed["preferred_username"]
 	if !ok {
-		return nil, fmt.Errorf("transformed OIDC ID token does not contain 'handle'")
+		return nil, fmt.Errorf("transformed OIDC ID token does not contain 'preferred_username'")
 	}
-	if wireID.Handle != handle {
-		return nil, fmt.Errorf("invalid 'handle' %q after transformation", handle)
+	if wireID.Handle != preferredUsername {
+		return nil, fmt.Errorf("invalid 'preferred_username' %q after transformation", preferredUsername)
 	}
 
 	return transformed, nil
@@ -480,6 +490,10 @@ func wireDPOP01Validate(ctx context.Context, ch *Challenge, db DB, accountJWK *j
 	if !ok {
 		return NewErrorISE("missing provisioner")
 	}
+	linker, ok := LinkerFromContext(ctx)
+	if !ok {
+		return NewErrorISE("missing linker")
+	}
 
 	var dpopPayload wireDpopPayload
 	if err := json.Unmarshal(payload, &dpopPayload); err != nil {
@@ -507,12 +521,16 @@ func wireDPOP01Validate(ctx context.Context, ch *Challenge, db DB, accountJWK *j
 		return WrapErrorISE(err, "invalid Go template registered for 'target'")
 	}
 
+	// audience is the full URL to the challenge
+	audience := linker.GetLink(ctx, ChallengeLinkType, ch.AuthorizationID, ch.ID)
+
 	params := wireVerifyParams{
 		token:     dpopPayload.AccessToken,
 		tokenKey:  dpopOptions.GetSigningKey(),
 		dpopKey:   accountJWK.Public(),
 		dpopKeyID: accountJWK.KeyID,
 		issuer:    issuer,
+		audience:  audience,
 		wireID:    wireID,
 		chToken:   ch.Token,
 		t:         clock.Now().UTC(),
@@ -555,6 +573,7 @@ type wireCnf struct {
 type wireAccessToken struct {
 	jose.Claims
 	Challenge  string  `json:"chal"`
+	Nonce      string  `json:"nonce"`
 	Cnf        wireCnf `json:"cnf"`
 	Proof      string  `json:"proof"`
 	ClientID   string  `json:"client_id"`
@@ -562,6 +581,14 @@ type wireAccessToken struct {
 	Scope      string  `json:"scope"`
 }
 
+type wireDpopJwt struct {
+	jose.Claims
+	ClientID  string `json:"client_id"`
+	Challenge string `json:"chal"`
+	Nonce     string `json:"nonce"`
+	HTU       string `json:"htu"`
+}
+
 type wireDpopToken map[string]any
 
 type wireVerifyParams struct {
@@ -570,6 +597,7 @@ type wireVerifyParams struct {
 	dpopKey   crypto.PublicKey
 	dpopKeyID string
 	issuer    string
+	audience  string
 	wireID    wire.ID
 	chToken   string
 	t         time.Time
@@ -581,32 +609,97 @@ func parseAndVerifyWireAccessToken(v wireVerifyParams) (*wireAccessToken, *wireD
 		return nil, nil, fmt.Errorf("failed parsing token: %w", err)
 	}
 
+	if len(jwt.Headers) != 1 {
+		return nil, nil, fmt.Errorf("token has wrong number of headers %d", len(jwt.Headers))
+	}
+	keyID, err := KeyToID(&jose.JSONWebKey{Key: v.tokenKey})
+	if err != nil {
+		return nil, nil, fmt.Errorf("failed calculating token key ID: %w", err)
+	}
+	jwtKeyID := jwt.Headers[0].KeyID
+	if jwtKeyID == "" {
+		if jwtKeyID, err = KeyToID(jwt.Headers[0].JSONWebKey); err != nil {
+			return nil, nil, fmt.Errorf("failed extracting token key ID: %w", err)
+		}
+	}
+	if jwtKeyID != keyID {
+		return nil, nil, fmt.Errorf("invalid token key ID %q", jwtKeyID)
+	}
+
 	var accessToken wireAccessToken
 	if err = jwt.Claims(v.tokenKey, &accessToken); err != nil {
 		return nil, nil, fmt.Errorf("failed validating Wire DPoP token claims: %w", err)
 	}
 
 	if err := accessToken.ValidateWithLeeway(jose.Expected{
-		Time:   v.t,
-		Issuer: v.issuer,
-	}, 360*time.Second); err != nil {
+		Time:     v.t,
+		Issuer:   v.issuer,
+		Audience: jose.Audience{v.audience},
+	}, 1*time.Minute); err != nil {
 		return nil, nil, fmt.Errorf("failed validation: %w", err)
 	}
 
-	if accessToken.Cnf.Kid != v.dpopKeyID {
+	if accessToken.Challenge == "" {
+		return nil, nil, errors.New("access token challenge must not be empty")
+	}
+	if accessToken.Cnf.Kid == "" || accessToken.Cnf.Kid != v.dpopKeyID {
 		return nil, nil, fmt.Errorf("expected kid %q; got %q", v.dpopKeyID, accessToken.Cnf.Kid)
 	}
 	if accessToken.ClientID != v.wireID.ClientID {
 		return nil, nil, fmt.Errorf("invalid Wire client ID %q", accessToken.ClientID)
 	}
-	if accessToken.Expiry.Time().After(v.t.Add(time.Hour * 24 * 365)) {
+	if accessToken.Expiry.Time().After(v.t.Add(time.Hour)) {
 		return nil, nil, fmt.Errorf("'exp' %s is too far into the future", accessToken.Expiry.Time().String())
 	}
+	if accessToken.Scope != "wire_client_id" {
+		return nil, nil, fmt.Errorf("invalid Wire scope %q", accessToken.Scope)
+	}
 
 	dpopJWT, err := jose.ParseSigned(accessToken.Proof)
 	if err != nil {
 		return nil, nil, fmt.Errorf("invalid Wire DPoP token: %w", err)
 	}
+	if len(dpopJWT.Headers) != 1 {
+		return nil, nil, fmt.Errorf("DPoP token has wrong number of headers %d", len(jwt.Headers))
+	}
+	dpopJwtKeyID := dpopJWT.Headers[0].KeyID
+	if dpopJwtKeyID == "" {
+		if dpopJwtKeyID, err = KeyToID(dpopJWT.Headers[0].JSONWebKey); err != nil {
+			return nil, nil, fmt.Errorf("failed extracting DPoP token key ID: %w", err)
+		}
+	}
+	if dpopJwtKeyID != v.dpopKeyID {
+		return nil, nil, fmt.Errorf("invalid DPoP token key ID %q", dpopJWT.Headers[0].KeyID)
+	}
+
+	var wireDpop wireDpopJwt
+	if err := dpopJWT.Claims(v.dpopKey, &wireDpop); err != nil {
+		return nil, nil, fmt.Errorf("failed validating Wire DPoP token claims: %w", err)
+	}
+
+	if err := wireDpop.ValidateWithLeeway(jose.Expected{
+		Time:     v.t,
+		Audience: jose.Audience{v.audience},
+	}, 1*time.Minute); err != nil {
+		return nil, nil, fmt.Errorf("failed DPoP validation: %w", err)
+	}
+	if wireDpop.HTU == "" || wireDpop.HTU != v.issuer { // DPoP doesn't contains "iss" claim, but has it in the "htu" claim
+		return nil, nil, fmt.Errorf("DPoP contains invalid issuer (htu) %q", wireDpop.HTU)
+	}
+	if wireDpop.Expiry.Time().After(v.t.Add(time.Hour)) {
+		return nil, nil, fmt.Errorf("'exp' %s is too far into the future", wireDpop.Expiry.Time().String())
+	}
+	if wireDpop.Subject != v.wireID.ClientID {
+		return nil, nil, fmt.Errorf("DPoP contains invalid Wire client ID %q", wireDpop.ClientID)
+	}
+	if wireDpop.Nonce == "" || wireDpop.Nonce != accessToken.Nonce {
+		return nil, nil, fmt.Errorf("DPoP contains invalid nonce %q", wireDpop.Nonce)
+	}
+	if wireDpop.Challenge == "" || wireDpop.Challenge != accessToken.Challenge {
+		return nil, nil, fmt.Errorf("DPoP contains invalid challenge %q", wireDpop.Challenge)
+	}
+
+	// TODO(hs): can we use the wireDpopJwt and map that instead of doing Claims() twice?
 	var dpopToken wireDpopToken
 	if err := dpopJWT.Claims(v.dpopKey, &dpopToken); err != nil {
 		return nil, nil, fmt.Errorf("failed validating Wire DPoP token claims: %w", err)
@@ -616,7 +709,7 @@ func parseAndVerifyWireAccessToken(v wireVerifyParams) (*wireAccessToken, *wireD
 	if !ok {
 		return nil, nil, fmt.Errorf("invalid challenge in Wire DPoP token")
 	}
-	if challenge != v.chToken {
+	if challenge == "" || challenge != v.chToken {
 		return nil, nil, fmt.Errorf("invalid Wire DPoP challenge %q", challenge)
 	}
 
@@ -624,7 +717,7 @@ func parseAndVerifyWireAccessToken(v wireVerifyParams) (*wireAccessToken, *wireD
 	if !ok {
 		return nil, nil, fmt.Errorf("invalid handle in Wire DPoP token")
 	}
-	if handle != v.wireID.Handle {
+	if handle == "" || handle != v.wireID.Handle {
 		return nil, nil, fmt.Errorf("invalid Wire client handle %q", handle)
 	}
 

+ 29 - 24
acme/challenge_test.go

@@ -202,7 +202,7 @@ func newWireProvisionerWithOptions(t *testing.T, options *provisioner.Options) *
 	t.Helper()
 	prov := &provisioner.ACME{
 		Type:    "ACME",
-		Name:    "acme",
+		Name:    "wire",
 		Options: options,
 		Challenges: []provisioner.ACMEChallenge{
 			provisioner.WIREOIDC_01,
@@ -891,6 +891,8 @@ MCowBQYDK2VwAyEA5c+4NKZSNQcR1T8qN6SjwgdPZQ0Ge12Ylx/YeGAJ35k=
 				jose.Claims
 				Name              string `json:"name,omitempty"`
 				PreferredUsername string `json:"preferred_username,omitempty"`
+				KeyAuth           string `json:"keyauth"`
+				ACMEAudience      string `json:"acme_aud"`
 			}{
 				Claims: jose.Claims{
 					Issuer:   srv.URL,
@@ -899,6 +901,8 @@ MCowBQYDK2VwAyEA5c+4NKZSNQcR1T8qN6SjwgdPZQ0Ge12Ylx/YeGAJ35k=
 				},
 				Name:              "Alice Smith",
 				PreferredUsername: "wireapp://%40alice_wire@wire.com",
+				KeyAuth:           keyAuth,
+				ACMEAudience:      "https://ca.example.com/acme/wire/challenge/azID/chID",
 			})
 			require.NoError(t, err)
 			signed, err := signer.Sign(tokenBytes)
@@ -907,10 +911,8 @@ MCowBQYDK2VwAyEA5c+4NKZSNQcR1T8qN6SjwgdPZQ0Ge12Ylx/YeGAJ35k=
 			require.NoError(t, err)
 			payload, err := json.Marshal(struct {
 				IDToken string `json:"id_token"`
-				KeyAuth string `json:"keyauth"`
 			}{
 				IDToken: idToken,
-				KeyAuth: keyAuth,
 			})
 			require.NoError(t, err)
 			valueBytes, err := json.Marshal(struct {
@@ -929,17 +931,14 @@ MCowBQYDK2VwAyEA5c+4NKZSNQcR1T8qN6SjwgdPZQ0Ge12Ylx/YeGAJ35k=
 				Wire: &wireprovisioner.Options{
 					OIDC: &wireprovisioner.OIDCOptions{
 						Provider: &wireprovisioner.Provider{
-							IssuerURL: srv.URL,
-							JWKSURL:   srv.URL + "/keys",
+							IssuerURL:  srv.URL,
+							JWKSURL:    srv.URL + "/keys",
+							Algorithms: []string{"ES256"},
 						},
 						Config: &wireprovisioner.Config{
-							ClientID:                   "test",
-							SignatureAlgorithms:        []string{"ES256"},
-							SkipClientIDCheck:          false,
-							SkipExpiryCheck:            false,
-							SkipIssuerCheck:            false,
-							InsecureSkipSignatureCheck: false,
-							Now:                        time.Now,
+							ClientID:            "test",
+							SignatureAlgorithms: []string{"ES256"},
+							Now:                 time.Now,
 						},
 						TransformTemplate: "",
 					},
@@ -948,6 +947,7 @@ MCowBQYDK2VwAyEA5c+4NKZSNQcR1T8qN6SjwgdPZQ0Ge12Ylx/YeGAJ35k=
 					},
 				},
 			}))
+			ctx = NewLinkerContext(ctx, NewLinker("ca.example.com", "acme"))
 			return test{
 				ch: &Challenge{
 					ID:              "chID",
@@ -978,7 +978,7 @@ MCowBQYDK2VwAyEA5c+4NKZSNQcR1T8qN6SjwgdPZQ0Ge12Ylx/YeGAJ35k=
 					MockCreateOidcToken: func(ctx context.Context, orderID string, idToken map[string]interface{}) error {
 						assert.Equal(t, "orderID", orderID)
 						assert.Equal(t, "Alice Smith", idToken["name"].(string))
-						assert.Equal(t, "wireapp://%40alice_wire@wire.com", idToken["handle"].(string))
+						assert.Equal(t, "wireapp://%40alice_wire@wire.com", idToken["preferred_username"].(string))
 						return nil
 					},
 				},
@@ -1002,17 +1002,21 @@ MCowBQYDK2VwAyEA5c+4NKZSNQcR1T8qN6SjwgdPZQ0Ge12Ylx/YeGAJ35k=
 			signerPEMBlock, err := pemutil.Serialize(signerJWK.Public().Key)
 			require.NoError(t, err)
 			signerPEMBytes := pem.EncodeToMemory(signerPEMBlock)
-
 			dpopBytes, err := json.Marshal(struct {
 				jose.Claims
 				Challenge string `json:"chal,omitempty"`
 				Handle    string `json:"handle,omitempty"`
+				Nonce     string `json:"nonce,omitempty"`
+				HTU       string `json:"htu,omitempty"`
 			}{
 				Claims: jose.Claims{
-					Subject: "wireapp://CzbfFjDOQrenCbDxVmgnFw!594930e9d50bb175@wire.com",
+					Subject:  "wireapp://CzbfFjDOQrenCbDxVmgnFw!594930e9d50bb175@wire.com",
+					Audience: jose.Audience{"https://ca.example.com/acme/wire/challenge/azID/chID"},
 				},
 				Challenge: "token",
 				Handle:    "wireapp://%40alice_wire@wire.com",
+				Nonce:     "nonce",
+				HTU:       "http://issuer.example.com",
 			})
 			require.NoError(t, err)
 			dpop, err := dpopSigner.Sign(dpopBytes)
@@ -1022,6 +1026,7 @@ MCowBQYDK2VwAyEA5c+4NKZSNQcR1T8qN6SjwgdPZQ0Ge12Ylx/YeGAJ35k=
 			tokenBytes, err := json.Marshal(struct {
 				jose.Claims
 				Challenge string `json:"chal,omitempty"`
+				Nonce     string `json:"nonce,omitempty"`
 				Cnf       struct {
 					Kid string `json:"kid,omitempty"`
 				} `json:"cnf"`
@@ -1032,10 +1037,11 @@ MCowBQYDK2VwAyEA5c+4NKZSNQcR1T8qN6SjwgdPZQ0Ge12Ylx/YeGAJ35k=
 			}{
 				Claims: jose.Claims{
 					Issuer:   "http://issuer.example.com",
-					Audience: []string{"test"},
+					Audience: jose.Audience{"https://ca.example.com/acme/wire/challenge/azID/chID"},
 					Expiry:   jose.NewNumericDate(time.Now().Add(1 * time.Minute)),
 				},
 				Challenge: "token",
+				Nonce:     "nonce",
 				Cnf: struct {
 					Kid string `json:"kid,omitempty"`
 				}{
@@ -1073,24 +1079,23 @@ MCowBQYDK2VwAyEA5c+4NKZSNQcR1T8qN6SjwgdPZQ0Ge12Ylx/YeGAJ35k=
 				Wire: &wireprovisioner.Options{
 					OIDC: &wireprovisioner.OIDCOptions{
 						Provider: &wireprovisioner.Provider{
-							IssuerURL: "http://issuerexample.com",
+							IssuerURL:  "http://issuerexample.com",
+							Algorithms: []string{"ES256"},
 						},
 						Config: &wireprovisioner.Config{
-							ClientID:                   "test",
-							SignatureAlgorithms:        []string{"ES256"},
-							SkipClientIDCheck:          false,
-							SkipExpiryCheck:            false,
-							SkipIssuerCheck:            false,
-							InsecureSkipSignatureCheck: false,
-							Now:                        time.Now,
+							ClientID:            "test",
+							SignatureAlgorithms: []string{"ES256"},
+							Now:                 time.Now,
 						},
 						TransformTemplate: "",
 					},
 					DPOP: &wireprovisioner.DPOPOptions{
+						Target:     "http://issuer.example.com",
 						SigningKey: signerPEMBytes,
 					},
 				},
 			}))
+			ctx = NewLinkerContext(ctx, NewLinker("ca.example.com", "acme"))
 			return test{
 				ch: &Challenge{
 					ID:              "chID",

Разница между файлами не показана из-за своего большого размера
+ 235 - 137
acme/challenge_wire_test.go


+ 13 - 11
acme/db/nosql/wire.go

@@ -6,7 +6,6 @@ import (
 	"fmt"
 	"time"
 
-	"github.com/pkg/errors"
 	"github.com/smallstep/certificates/acme"
 	"github.com/smallstep/nosql"
 )
@@ -20,15 +19,16 @@ type dbDpopToken struct {
 // getDBDpopToken retrieves and unmarshals an DPoP type from the database.
 func (db *DB) getDBDpopToken(_ context.Context, orderID string) (*dbDpopToken, error) {
 	b, err := db.db.Get(wireDpopTokenTable, []byte(orderID))
-	if nosql.IsErrNotFound(err) {
-		return nil, acme.NewError(acme.ErrorMalformedType, "dpop token %q not found", orderID)
-	} else if err != nil {
-		return nil, errors.Wrapf(err, "error loading dpop %q", orderID)
+	if err != nil {
+		if nosql.IsErrNotFound(err) {
+			return nil, acme.NewError(acme.ErrorMalformedType, "dpop token %q not found", orderID)
+		}
+		return nil, fmt.Errorf("failed loading dpop token %q: %w", orderID, err)
 	}
 
 	d := new(dbDpopToken)
 	if err := json.Unmarshal(b, d); err != nil {
-		return nil, errors.Wrapf(err, "error unmarshaling dpop %q into dbDpopToken", orderID)
+		return nil, fmt.Errorf("failed unmarshaling dpop token %q into dbDpopToken: %w", orderID, err)
 	}
 	return d, nil
 }
@@ -74,14 +74,16 @@ type dbOidcToken struct {
 // getDBOidcToken retrieves and unmarshals an OIDC id token type from the database.
 func (db *DB) getDBOidcToken(_ context.Context, orderID string) (*dbOidcToken, error) {
 	b, err := db.db.Get(wireOidcTokenTable, []byte(orderID))
-	if nosql.IsErrNotFound(err) {
-		return nil, acme.NewError(acme.ErrorMalformedType, "oidc token %q not found", orderID)
-	} else if err != nil {
-		return nil, errors.Wrapf(err, "error loading oidc token %q", orderID)
+	if err != nil {
+		if nosql.IsErrNotFound(err) {
+			return nil, acme.NewError(acme.ErrorMalformedType, "oidc token %q not found", orderID)
+		}
+		return nil, fmt.Errorf("failed loading oidc token %q: %w", orderID, err)
 	}
+
 	o := new(dbOidcToken)
 	if err := json.Unmarshal(b, o); err != nil {
-		return nil, errors.Wrapf(err, "error unmarshaling oidc token %q into dbOidcToken", orderID)
+		return nil, fmt.Errorf("failed unmarshaling oidc token %q into dbOidcToken: %w", orderID, err)
 	}
 	return o, nil
 }

+ 11 - 11
acme/db/nosql/wire_test.go

@@ -57,7 +57,7 @@ func TestDB_GetDpopToken(t *testing.T) {
 					db: db,
 				},
 				orderID:     "orderID",
-				expectedErr: errors.New(`error unmarshaling dpop "orderID" into dbDpopToken: invalid character ':' after top-level value`),
+				expectedErr: errors.New(`failed unmarshaling dpop token "orderID" into dbDpopToken: invalid character ':' after top-level value`),
 			}
 		},
 		"fail/db.Get": func(t *testing.T) test {
@@ -73,7 +73,7 @@ func TestDB_GetDpopToken(t *testing.T) {
 					db: db,
 				},
 				orderID:     "orderID",
-				expectedErr: errors.New(`error loading dpop "orderID": fail`),
+				expectedErr: errors.New(`failed loading dpop token "orderID": fail`),
 			}
 		},
 		"ok": func(t *testing.T) test {
@@ -245,7 +245,7 @@ func TestDB_GetOidcToken(t *testing.T) {
 					db: db,
 				},
 				orderID:     "orderID",
-				expectedErr: errors.New(`error unmarshaling oidc token "orderID" into dbOidcToken: invalid character ':' after top-level value`),
+				expectedErr: errors.New(`failed unmarshaling oidc token "orderID" into dbOidcToken: invalid character ':' after top-level value`),
 			}
 		},
 		"fail/db.Get": func(t *testing.T) test {
@@ -261,7 +261,7 @@ func TestDB_GetOidcToken(t *testing.T) {
 					db: db,
 				},
 				orderID:     "orderID",
-				expectedErr: errors.New(`error loading oidc token "orderID": fail`),
+				expectedErr: errors.New(`failed loading oidc token "orderID": fail`),
 			}
 		},
 		"ok": func(t *testing.T) test {
@@ -270,7 +270,7 @@ func TestDB_GetOidcToken(t *testing.T) {
 			require.NoError(t, err)
 			token := dbOidcToken{
 				ID:        "orderID",
-				Content:   []byte(`{"name": "Alice Smith", "handle": "@alice.smith"}`),
+				Content:   []byte(`{"name": "Alice Smith", "preferred_username": "@alice.smith"}`),
 				CreatedAt: time.Now(),
 			}
 			b, err := json.Marshal(token)
@@ -283,8 +283,8 @@ func TestDB_GetOidcToken(t *testing.T) {
 				},
 				orderID: "orderID",
 				expected: map[string]any{
-					"name":   "Alice Smith",
-					"handle": "@alice.smith",
+					"name":               "Alice Smith",
+					"preferred_username": "@alice.smith",
 				},
 			}
 		},
@@ -335,8 +335,8 @@ func TestDB_CreateOidcToken(t *testing.T) {
 				},
 				orderID: "orderID",
 				oidc: map[string]any{
-					"name":   "Alice Smith",
-					"handle": "@alice.smith",
+					"name":               "Alice Smith",
+					"preferred_username": "@alice.smith",
 				},
 				expectedErr: errors.New("failed saving oidc token: error saving acme oidc: fail"),
 			}
@@ -351,8 +351,8 @@ func TestDB_CreateOidcToken(t *testing.T) {
 				},
 				orderID: "orderID",
 				oidc: map[string]any{
-					"name":   "Alice Smith",
-					"handle": "@alice.smith",
+					"name":               "Alice Smith",
+					"preferred_username": "@alice.smith",
 				},
 			}
 		},

+ 1 - 1
authority/provisioner/wire/dpop_options.go

@@ -10,7 +10,7 @@ import (
 )
 
 type DPOPOptions struct {
-	// Public part of the  signing key for DPoP access token
+	// Public part of the  signing key for DPoP access token in PEM format
 	SigningKey []byte `json:"key"`
 	// URI template for the URI the ACME client must call to fetch the DPoP challenge proof (an access token from wire-server)
 	Target string `json:"target"`

+ 5 - 3
authority/provisioner/wire/oidc_options.go

@@ -24,8 +24,10 @@ type Provider struct {
 }
 
 type Config struct {
-	ClientID                   string           `json:"clientId,omitempty"`
-	SignatureAlgorithms        []string         `json:"signatureAlgorithms,omitempty"`
+	ClientID            string   `json:"clientId,omitempty"`
+	SignatureAlgorithms []string `json:"signatureAlgorithms,omitempty"`
+
+	// the properties below are only used for testing
 	SkipClientIDCheck          bool             `json:"-"`
 	SkipExpiryCheck            bool             `json:"-"`
 	SkipIssuerCheck            bool             `json:"-"`
@@ -66,7 +68,7 @@ func (o *OIDCOptions) GetConfig() *oidc.Config {
 	}
 }
 
-const defaultTemplate = `{"name": "{{ .name }}", "handle": "{{ .preferred_username }}"}`
+const defaultTemplate = `{"name": "{{ .name }}", "preferred_username": "{{ .preferred_username }}"}`
 
 func (o *OIDCOptions) validateAndInitialize() (err error) {
 	if o.Provider == nil {

+ 6 - 8
authority/provisioner/wire/oidc_options_test.go

@@ -11,9 +11,9 @@ import (
 func TestOIDCOptions_Transform(t *testing.T) {
 	defaultTransform, err := parseTransform(``)
 	require.NoError(t, err)
-	swapTransform, err := parseTransform(`{"name": "{{ .preferred_username }}", "handle": "{{ .name }}"}`)
+	swapTransform, err := parseTransform(`{"name": "{{ .preferred_username }}", "preferred_username": "{{ .name }}"}`)
 	require.NoError(t, err)
-	funcTransform, err := parseTransform(`{"name": "{{ .name }}", "handle": "{{ first .usernames }}"}`)
+	funcTransform, err := parseTransform(`{"name": "{{ .name }}", "preferred_username": "{{ first .usernames }}"}`)
 	require.NoError(t, err)
 	type fields struct {
 		transform *template.Template
@@ -67,7 +67,6 @@ func TestOIDCOptions_Transform(t *testing.T) {
 			},
 			want: map[string]any{
 				"name":               "Example",
-				"handle":             "Preferred",
 				"preferred_username": "Preferred",
 			},
 		},
@@ -84,8 +83,7 @@ func TestOIDCOptions_Transform(t *testing.T) {
 			},
 			want: map[string]any{
 				"name":               "Preferred",
-				"handle":             "Example",
-				"preferred_username": "Preferred",
+				"preferred_username": "Example",
 			},
 		},
 		{
@@ -100,9 +98,9 @@ func TestOIDCOptions_Transform(t *testing.T) {
 				},
 			},
 			want: map[string]any{
-				"name":      "Example",
-				"handle":    "name-1",
-				"usernames": []string{"name-1", "name-2", "name-3"},
+				"name":               "Example",
+				"preferred_username": "name-1",
+				"usernames":          []string{"name-1", "name-2", "name-3"},
 			},
 		},
 	}

+ 3 - 14
authority/provisioner/wire/wire_options.go

@@ -3,16 +3,12 @@ package wire
 import (
 	"errors"
 	"fmt"
-	"sync"
 )
 
 // Options holds the Wire ACME extension options
 type Options struct {
 	OIDC *OIDCOptions `json:"oidc,omitempty"`
 	DPOP *DPOPOptions `json:"dpop,omitempty"`
-
-	validateOnce  sync.Once
-	validationErr error
 }
 
 // GetOIDCOptions returns the OIDC options.
@@ -31,17 +27,10 @@ func (o *Options) GetDPOPOptions() *DPOPOptions {
 	return o.DPOP
 }
 
+// Validate validates and initializes the Wire OIDC and DPoP options.
+//
+// TODO(hs): find a good way to perform this only once.
 func (o *Options) Validate() error {
-	o.validateOnce.Do(
-		func() {
-			o.validationErr = validate(o)
-		},
-	)
-
-	return o.validationErr
-}
-
-func validate(o *Options) error {
 	if oidc := o.GetOIDCOptions(); oidc != nil {
 		if err := oidc.validateAndInitialize(); err != nil {
 			return fmt.Errorf("failed initializing OIDC options: %w", err)

Некоторые файлы не были показаны из-за большого количества измененных файлов