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

Improve access and dpop token validation
pull/1670/head v0.25.3-rc.1
Herman Slatman 5 months ago committed by GitHub
commit 51d1270541
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

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

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

@ -355,8 +355,6 @@ func dns01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSONWebK
type wireOidcPayload struct { type wireOidcPayload struct {
// IDToken contains the OIDC identity token // IDToken contains the OIDC identity token
IDToken string `json:"id_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 { 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 { if !ok {
return NewErrorISE("missing provisioner") return NewErrorISE("missing provisioner")
} }
linker, ok := LinkerFromContext(ctx)
if !ok {
return NewErrorISE("missing linker")
}
var oidcPayload wireOidcPayload var oidcPayload wireOidcPayload
err := json.Unmarshal(payload, &oidcPayload) 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") 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() oidcOptions := wireOptions.GetOIDCOptions()
verifier := oidcOptions.GetProvider(ctx).Verifier(oidcOptions.GetConfig()) verifier := oidcOptions.GetProvider(ctx).Verifier(oidcOptions.GetConfig())
idToken, err := verifier.Verify(ctx, oidcPayload.IDToken) 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 { var claims struct {
Name string `json:"preferred_username,omitempty"` Name string `json:"preferred_username,omitempty"`
Handle string `json:"name"` Handle string `json:"name"`
Issuer string `json:"iss,omitempty"` Issuer string `json:"iss,omitempty"`
GivenName string `json:"given_name,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 KeyAuth string `json:"keyauth"`
ACMEAudience string `json:"acme_aud,omitempty"`
} }
if err := idToken.Claims(&claims); err != nil { if err := idToken.Claims(&claims); err != nil {
return storeError(ctx, db, ch, true, WrapError(ErrorRejectedIdentifierType, err, return storeError(ctx, db, ch, true, WrapError(ErrorRejectedIdentifierType, err,
"error retrieving claims from ID token")) "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) transformedIDToken, err := validateWireOIDCClaims(oidcOptions, idToken, wireID)
if err != nil { if err != nil {
return storeError(ctx, db, ch, true, WrapError(ErrorRejectedIdentifierType, err, "claims in OIDC ID token don't match")) 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) return nil, fmt.Errorf("invalid 'name' %q after transformation", name)
} }
handle, ok := transformed["handle"] preferredUsername, ok := transformed["preferred_username"]
if !ok { 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 { if wireID.Handle != preferredUsername {
return nil, fmt.Errorf("invalid 'handle' %q after transformation", handle) return nil, fmt.Errorf("invalid 'preferred_username' %q after transformation", preferredUsername)
} }
return transformed, nil return transformed, nil
@ -480,6 +490,10 @@ func wireDPOP01Validate(ctx context.Context, ch *Challenge, db DB, accountJWK *j
if !ok { if !ok {
return NewErrorISE("missing provisioner") return NewErrorISE("missing provisioner")
} }
linker, ok := LinkerFromContext(ctx)
if !ok {
return NewErrorISE("missing linker")
}
var dpopPayload wireDpopPayload var dpopPayload wireDpopPayload
if err := json.Unmarshal(payload, &dpopPayload); err != nil { 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'") 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{ params := wireVerifyParams{
token: dpopPayload.AccessToken, token: dpopPayload.AccessToken,
tokenKey: dpopOptions.GetSigningKey(), tokenKey: dpopOptions.GetSigningKey(),
dpopKey: accountJWK.Public(), dpopKey: accountJWK.Public(),
dpopKeyID: accountJWK.KeyID, dpopKeyID: accountJWK.KeyID,
issuer: issuer, issuer: issuer,
audience: audience,
wireID: wireID, wireID: wireID,
chToken: ch.Token, chToken: ch.Token,
t: clock.Now().UTC(), t: clock.Now().UTC(),
@ -555,6 +573,7 @@ type wireCnf struct {
type wireAccessToken struct { type wireAccessToken struct {
jose.Claims jose.Claims
Challenge string `json:"chal"` Challenge string `json:"chal"`
Nonce string `json:"nonce"`
Cnf wireCnf `json:"cnf"` Cnf wireCnf `json:"cnf"`
Proof string `json:"proof"` Proof string `json:"proof"`
ClientID string `json:"client_id"` ClientID string `json:"client_id"`
@ -562,6 +581,14 @@ type wireAccessToken struct {
Scope string `json:"scope"` 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 wireDpopToken map[string]any
type wireVerifyParams struct { type wireVerifyParams struct {
@ -570,6 +597,7 @@ type wireVerifyParams struct {
dpopKey crypto.PublicKey dpopKey crypto.PublicKey
dpopKeyID string dpopKeyID string
issuer string issuer string
audience string
wireID wire.ID wireID wire.ID
chToken string chToken string
t time.Time t time.Time
@ -581,32 +609,97 @@ func parseAndVerifyWireAccessToken(v wireVerifyParams) (*wireAccessToken, *wireD
return nil, nil, fmt.Errorf("failed parsing token: %w", err) 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 var accessToken wireAccessToken
if err = jwt.Claims(v.tokenKey, &accessToken); err != nil { if err = jwt.Claims(v.tokenKey, &accessToken); err != nil {
return nil, nil, fmt.Errorf("failed validating Wire DPoP token claims: %w", err) return nil, nil, fmt.Errorf("failed validating Wire DPoP token claims: %w", err)
} }
if err := accessToken.ValidateWithLeeway(jose.Expected{ if err := accessToken.ValidateWithLeeway(jose.Expected{
Time: v.t, Time: v.t,
Issuer: v.issuer, Issuer: v.issuer,
}, 360*time.Second); err != nil { Audience: jose.Audience{v.audience},
}, 1*time.Minute); err != nil {
return nil, nil, fmt.Errorf("failed validation: %w", err) 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) return nil, nil, fmt.Errorf("expected kid %q; got %q", v.dpopKeyID, accessToken.Cnf.Kid)
} }
if accessToken.ClientID != v.wireID.ClientID { if accessToken.ClientID != v.wireID.ClientID {
return nil, nil, fmt.Errorf("invalid Wire client ID %q", accessToken.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()) 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) dpopJWT, err := jose.ParseSigned(accessToken.Proof)
if err != nil { if err != nil {
return nil, nil, fmt.Errorf("invalid Wire DPoP token: %w", err) 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 var dpopToken wireDpopToken
if err := dpopJWT.Claims(v.dpopKey, &dpopToken); err != nil { if err := dpopJWT.Claims(v.dpopKey, &dpopToken); err != nil {
return nil, nil, fmt.Errorf("failed validating Wire DPoP token claims: %w", err) 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 { if !ok {
return nil, nil, fmt.Errorf("invalid challenge in Wire DPoP token") 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) return nil, nil, fmt.Errorf("invalid Wire DPoP challenge %q", challenge)
} }
@ -624,7 +717,7 @@ func parseAndVerifyWireAccessToken(v wireVerifyParams) (*wireAccessToken, *wireD
if !ok { if !ok {
return nil, nil, fmt.Errorf("invalid handle in Wire DPoP token") 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) return nil, nil, fmt.Errorf("invalid Wire client handle %q", handle)
} }

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

File diff suppressed because it is too large Load Diff

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

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

@ -10,7 +10,7 @@ import (
) )
type DPOPOptions struct { 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"` 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) // 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"` Target string `json:"target"`

@ -24,8 +24,10 @@ type Provider struct {
} }
type Config struct { type Config struct {
ClientID string `json:"clientId,omitempty"` ClientID string `json:"clientId,omitempty"`
SignatureAlgorithms []string `json:"signatureAlgorithms,omitempty"` SignatureAlgorithms []string `json:"signatureAlgorithms,omitempty"`
// the properties below are only used for testing
SkipClientIDCheck bool `json:"-"` SkipClientIDCheck bool `json:"-"`
SkipExpiryCheck bool `json:"-"` SkipExpiryCheck bool `json:"-"`
SkipIssuerCheck 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) { func (o *OIDCOptions) validateAndInitialize() (err error) {
if o.Provider == nil { if o.Provider == nil {

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

@ -3,16 +3,12 @@ package wire
import ( import (
"errors" "errors"
"fmt" "fmt"
"sync"
) )
// Options holds the Wire ACME extension options // Options holds the Wire ACME extension options
type Options struct { type Options struct {
OIDC *OIDCOptions `json:"oidc,omitempty"` OIDC *OIDCOptions `json:"oidc,omitempty"`
DPOP *DPOPOptions `json:"dpop,omitempty"` DPOP *DPOPOptions `json:"dpop,omitempty"`
validateOnce sync.Once
validationErr error
} }
// GetOIDCOptions returns the OIDC options. // GetOIDCOptions returns the OIDC options.
@ -31,17 +27,10 @@ func (o *Options) GetDPOPOptions() *DPOPOptions {
return o.DPOP 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 { 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 oidc := o.GetOIDCOptions(); oidc != nil {
if err := oidc.validateAndInitialize(); err != nil { if err := oidc.validateAndInitialize(); err != nil {
return fmt.Errorf("failed initializing OIDC options: %w", err) return fmt.Errorf("failed initializing OIDC options: %w", err)

Loading…
Cancel
Save