Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for additional IdP authentication parameters in OIDC connector #3831

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 63 additions & 38 deletions connector/oidc/oidc.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"encoding/json"
"errors"
"fmt"
"golang.org/x/exp/slices"
"log/slog"
"net/http"
"net/url"
Expand Down Expand Up @@ -105,6 +106,9 @@ type Config struct {
NewGroupFromClaims []NewGroupFromClaims `json:"newGroupFromClaims"`
FilterGroupClaims FilterGroupClaims `json:"filterGroupClaims"`
} `json:"claimModifications"`

// AdditionalAuthRequestParams allows to add additional authorization request parameters to access IdP specific features.
AdditionalAuthRequestParams map[string]string `json:"additionalAuthRequestParams"`
}

type ProviderDiscoveryOverrides struct {
Expand Down Expand Up @@ -202,6 +206,18 @@ type connectorData struct {
RefreshToken []byte
}

var managedAuthParams = []string{
// In this implementation and golang.org/x/oauth2
"client_id",
"state",
"hd",
"acr_values",
"response_type",
"scope",
"redirect_uri",
"prompt",
}

// Detect auth header provider issues for known providers. This lets users
// avoid having to explicitly set "basicAuthUnsupported" in their config.
//
Expand Down Expand Up @@ -290,23 +306,24 @@ func (c *Config) Open(id string, logger *slog.Logger) (conn connector.Connector,
ctx, // Pass our ctx with customized http.Client
&oidc.Config{ClientID: clientID},
),
logger: logger.With(slog.Group("connector", "type", "oidc", "id", id)),
cancel: cancel,
httpClient: httpClient,
insecureSkipEmailVerified: c.InsecureSkipEmailVerified,
insecureEnableGroups: c.InsecureEnableGroups,
allowedGroups: c.AllowedGroups,
acrValues: c.AcrValues,
getUserInfo: c.GetUserInfo,
promptType: promptType,
userIDKey: c.UserIDKey,
userNameKey: c.UserNameKey,
overrideClaimMapping: c.OverrideClaimMapping,
preferredUsernameKey: c.ClaimMapping.PreferredUsernameKey,
emailKey: c.ClaimMapping.EmailKey,
groupsKey: c.ClaimMapping.GroupsKey,
newGroupFromClaims: c.ClaimMutations.NewGroupFromClaims,
groupsFilter: groupsFilter,
logger: logger.With(slog.Group("connector", "type", "oidc", "id", id)),
cancel: cancel,
httpClient: httpClient,
insecureSkipEmailVerified: c.InsecureSkipEmailVerified,
insecureEnableGroups: c.InsecureEnableGroups,
allowedGroups: c.AllowedGroups,
acrValues: c.AcrValues,
getUserInfo: c.GetUserInfo,
promptType: promptType,
userIDKey: c.UserIDKey,
userNameKey: c.UserNameKey,
overrideClaimMapping: c.OverrideClaimMapping,
preferredUsernameKey: c.ClaimMapping.PreferredUsernameKey,
emailKey: c.ClaimMapping.EmailKey,
groupsKey: c.ClaimMapping.GroupsKey,
newGroupFromClaims: c.ClaimMutations.NewGroupFromClaims,
groupsFilter: groupsFilter,
additionalAuthRequestParams: c.AdditionalAuthRequestParams,
}, nil
}

Expand All @@ -316,27 +333,28 @@ var (
)

type oidcConnector struct {
provider *oidc.Provider
redirectURI string
oauth2Config *oauth2.Config
verifier *oidc.IDTokenVerifier
cancel context.CancelFunc
logger *slog.Logger
httpClient *http.Client
insecureSkipEmailVerified bool
insecureEnableGroups bool
allowedGroups []string
acrValues []string
getUserInfo bool
promptType string
userIDKey string
userNameKey string
overrideClaimMapping bool
preferredUsernameKey string
emailKey string
groupsKey string
newGroupFromClaims []NewGroupFromClaims
groupsFilter *regexp.Regexp
provider *oidc.Provider
redirectURI string
oauth2Config *oauth2.Config
verifier *oidc.IDTokenVerifier
cancel context.CancelFunc
logger *slog.Logger
httpClient *http.Client
insecureSkipEmailVerified bool
insecureEnableGroups bool
allowedGroups []string
acrValues []string
getUserInfo bool
promptType string
userIDKey string
userNameKey string
overrideClaimMapping bool
preferredUsernameKey string
emailKey string
groupsKey string
newGroupFromClaims []NewGroupFromClaims
groupsFilter *regexp.Regexp
additionalAuthRequestParams map[string]string
}

func (c *oidcConnector) Close() error {
Expand All @@ -359,6 +377,13 @@ func (c *oidcConnector) LoginURL(s connector.Scopes, callbackURL, state string)
if s.OfflineAccess {
opts = append(opts, oauth2.AccessTypeOffline, oauth2.SetAuthURLParam("prompt", c.promptType))
}

for k, v := range c.additionalAuthRequestParams {
if !slices.Contains(managedAuthParams, k) {
opts = append(opts, oauth2.SetAuthURLParam(k, v))
}
}

return c.oauth2Config.AuthCodeURL(state, opts...), nil
}

Expand Down
186 changes: 167 additions & 19 deletions connector/oidc/oidc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"strings"
"testing"
"time"

"github.com/dexidp/dex/connector"
"github.com/go-jose/go-jose/v4"
"github.com/stretchr/testify/require"

"github.com/dexidp/dex/connector"
)

