This repository has been archived on 2023-08-14. You can view files and clone it, but cannot push or open issues or pull requests.
dex/server/oauth2_test.go

616 lines
15 KiB
Go
Raw Normal View History

2016-07-25 20:00:28 +00:00
package server
import (
"context"
2019-06-20 17:15:59 +00:00
"crypto/rand"
"crypto/rsa"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"github.com/stretchr/testify/require"
"gopkg.in/square/go-jose.v2"
"github.com/dexidp/dex/storage"
2019-06-20 17:15:59 +00:00
"github.com/dexidp/dex/storage/memory"
)
func TestParseAuthorizationRequest(t *testing.T) {
tests := []struct {
name string
clients []storage.Client
supportedResponseTypes []string
usePOST bool
queryParams map[string]string
wantErr bool
exactError *authErr
}{
{
name: "normal request",
clients: []storage.Client{
{
ID: "foo",
RedirectURIs: []string{"https://example.com/foo"},
},
},
supportedResponseTypes: []string{"code"},
queryParams: map[string]string{
"client_id": "foo",
"redirect_uri": "https://example.com/foo",
"response_type": "code",
"scope": "openid email profile",
},
},
{
name: "POST request",
clients: []storage.Client{
{
ID: "foo",
RedirectURIs: []string{"https://example.com/foo"},
},
},
supportedResponseTypes: []string{"code"},
queryParams: map[string]string{
"client_id": "foo",
"redirect_uri": "https://example.com/foo",
"response_type": "code",
"scope": "openid email profile",
},
usePOST: true,
},
{
name: "invalid client id",
clients: []storage.Client{
{
ID: "foo",
RedirectURIs: []string{"https://example.com/foo"},
},
},
supportedResponseTypes: []string{"code"},
queryParams: map[string]string{
"client_id": "bar",
"redirect_uri": "https://example.com/foo",
"response_type": "code",
"scope": "openid email profile",
},
wantErr: true,
},
{
name: "invalid redirect uri",
clients: []storage.Client{
{
ID: "bar",
RedirectURIs: []string{"https://example.com/bar"},
},
},
supportedResponseTypes: []string{"code"},
queryParams: map[string]string{
"client_id": "bar",
"redirect_uri": "https://example.com/foo",
"response_type": "code",
"scope": "openid email profile",
},
wantErr: true,
},
{
name: "implicit flow",
clients: []storage.Client{
{
ID: "bar",
RedirectURIs: []string{"https://example.com/bar"},
},
},
supportedResponseTypes: []string{"code", "id_token", "token"},
queryParams: map[string]string{
"client_id": "bar",
"redirect_uri": "https://example.com/bar",
"response_type": "code id_token",
"scope": "openid email profile",
},
},
{
name: "unsupported response type",
clients: []storage.Client{
{
ID: "bar",
RedirectURIs: []string{"https://example.com/bar"},
},
},
supportedResponseTypes: []string{"code"},
queryParams: map[string]string{
"client_id": "bar",
"redirect_uri": "https://example.com/bar",
"response_type": "code id_token",
"scope": "openid email profile",
},
wantErr: true,
},
{
name: "only token response type",
clients: []storage.Client{
{
ID: "bar",
RedirectURIs: []string{"https://example.com/bar"},
},
},
supportedResponseTypes: []string{"code", "id_token", "token"},
queryParams: map[string]string{
"client_id": "bar",
"redirect_uri": "https://example.com/bar",
"response_type": "token",
"scope": "openid email profile",
},
wantErr: true,
},
{
name: "choose connector_id",
clients: []storage.Client{
{
ID: "bar",
RedirectURIs: []string{"https://example.com/bar"},
},
},
supportedResponseTypes: []string{"code", "id_token", "token"},
queryParams: map[string]string{
"connector_id": "mock",
"client_id": "bar",
"redirect_uri": "https://example.com/bar",
"response_type": "code id_token",
"scope": "openid email profile",
},
},
{
name: "choose second connector_id",
clients: []storage.Client{
{
ID: "bar",
RedirectURIs: []string{"https://example.com/bar"},
},
},
supportedResponseTypes: []string{"code", "id_token", "token"},
queryParams: map[string]string{
"connector_id": "mock2",
"client_id": "bar",
"redirect_uri": "https://example.com/bar",
"response_type": "code id_token",
"scope": "openid email profile",
},
},
{
name: "choose invalid connector_id",
clients: []storage.Client{
{
ID: "bar",
RedirectURIs: []string{"https://example.com/bar"},
},
},
supportedResponseTypes: []string{"code", "id_token", "token"},
queryParams: map[string]string{
"connector_id": "bogus",
"client_id": "bar",
"redirect_uri": "https://example.com/bar",
"response_type": "code id_token",
"scope": "openid email profile",
},
wantErr: true,
},
PKCE implementation (#1784) * Basic implementation of PKCE Signed-off-by: Tadeusz Magura-Witkowski <tadeuszmw@gmail.com> * @mfmarche on 24 Feb: when code_verifier is set, don't check client_secret In PKCE flow, no client_secret is used, so the check for a valid client_secret would always fail. Signed-off-by: Bernd Eckstein <Bernd.Eckstein@faro.com> * @deric on 16 Jun: return invalid_grant when wrong code_verifier Signed-off-by: Bernd Eckstein <Bernd.Eckstein@faro.com> * Enforce PKCE flow on /token when PKCE flow was started on /auth Also dissallow PKCE on /token, when PKCE flow was not started on /auth Signed-off-by: Bernd Eckstein <Bernd.Eckstein@faro.com> * fixed error messages when mixed PKCE/no PKCE flow. Signed-off-by: Bernd Eckstein <Bernd.Eckstein@faro.com> * server_test.go: Added PKCE error cases on /token endpoint * Added test for invalid_grant, when wrong code_verifier is sent * Added test for mixed PKCE / no PKCE auth flows. Signed-off-by: Bernd Eckstein <Bernd.Eckstein@faro.com> * cleanup: extracted method checkErrorResponse and type TestDefinition * fixed connector being overwritten Signed-off-by: Bernd Eckstein <Bernd.Eckstein@faro.com> * /token endpoint: skip client_secret verification only for grand type authorization_code with PKCE extension Signed-off-by: Bernd Eckstein <Bernd.Eckstein@faro.com> * Allow "Authorization" header in CORS handlers * Adds "Authorization" to the default CORS headers{"Accept", "Accept-Language", "Content-Language", "Origin"} Signed-off-by: Bernd Eckstein <Bernd.Eckstein@faro.com> * Add "code_challenge_methods_supported" to discovery endpoint discovery endpoint /dex/.well-known/openid-configuration now has the following entry: "code_challenge_methods_supported": [ "S256", "plain" ] Signed-off-by: Bernd Eckstein <Bernd.Eckstein@faro.com> * Updated tests (mixed-up comments), added a PKCE test * @asoorm added test that checks if downgrade to "plain" on /token endpoint Signed-off-by: Bernd Eckstein <Bernd.Eckstein@faro.com> * remove redefinition of providedCodeVerifier, fixed spelling (#6) Signed-off-by: Bernd Eckstein <Bernd.Eckstein@faro.com> Signed-off-by: Bernd Eckstein <HEllRZA@users.noreply.github.com> * Rename struct CodeChallenge to PKCE Signed-off-by: Bernd Eckstein <Bernd.Eckstein@faro.com> * PKCE: Check clientSecret when available In authorization_code flow with PKCE, allow empty client_secret on /auth and /token endpoints. But check the client_secret when it is given. Signed-off-by: Bernd Eckstein <Bernd.Eckstein@faro.com> * Enable PKCE with public: true dex configuration public on staticClients now enables the following behavior in PKCE: - Public: false, PKCE will always check client_secret. This means PKCE in it's natural form is disabled. - Public: true, PKCE is enabled. It will only check client_secret if the client has sent one. But it allows the code flow if the client didn't sent one. Signed-off-by: Bernd Eckstein <Bernd.Eckstein@faro.com> * Redirect error on unsupported code_challenge_method - Check for unsupported code_challenge_method after redirect uri is validated, and use newErr() to return the error. - Add PKCE tests to oauth2_test.go Signed-off-by: Bernd Eckstein <Bernd.Eckstein@faro.com> * Reverted go.mod and go.sum to the state of master Signed-off-by: Bernd Eckstein <Bernd.Eckstein@faro.com> * Don't omit client secret check for PKCE Signed-off-by: Bernd Eckstein <Bernd.Eckstein@faro.com> * Allow public clients (e.g. with PKCE) to have redirect URIs configured Signed-off-by: Martin Heide <martin.heide@faro.com> * Remove "Authorization" as Accepted Headers on CORS, small fixes Signed-off-by: Bernd Eckstein <Bernd.Eckstein@faro.com> * Revert "Allow public clients (e.g. with PKCE) to have redirect URIs configured" This reverts commit b6e297b78537dc44cd3e1374f0b4d34bf89404ac. Signed-off-by: Martin Heide <martin.heide@faro.com> * PKCE on client_secret client error message * When connecting to the token endpoint with PKCE without client_secret, but the client is configured with a client_secret, generate a special error message. Signed-off-by: Bernd Eckstein <Bernd.Eckstein@faro.com> * Output info message when PKCE without client_secret used on confidential client * removes the special error message Signed-off-by: Bernd Eckstein <Bernd.Eckstein@faro.com> * General missing/invalid client_secret message on token endpoint Signed-off-by: Bernd Eckstein <Bernd.Eckstein@faro.com> Co-authored-by: Tadeusz Magura-Witkowski <tadeuszmw@gmail.com> Co-authored-by: Martin Heide <martin.heide@faro.com> Co-authored-by: M. Heide <66078329+heidemn-faro@users.noreply.github.com>
2020-10-26 10:33:40 +00:00
{
name: "PKCE code_challenge_method plain",
clients: []storage.Client{
{
ID: "bar",
RedirectURIs: []string{"https://example.com/bar"},
},
},
supportedResponseTypes: []string{"code"},
queryParams: map[string]string{
"client_id": "bar",
"redirect_uri": "https://example.com/bar",
"response_type": "code",
"code_challenge": "123",
"code_challenge_method": "plain",
"scope": "openid email profile",
},
},
{
name: "PKCE code_challenge_method default plain",
clients: []storage.Client{
{
ID: "bar",
RedirectURIs: []string{"https://example.com/bar"},
},
},
supportedResponseTypes: []string{"code"},
queryParams: map[string]string{
"client_id": "bar",
"redirect_uri": "https://example.com/bar",
"response_type": "code",
"code_challenge": "123",
"scope": "openid email profile",
},
},
{
name: "PKCE code_challenge_method S256",
clients: []storage.Client{
{
ID: "bar",
RedirectURIs: []string{"https://example.com/bar"},
},
},
supportedResponseTypes: []string{"code"},
queryParams: map[string]string{
"client_id": "bar",
"redirect_uri": "https://example.com/bar",
"response_type": "code",
"code_challenge": "123",
"code_challenge_method": "S256",
"scope": "openid email profile",
},
},
{
name: "PKCE invalid code_challenge_method",
clients: []storage.Client{
{
ID: "bar",
RedirectURIs: []string{"https://example.com/bar"},
},
},
supportedResponseTypes: []string{"code"},
queryParams: map[string]string{
"client_id": "bar",
"redirect_uri": "https://example.com/bar",
"response_type": "code",
"code_challenge": "123",
"code_challenge_method": "invalid_method",
"scope": "openid email profile",
},
wantErr: true,
},
{
name: "No response type",
clients: []storage.Client{
{
ID: "bar",
RedirectURIs: []string{"https://example.com/bar"},
},
},
supportedResponseTypes: []string{"code"},
queryParams: map[string]string{
"client_id": "bar",
"redirect_uri": "https://example.com/bar",
"code_challenge": "123",
"code_challenge_method": "plain",
"scope": "openid email profile",
},
wantErr: true,
exactError: &authErr{
RedirectURI: "https://example.com/bar",
Type: "invalid_request",
Description: "No response_type provided",
},
},
}
for _, tc := range tests {
func() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
httpServer, server := newTestServerMultipleConnectors(ctx, t, func(c *Config) {
c.SupportedResponseTypes = tc.supportedResponseTypes
c.Storage = storage.WithStaticClients(c.Storage, tc.clients)
})
defer httpServer.Close()
params := url.Values{}
for k, v := range tc.queryParams {
params.Set(k, v)
}
var req *http.Request
if tc.usePOST {
body := strings.NewReader(params.Encode())
req = httptest.NewRequest("POST", httpServer.URL+"/auth", body)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
} else {
req = httptest.NewRequest("GET", httpServer.URL+"/auth?"+params.Encode(), nil)
}
_, err := server.parseAuthorizationRequest(req)
if tc.wantErr {
require.Error(t, err)
if tc.exactError != nil {
require.Equal(t, tc.exactError, err)
}
} else {
require.NoError(t, err)
}
}()
}
}
const (
// at_hash value and access_token returned by Google.
googleAccessTokenHash = "piwt8oCH-K2D9pXlaS1Y-w"
googleAccessToken = "ya29.CjHSA1l5WUn8xZ6HanHFzzdHdbXm-14rxnC7JHch9eFIsZkQEGoWzaYG4o7k5f6BnPLj"
googleSigningAlg = jose.RS256
)
func TestAccessTokenHash(t *testing.T) {
atHash, err := accessTokenHash(googleSigningAlg, googleAccessToken)
if err != nil {
t.Fatal(err)
}
if atHash != googleAccessTokenHash {
t.Errorf("expected %q got %q", googleAccessTokenHash, atHash)
}
}
func TestValidRedirectURI(t *testing.T) {
tests := []struct {
client storage.Client
redirectURI string
wantValid bool
}{
{
client: storage.Client{
RedirectURIs: []string{"http://foo.com/bar"},
},
redirectURI: "http://foo.com/bar",
wantValid: true,
},
{
client: storage.Client{
RedirectURIs: []string{"http://foo.com/bar"},
},
redirectURI: "http://foo.com/bar/baz",
wantValid: false,
},
// These special desktop + device + localhost URIs are allowed by default.
{
client: storage.Client{
Public: true,
},
redirectURI: "urn:ietf:wg:oauth:2.0:oob",
wantValid: true,
},
{
client: storage.Client{
Public: true,
},
redirectURI: "/device/callback",
wantValid: true,
},
{
client: storage.Client{
Public: true,
},
redirectURI: "http://localhost:8080/",
wantValid: true,
},
{
client: storage.Client{
Public: true,
},
redirectURI: "http://localhost:991/bar",
wantValid: true,
},
{
client: storage.Client{
Public: true,
},
redirectURI: "http://localhost",
wantValid: true,
},
// Both Public + RedirectURIs configured: Could e.g. be a PKCE-enabled web app.
{
client: storage.Client{
Public: true,
RedirectURIs: []string{"http://foo.com/bar"},
},
redirectURI: "http://foo.com/bar",
wantValid: true,
},
{
client: storage.Client{
Public: true,
RedirectURIs: []string{"http://foo.com/bar"},
},
redirectURI: "http://foo.com/bar/baz",
wantValid: false,
},
// These special desktop + device + localhost URIs are not allowed implicitly when RedirectURIs is non-empty.
{
client: storage.Client{
Public: true,
RedirectURIs: []string{"http://foo.com/bar"},
},
redirectURI: "urn:ietf:wg:oauth:2.0:oob",
wantValid: false,
},
{
client: storage.Client{
Public: true,
RedirectURIs: []string{"http://foo.com/bar"},
},
redirectURI: "/device/callback",
wantValid: false,
},
{
client: storage.Client{
Public: true,
RedirectURIs: []string{"http://foo.com/bar"},
},
redirectURI: "http://localhost:8080/",
wantValid: false,
},
{
client: storage.Client{
Public: true,
RedirectURIs: []string{"http://foo.com/bar"},
},
redirectURI: "http://localhost:991/bar",
wantValid: false,
},
{
client: storage.Client{
Public: true,
RedirectURIs: []string{"http://foo.com/bar"},
},
redirectURI: "http://localhost",
wantValid: false,
},
// These special desktop + device + localhost URIs can still be specified explicitly.
{
client: storage.Client{
Public: true,
RedirectURIs: []string{"http://foo.com/bar", "urn:ietf:wg:oauth:2.0:oob"},
},
redirectURI: "urn:ietf:wg:oauth:2.0:oob",
wantValid: true,
},
{
client: storage.Client{
Public: true,
RedirectURIs: []string{"http://foo.com/bar", "/device/callback"},
},
redirectURI: "/device/callback",
wantValid: true,
},
{
client: storage.Client{
Public: true,
RedirectURIs: []string{"http://foo.com/bar", "http://localhost:8080/"},
},
redirectURI: "http://localhost:8080/",
wantValid: true,
},
{
client: storage.Client{
Public: true,
RedirectURIs: []string{"http://foo.com/bar", "http://localhost:991/bar"},
},
redirectURI: "http://localhost:991/bar",
wantValid: true,
},
{
client: storage.Client{
Public: true,
RedirectURIs: []string{"http://foo.com/bar", "http://localhost"},
},
redirectURI: "http://localhost",
wantValid: true,
},
// Non-localhost URIs are not allowed implicitly.
{
client: storage.Client{
Public: true,
},
redirectURI: "http://foo.com/bar",
wantValid: false,
},
{
client: storage.Client{
Public: true,
},
redirectURI: "http://localhost.localhost:8080/",
wantValid: false,
},
}
for _, test := range tests {
got := validateRedirectURI(test.client, test.redirectURI)
if got != test.wantValid {
t.Errorf("client=%#v, redirectURI=%q, wanted valid=%t, got=%t",
test.client, test.redirectURI, test.wantValid, got)
}
}
}
2019-06-20 17:15:59 +00:00
func TestStorageKeySet(t *testing.T) {
s := memory.New(logger)
if err := s.UpdateKeys(func(keys storage.Keys) (storage.Keys, error) {
keys.SigningKey = &jose.JSONWebKey{
Key: testKey,
KeyID: "testkey",
Algorithm: "RS256",
Use: "sig",
}
keys.SigningKeyPub = &jose.JSONWebKey{
Key: testKey.Public(),
KeyID: "testkey",
Algorithm: "RS256",
Use: "sig",
}
return keys, nil
}); err != nil {
t.Fatal(err)
}
tests := []struct {
name string
tokenGenerator func() (jwt string, err error)
wantErr bool
}{
{
name: "valid token",
tokenGenerator: func() (string, error) {
signer, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.RS256, Key: testKey}, nil)
if err != nil {
return "", err
}
jws, err := signer.Sign([]byte("payload"))
if err != nil {
return "", err
}
return jws.CompactSerialize()
},
wantErr: false,
},
{
name: "token signed by different key",
tokenGenerator: func() (string, error) {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return "", err
}
signer, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.RS256, Key: key}, nil)
if err != nil {
return "", err
}
jws, err := signer.Sign([]byte("payload"))
if err != nil {
return "", err
}
return jws.CompactSerialize()
},
wantErr: true,
},
}
for _, tc := range tests {
tc := tc
t.Run(tc.name, func(t *testing.T) {
jwt, err := tc.tokenGenerator()
if err != nil {
t.Fatal(err)
}
keySet := &storageKeySet{s}
_, err = keySet.VerifySignature(context.Background(), jwt)
if (err != nil && !tc.wantErr) || (err == nil && tc.wantErr) {
t.Fatalf("wantErr = %v, but got err = %v", tc.wantErr, err)
}
})
}
}