zitadel/internal/api/oidc/keys_integration_test.go
Tim Möhlmann fd0c15dd4f
feat(oidc): use web keys for token signing and verification (#8449)
# Which Problems Are Solved

Use web keys, managed by the `resources/v3alpha/web_keys` API, for OIDC
token signing and verification,
as well as serving the public web keys on the jwks / keys endpoint.
Response header on the keys endpoint now allows caching of the response.
This is now "safe" to do since keys can be created ahead of time and
caches have sufficient time to pickup the change before keys get
enabled.

# How the Problems Are Solved

- The web key format is used in the `getSignerOnce` function in the
`api/oidc` package.
- The public key cache is changed to get and store web keys.
- The jwks / keys endpoint returns the combined set of valid "legacy"
public keys and all available web keys.
- Cache-Control max-age default to 5 minutes and is configured in
`defaults.yaml`.

When the web keys feature is enabled, fallback mechanisms are in place
to obtain and convert "legacy" `query.PublicKey` as web keys when
needed. This allows transitioning to the feature without invalidating
existing tokens. A small performance overhead may be noticed on the keys
endpoint, because 2 queries need to be run sequentially. This will
disappear once the feature is stable and the legacy code gets cleaned
up.

# Additional Changes

- Extend legacy key lifetimes so that tests can be run on an existing
database with more than 6 hours apart.
- Discovery endpoint returns all supported algorithms when the Web Key
feature is enabled.

# Additional Context

- Closes https://github.com/zitadel/zitadel/issues/8031
- Part of https://github.com/zitadel/zitadel/issues/7809
- After https://github.com/zitadel/oidc/pull/637
- After https://github.com/zitadel/oidc/pull/638
2024-08-23 14:43:46 +02:00

116 lines
3.3 KiB
Go

//go:build integration
package oidc_test
import (
"crypto/rsa"
"encoding/json"
"net/http"
"testing"
"time"
"github.com/go-jose/go-jose/v4"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/zitadel/oidc/v3/pkg/client"
"github.com/zitadel/oidc/v3/pkg/oidc"
"google.golang.org/protobuf/proto"
http_util "github.com/zitadel/zitadel/internal/api/http"
"github.com/zitadel/zitadel/internal/crypto"
"github.com/zitadel/zitadel/pkg/grpc/feature/v2"
oidc_pb "github.com/zitadel/zitadel/pkg/grpc/oidc/v2"
)
func TestServer_Keys(t *testing.T) {
// TODO: isolated instance
clientID, _ := createClient(t)
authRequestID := createAuthRequest(t, clientID, redirectURI, oidc.ScopeOpenID, oidc.ScopeOfflineAccess, zitadelAudienceScope)
sessionID, sessionToken, _, _ := Tester.CreateVerifiedWebAuthNSession(t, CTXLOGIN, User.GetUserId())
linkResp, err := Tester.Client.OIDCv2.CreateCallback(CTXLOGIN, &oidc_pb.CreateCallbackRequest{
AuthRequestId: authRequestID,
CallbackKind: &oidc_pb.CreateCallbackRequest_Session{
Session: &oidc_pb.Session{
SessionId: sessionID,
SessionToken: sessionToken,
},
},
})
require.NoError(t, err)
// code exchange so we are sure there is 1 legacy key pair.
code := assertCodeResponse(t, linkResp.GetCallbackUrl())
_, err = exchangeTokens(t, clientID, code, redirectURI)
require.NoError(t, err)
issuer := http_util.BuildHTTP(Tester.Config.ExternalDomain, Tester.Config.Port, Tester.Config.ExternalSecure)
discovery, err := client.Discover(CTX, issuer, http.DefaultClient)
require.NoError(t, err)
tests := []struct {
name string
webKeyFeature bool
wantLen int
}{
{
name: "legacy only",
webKeyFeature: false,
wantLen: 1,
},
{
name: "webkeys with legacy",
webKeyFeature: true,
wantLen: 3, // 1 legacy + 2 created by enabling feature flag
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ensureWebKeyFeature(t, tt.webKeyFeature)
assert.EventuallyWithT(t, func(ttt *assert.CollectT) {
resp, err := http.Get(discovery.JwksURI)
require.NoError(ttt, err)
require.Equal(ttt, resp.StatusCode, http.StatusOK)
defer resp.Body.Close()
got := new(jose.JSONWebKeySet)
err = json.NewDecoder(resp.Body).Decode(got)
require.NoError(ttt, err)
assert.Len(t, got.Keys, tt.wantLen)
for _, key := range got.Keys {
_, ok := key.Key.(*rsa.PublicKey)
require.True(ttt, ok)
require.NotEmpty(ttt, key.KeyID)
require.Equal(ttt, key.Algorithm, string(jose.RS256))
require.Equal(ttt, key.Use, crypto.KeyUsageSigning.String())
}
cacheControl := resp.Header.Get("cache-control")
if tt.webKeyFeature {
require.Equal(ttt, "max-age=300, must-revalidate", cacheControl)
return
}
require.Equal(ttt, "no-store", cacheControl)
}, time.Minute, time.Second/10)
})
}
}
func ensureWebKeyFeature(t *testing.T, set bool) {
_, err := Tester.Client.FeatureV2.SetInstanceFeatures(CTXIAM, &feature.SetInstanceFeaturesRequest{
WebKey: proto.Bool(set),
})
require.NoError(t, err)
t.Cleanup(func() {
_, err := Tester.Client.FeatureV2.SetInstanceFeatures(CTXIAM, &feature.SetInstanceFeaturesRequest{
WebKey: proto.Bool(false),
})
require.NoError(t, err)
})
}