func TestKnownBrokenAuthHeaderProvider(t *testing.T) {
Expand All @@ -49,23 +49,24 @@
t.Helper()

tests := []struct {
name string
userIDKey string
userNameKey string
overrideClaimMapping bool
preferredUsernameKey string
emailKey string
groupsKey string
insecureSkipEmailVerified bool
scopes []string
expectUserID string
expectUserName string
expectGroups []string
expectPreferredUsername string
expectedEmailField string
token map[string]interface{}
groupsRegex string
newGroupFromClaims []NewGroupFromClaims
name string
userIDKey string
userNameKey string
overrideClaimMapping bool
preferredUsernameKey string
emailKey string
groupsKey string
insecureSkipEmailVerified bool
scopes []string
expectUserID string
expectUserName string
expectGroups []string
expectPreferredUsername string
expectedEmailField string
token map[string]interface{}
groupsRegex string
newGroupFromClaims []NewGroupFromClaims
additionalAuthRequestParams map[string]string
}{
{
name: "simpleCase",
Expand Down Expand Up @@ -739,6 +740,153 @@
})
}

func testLoginURL(t *testing.T, config Config, state string) (url.Values, error) {
token := map[string]interface{}{}

testServer, err := setupServer(token, true)
if err != nil {
t.Fatal("failed to setup test server", err)
}
defer testServer.Close()

serverUrl := testServer.URL

Check failure on line 752 in connector/oidc/oidc_test.go

View workflow job for this annotation

GitHub Actions / Lint

ST1003: var serverUrl should be serverURL (stylecheck)
config.Issuer = serverUrl

conn, err := newConnector(config)
if err != nil {
t.Fatal("failed to create new connector", err)
}

// what we are testing, generation of LoginURL
loginUrl, err := conn.LoginURL(connector.Scopes{OfflineAccess: false, Groups: false}, config.RedirectURI, state)

Check failure on line 761 in connector/oidc/oidc_test.go

View workflow job for this annotation

GitHub Actions / Lint

ST1003: var loginUrl should be loginURL (stylecheck)
if err != nil {
return nil, err
}

u, err := url.Parse(loginUrl)
if err != nil {
return nil, err
}

values, err := url.ParseQuery(u.RawQuery)
if err != nil {
return nil, err
}
return values, nil
}

func TestLoginURLCustomerParam(t *testing.T) {
cfg := Config{
ClientID: "client",
RedirectURI: "callback",
AdditionalAuthRequestParams: map[string]string{
"organization": "myorg",
},
}
values, err := testLoginURL(t, cfg, "1234")

require.NoError(t, err)
require.Len(t, values, 6)
expectEquals(t, values.Get("organization"), "myorg")
expectEquals(t, values.Get("client_id"), "client")
expectEquals(t, values.Get("redirect_uri"), "callback")
expectEquals(t, values.Get("state"), "1234")
expectEquals(t, values.Get("response_type"), "code")
expectEquals(t, values.Get("scope"), "openid profile email")
}

func TestCustomLoginURLEmptyParams(t *testing.T) {
cfg := Config{
ClientID: "client",
RedirectURI: "callback",
AdditionalAuthRequestParams: map[string]string{},
}
values, err := testLoginURL(t, cfg, "1234")

require.NoError(t, err)
require.Len(t, values, 5)
expectEquals(t, values.Get("client_id"), "client")
expectEquals(t, values.Get("redirect_uri"), "callback")
expectEquals(t, values.Get("state"), "1234")
expectEquals(t, values.Get("response_type"), "code")
expectEquals(t, values.Get("scope"), "openid profile email")
}

func TestLoginURLParameterProtection(t *testing.T) {
tests := []struct {
name string
paramToOverride string
expectedValue string
}{
{
name: "client_id cannot be overridden",
paramToOverride: "client_id",
expectedValue: "client", // Should remain the config value
},
{
name: "redirect_uri cannot be overridden",
paramToOverride: "redirect_uri",
expectedValue: "callback", // Should remain the config value
},
{
name: "state cannot be overridden",
paramToOverride: "state",
expectedValue: "1234", // Should remain the state parameter value
},
{
name: "response_type cannot be overridden",
paramToOverride: "response_type",
expectedValue: "code", // Should remain the default OAuth2 value
},
{
name: "scope cannot be overridden",
paramToOverride: "scope",
expectedValue: "openid profile email", // Should remain the default scopes
},
{
name: "prompt cannot be overridden",
paramToOverride: "prompt",
expectedValue: "", // Should not be set unless offline access is requested
},
{
name: "hd cannot be overridden",
paramToOverride: "hd",
expectedValue: "", // Should not be set as hosted domains are not configured
},
{
name: "acr_values cannot be overridden",
paramToOverride: "acr_values",
expectedValue: "", // Should not be set as acr_values are not configured
},
}

for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
cfg := Config{
ClientID: "client",
RedirectURI: "callback",
AdditionalAuthRequestParams: map[string]string{
tc.paramToOverride: "not-so-fast",
},
}

values, err := testLoginURL(t, cfg, "1234")
require.NoError(t, err)

// Check that the parameter contains the expected value, not the override attempt
gotValue := values.Get(tc.paramToOverride)
if tc.expectedValue == "" {
// If we expect no value, the parameter should not be present
require.Empty(t, gotValue, "parameter %s should not be present", tc.paramToOverride)
} else {
require.Equal(t, tc.expectedValue, gotValue,
"parameter %s should be %q but got %q",
tc.paramToOverride, tc.expectedValue, gotValue)
}
})
}
}

func setupServer(tok map[string]interface{}, idTokenDesired bool) (*httptest.Server, error) {
key, err := rsa.GenerateKey(rand.Reader, 1024)
if err != nil {
Expand Down
Loading